multi-agent.ts
1 /** 2 * AI SDK Multi-Agent Attribution Example 3 * 4 * Demonstrates how to propagate attribution context (agentId, runId, traceId) 5 * to LLM calls for multi-agent observability and safety. 6 * 7 * Usage: 8 * npx ts-node multi-agent.ts 9 * 10 * Environment: 11 * OPENAI_API_KEY - Your OpenAI API key 12 */ 13 14 import { createAISDKBackend } from 'praisonai'; 15 16 // Simulate a multi-agent system with attribution 17 interface AgentContext { 18 agentId: string; 19 runId: string; 20 traceId: string; 21 sessionId?: string; 22 } 23 24 async function runAgent(name: string, task: string, context: AgentContext) { 25 console.log(`\n[${name}] Starting task: ${task}`); 26 console.log(` Attribution: agentId=${context.agentId}, runId=${context.runId}`); 27 28 const backend = createAISDKBackend('openai/gpt-4o-mini', { 29 attribution: context, 30 timeout: 30000, 31 }); 32 33 const result = await backend.generateText({ 34 messages: [ 35 { role: 'system', content: `You are ${name}, a specialized AI agent.` }, 36 { role: 'user', content: task } 37 ], 38 maxTokens: 100, 39 }); 40 41 console.log(` Response: ${result.text.slice(0, 100)}...`); 42 return result.text; 43 } 44 45 async function main() { 46 // Create a shared trace ID for the entire workflow 47 const traceId = `trace-${Date.now().toString(36)}`; 48 const sessionId = 'session-user123'; 49 50 console.log('Multi-Agent Workflow with Attribution'); 51 console.log('====================================='); 52 console.log(`Trace ID: ${traceId}`); 53 console.log(`Session ID: ${sessionId}`); 54 55 // Agent 1: Research Agent 56 const researchResult = await runAgent( 57 'ResearchAgent', 58 'What are the key benefits of TypeScript?', 59 { 60 agentId: 'agent-research', 61 runId: `run-${Date.now().toString(36)}-1`, 62 traceId, 63 sessionId, 64 } 65 ); 66 67 // Agent 2: Summary Agent 68 const summaryResult = await runAgent( 69 'SummaryAgent', 70 `Summarize this in one sentence: ${researchResult}`, 71 { 72 agentId: 'agent-summary', 73 runId: `run-${Date.now().toString(36)}-2`, 74 traceId, 75 sessionId, 76 } 77 ); 78 79 // Agent 3: Review Agent 80 await runAgent( 81 'ReviewAgent', 82 `Review this summary for accuracy: ${summaryResult}`, 83 { 84 agentId: 'agent-review', 85 runId: `run-${Date.now().toString(36)}-3`, 86 traceId, 87 sessionId, 88 } 89 ); 90 91 console.log('\n\nWorkflow complete!'); 92 console.log('All requests were tagged with the same trace ID for observability.'); 93 console.log('Check your LLM provider dashboard to see the correlated requests.'); 94 } 95 96 main().catch(console.error);