Create custom spans with a tracer
Custom spans te permiten representar business-specific operations en tu trace data. En una RAG pipe pueden ser operaciones como generate embedding, search vector index o assemble prompt.
Estos spans aparecen en Application Insights como end-to-end transactions junto a todos los spans recogidos automaticamente.
En python usamos opentelemetry.trace como entry point para crear spans. Se llama trace.get_tracer("name") para obtener un tracer para tu servicio o componente.
create a tracer and start a custom span
# Code fragment - focus on creating a custom tracer and span
from azure.monitor.opentelemetry import configure_azure_monitor
from opentelemetry import trace
configure_azure_monitor()
# Equivalent to creating an instrumentation source — use once per service/component
tracer = trace.get_tracer("embedding-service")
# start_as_current_span is a context manager — the span ends automatically when the block exits
with tracer.start_as_current_span("GenerateEmbedding") as span:
span.set_attribute("embedding.model", "text-embedding-ada-002")
span.set_attribute("embedding.token_count", token_count)
# Embedding generation logic
embedding = generate_embedding(input_text)
Add attributes to spans
Span attributes enriquecen tus trace data con información contextual que ayuda a filtrar, buscar y analizar trazas.
Resources attributes - describen el servicio en si mismo y aplican a toda la telemetria de ese servicio. Configuras los atributos una unica vez durante el startup.
Span attributes - describen una operacion especifica y aplican solo al span individual. Configuras span attributes dentro del scope de un span activo para capturar detalles particulares de esa operacion.
# Code fragment - focus on adding meaningful attributes to a span
with tracer.start_as_current_span("SearchVectorIndex") as span:
span.set_attribute("search.index_name", "product-docs")
span.set_attribute("search.query_vector_dimension", 1536)
span.set_attribute("search.top_k", 10)
results = search_index(embedding)
span.set_attribute("search.result_count", len(results))
span.set_attribute("search.similarity_threshold", 0.78)
Cuando exportamos estos atributos a Application Insights, aparecen dentro de la columna customDimensions.
Control span kinds and status
El span kind indica el tipo de operacion que representa un span. Application Insights usa estos valores para clasificar spans como requests o dependencias.
Tipos de spans
SpanKind.SERVERincoming request gerstionada por el servicioSpanKind.CLIENToutgoing call a un servicio o recurso externoSpanKind.INTERNALoperacion interna dentro del servicio que no cruza process boundariesSpanKind.PRODUCERiniciar una async op (enviar un mensaje a una queue)SpanKind.CONSUMERconsume una async op (recibir un mensaje de una queue)
# Code fragment - focus on setting span kind for an outgoing LLM API call
from opentelemetry.trace import SpanKind
with tracer.start_as_current_span("CallLlmApi", kind=SpanKind.CLIENT) as span:
span.set_attribute("llm.provider", "azure-openai")
span.set_attribute("llm.model", "gpt-4o")
# LLM API call logic
response = call_llm(prompt)
span.set_attribute("llm.response_tokens", response.usage.completion_tokens)
# Code fragment - focus on recording errors and exceptions on a span
from opentelemetry.trace import Status, StatusCode
with tracer.start_as_current_span("GenerateEmbedding") as span:
try:
embedding = generate_embedding(input_text)
span.set_status(Status(StatusCode.OK))
except Exception as ex:
span.record_exception(ex)
span.set_status(Status(StatusCode.ERROR, "Embedding generation failed"))
raise
Model nested operations in a trace
Nested spans crean una jerarquia parent-child que representa el flow logico de una request a traves de tu app.
En python se nestea poniendo start_as_current_span uno dentro de otro. Cuando un span comienza mientras otro span está activo, OpenTelemetry marca el activo como padre del nuevo.
nested spans model a simplified RAG pipe request flow
# Code fragment - focus on nested spans modeling a RAG pipeline request flow
from azure.monitor.opentelemetry import configure_azure_monitor
from opentelemetry import trace
from opentelemetry.trace import SpanKind
configure_azure_monitor()
tracer = trace.get_tracer("llm-orchestrator")
def process_query(query: str) -> str:
with tracer.start_as_current_span("ProcessQuery", kind=SpanKind.SERVER) as root_span:
root_span.set_attribute("query.length", len(query))
# Child span: Generate embedding
with tracer.start_as_current_span("GenerateEmbedding") as embed_span:
embed_span.set_attribute("embedding.model", "text-embedding-ada-002")
embedding = embedding_service.generate(query)
embed_span.set_attribute("embedding.dimensions", len(embedding))
# Child span: Search vector index
with tracer.start_as_current_span("SearchVectorIndex") as search_span:
search_span.set_attribute("search.top_k", 5)
results = vector_search.search(embedding, top_k=5)
search_span.set_attribute("search.result_count", len(results))
# Child span: Call LLM
with tracer.start_as_current_span("CallLlm", kind=SpanKind.CLIENT) as llm_span:
prompt = build_prompt(query, results)
llm_span.set_attribute("llm.prompt_tokens", count_tokens(prompt))
response = llm_client.get_completion(prompt)
llm_span.set_attribute("llm.response_tokens", response.usage.completion_tokens)
return response.content
Cuando ves esto a través de Application Insights end-to-end transaction view, lo ves como un waterfall chart.
ProcessQUery aparece como el root span, con GenerateEmbedding, SearchVectorIndex y CallLLM como child spans nesteados.