Netra’s manual tracing capabilities allow you to track external API calls and custom operations with detailed observability. This section covers how to use the custom span tracking utility to monitor your application’s behavior at a granular level.

Getting Started with Manual Tracing

To start manual tracing, you’ll need to:
  1. Import the required classes
  2. Create a new span
  3. Track your operations
  4. Add relevant attributes and events
Here’s a basic example:

Start a New Span

from netra import Netra, UsageModel, ActionModel
from netra.instrumentation.instruments import InstrumentSet

# Initialize the SDK (if not already initialized)
Netra.init(app_name="Your Application Name", instruments={InstrumentSet.OPENAI})

# Start a new span
with Netra.start_span("image_generation") as span:
    # Your API calls or operations here
    # ...

Setting Span Attributes

You can add various attributes to your spans to provide more context about the operation:
# Set span attributes
span.set_prompt("A beautiful sunset over mountains")
span.set_negative_prompt("blurry, low quality")
span.set_model("dall-e-3")
span.set_llm_system("openai")

Tracking Usage Data

Use the UsageModel to track resource usage and costs:
# Create usage data
usage_data = [
    UsageModel(
        model="dall-e-3",
        usage_type="image_generation",
        units_used=1,
        cost_in_usd=0.02
    )
]

# Set usage data on span
span.set_usage(usage_data)

Adding Custom Attributes

Add custom attributes to provide additional context about your operation:
# Add custom attributes
span.set_attribute("image_size", "1024x1024")
span.set_attribute("processing_time", 2.5)  # in seconds
span.set_attribute("retry_count", 0)

Adding Action Tracking

Enable custom action tracking in your application using our action tracking utility. The action tracking utility in Netra follows the given schema:
[
    {
        "action": str,                # Type of action (e.g., "DB", "API", "CACHE")
        "action_type": str,           # Action subtype (e.g., "INSERT", "SELECT", "CALL")
        "affected_records": [         # Optional: List of records affected
            {
                "record_id": str,     # ID of the affected record
                "record_type": str    # Type of the record
            }
        ],
        "metadata": Dict[str, str],   # Additional metadata as key-value pairs
        "success": bool              # Whether the action succeeded
    }
]
Refer the sample code given to understand how to implement action tracking utility in your application.
# Track database operations and other actions
    action = ActionModel(
        action="DB",
        action_type="INSERT",
        affected_records=[
            {"record_id": "user_123", "record_type": "user"},
            {"record_id": "profile_456", "record_type": "profile"}
        ],
        metadata={
            "table": "users",
            "operation_id": "tx_789",
            "duration_ms": "45"
        },
        success=True
    )
    span.set_action([action])

Recording Events

Track important events during the span’s lifecycle:
# Add events
span.add_event("generation_started", {"step": "1", "status": "processing"})
span.add_event("processing_completed", {"step": "rendering"})
span.add_event("image_generated", {"status": "success", "output_format": "png"})

Real-world Examples

1. Image Generation Workflow

python
from netra import Netra, UsageModel

# Start span for image generation
with Netra.start_span("image_generation") as span:
    # Set initial attributes
    span.set_prompt("A futuristic cityscape")
    span.set_model("dall-e-3")
    span.set_llm_system("openai")
    
    # Track usage
    usage_data = [
        UsageModel(
            model="dall-e-3",
            usage_type="image_generation",
            units_used=1,
            cost_in_usd=0.02
        )
    ]
    span.set_usage(usage_data)
    
    # Record workflow events
    span.add_event("generation_started", {"status": "processing"})
    
    # Your actual image generation code here
    # ...
    
    span.add_event("image_generated", {"status": "success"})

	# Record API calls
    api_action = ActionModel(
        action="API",
        action_type="CALL",
        metadata={
            "endpoint": "/api/v1/process",
            "method": "POST",
            "status_code": 200,
            "duration_ms": "120"
        },
        success=True
    )
    span.set_action([api_action])

2. API Request Processing

python
from netra import Netra, UsageModel

# Start span for API request
with Netra.start_span("api_request") as span:
    # Set request attributes
    span.set_attribute("endpoint", "/v1/images/generate")
    span.set_attribute("method", "POST")
    span.set_attribute("request_id", "req_123")
    
    # Track request processing
    span.add_event("request_received", {"timestamp": "2024-01-15T10:30:00Z"})
    
    # Process request
    # ...
    
    span.add_event("request_processed", {"status": "success", "duration_ms": 150})

3. Batch Processing

python
from netra import Netra, UsageModel

# Start span for batch processing
with Netra.start_span("batch_processing") as span:
    # Set batch attributes
    span.set_attribute("batch_size", 100)
    span.set_attribute("batch_id", "batch_123")
    span.set_attribute("operation", "image_enhancement")
    
    # Track batch processing
    span.add_event("batch_started", {"total_items": 100})
    
    # Process items in batch
    processed_count = 0
    for item in batch_items:
        # Process item
        # ...
        processed_count += 1
        
        if processed_count % 10 == 0:
            span.add_event("progress_update", {
                "processed": processed_count,
                "percentage": (processed_count / len(batch_items)) * 100
            })
    
    span.add_event("batch_completed", {
        "status": "success",
        "total_time_ms": 2500
    })

Common Use Cases

  1. API Request/Response Tracking
    • Track HTTP requests and responses
    • Monitor response times
    • Track error rates
    • Record request parameters
  2. Batch Processing
    • Track batch operations
    • Monitor progress
    • Record processing times
    • Track success/failure rates
  3. Image/Video Processing
    • Track media processing operations
    • Monitor resource usage
    • Record processing times
    • Track quality metrics
  4. Data Processing Pipelines
    • Track data transformation steps
    • Monitor processing stages
    • Record data volumes
    • Track error rates
  5. Machine Learning Operations
    • Track model inference
    • Monitor resource usage
    • Record processing times
    • Track model performance metricstitle: “Manual Tracking” description: “Welcome to the home of your new documentation”