-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy path02-tools.ts
More file actions
171 lines (161 loc) · 5.62 KB
/
Copy path02-tools.ts
File metadata and controls
171 lines (161 loc) · 5.62 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
/**
* Tools — multiple tools, async, approval.
*
* Demonstrates:
* - Multiple tool() functions
* - Approval-required tools (human-in-the-loop)
* - How tools become Conductor task definitions
*
* Requirements:
* - Conductor server with LLM support
* - AGENTSPAN_SERVER_URL=http://localhost:8080/api as environment variable
* - AGENTSPAN_LLM_MODEL=openai/gpt-4o-mini as environment variable
*/
import * as readline from 'node:readline/promises';
import { stdin, stdout } from 'node:process';
import { Agent, AgentRuntime, tool } from '@io-orkes/conductor-javascript/agents';
import type { AgentHandle } from '@io-orkes/conductor-javascript/agents';
import { llmModel } from './settings';
const getWeather = tool(
async (args: { city: string }) => {
const weatherData: Record<string, { temp: number; condition: string }> = {
'new york': { temp: 72, condition: 'Partly Cloudy' },
'san francisco': { temp: 58, condition: 'Foggy' },
'miami': { temp: 85, condition: 'Sunny' },
};
const data = weatherData[args.city.toLowerCase()] ?? { temp: 70, condition: 'Clear' };
return { city: args.city, temperature_f: data.temp, condition: data.condition };
},
{
name: 'get_weather',
description: 'Get current weather for a city.',
inputSchema: {
type: 'object',
properties: {
city: { type: 'string', description: 'The city to get weather for' },
},
required: ['city'],
},
},
);
const calculate = tool(
async (args: { expression: string }) => {
const safeBuiltins: Record<string, unknown> = {
abs: Math.abs,
round: Math.round,
min: Math.min,
max: Math.max,
sqrt: Math.sqrt,
pow: Math.pow,
pi: Math.PI,
e: Math.E,
};
try {
// Simple expression evaluator (demo only — not production-safe)
const fn = new Function(
...Object.keys(safeBuiltins),
`return (${args.expression});`,
);
const result = fn(...Object.values(safeBuiltins));
return { expression: args.expression, result };
} catch (e: unknown) {
return { expression: args.expression, error: String(e) };
}
},
{
name: 'calculate',
description: 'Evaluate a math expression.',
inputSchema: {
type: 'object',
properties: {
expression: { type: 'string', description: 'The math expression to evaluate' },
},
required: ['expression'],
},
},
);
const sendEmail = tool(
async (args: { to: string; subject: string; body: string }) => {
// In production, this would actually send an email
return { status: 'sent', to: args.to, subject: args.subject };
},
{
name: 'send_email',
description: 'Send an email.',
inputSchema: {
type: 'object',
properties: {
to: { type: 'string', description: 'Recipient email address' },
subject: { type: 'string', description: 'Email subject' },
body: { type: 'string', description: 'Email body' },
},
required: ['to', 'subject', 'body'],
},
approvalRequired: true,
timeoutSeconds: 60,
},
);
export const agent = new Agent({
name: 'tool_demo_agent',
model: llmModel,
tools: [getWeather, calculate, sendEmail],
instructions:
'You are a helpful assistant with access to weather, calculator, and email tools.',
});
async function promptHuman(
rl: readline.Interface,
pendingTool: Record<string, unknown>,
): Promise<Record<string, unknown>> {
const schema = (pendingTool.response_schema ?? {}) as Record<string, unknown>;
const props = (schema.properties ?? {}) as Record<string, Record<string, unknown>>;
const response: Record<string, unknown> = {};
for (const [field, fs] of Object.entries(props)) {
const desc = (fs.description || fs.title || field) as string;
if (fs.type === 'boolean') {
const val = await rl.question(` ${desc} (y/n): `);
response[field] = ['y', 'yes'].includes(val.trim().toLowerCase());
} else {
response[field] = await rl.question(` ${desc}: `);
}
}
return response;
}
const rl = readline.createInterface({ input: stdin, output: stdout });
const runtime = new AgentRuntime();
try {
const handle = await runtime.start(
agent,
'send email to developer@orkes.io with current weather details in SF',
);
console.log(`Started: ${handle.executionId}\n`);
for await (const event of handle.stream()) {
if (event.type === 'thinking') {
console.log(` [thinking] ${event.content}`);
} else if (event.type === 'tool_call') {
console.log(` [tool_call] ${event.toolName}(${JSON.stringify(event.args)})`);
} else if (event.type === 'tool_result') {
console.log(` [tool_result] ${event.toolName} -> ${JSON.stringify(event.result).slice(0, 100)}`);
} else if (event.type === 'waiting') {
const status = await handle.getStatus();
const pt = (status.pendingTool ?? {}) as Record<string, unknown>;
console.log('\n--- Human input required ---');
const response = await promptHuman(rl, pt);
await handle.respond(response);
console.log();
} else if (event.type === 'done') {
console.log(`\nDone: ${JSON.stringify(event.output)}`);
}
}
// Non-interactive alternative (no HITL, will block on human tasks):
// const result = await runtime.run(agent, 'What is the weather in San Francisco?');
// result.printResult();
// Production pattern:
// 1. Deploy once during CI/CD (optional -- serve() below also deploys):
// await runtime.deploy(agent);
//
// 2. In a separate long-lived worker process (deploys + registers workers + starts polling):
// await runtime.serve(agent);
} finally {
rl.close();
await runtime.shutdown();
}