-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandler.ts
78 lines (70 loc) · 2.32 KB
/
handler.ts
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
"use strict";
import { ErrorHandler, RequestHandler, SkillBuilders } from "ask-sdk";
import { IntentRequest } from "ask-sdk-model";
import { Configuration, OpenAIApi } from "openai";
const config = new Configuration({
apiKey: process.env.OPENAI_API_KEY,
});
const openaiApiClient = new OpenAIApi(config);
const ChatGptHandler: RequestHandler = {
canHandle(handlerInput) {
return (
handlerInput.requestEnvelope.request.type === "IntentRequest" &&
handlerInput.requestEnvelope.request.intent.name === "askChatGpt"
);
},
async handle(handlerInput) {
const handlerInputIntent = (
handlerInput.requestEnvelope.request as IntentRequest
).intent;
const queryValue = handlerInputIntent?.slots?.query?.value;
if (queryValue) {
console.log("input is", queryValue);
const result = await openaiApiClient.createChatCompletion({
model: "gpt-3.5-turbo",
messages: [{ role: "user", content: queryValue }],
});
console.log("result is", result?.data?.choices[0]?.message?.content);
return handlerInput.responseBuilder
.speak(result?.data?.choices[0]?.message?.content || "Result Error")
.withSimpleCard(
"GPT says",
result?.data?.choices[0]?.message?.content || "Result Error"
)
.getResponse();
}
return handlerInput.responseBuilder
.speak("Missing query term")
.withSimpleCard("Missing query Term", "Missing Query Term")
.getResponse();
},
};
const ErrorHandler: ErrorHandler = {
canHandle() {
return true;
},
handle(input, error) {
console.log(`Handling error: ${error}`);
return input.responseBuilder
.speak("Sorry, I can't understand that")
.reprompt("Please say it again")
.getResponse();
},
};
const LaunchRequestHandler: RequestHandler = {
canHandle(handlerInput) {
return handlerInput.requestEnvelope.request.type === "LaunchRequest";
},
handle(handlerInput) {
const speechText = "Welcome to ChatGPT, you can ask me anything";
return handlerInput.responseBuilder
.speak(speechText)
.reprompt(speechText)
.withSimpleCard("AlexaGPT", speechText)
.getResponse();
},
};
export const callGpt = SkillBuilders.custom()
.addRequestHandlers(ChatGptHandler, LaunchRequestHandler)
.addErrorHandlers(ErrorHandler)
.lambda();