-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathagent.ts
55 lines (46 loc) · 1.59 KB
/
agent.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
import OpenAI from "openai";
import { getCurrentWeather } from "./tools/getCurrentWeather";
import { runJavascriptCode } from "./tools/runJavascriptCode";
import {
handleFunctionCall,
generateFunctions,
truncateMessages,
} from "../src";
const openai = new OpenAI();
async function runAgent(prompt: string) {
let messages: OpenAI.ChatCompletionMessageParam[] = [
{
role: "user",
content: prompt,
},
];
const tools = [getCurrentWeather, runJavascriptCode];
const maximumDepth = 5;
for (let i = 0; i < maximumDepth; i++) {
const response = await openai.chat.completions.create({
model: "gpt-3.5-turbo",
// Removes older messages if necessary to stay under the token limit
messages: truncateMessages({ messages, tools, tokenLimit: 1000 }),
// Formats the tools into the shape that OpenAI expects
functions: generateFunctions(tools),
});
const responseMessage = response.choices[0].message;
messages.push(responseMessage);
if (responseMessage.function_call) {
// Validates arguments and calls the function
const functionResponseMessage = await handleFunctionCall({
functionCall: responseMessage.function_call,
tools,
});
messages.push(functionResponseMessage);
} else {
return responseMessage.content;
}
}
return messages;
}
runAgent("Get the temperature in Boston and calculate the wind chill.")
.then(console.log)
.catch(console.error);
// Outputs: The current temperature in Boston, MA is 42 °F with a wind speed of
// 30 mph. The wind chill is calculated to be 31 °F.