-
Notifications
You must be signed in to change notification settings - Fork 945
Expand file tree
/
Copy pathchat.ts
More file actions
77 lines (66 loc) · 2.15 KB
/
Copy pathchat.ts
File metadata and controls
77 lines (66 loc) · 2.15 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
import { Agent, run, tool, user, withTrace } from '@openai/agents';
import type { AgentInputItem } from '@openai/agents';
import { createInterface } from 'node:readline/promises';
import { z } from 'zod';
const autoMode = process.env.EXAMPLES_INTERACTIVE_MODE === 'auto';
async function ask(prompt: string, fallback: string) {
if (autoMode) return fallback;
const rl = createInterface({ input: process.stdin, output: process.stdout });
const message = await rl.question(prompt);
rl.close();
return message;
}
const getWeatherTool = tool({
name: 'get_weather',
description: 'Get the weather for a given city',
parameters: z.object({
city: z.string(),
}),
execute: async (input) => {
return `The weather in ${input.city} is sunny`;
},
});
const weatherAgent = new Agent({
name: 'Weather Agent',
instructions:
'You answer weather questions. Always call get_weather before answering.',
handoffDescription: 'Knows everything about the weather but nothing else.',
modelSettings: {
toolChoice: 'required',
},
tools: [getWeatherTool],
});
const agent = new Agent({
name: 'Basic test agent',
instructions:
'You are a basic agent. Hand off weather questions to the Weather Agent instead of answering them yourself.',
handoffDescription: 'An expert on everything but the weather.',
handoffs: [weatherAgent],
});
weatherAgent.handoffs.push(agent);
let history: AgentInputItem[] = [];
let latestAgent: Agent = agent;
async function main() {
console.log('Type exit() to leave');
await withTrace('Chat Session', async () => {
while (true) {
const message = await ask('> ', 'What is the weather in Tokyo?');
if (message === 'exit()') {
return;
}
history.push(user(message));
const result = await run(latestAgent, history);
const outputAgent = result.lastAgent ?? latestAgent;
console.log(`[${outputAgent.name}] ${result.finalOutput}`);
if (result.lastAgent) {
latestAgent = result.lastAgent;
}
history = result.history;
if (autoMode) return; // single turn in auto mode
}
});
}
main().catch((error) => {
console.error(error);
process.exit(1);
});