Real-time execution visibility and debugging through comprehensive trace data
Traces provide complete visibility into agent execution, exposing every decision, tool call, and reasoning step as a primitive for debugging, monitoring, and optimization.
Overview
The Traces primitive gives you real-time insight into agent execution by streaming detailed events about what the agent is thinking, which tools it’s using, and how it’s progressing toward task completion. Traces are the foundation for understanding, debugging, and optimizing agent behavior.Traces are essential for:
Debugging: Understand why agents make specific decisions or encounter errors
Optimization: Identify inefficiencies and opportunities for improvement
Monitoring: Track agent performance and behavior in production
Audit: Maintain detailed records of agent actions
Learning: Understand agent reasoning patterns and decision-making
Real-Time Streaming
Receive execution events as they happen during agent processing
Complete Visibility
See every thought, tool call, and intermediate result
Structured Events
Well-defined event types make traces easy to parse and analyze
Zero Configuration
Traces available automatically for every agent request
How Traces Work
Event Stream
Traces are delivered as a stream of events:
Agent Starts: Execution begins
Thinking Events: Agent reasons about the task
Tool Use Events: Agent calls tools
Tool Response Events: Tools return results
Step Completion: Agent finishes a reasoning step
Cost Events: Cost incurred for operations
Error Events: Errors encountered during execution
Completion: Agent finishes successfully
Event Structure
Each trace event contains:
Event Type: What kind of event occurred
Timestamp: When the event happened
Context: Session ID, step number, etc.
Payload: Event-specific data
Metadata: Additional contextual information
Streaming by Default: Set stream: true to receive events in real-time. Without streaming, you only get the final result.
Code Examples
Basic Trace Streaming
import { Agentbase } from '@agentbase/sdk';const agentbase = new Agentbase({ apiKey: process.env.AGENTBASE_API_KEY});// Enable streaming to receive tracesconst result = await agentbase.runAgent({ message: "Analyze this data and create a report", mode: "base", stream: true // Enable trace streaming});// Iterate over trace eventsfor await (const event of result) { console.log(`[${event.type}]`, event); switch (event.type) { case 'agent_thinking': console.log('💭 Thinking:', event.content); break; case 'agent_tool_use': console.log('🔧 Using tool:', event.tool); console.log(' Input:', event.input); break; case 'agent_tool_response': console.log('✅ Tool response received'); break; case 'agent_step': console.log(`📍 Completed step ${event.stepNumber}`); break; case 'agent_cost': console.log(`💰 Cost: $${event.cost}`); break; case 'agent_message': console.log('📨 Final message:', event.content); break; case 'agent_error': console.error('❌ Error:', event.error); break; }}
from agentbase import Agentbaseagentbase = Agentbase(api_key=os.environ['AGENTBASE_API_KEY'])# Enable streaming to receive tracesresult = agentbase.run_agent( message="Analyze this data and create a report", mode="base", stream=True # Enable trace streaming)# Iterate over trace eventsfor event in result: print(f"[{event.type}]", event) if event.type == 'agent_thinking': print(f"💭 Thinking: {event.content}") elif event.type == 'agent_tool_use': print(f"🔧 Using tool: {event.tool}") print(f" Input: {event.input}") elif event.type == 'agent_tool_response': print("✅ Tool response received") elif event.type == 'agent_step': print(f"📍 Completed step {event.step_number}") elif event.type == 'agent_cost': print(f"💰 Cost: ${event.cost}") elif event.type == 'agent_message': print(f"📨 Final message: {event.content}") elif event.type == 'agent_error': print(f"❌ Error: {event.error}")
# Collect and analyze trace dataclass TraceAnalyzer: def __init__(self): self.events = [] self.start_time = time.time() async def analyze_execution(self, message: str): self.events = [] self.start_time = time.time() result = agentbase.run_agent( message=message, mode="base", stream=True ) # Collect all events for event in result: self.events.append({ **event.__dict__, 'relative_time': time.time() - self.start_time }) # Analyze collected events return self.generate_analysis() def generate_analysis(self): thinking = [e for e in self.events if e['type'] == 'agent_thinking'] tool_uses = [e for e in self.events if e['type'] == 'agent_tool_use'] steps = [e for e in self.events if e['type'] == 'agent_step'] errors = [e for e in self.events if e['type'] == 'agent_error'] total_duration = time.time() - self.start_time tools_used = [t['tool'] for t in tool_uses] unique_tools = list(set(tools_used)) return { 'total_duration': total_duration, 'total_steps': len(steps), 'thinking_events': len(thinking), 'tool_calls': len(tool_uses), 'tools_used': unique_tools, 'errors': len(errors), 'avg_step_duration': total_duration / len(steps) if steps else 0, 'events': self.events }# Usageanalyzer = TraceAnalyzer()analysis = await analyzer.analyze_execution( "Research AI trends and write summary")print(f"Analysis: {analysis}")
Filtering and Focusing Traces
// Filter traces to specific event typesasync function focusedTracing(message: string, focusOn: string[]) { const result = await agentbase.runAgent({ message, mode: "base", stream: true }); const relevantEvents = []; for await (const event of result) { // Only process events we care about if (focusOn.includes(event.type)) { relevantEvents.push(event); switch (event.type) { case 'agent_tool_use': console.log(`Tool: ${event.tool}`); console.log(`Input: ${JSON.stringify(event.input, null, 2)}`); break; case 'agent_error': console.error(`Error detected: ${event.error}`); await notifyTeam('Agent error', event.error); break; } } } return relevantEvents;}// Focus on tool usage onlyconst toolEvents = await focusedTracing( "Analyze customer data", ['agent_tool_use', 'agent_tool_response']);// Focus on errorsconst errors = await focusedTracing( "Risky operation", ['agent_error']);
Real-Time Progress Tracking
// Track progress in real-timeasync function trackProgress(message: string, onProgress: (progress: number) => void) { const result = await agentbase.runAgent({ message, mode: "base", stream: true }); let currentStep = 0; let estimatedTotalSteps = 10; // Will be updated for await (const event of result) { if (event.type === 'agent_step') { currentStep = event.stepNumber; // Calculate progress percentage const progress = Math.min((currentStep / estimatedTotalSteps) * 100, 95); // Call progress callback onProgress(progress); } if (event.type === 'agent_message') { // Task complete onProgress(100); } }}// Usage with UI updatesawait trackProgress( "Generate comprehensive report", (progress) => { updateProgressBar(progress); console.log(`Progress: ${progress.toFixed(0)}%`); });
# Track progress in real-timeasync def track_progress(message: str, on_progress: callable): result = agentbase.run_agent( message=message, mode="base", stream=True ) current_step = 0 estimated_total_steps = 10 # Will be updated for event in result: if event.type == 'agent_step': current_step = event.step_number # Calculate progress percentage progress = min((current_step / estimated_total_steps) * 100, 95) # Call progress callback on_progress(progress) if event.type == 'agent_message': # Task complete on_progress(100)# Usage with UI updatesawait track_progress( "Generate comprehensive report", lambda progress: update_progress_bar(progress))
Trace Event Types
Agent Thinking
Shows agent’s internal reasoning:
{ "type": "agent_thinking", "content": "I need to first load the data file, then analyze it for trends. I'll use the file reading tool.", "timestamp": "2025-01-08T10:30:00Z", "session": "agent_session_abc123"}
// Analyze agent patternsasync function analyzePatterns(messages: string[]) { const patterns = { commonTools: new Map<string, number>(), avgStepsByTaskType: new Map<string, number[]>(), successfulApproaches: [] }; for (const message of messages) { const result = await agentbase.runAgent({ message, mode: "base", stream: true }); const trace = { tools: [], steps: 0, success: false }; for await (const event of result) { if (event.type === 'agent_tool_use') { trace.tools.push(event.tool); const count = patterns.commonTools.get(event.tool) || 0; patterns.commonTools.set(event.tool, count + 1); } if (event.type === 'agent_step') { trace.steps++; } if (event.type === 'agent_message') { trace.success = true; } } // Categorize by task type const taskType = categorizeTask(message); const steps = patterns.avgStepsByTaskType.get(taskType) || []; steps.push(trace.steps); patterns.avgStepsByTaskType.set(taskType, steps); // Record successful approaches if (trace.success) { patterns.successfulApproaches.push({ taskType, tools: trace.tools, steps: trace.steps }); } } return generateInsights(patterns);}function generateInsights(patterns: any) { // Find most common tools const topTools = Array.from(patterns.commonTools.entries()) .sort((a, b) => b[1] - a[1]) .slice(0, 5); // Find optimal approaches const insights = { mostUsedTools: topTools.map(([tool]) => tool), taskTypePerformance: Array.from(patterns.avgStepsByTaskType.entries()).map(([type, steps]) => ({ taskType: type, avgSteps: steps.reduce((a, b) => a + b, 0) / steps.length, samples: steps.length })), recommendations: [] }; // Generate recommendations for (const approach of patterns.successfulApproaches) { if (approach.steps < 3) { insights.recommendations.push( `For ${approach.taskType}: Use tools ${approach.tools.join(', ')} (efficient approach)` ); } } return insights;}
Best Practices
Efficient Trace Processing
Process Events Incrementally
// Good: Process events as they arrivefor await (const event of stream) { processEvent(event); // Handle immediately}// Avoid: Collecting all events in memoryconst allEvents = [];for await (const event of stream) { allEvents.push(event); // Memory intensive}
Filter Early
// Filter to only relevant eventsfor await (const event of stream) { // Only process events we care about if (event.type === 'agent_error' || event.type === 'agent_tool_use') { await handleImportantEvent(event); } // Ignore other events}
Latency: No additional latency added to agent execution
Optimization Tips
// Optimize trace processingconst processedEvents = new Set();for await (const event of stream) { // Deduplicate events if needed const eventKey = `${event.type}-${event.timestamp}`; if (processedEvents.has(eventKey)) continue; processedEvents.add(eventKey); // Async processing without blocking processEventAsync(event).catch(console.error);}
Troubleshooting
Not Receiving Trace Events
Solution: Ensure streaming is enabled
// Must set stream: trueconst result = await agentbase.runAgent({ message: "Task", stream: true // Required for traces});
Missing Events
Solution: Some events may not occur for all requests
// Not all requests will have errors// Not all tasks use tools// Handle optional events gracefullyif (event.type === 'agent_error') { // May not occur}
Related Primitives
Hooks
Custom callbacks for trace events
Evals
Test agents using trace data
Background Tasks
Monitor async task progress
Self-Healing
Debug error recovery with traces
Additional Resources
Event Types Reference
Complete event documentation
Debugging Guide
Advanced debugging techniques
API Reference
Streaming parameters
Remember: Traces are most powerful when processed incrementally. Stream events, filter to what matters, and handle them as they arrive for optimal performance and insights.