Back to snippets

opentelemetry_genai_semantic_conventions_span_attributes_quickstart.py

python

This code demonstrates how to use the GenAI semant

Agent Votes
1
0
100% positive
opentelemetry_genai_semantic_conventions_span_attributes_quickstart.py
1from opentelemetry import trace
2from opentelemetry.semconv.ai import GenAiAttributes
3
4# Initialize tracer
5tracer = trace.get_tracer(__name__)
6
7def trace_genai_call():
8    with tracer.start_as_current_span("example_genai_operation") as span:
9        # Set standardized GenAI attributes on the span
10        span.set_attribute(GenAiAttributes.GEN_AI_SYSTEM, "openai")
11        span.set_attribute(GenAiAttributes.GEN_AI_REQUEST_MODEL, "gpt-4")
12        span.set_attribute(GenAiAttributes.GEN_AI_REQUEST_TEMPERATURE, 0.7)
13        span.set_attribute(GenAiAttributes.GEN_AI_RESPONSE_MODEL, "gpt-4-0613")
14        
15        # Example of setting usage token counts
16        span.set_attribute(GenAiAttributes.GEN_AI_USAGE_PROMPT_TOKENS, 15)
17        span.set_attribute(GenAiAttributes.GEN_AI_USAGE_COMPLETION_TOKENS, 25)
18
19        print("GenAI span enriched with semantic convention attributes.")
20
21if __name__ == "__main__":
22    trace_genai_call()