1import OpenAI from 'openai';
2
3const openai = new OpenAI();
4
5// 1. Tool registry
6const tools = [{
7 type: 'function' as const,
8 function: {
9 name: 'search_docs',
10 description: 'Search internal documentation',
11 parameters: { type: 'object', properties: { q: { type: 'string' } }, required: ['q'] },
12 },
13}];
14
15const tool_handlers: Record<string, (args: any) => Promise<string>> = {
16 search_docs: async ({ q }) => `results for "${q}": [...]`,
17};
18
19export async function runAgent(goal: string) {
20 const messages: any[] = [
21 { role: 'system', content: 'You are a research agent. Use search_docs for facts. Stop when goal met.' },
22 { role: 'user', content: goal },
23 ];
24
25 // 2. ReAct loop with safety cap
26 for (let step = 0; step < 10; step++) {
27 const res = await openai.chat.completions.create({
28 model: 'gpt-4o-mini', messages, tools, tool_choice: 'auto',
29 });
30 const msg = res.choices[0].message;
31 messages.push(msg);
32
33 // 3. No tool call -> final answer
34 if (!msg.tool_calls?.length) return { steps: step, answer: msg.content };
35
36 // 4. Execute each tool call, append observation
37 for (const call of msg.tool_calls) {
38 const args = JSON.parse(call.function.arguments);
39 const result = await tool_handlers[call.function.name](args);
40 messages.push({ role: 'tool', tool_call_id: call.id, content: result });
41 }
42 }
43
44 // 5. Loop cap hit
45 return { steps: 10, answer: 'Gave up — could not converge.' };
46}