-
Notifications
You must be signed in to change notification settings - Fork 54
/
lambda_function.py
133 lines (110 loc) · 4.65 KB
/
lambda_function.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
from ask_sdk_core.dispatch_components import AbstractExceptionHandler
from ask_sdk_core.dispatch_components import AbstractRequestHandler
from ask_sdk_core.skill_builder import SkillBuilder
from ask_sdk_core.handler_input import HandlerInput
from ask_sdk_model import Response
import ask_sdk_core.utils as ask_utils
import requests
import logging
import json
# Set your OpenAI API key
api_key = "YOUR_API_KEY"
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
class LaunchRequestHandler(AbstractRequestHandler):
"""Handler for Skill Launch."""
def can_handle(self, handler_input):
# type: (HandlerInput) -> bool
return ask_utils.is_request_type("LaunchRequest")(handler_input)
def handle(self, handler_input):
# type: (HandlerInput) -> Response
speak_output = "Chat G.P.T. mode activated"
session_attr = handler_input.attributes_manager.session_attributes
session_attr["chat_history"] = []
return (
handler_input.response_builder
.speak(speak_output)
.ask(speak_output)
.response
)
class GptQueryIntentHandler(AbstractRequestHandler):
"""Handler for Gpt Query Intent."""
def can_handle(self, handler_input):
# type: (HandlerInput) -> bool
return ask_utils.is_intent_name("GptQueryIntent")(handler_input)
def handle(self, handler_input):
# type: (HandlerInput) -> Response
query = handler_input.request_envelope.request.intent.slots["query"].value
session_attr = handler_input.attributes_manager.session_attributes
if "chat_history" not in session_attr:
session_attr["chat_history"] = []
response = generate_gpt_response(session_attr["chat_history"], query)
session_attr["chat_history"].append((query, response))
return (
handler_input.response_builder
.speak(response)
.ask("Any other questions?")
.response
)
class CatchAllExceptionHandler(AbstractExceptionHandler):
"""Generic error handling to capture any syntax or routing errors."""
def can_handle(self, handler_input, exception):
# type: (HandlerInput, Exception) -> bool
return True
def handle(self, handler_input, exception):
# type: (HandlerInput, Exception) -> Response
logger.error(exception, exc_info=True)
speak_output = "Sorry, I had trouble doing what you asked. Please try again."
return (
handler_input.response_builder
.speak(speak_output)
.ask(speak_output)
.response
)
class CancelOrStopIntentHandler(AbstractRequestHandler):
"""Single handler for Cancel and Stop Intent."""
def can_handle(self, handler_input):
# type: (HandlerInput) -> bool
return (ask_utils.is_intent_name("AMAZON.CancelIntent")(handler_input) or
ask_utils.is_intent_name("AMAZON.StopIntent")(handler_input))
def handle(self, handler_input):
# type: (HandlerInput) -> Response
speak_output = "Leaving Chat G.P.T. mode"
return (
handler_input.response_builder
.speak(speak_output)
.response
)
def generate_gpt_response(chat_history, new_question):
"""Generates a GPT response to a new question"""
headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json"
}
url = "https://api.openai.com/v1/chat/completions"
messages = [{"role": "system", "content": "You are a helpful assistant. Answer in 50 words or less."}]
for question, answer in chat_history[-10:]:
messages.append({"role": "user", "content": question})
messages.append({"role": "assistant", "content": answer})
messages.append({"role": "user", "content": new_question})
data = {
"model": "gpt-4o-mini",
"messages": messages,
"max_tokens": 300,
"temperature": 0.5
}
try:
response = requests.post(url, headers=headers, data=json.dumps(data))
response_data = response.json()
if response.ok:
return response_data['choices'][0]['message']['content']
else:
return f"Error {response.status_code}: {response_data['error']['message']}"
except Exception as e:
return f"Error generating response: {str(e)}"
sb = SkillBuilder()
sb.add_request_handler(LaunchRequestHandler())
sb.add_request_handler(GptQueryIntentHandler())
sb.add_request_handler(CancelOrStopIntentHandler())
sb.add_exception_handler(CatchAllExceptionHandler())
lambda_handler = sb.lambda_handler()