alexa gpt
1.0.0
通过使其响应为 ChatGPT 来增强您的 Alexa。
此存储库包含有关如何创建简单的 Alexa 技能的教程,该技能使用 OpenAI API 从 ChatGPT 模型生成响应。
登录您的 Amazon 开发者帐户并导航至 Alexa 开发者控制台。
单击“创建技能”并将技能命名为“聊天”。根据您的语言选择主要区域设置。
为模型选择“其他”和“自定义”。
选择“Alexa-hosted (Python)”作为后端资源。
您现在有两个选择:
或者如果您想手动创建技能
在“构建”部分中,导航到“JSON 编辑器”选项卡。
如果您直接从该存储库导入技能,只需将“inplicationName”更改为“chat”或其他首选单词即可激活,然后继续执行步骤 12。
但是,如果您选择手动创建技能,请将现有 JSON 内容替换为提供的 JSON 内容:
{
"interactionModel" : {
"languageModel" : {
"invocationName" : " chat " ,
"intents" : [
{
"name" : " GptQueryIntent " ,
"slots" : [
{
"name" : " query " ,
"type" : " AMAZON.Person "
}
],
"samples" : [
" {query} "
]
},
{
"name" : " AMAZON.CancelIntent " ,
"samples" : []
},
{
"name" : " AMAZON.HelpIntent " ,
"samples" : []
},
{
"name" : " AMAZON.StopIntent " ,
"samples" : []
},
{
"name" : " AMAZON.NavigateHomeIntent " ,
"samples" : []
}
],
"types" : []
}
}
}
保存模型并单击“构建模型”。
转到“代码”部分并将“openai”添加到requirements.txt。您的requirements.txt 应如下所示:
ask-sdk-core==1.11.0
boto3==1.9.216
requests>=2.20.0
通过单击“+ 创建新密钥”在 API 密钥页面上创建 OpenAI API 密钥。
将 lambda_functions.py 文件替换为提供的 lambda_function.py。
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 ()
输入您从 OpenAI 帐户获得的 OpenAI API 密钥
保存并部署。进入“测试”部分并在“开发”中启用“技能测试”。
您现在可以在 ChatGPT 模式下使用 Alexa。您应该看到如下结果:
请注意,运行此技能将产生使用 AWS Lambda 和 OpenAI API 的费用。确保您了解定价结构并监控您的使用情况,以避免意外收费。