This repository was archived by the owner on Oct 7, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathai.ts
More file actions
221 lines (200 loc) · 6.18 KB
/
ai.ts
File metadata and controls
221 lines (200 loc) · 6.18 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
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
import { OpenAI } from "openai";
import { assertExists } from "./utils";
import {
ChatCompletionChunk,
ChatCompletionMessage,
ChatCompletionMessageParam,
ChatCompletionRole,
} from "openai/resources/chat";
import { VectorDbService } from "./vector-db";
import { Logger } from "pino";
const embeddingModel = "text-embedding-ada-002";
const chatModel = "gpt-3.5-turbo";
const functions = [
{
name: "lookup_game_rules",
description:
"lets you look up the rules for a game that the user wants to play",
parameters: {
type: "object",
properties: {
activity: { type: "string", description: "the game to play" },
},
},
},
];
interface MessageChunk {
type: "message_chunk";
message: string;
}
interface CompleteChunk {
type: "complete";
reason: ChatCompletionChunk.Choice["finish_reason"];
content: string;
}
interface FunctionCallChunk {
type: "function_call";
functionCall: ChatCompletionMessage["function_call"];
}
export type ProgressMessage = MessageChunk | CompleteChunk | FunctionCallChunk;
export class EmbeddingService {
static async initialize() {
const client = new OpenAI({
apiKey: assertExists(
process.env.OPENAI_API_KEY,
"Expected OpenAI api key"
),
});
return new EmbeddingService(client);
}
private constructor(private client: OpenAI) { }
async createEmbedding(str: string) {
const embedding = await this.client.embeddings.create({
input: str,
model: embeddingModel,
});
return embedding.data[0].embedding;
}
}
export class AiService {
static async initialize(vectorDbService: VectorDbService) {
const client = new OpenAI({
apiKey: assertExists(
process.env.OPENAI_API_KEY,
"Expected OpenAI api key"
),
});
return new AiService(client, vectorDbService);
}
private constructor(
private client: OpenAI,
private vectorDbService: VectorDbService
) { }
generateInitialPrompt(message: string): ChatCompletionMessageParam[] {
return [
{
role: "system",
content: `\
You are an assistant who likes to play text based games. \
When a user asks to play a game, you should print the rules \
of the game and provide any visual cues needed for the user to start playing`,
},
{
role: "user",
content: message,
},
];
}
async completeChat(
messages: ChatCompletionMessageParam[],
logger: Logger,
streaming: boolean,
onProgress: (progress: ProgressMessage) => void
) {
const contextMessages: ChatCompletionMessageParam[] = [...messages];
do {
logger.info("Calling GPT");
const nextMessage = await (streaming
? this.streamNextMessage(contextMessages, onProgress)
: this.completeNextMessage(contextMessages));
contextMessages.push(nextMessage as any);
if (nextMessage.function_call) {
logger.info(
{ calledFunction: nextMessage.function_call.name },
"GPT requesting function call: %s",
nextMessage.function_call.name
);
console.log("function call: " + JSON.stringify(nextMessage.function_call));
const funcResult = await this.evalFunction(nextMessage.function_call);
logger.info(
{ calledFunction: nextMessage.function_call.name },
"GPT produced response: %s",
funcResult.substring(0, 100)
);
contextMessages.push({
role: "function",
name: nextMessage.function_call.name,
content: funcResult,
});
}
} while (contextMessages[contextMessages.length - 1].role !== "assistant");
return contextMessages;
}
private async completeNextMessage(
contextMessages: ChatCompletionMessageParam[]
) {
const completion = await this.client.chat.completions.create({
model: chatModel,
messages: contextMessages,
function_call: "auto",
functions,
});
return completion.choices[0].message;
}
private async streamNextMessage(
contextMessages: ChatCompletionMessageParam[],
streamProgress: (progress: ProgressMessage) => void
) {
let content = "";
let functionCall: ChatCompletionMessage.FunctionCall | undefined =
undefined;
let role: ChatCompletionRole = "assistant";
for await (const chunk of await this.client.chat.completions.create({
model: chatModel,
messages: contextMessages,
function_call: "auto",
functions,
stream: true,
})) {
const delta = chunk.choices?.[0]?.delta;
if (delta?.content) {
content += delta.content;
streamProgress({ type: "message_chunk", message: delta.content });
} else if (delta?.function_call) {
functionCall = functionCall ?? {
name: "",
arguments: "",
};
functionCall.name += delta.function_call.name ?? "";
functionCall.arguments += delta.function_call.arguments ?? "";
} else if (chunk.choices?.[0]?.finish_reason === "stop") {
streamProgress({
type: "complete",
reason: chunk.choices[0].finish_reason,
content,
});
} else if (chunk.choices?.[0]?.finish_reason === "function_call") {
streamProgress({
type: "function_call",
functionCall,
});
}
if (delta?.role) {
role = delta.role;
}
}
return {
content,
role: role,
function_call: functionCall,
};
}
private async evalFunction(
functionCall: OpenAI.Chat.Completions.ChatCompletionMessage.FunctionCall
): Promise<string> {
const args = JSON.parse(functionCall.arguments ?? "{}") as any;
console.log("args: " + JSON.stringify(args));
switch (functionCall.name) {
case "lookup_game_rules":
if (args.activity.toLowerCase().includes("monopoly")) {
throw new Error("Come on. Nobody likes monopoly");
}
const activity = await this.vectorDbService.queryActivity(
args.activity
);
return activity.description;
default:
return "You cannot perform the next action to complete the user's request. Please let them know and politely ask if there's anything else you can help with";
}
}
}