-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbasicExample.ts
More file actions
418 lines (369 loc) Β· 15.2 KB
/
basicExample.ts
File metadata and controls
418 lines (369 loc) Β· 15.2 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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
/**
* Basic Agent Example
*
* This example demonstrates how to use our Agent framework with:
* 1. Multiple chat providers (Gemini, OpenAI, OpenAI Response API)
* 2. TokenTracker for usage monitoring
* 3. CoreToolScheduler for tool execution
* 4. Event system for real-time monitoring
*/
import { error } from 'console';
import {
StandardAgent,
AgentEventType,
AgentEvent,
AllConfig,
ITool,
LogLevel,
configureLogger,
Type,
Schema,
} from '../src/index.js';
import { createWeatherTool,createSubTool } from './tools';
import dotenv from 'dotenv';
import { LLMChunkTextDelta, LLMChunkTextDone } from '../src/interfaces.js';
dotenv.config();
const weatherTool = createWeatherTool();
const subTool = createSubTool();
/**
* Create Agent using StandardAgent with specified chat provider
*/
function createAgent(config: AllConfig & { chatProvider?: 'gemini' | 'openai' }, tools: ITool[]): StandardAgent {
return new StandardAgent(tools, config);
}
/**
* Parse command line arguments for provider selection
*/
function parseCommandLineArgs(): { providers: ('gemini' | 'openai')[], showHelp: boolean } {
const args = process.argv.slice(2);
const providers: ('gemini' | 'openai')[] = [];
let showHelp = false;
for (const arg of args) {
switch (arg.toLowerCase()) {
case '--gemini':
if (!providers.includes('gemini')) providers.push('gemini');
break;
case '--openai':
if (!providers.includes('openai')) providers.push('openai');
break;
case '--all':
return { providers: ['gemini', 'openai'], showHelp: false };
case '--help':
case '-h':
showHelp = true;
break;
default:
console.log(`β οΈ Unknown argument: ${arg}`);
showHelp = true;
break;
}
}
return { providers, showHelp };
}
/**
* Show help message
*/
function showHelpMessage() {
console.log('π Agent Framework Basic Example');
console.log('================================\n');
console.log('Usage: npx tsx examples/basicExample.ts [options]\n');
console.log('Options:');
console.log(' --gemini Test with Gemini provider');
console.log(' --openai Test with OpenAI Chat Completions API');
console.log(' --openairep Test with OpenAI Response API');
console.log(' --all Test with all available providers');
console.log(' --help, -h Show this help message\n');
console.log('Environment Variables:');
console.log(' GEMINI_API_KEY API key for Gemini provider');
console.log(' OPENAI_API_KEY API key for OpenAI providers');
console.log(' LOG_LEVEL Set log level (NONE|ERROR|WARN|INFO|DEBUG)\n');
console.log('Examples:');
console.log(' npx tsx examples/basicExample.ts --gemini');
console.log(' npx tsx examples/basicExample.ts --openai --openairep');
console.log(' npx tsx examples/basicExample.ts --all');
console.log(' OPENAI_API_KEY="sk-..." npx tsx examples/basicExample.ts --openai\n');
}
/**
* Test a specific provider
*/
async function testProvider(
provider: 'gemini' | 'openai',
finalLogLevel: LogLevel
): Promise<{ success: boolean; tokenUsage?: any; error?: string }> {
console.log(`\n${'='.repeat(70)}`);
console.log(`π§ͺ Testing ${provider.toUpperCase()} Provider`);
console.log(`${'='.repeat(70)}`);
try {
// Determine API key based on provider
let apiKey: string;
switch (provider) {
case 'openai':
apiKey = process.env.OPENAI_API_KEY || '';
if (!apiKey) {
console.error('β Error: OPENAI_API_KEY environment variable is not set');
console.log('Please set your API key:');
console.log('export OPENAI_API_KEY="your-api-key-here"');
return { success: false, error: 'Missing OPENAI_API_KEY' };
}
break;
case 'gemini':
default:
apiKey = process.env.GEMINI_API_KEY || '';
if (!apiKey) {
console.error('β Error: GEMINI_API_KEY environment variable is not set');
console.log('Please set your API key:');
console.log('export GEMINI_API_KEY="your-api-key-here"');
return { success: false, error: 'Missing GEMINI_API_KEY' };
}
break;
}
// Determine model name based on provider
let modelName: string;
switch (provider) {
case 'openai':
modelName = 'o1';
break;
case 'gemini':
default:
modelName = 'gemini-2.0-flash';
break;
}
// Create agent configuration
const config: AllConfig & { chatProvider?: 'gemini' | 'openai' } = {
chatProvider: provider,
agentConfig: {
model: modelName,
workingDirectory: process.cwd(),
apiKey: apiKey,
sessionId: `demo-${provider}-${Date.now()}`,
maxHistoryTokens: 100000,
debugMode: finalLogLevel === LogLevel.DEBUG,
},
chatConfig: {
apiKey: apiKey,
modelName: modelName,
tokenLimit: 100000,
systemPrompt: `You are a helpful assistant with access to the following tools:
1. get_weather: Get current weather temperature for any coordinates
2. subtract: Perform subtraction between two numbers
IMPORTANT: After using tools to gather information, you must provide a complete text response to the user with your analysis and final answer. Always respond with the results in a clear, human-readable format.
For this specific task: After getting weather data for both cities, calculate the temperature difference and provide a summary in your response.`,
},
toolSchedulerConfig: {
approvalMode: 'yolo', // Auto-approve for demo
onAllToolCallsComplete: (calls) => {
console.log(`β
[${provider}] ${calls.length} tool(s) completed`);
for (const call of calls) {
console.log(` - ${call.request.name}: ${call.status}`);
}
},
onToolCallsUpdate: (calls) => {
console.log(`π [${provider}] Tool status update: ${calls.length} active calls`);
},
outputUpdateHandler: (callId, output) => {
console.log(`π€ [${provider}] [${callId}] ${output}`);
},
},
};
console.log('π API Key configured: Yes');
console.log('π€ Model:', config.agentConfig.model);
console.log('πΎ Working Directory:', config.agentConfig.workingDirectory);
console.log('π’ Token Limit:', config.agentConfig.maxHistoryTokens);
console.log('');
// Create agent
console.log('π€ Creating agent...');
const tools = [weatherTool, subTool];
const agent = createAgent(config, tools);
// Test basic conversation
console.log('π¬ Starting conversation...');
const sessionId = config.agentConfig.sessionId || 'demo-session';
const abortController = new AbortController();
// Set timeout
setTimeout(() => {
console.log(`\nβ° [${provider}] Timeout reached, aborting...`);
abortController.abort();
}, 45000);
// Process user input
const userMessages = [`Get the current weather temperature
for Beijing (latitude: 39.9042, longitude: 116.4074) , and then calculate the temperature difference between Beijing and Shanghai (latitude: 31.2304, longitude: 121.4737).
`];
const events = agent.processUserMessages(userMessages, sessionId, abortController.signal);
for await (const event of events) {
switch (event.type) {
case AgentEventType.UserMessage:
console.log(`π€ [${provider}] User message:`, event.data);
break;
case AgentEventType.TurnComplete:
console.log(`π [${provider}] Turn complete:`, event.data);
break;
case AgentEventType.ToolExecutionStart:
const toolStartData = event.data as any;
console.log(`\nπ§ [${provider}] Tool started: ${toolStartData.toolName}`);
console.log(` Args: ${JSON.stringify(toolStartData.args)}`);
break;
case AgentEventType.ToolExecutionDone:
const toolDoneData = event.data as any;
const status = toolDoneData.error ? 'failed' : 'completed';
console.log(`π§ [${provider}] Tool ${status}: ${toolDoneData.toolName}`);
if (toolDoneData.error) {
console.log(` Error: ${toolDoneData.error}`);
} else if (toolDoneData.result) {
console.log(` Result: ${toolDoneData.result}`);
}
break;
case AgentEventType.Error:
const errorData = event.data as any;
console.error(`β [${provider}] Error: ${errorData.message}`);
break;
// Handle LLM Response events
case AgentEventType.ResponseChunkTextDelta:
const deltaData = event.data as LLMChunkTextDelta;
console.log(`\nπ [${provider}] Text Delta Event:`, deltaData.content.text_delta);
break;
case AgentEventType.ResponseChunkTextDone:
const textDoneData = event.data as LLMChunkTextDone;
console.log(`π€ [${provider}] Complete Response: "${textDoneData.content.text}"`);
break;
case AgentEventType.ResponseComplete:
console.log(`β
[${provider}] LLM Response complete`);
break;
case AgentEventType.ResponseFailed:
const failedData = event.data as any;
console.error(`β [${provider}] LLM Response failed:`, failedData);
break;
default:
// Log other event types for debugging
if (finalLogLevel === LogLevel.DEBUG) {
console.log(`π [${provider}] Event: ${event.type}`, event.data);
}
break;
}
}
const history = agent.getChat().getHistory();
console.log(`\n====History====`);
history.forEach((message, index) => {
console.log(`\n[${index + 1}] ${message.role}:`);
if (message.content.type === 'text') {
console.log(` Text: "${message.content.text}"`);
if (message.content.metadata) {
console.log(` Metadata:`, JSON.stringify(message.content.metadata, null, 2));
}
} else if (message.content.type === 'function_call') {
console.log(` Function Call:`);
console.log(` β’ Name: ${message.content.functionCall?.name}`);
console.log(` β’ ID: ${message.content.functionCall?.id}`);
console.log(` β’ Call ID: ${message.content.functionCall?.call_id}`);
console.log(` β’ Args: ${message.content.functionCall?.args}`);
} else if (message.content.type === 'function_response') {
console.log(` Function Response:`);
console.log(` β’ Name: ${message.content.functionResponse?.name}`);
console.log(` β’ ID: ${message.content.functionResponse?.id}`);
console.log(` β’ Call ID: ${message.content.functionResponse?.call_id}`);
console.log(` β’ Result: ${message.content.functionResponse?.result}`);
}
});
console.log(`\n====End History====`);
// Show final status
console.log(`\nπ [${provider}] Final Status:`);
const status = agent.getStatus();
console.log(` β’ Processing: ${status.isRunning ? 'Yes' : 'No'}`);
console.log(` β’ Tokens used: ${status.tokenUsage.totalTokens}`);
console.log(` β’ Token limit: ${status.tokenUsage.tokenLimit}`);
console.log(` β’ Usage: ${status.tokenUsage.usagePercentage.toFixed(2)}%`);
// Show usage summary
console.log(`\nπ [${provider}] Token Usage Summary:`);
const tokenUsage = agent.getTokenUsage();
console.log(` β’ Input tokens: ${tokenUsage.inputTokens}`);
console.log(` β’ Cached tokens: ${tokenUsage.inputTokenDetails?.cachedTokens}`);
console.log(` β’ Output tokens: ${tokenUsage.outputTokens}`);
console.log(` β’ Reasoning tokens: ${tokenUsage.outputTokenDetails?.reasoningTokens}`);
console.log(` β’ Total tokens: ${tokenUsage.totalTokens}`);
console.log(`\nβ
[${provider}] Test completed successfully!`);
return { success: true, tokenUsage: status.tokenUsage };
} catch (error) {
console.error(`β [${provider}] Test failed:`, error);
if (error instanceof Error) {
console.error('Stack trace:', error.stack);
}
return { success: false, error: error instanceof Error ? error.message : String(error) };
}
}
/**
* Main demonstration function
*/
async function main() {
// Parse command line arguments
const { providers, showHelp } = parseCommandLineArgs();
if (showHelp) {
showHelpMessage();
return;
}
// If no providers specified, fall back to environment variable or default
const providersToTest = providers.length > 0
? providers
: [(process.env.CHAT_PROVIDER as 'gemini' | 'openai') || 'gemini'];
console.log('π Agent Framework Basic Example');
console.log('================================\n');
// Configure logger based on environment
const logLevel = process.env.LOG_LEVEL?.toUpperCase() as keyof typeof LogLevel;
const finalLogLevel = logLevel && LogLevel[logLevel] !== undefined ? LogLevel[logLevel] : LogLevel.INFO;
configureLogger({
level: finalLogLevel,
autoDetectContext: true,
includeTimestamp: true,
enableColors: true,
});
console.log(`πͺ΅ Logger Level: ${LogLevel[finalLogLevel]}`);
console.log(' Set LOG_LEVEL environment variable (NONE|ERROR|WARN|INFO|DEBUG) to change');
console.log(`π§ͺ Testing Providers: ${providersToTest.join(', ')}`);
console.log('');
// Test each provider
const results: Array<{ provider: string; success: boolean; tokenUsage?: any; error?: string }> = [];
for (const provider of providersToTest) {
const result = await testProvider(provider, finalLogLevel);
results.push({ provider, ...result });
}
// Show summary if testing multiple providers
if (results.length > 1) {
console.log(`\n${'='.repeat(80)}`);
console.log('π SUMMARY RESULTS');
console.log(`${'='.repeat(80)}`);
let successful = 0;
let failed = 0;
for (const result of results) {
if (result.success) {
successful++;
console.log(`β
${result.provider.toUpperCase()}:`);
if (result.tokenUsage) {
console.log(` β’ Total tokens: ${result.tokenUsage.totalTokens}`);
console.log(` β’ Usage: ${result.tokenUsage.usagePercentage.toFixed(2)}%`);
}
} else {
failed++;
console.log(`β ${result.provider.toUpperCase()}: ${result.error || 'Failed'}`);
}
}
console.log(`\nπ Overall Results: ${successful} successful, ${failed} failed out of ${results.length} providers`);
if (successful > 0) {
console.log('\nπ― Key Differences:');
console.log('β’ gemini: Google\'s Generative AI with thinking support');
console.log('β’ openai: OpenAI Chat Completions API');
console.log('β’ openai-response: OpenAI Response API with structured events');
}
}
const allSuccessful = results.every(r => r.success);
console.log(`\n${allSuccessful ? 'β
' : 'β οΈ'} Example completed ${allSuccessful ? 'successfully' : 'with some failures'}!`);
if (!allSuccessful) {
process.exit(1);
}
}
// Handle graceful shutdown
process.on('SIGINT', () => {
console.log('\nπ Received interrupt signal, shutting down...');
process.exit(0);
});
// Run the example
if (import.meta.url === `file://${process.argv[1]}`) {
main().catch(console.error);
}
export { main as runBasicExample };