apps/opik-documentation/python-sdk-docs/source/context_manager/index.rst
Opik provides context managers for creating and managing traces and spans in your application. These context managers allow you to easily instrument your code with tracing capabilities while ensuring proper cleanup and error handling.
Context managers are particularly useful when you need fine-grained control over trace and span creation, or when working with code that doesn't fit well with the @track decorator pattern.
.. toctree:: :maxdepth: 1 :titlesonly:
start_as_current_span start_as_current_trace distributed_headers
.. code-block:: python
import opik
with opik.start_as_current_trace("my-trace", project_name="my-project") as trace: # Your application logic here trace.input = {"user_query": "Explain quantum computing"} trace.output = {"response": "Quantum computing is..."} trace.tags = ["chat"] trace.metadata = {"model": "gpt-4", "temperature": 0.7}
# Basic span creation
with opik.start_as_current_span("llm-call", type="llm", project_name="my-project") as span:
# Your LLM call here
span.input = {"prompt": "Explain quantum computing"}
span.output = {"response": "Quantum computing is..."}
span.model = "gpt-4"
span.provider = "openai"
span.usage = {
"prompt_tokens": 10,
"completion_tokens": 50,
"total_tokens": 60
}
Use context managers when:
For simpler use cases, consider using the @track decorator instead.