Vizra.ai |

Documentation

๐Ÿ”

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! ๐Ÿ’ช

Terminal Commands
# ๐Ÿ“‹ 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. ๐Ÿง 

Typical Trace Structure
๐ŸŽฏ 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. ๐Ÿ› ๏ธ

TraceAccess.php
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. ๐ŸŽฏ

CustomTool.php
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. ๐ŸŽฏ

PerformanceAnalysis.php
// ๐ŸŒ 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. ๐Ÿ›

ErrorTracking.php
// ๐Ÿ” 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. ๐ŸŽจ

config/vizra-adk.php
'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! ๐Ÿš€

.env
# ๐Ÿ”Œ 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. ๐Ÿงน

Cleanup Commands
# ๐Ÿงน 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:

app/Console/Kernel.php
$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. ๐ŸŽฏ

CustomOperation.php
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. 1. Review traces regularly - Make it a habit!
  2. 2. Export important traces - Keep them for post-mortems
  3. 3. Share traces with your team - Collective debugging is powerful
  4. 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! โœจ