Tingkatkan Alexa Anda dengan menjadikannya merespons sebagai ChatGPT.
Repositori ini berisi tutorial tentang cara membuat keterampilan Alexa sederhana yang menggunakan OpenAI API untuk menghasilkan respons dari model ChatGPT.
Masuk ke akun Pengembang Amazon Anda dan navigasikan ke Konsol Pengembang Alexa.
Klik "Buat Keterampilan" dan beri nama keterampilan "Obrolan". Pilih lokal utama sesuai dengan bahasa Anda.
Pilih "Lainnya" dan "Kustom" untuk modelnya.
Pilih "Alexa-hosted (Python)" untuk sumber daya backend.
Anda sekarang memiliki dua opsi:
Atau jika ingin membuat skillnya secara manual
Di bagian "Build", navigasikan ke tab "JSON Editor".
Jika Anda sudah langsung mengimpor skill dari repositori ini, ubah saja "invocationName" menjadi "chat" atau kata lain yang disukai untuk aktivasi dan lanjutkan ke langkah 12.
Namun, jika Anda memilih untuk membuat keterampilan secara manual, ganti konten JSON yang ada dengan konten JSON yang disediakan:
{
"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" : []
}
}
}
Simpan model dan klik "Bangun Model".
Buka bagian "Kode" dan tambahkan "openai" ke persyaratan.txt. Persyaratan.txt Anda akan terlihat seperti ini:
ask-sdk-core==1.11.0
boto3==1.9.216
requests>=2.20.0
Buat kunci API OpenAI di halaman kunci API dengan mengklik "+ Buat kunci rahasia baru".
Ganti file lambda_functions.py Anda dengan lambda_function.py yang disediakan.
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 ()
Masukkan kunci API OpenAI yang Anda dapatkan dari akun OpenAI Anda
Simpan dan terapkan. Buka bagian "Tes" dan aktifkan "Tes keterampilan" di "Pengembangan".
Anda sekarang siap menggunakan Alexa Anda dalam mode ChatGPT. Anda akan melihat hasil seperti ini:
Harap perhatikan bahwa menjalankan keterampilan ini akan dikenakan biaya untuk menggunakan AWS Lambda dan OpenAI API. Pastikan Anda memahami struktur harga dan memantau penggunaan Anda untuk menghindari biaya tak terduga.