Multi-agent debugging: trace and observability
Quando costruisci sistemi multi-agenti complessi (RAG, workflow orchestrati, tool-use coordinato), il debugging diventa esponenzialmente più difficile. Non hai una singola traccia di esecuzione — hai decine di agenti che comunicano in parallelo, delegano task, richiamano LLM e interact con tool esterni. Senza osservabilità end-to-end, ogni bug diventa un incubo: "Dove è fallito? Perché l'agente A ha restituito un risultato sbagliato? Quali strumenti sono stati chiamati e in quale ordine?". Questo articolo ti mostra come implementare un sistema di tracing distribuito, logging strutturato e metriche per veder chiaramente cosa succede dentro il tuo stack agentico.
Il problema: debugging cieco nei sistemi multi-agenti
Un sistema agentico tipico composto da:
- Orchestrator centrale — coordina gli agenti, gestisce lo stato globale
- Agenti specializzati — ricerca dati, filtraggio, generazione, revisione
- Tool integrati — API REST, database, search engine, LLM on-prem (Ollama)
- Coda di task — queue asincrone per i job lunghi
Quando un utente fa una query, il flusso attraversa 10-20 componenti, spesso in parallelo. Se il risultato è sbagliato, le domande naturali sono: "A quale step è successo l'errore? Quale agente ha preso una decisione sbagliata? Quale tool ha restituito dati corrotti? Quale LLM ha allucinato?". Senza tracing centralizzato, rispondi solo analizzando log sparsi su file diversi, sperando di ricordare quale request-id usava quale agente.
Architettura osservabilità end-to-end
Una soluzione completa per osservabilità in sistemi agentic richiede tre componenti:
- Tracing distribuito — seguire il flow di una singola request attraverso tutti gli agenti e tool (OpenTelemetry + Jaeger)
- Logging strutturato — emit JSON log con contesto traccia, metadata agente, stato input/output
- Metriche — latenza end-to-end, token LLM consumati, rate tool success/failure, anomalie
Il pezzo critico è il trace context — un ID univoco e un parent-child ID che propago in ogni componente, così che tutti gli eventi correlati siano linkati insieme in una view unica.
Setup OpenTelemetry + Jaeger locale
Per una piattaforma agentica self-hosted su VPS Hetzner, usiamo OpenTelemetry (SDK) esportato a Jaeger locale. Jaeger non richiede subscription cloud e gira su un container Docker.
# docker-compose.yml - aggiungere al monorepo
services:
jaeger:
image: jaegertracing/all-in-one:latest
ports:
- "16686:16686" # Jaeger UI
- "6831:6831/udp" # Jaeger agent (UDP)
environment:
- COLLECTOR_OTLP_ENABLED=true
prometheus:
image: prom/prometheus:latest
ports:
- "9090:9090"
volumes:
- ./prometheus.yml:/etc/prometheus/prometheus.yml
command:
- "--config.file=/etc/prometheus/prometheus.yml"
Jaeger expone Prometheus metriche su localhost:14269/metrics. Prometheus scrapes e Grafana visualizza grafici latenza/errori/throughput.
Strumentazione FastAPI con OpenTelemetry
Nel tuo microservizio FastAPI (ml-service nel monorepo), aggiungi la strumentazione automatica:
from opentelemetry import trace, metrics
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from opentelemetry.exporter.jaeger.thrift import JaegerExporter
from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor
from opentelemetry.instrumentation.httpx import HTTPXClientInstrumentor
from opentelemetry.instrumentation.sqlalchemy import SQLAlchemyInstrumentor
from opentelemetry.sdk.resources import SERVICE_NAME, Resource
# Setup tracer provider
resource = Resource(attributes={
SERVICE_NAME: "agentic-ml-service",
"environment": "production",
"platform": "ollama-rag"
})
jaeger_exporter = JaegerExporter(
agent_host_name="localhost",
agent_port=6831,
)
trace_provider = TracerProvider(resource=resource)
trace_provider.add_span_processor(BatchSpanProcessor(jaeger_exporter))
trace.set_tracer_provider(trace_provider)
# Istanzia FastAPI con strumentazione
app = FastAPI()
FastAPIInstrumentor.instrument_app(app)
HTTPXClientInstrumentor().instrument() # Traccia HTTP client calls (e.g., verso Ollama)
SQLAlchemyInstrumentor().instrument() # Traccia query DB
tracer = trace.get_tracer(__name__)
Con questa configurazione, ogni request FastAPI genera automaticamente un trace span. Aggiungiamo span customizzati per logica agentica.
Strumentazione agenti e tool
Ogni agente che chiama un tool esterno (Ollama LLM, search API, database) deve creare span per tracciare latenza e risultati:
class ResearchAgent:
def __init__(self):
self.tracer = trace.get_tracer(__name__)
async def search_documents(self, query: str, top_k: int = 5) -> List[str]:
with self.tracer.start_as_current_span("research_agent.search_documents") as span:
span.set_attribute("query", query)
span.set_attribute("top_k", top_k)
# Ricerca documentale
with self.tracer.start_as_current_span("redis_search") as search_span:
results = await self.vectordb.query(query, top_k)
search_span.set_attribute("results_count", len(results))
return results
async def generate_summary(self, documents: List[str]) -> str:
with self.tracer.start_as_current_span("research_agent.generate_summary") as span:
# Chiama Ollama LLM
with self.tracer.start_as_current_span("ollama_llm_call") as llm_span:
prompt = f"Summarize: {' '.join(documents)}"
try:
response = await self.ollama_client.generate(
model="llama3.1:8b",
prompt=prompt
)
llm_span.set_attribute("model", "llama3.1:8b")
llm_span.set_attribute("tokens_generated", response.get("n_tokens", 0))
return response["text"]
except Exception as e:
llm_span.record_exception(e)
span.add_event("llama_error", {"reason": str(e)})
raise
Ogni span include attributi (query, model, count risultati), e gli errori sono automaticamente loggati nel trace. Nel Jaeger UI vedrai la catena completa: orchestrator → agent.search → redis_search → redis_latency.
Logging strutturato con contesto traccia
I log puri sono noiosi per i sistemi complessi. Usa logging strutturato (JSON) che includa il trace-id automaticamente:
import logging
import json
from opentelemetry import trace
class StructuredLogFormatter(logging.Formatter):
def format(self, record):
# Cattura trace-id corrente
span = trace.get_current_span()
trace_id = span.get_span_context().trace_id
log_data = {
"timestamp": record.created,
"level": record.levelname,
"logger": record.name,
"message": record.getMessage(),
"trace_id": f"{trace_id:032x}", # 128-bit hex
"span_id": f"{span.get_span_context().span_id:016x}",
}
# Includi extra fields
if hasattr(record, 'agent_id'):
log_data["agent_id"] = record.agent_id
if hasattr(record, 'tool_name'):
log_data["tool_name"] = record.tool_name
return json.dumps(log_data, default=str)
# Setup logger
logger = logging.getLogger("agentic-system")
handler = logging.StreamHandler()
handler.setFormatter(StructuredLogFormatter())
logger.addHandler(handler)
# Uso nel codice agente
def call_external_api(endpoint: str):
logger.info(
"Calling external API",
extra={
"tool_name": "search_api",
"endpoint": endpoint,
"agent_id": "research-001"
}
)
Ora ogni log contiene il trace-id. Elasticsearch / Loki ingerisce questi JSON log e puoi cercare tutti gli eventi di una singola request usando il trace-id.
Metriche chiave per sistemi agentic
Oltre a tracing e logging, monitora metriche per rilevare anomalie a livello di sistema:
from opentelemetry.sdk.metrics import MeterProvider
from opentelemetry.exporter.prometheus import PrometheusMetricReader
from prometheus_client import start_http_server
# Prometheus metrics
prometheus_reader = PrometheusMetricReader()
meter_provider = MeterProvider(metric_readers=[prometheus_reader])
meter = meter_provider.get_meter(__name__)
# Latenza request end-to-end
request_duration = meter.create_histogram(
"request_duration_seconds",
unit="s",
description="End-to-end request latency"
)
# Token LLM consumati per request
llm_tokens_consumed = meter.create_counter(
"llm_tokens_consumed_total",
unit="1",
description="Total tokens sent to LLM"
)
# Tool call success rate
tool_success_rate = meter.create_counter(
"tool_calls_total",
unit="1",
description="Tool invocations by status"
)
# Uso nel request handler
@app.post("/chat")
async def chat_endpoint(req: ChatRequest):
start = time.time()
try:
result = await orchestrator.run(req.query)
duration = time.time() - start
request_duration.record(duration)
llm_tokens_consumed.add(result.get("tokens_used", 0))
tool_success_rate.add(1, {"status": "success"})
return result
except Exception as e:
tool_success_rate.add(1, {"status": "error", "error_type": type(e).__name__})
raise
Grafica queste metriche in Grafana. Aumenti improvvisi di latenza o drop del success rate segnalano problemi (Ollama down, tool lento, overload).
Debugging pratico: tracciare una richiesta fallita
Uno scenario reale: l'utente sottomette una query, il sistema restituisce un risultato sbagliato. Workflow di debugging:
- Accedi a Jaeger UI (localhost:16686) e filtra per service "agentic-ml-service"
- Cerca il timestamp della richiesta (es. ultimi 5 minuti)
-
Clicca sul trace — vedrai una waterfall con tutti gli span:
- orchestrator.run_query (5.2s totali)
- → research_agent.search_documents (1.3s)
- → redis_search (0.8s)
- → research_agent.generate_summary (3.1s)
- → ollama_llm_call (2.9s)
- → filtering_agent.rank_results (0.8s)
- Ispeziona il filtro agent — output mostrava score bassi? Controlla gli attributi dello span (score_threshold, results_before_filter, results_after_filter)
- Se il bug è in Ollama, clicca su ollama_llm_call — vedrai il prompt inviato, token count, temperature, model. Ripeti la stessa query in Ollama manualmente e confronta output.
Questo workflow è 100x più veloce che cercare negli aggregati log.
Gestione degli errori e anomalie
Jaeger supporta visualizzazione di errori. Quando un'eccezione è registrata in uno span, la UI mostra quel nodo in rosso. Aggiungi un layer di anomaly detection:
async def detect_anomalies():
"""Monitora metriche Prometheus e allerta su anomalie"""
while True:
await asyncio.sleep(60) # Check ogni minuto
# Latenza medio-alta: threshold 8 secondi
avg_latency = await prometheus_client.query(
'avg(rate(request_duration_seconds_sum[5m]))'
)
if avg_latency > 8:
logger.warning("High latency detected", extra={"latency_s": avg_latency})
# Invia alert (email, Slack, ecc.)
# Error rate > 5%
error_rate = await prometheus_client.query(
'sum(rate(tool_calls_total{status="error"}[5m])) / sum(rate(tool_calls_total[5m]))'
)
if error_rate > 0.05:
logger.error("High error rate", extra={"error_rate": error_rate})
# Trigger incident
Best practices osservabilità per agentic platforms
- Includi decisioni agente nei span — es. "agent scelto: research_agent", "fallback_strategy: use_cache". Aiuta a capire il flusso logico.
- Traccia input e output parziali — non loggare il testo intero di documenti (noise), ma hash + lunghezza.
- Propaga trace-id cross-service — se Ollama è su un'altra macchina, passa l'header traceparent nelle HTTP request verso Ollama.
- Sampling in produzione — tracing di OGNI request può essere costoso. Usa sampling probabilistico (es. 10% in produzione, 100% in staging).
- Retention policy — Jaeger di default tiene trace per 72h. Configuralo in base a storage/costi.
- Alerta su timeout tool — se una chiamata a Ollama impiega >30s, registra subito un alert (segno di overload o crash).
Roadmap: observability avanzata (2026-2027)
- Correlation di anomalie — se latenza sale quando token/min sale, suggerisci scaling Ollama
- Replay trace per testing — registra input/output di una trace "corretta", e replica esattamente le chiamate tool per regression testing
- Observability LLM nativa — Ollama/Llama 3.x in futuro potrebbero esporre token distribution per rilevare hallucination (es. se confidence di un token scende sotto soglia)
- Distributed sampling intelligent — sample 100% degli errori, 10% dei success, 1% dei very-fast requests
FAQ
D: Jaeger locale ha costi di storage? Posso usarlo in produzione?
R: Sì, Jaeger è open-source e self-hosted — zero costi cloud. In produzione su VPS Hetzner (CCX23, 16 GB RAM) puoi tenere Jaeger in una configurazione "small" che retiene trace per 72-168h. Per retention più lungo (1 anno), integra Cassandra come backend storage (non trattato qui, ma documentato in Jaeger docs).
D: Come tracciare un tool che non è HTTP (es. query diretta a database)?
R: Usa le instrumentazioni OpenTelemetry già built-in: SQLAlchemyInstrumentor per SQLAlchemy queries, o wrappa il codice con tracer.start_as_current_span("db_query").
D: Posso tracciare token cost Ollama in real-time per fatturazione cliente?
R: Sì — nel span ollama_llm_call registra il campo `tokens_generated` (fornito da Ollama nella response) e `tokens_input` (lunghezza prompt). Summammo questi in una metrica Prometheus counter, ed esporta in un sistema di billing via API.
D: Overhead di tracing è significativo?
R: Negligibile (<2% latenza aggiunto) con batch span processor. Il tracing avviene in background thread. OpenTelemetry è stato ottimizzato per produzione.
D: Se Jaeger è down, il sistema si blocca?
R: No — Jaeger export è async e fault-tolerant. Se il collector non raggiunge, gli span sono bufferizzati e riproven quando torna online. Se il buffer esaurisce la memoria, gli span più vecchi vengono scartati (configurabile).

Commenti
Caricamento commenti...
Accedi per commentare