withAgent()

Wrap an async function as a traced agent

Overview

Use withAgent(options, fn) for agentic patterns where an agent orchestrates multiple tools or sub-tasks. Agents are specialized workflow units designed for AI agent architectures.

Signature

1withAgent<T>(
2 options: {
3 name: string;
4 version?: number;
5 associationProperties?: Record<string, any>;
6 },
7 fn: () => Promise<T>
8): Promise<T>

Basic Usage

1import { RespanTelemetry } from '@respan/tracing';
2
3const respanAi = new RespanTelemetry({
4 apiKey: process.env.RESPAN_API_KEY,
5 appName: 'my-app'
6});
7
8await respanAi.initialize();
9
10const result = await respanAi.withAgent(
11 {
12 name: 'research_assistant',
13 associationProperties: {
14 'agent_type': 'research',
15 'model': 'gpt-4'
16 }
17 },
18 async () => {
19 // Agent logic here
20 const analysis = await analyzeQuery();
21 const response = await generateResponse(analysis);
22 return response;
23 }
24);

Agent with Tools

1const customerAgent = async (query: string) => {
2 return await respanAi.withAgent(
3 {
4 name: 'customer_support_agent',
5 associationProperties: {
6 'query_type': 'support',
7 'customer_id': 'cust-123'
8 }
9 },
10 async () => {
11 // Tool 1: Search knowledge base
12 const kbResults = await respanAi.withTool(
13 { name: 'search_knowledge_base' },
14 async () => {
15 return await searchKB(query);
16 }
17 );
18
19 // Tool 2: Query CRM
20 const customerData = await respanAi.withTool(
21 { name: 'query_crm' },
22 async () => {
23 return await getCRMData('cust-123');
24 }
25 );
26
27 // Final response generation
28 return await generateSupportResponse(kbResults, customerData);
29 }
30 );
31};

Multi-Agent Workflow

1await respanAi.withWorkflow(
2 { name: 'multi_agent_system' },
3 async () => {
4 // Agent 1: Planning
5 const plan = await respanAi.withAgent(
6 { name: 'planner_agent' },
7 async () => {
8 return await createPlan();
9 }
10 );
11
12 // Agent 2: Execution
13 const result = await respanAi.withAgent(
14 { name: 'executor_agent' },
15 async () => {
16 return await executePlan(plan);
17 }
18 );
19
20 // Agent 3: Verification
21 const verified = await respanAi.withAgent(
22 { name: 'verifier_agent' },
23 async () => {
24 return await verifyResult(result);
25 }
26 );
27
28 return verified;
29 }
30);

With OpenAI Integration

1import OpenAI from 'openai';
2
3const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
4
5await respanAi.withAgent(
6 { name: 'ai_assistant' },
7 async () => {
8 // Tool calls are automatically traced
9 const completion = await openai.chat.completions.create({
10 model: 'gpt-4',
11 messages: [
12 { role: 'system', content: 'You are a helpful assistant.' },
13 { role: 'user', content: 'Explain quantum computing.' }
14 ],
15 });
16
17 return completion.choices[0].message.content;
18 }
19);

Parameters

name
stringRequired

Agent display name for identification in the Respan dashboard

version
number

Version number for tracking agent iterations

associationProperties
Record<string, any>

Custom metadata to associate with the agent (agent type, model, user context, etc.)

Return Value

Returns a Promise that resolves to the return value of the provided function.

Best Practices

  • Use agents for autonomous decision-making components
  • Nest tools within agents to track tool usage
  • Add association properties to identify agent types and contexts
  • Combine multiple agents in workflows for complex multi-agent systems
  • Agents automatically capture all nested tool calls and LLM interactions