forked from k4l1sh/alexa-gpt
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlambda_function.py
More file actions
153 lines (129 loc) · 5.42 KB
/
lambda_function.py
File metadata and controls
153 lines (129 loc) · 5.42 KB
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
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
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
import random
# Set your OpenAI API key
api_key = "your_openai_api_key"
logger = logging.getLogger()
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 = "What's up?"
session_attr = handler_input.attributes_manager.session_attributes
session_attr["chat_history"] = []
return (
handler_input.response_builder
.speak(get_ssml_voice(speak_output))
.ask(get_ssml_voice(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
# if response to "anything else?" is exactly "no"
if query and query.strip().lower() == "no":
speak_output = get_goodbye_phrase()
return (
handler_input.response_builder
.speak(get_ssml_voice(speak_output))
.set_should_end_session(True) # End the session
.response
)
session_attr = handler_input.attributes_manager.session_attributes
if "chat_history" not in session_attr:
session_attr["chat_history"] = []
speak_output = generate_gpt_response(session_attr["chat_history"], query)
session_attr["chat_history"].append((query, speak_output))
return (
handler_input.response_builder
.speak(get_ssml_voice(speak_output))
.ask(get_ssml_voice("Anything else?"))
.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 = "Fast pass is broken, something went wrong, check them logs"
return (
handler_input.response_builder
.speak(get_ssml_voice(speak_output))
.ask(get_ssml_voice(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):
speak_output = get_goodbye_phrase()
return (
handler_input.response_builder
.speak(get_ssml_voice(speak_output))
.response
)
def get_ssml_voice(text):
return f"<voice name='Salli'>{text}</voice>"
def get_goodbye_phrase():
goodbye_phrases = [
"Cool cool, see ya next time",
"Okay, see ya",
"Until next time, take care!",
"Peace out, see you soon!",
]
return random.choice(goodbye_phrases)
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 that prioritizes answering in one sentence."}]
for question, answer in chat_history[-50:]:
messages.append({"role": "user", "content": question})
messages.append({"role": "assistant", "content": answer})
messages.append({"role": "user", "content": new_question})
data = {
"model": "gpt-4o",
"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()