Tracing
Get X-ray vision into your agents! ๐ฌ See exactly what's happening inside with powerful debugging and performance insights.
๐ฏ What is Tracing?
Think of tracing as having superpowers that let you see through your agent's execution! Every conversation, every tool call, every decision - it's all captured in beautiful detail. No more guessing what went wrong or why something is slow! ๐
๐จ What Gets Captured?
โฑ๏ธ Execution Timeline
Complete timeline with nested spans showing exactly when each operation happened
๐ค LLM Interactions
Every request and response, including prompts, completions, and model details
๐ง Tool Executions
All tool calls with their parameters, results, and execution time
๐ง Memory Operations
Vector searches, context retrieval, and memory storage operations
๐ฐ Token Usage
Detailed token counts and costs for every LLM interaction
โก Performance Metrics
Bottlenecks, slow operations, and optimization opportunities
๐ Viewing Your Traces
๐ Web Interface - The Visual Experience!
Fire up your browser and navigate to http://your-app.test/vizra/traces
for the full visual experience! ๐จ
๐ Interactive Timeline
Zoom, pan, and explore your execution flow visually
๐ Span Details
Click any span to see inputs, outputs, and metadata
๐ง Waterfall Charts
Visualize performance bottlenecks at a glance
๐ Token Analytics
See exactly where your tokens are being spent
โก CLI Commands - For the Terminal Warriors!
Prefer the command line? We've got you covered with powerful CLI tools! ๐ช
# ๐ List recent traces
php artisan vizra:traces
# ๐ View a specific trace
php artisan vizra:trace abc123
# ๐ฏ Filter traces by agent or status
php artisan vizra:traces --agent=customer_support --status=failed
# ๐พ Export traces for external analysis
php artisan vizra:traces --export=json --output=traces.json
๐ณ Understanding Trace Structure
Traces are organized in a beautiful tree structure, just like a family tree! Each operation has parent and child relationships that show you exactly how your agent thinks. ๐ง
๐ฏ Agent Execution (root span)
โโโ ๐ Session Initialization
โโโ ๐ง Memory Retrieval
โ โโโ ๐ Vector Search
โ โโโ ๐ Context Building
โโโ ๐ค LLM Request
โ โโโ โ๏ธ Prompt Construction
โ โโโ ๐ API Call
โ โโโ ๐ฅ Response Processing
โโโ ๐ง Tool Execution
โ โโโ ๐ฆ Tool: order_lookup
โ โโโ ๐ง Tool: send_email
โโโ ๐พ Memory Storage
Root Span
The main execution
Parent Spans
Major operations
Child Spans
Detailed steps
๐ป Programmatic Tracing
๐ Accessing Traces in Code
Want to build your own debugging tools? Access trace data directly in your code! It's like having a debugger API at your fingertips. ๐ ๏ธ
use Vizra\ADK\Tracing\TraceManager;
// ๐ Get trace for a session
$trace = TraceManager::forSession($sessionId);
// ๐ Loop through all spans
foreach ($trace->spans as $span) {
echo $span->name . ': ' . $span->duration . "ms\n";
}
// ๐ Get performance metrics
$metrics = $trace->getMetrics();
echo "Total Duration: " . $metrics['total_duration'] . "ms\n";
echo "Token Usage: " . $metrics['total_tokens'] . "\n";
โจ Creating Custom Spans
Add your own spans to trace custom operations! Perfect for tracking database queries, API calls, or any complex logic. ๐ฏ
use Vizra\ADK\Tracing\Tracer;
class CustomTool extends BaseTool
{
public function execute(array $parameters): ToolResult
{
return Tracer::span('custom_operation', function() use ($parameters) {
// ๐ท๏ธ Add span attributes
Tracer::addAttribute('operation.type', 'database');
Tracer::addAttribute('query.complexity', 'high');
// ๐ Your operation
$result = $this->performOperation($parameters);
// ๐ Add result to span
Tracer::addEvent('operation_completed', [
'records_processed' => count($result),
]);
return ToolResult::success($result);
});
}
}
๐ก Pro Tip!
The Tracer::span()
method automatically handles timing, error capturing, and span hierarchy. Just wrap your code and let it do the magic! โจ
๐ Analyzing Your Traces
โก Performance Analysis
Find those pesky bottlenecks and optimize like a pro! Let's hunt down slow operations and expensive API calls. ๐ฏ
// ๐ Find slow operations
$slowSpans = $trace->getSlowSpans(1000); // Spans over 1 second
foreach ($slowSpans as $span) {
echo "Slow operation: {$span->name} took {$span->duration}ms\n";
}
// ๐ฐ Analyze token usage
$tokenAnalysis = $trace->analyzeTokenUsage();
echo "Most expensive span: " . $tokenAnalysis['most_expensive']->name;
echo " used " . $tokenAnalysis['most_expensive']->tokens . " tokens\n";
๐ฏ Quick Wins
Look for operations over 500ms - they're usually the easiest to optimize!
๐ก Token Tip
High token usage often means verbose prompts - try to be more concise!
๐จ Error Tracking
Errors happen to the best of us! Track them down and squash those bugs with precision. ๐
// ๐ Find failed spans
$errors = $trace->getErrors();
foreach ($errors as $error) {
echo "Error in {$error->span->name}: {$error->message}\n";
echo "Stack trace:\n{$error->stackTrace}\n";
}
๐ช Error Recovery Tips
- โข Check error patterns - repeated errors often have the same root cause
- โข Look at parent spans - context matters!
- โข Review input parameters - bad data in = errors out
- โข Monitor error rates over time to catch regressions early
โ๏ธ Configuring Tracing
๐๏ธ Configuration Options
Fine-tune your tracing setup to match your needs! Control what gets traced, how long to keep data, and more. ๐จ
'tracing' => [
'enabled' => env('VIZRA_ADK_TRACING_ENABLED', true),
'table' => 'agent_trace_spans',
'cleanup_days' => env('VIZRA_ADK_TRACING_CLEANUP_DAYS', 30),
];
๐ง Environment Variables
Set these in your .env
file to control tracing behavior across environments! ๐
# ๐ Enable/disable tracing
VIZRA_ADK_TRACING_ENABLED=true
# ๐
Days to keep trace data before cleanup
VIZRA_ADK_TRACING_CLEANUP_DAYS=30
๐ก Development Tip
Always enable tracing in development for maximum visibility!
๐ญ Production Tip
Consider sampling in production to balance insights with performance.
๐๏ธ Data Retention & Cleanup
Keep your database lean and mean! Set up automatic cleanup to remove old traces. ๐งน
# ๐งน Clean up old traces (uses config value)
php artisan vizra:trace:cleanup
# ๐
Clean up traces older than specific days
php artisan vizra:trace:cleanup --days=7
# ๐ Dry run to see what would be deleted
php artisan vizra:trace:cleanup --dry-run
โฐ Pro Tip: Schedule It!
Add this to your Laravel scheduler for automatic cleanup:
$schedule->command('vizra:trace:cleanup')->daily();
๐ฎ How Tracing Works Behind the Scenes
โจ Automatic Span Creation
The ADK works its magic by automatically creating spans for key operations. No manual instrumentation needed! ๐ฉ
๐ฏ Agent Execution
Root span created when agent runs
BaseLlmAgent::handle()
๐ค LLM Calls
Every AI interaction tracked
BaseLlmAgent::callLlm()
๐ง Tool Calls
Tool execution monitoring
BaseLlmAgent::executeTool()
๐ Sub-agent Calls
Delegation tracking
When delegating to sub-agents
๐ ๏ธ Manual Span Creation
Need more control? Create your own spans for custom operations! Perfect for tracking specific business logic. ๐ฏ
use Vizra\VizraADK\Services\Tracer;
class CustomOperation
{
public function process(Tracer $tracer)
{
// ๐ Start a custom span
$spanId = $tracer->startSpan(
type: 'custom_operation',
name: 'Process Data',
input: ['records' => 100],
metadata: ['batch_id' => 'abc123']
);
try {
// ๐ช Your operation
$result = $this->doWork();
// โ
End span with success
$tracer->endSpan($spanId, ['processed' => 100]);
} catch (\Throwable $e) {
// โ Mark span as failed
$tracer->failSpan($spanId, $e);
throw $e;
}
}
}
๐จ Span Best Practices
- โข Keep span names descriptive and consistent
- โข Add relevant metadata for better filtering
- โข Always handle errors to mark spans as failed
- โข Use nested spans for complex operations
๐ฌ Debugging Like a Detective
๐ต๏ธ Common Issues & Solutions
Let's solve those mysteries! Here are the most common issues and how to track them down. ๐
๐ Slow LLM Calls
Check prompt size and model selection
๐ก Tip: Smaller prompts = faster responses!
โ Failed Tool Calls
Review parameters and error messages
๐ก Tip: Check for missing required params!
๐ธ High Token Usage
Optimize prompts and context
๐ก Tip: Use system prompts wisely!
๐ง Memory Misses
Verify vector search configuration
๐ก Tip: Check embedding model consistency!
โฐ Timeout Errors
Identify bottlenecks in execution
๐ก Tip: Look for sequential operations!
๐ Retry Loops
Check for infinite retry patterns
๐ก Tip: Add exponential backoff!
๐ Tracing Best Practices
๐ Development
- โ Enable tracing for all requests - visibility is king!
- โ Add custom spans for business logic
- โ Use trace viewer frequently during development
๐ญ Production
- โ Use sampling to control costs and performance
- โ Set up alerts for anomalies and errors
- โ Regularly clean up old traces
๐ Golden Rules
- 1. Review traces regularly - Make it a habit!
- 2. Export important traces - Keep them for post-mortems
- 3. Share traces with your team - Collective debugging is powerful
- 4. Learn from patterns - Similar issues often have similar traces
๐ You're Now a Tracing Expert!
With the power of tracing, you can see through your agents like never before. No more mysteries, no more guessing - just pure visibility and control! ๐
Remember: Great debugging starts with great tracing. Use it liberally, learn from it constantly, and let it guide you to building amazing AI agents! โจ