Skip to main content
Assumes you are using openinference-instrumentation>=0.1.34
When working with spans that are automatically instrumented via OpenInference in your LLM applications, you often need to capture span contexts to apply feedback or annotations. The capture_span_context context manager provides a convenient way to capture all OpenInference spans within its scope, making it easier to apply feedback to specific spans in downstream operations. The capture_span_context context manager allows you to:
  • Capture all spans created within a specific code block
  • Retrieve span contexts for later use in feedback systems
  • Maintain a clean separation between span creation and annotation logic
  • Apply feedback to spans without needing to track span IDs manually

Understanding Span Topology

When your LLM application executes, it creates a hierarchy of spans representing different operations. For example, when using a framework, you might have:
The capture_span_context context manager helps you easily access:
  • First span: The root span of your operation (useful for high-level feedback and evaluations)
  • Last span: The most recent span created (often the final LLM call, useful for LLM-specific feedback)
  • All spans: A complete list of all spans created within the context (useful for comprehensive analysis)

Usage

Accessing First and Last Spans

When to Use First vs Last Spans

Use the first span (get_first_span_id()) when:
  • Adding user feedback about the overall experience
  • Recording evaluation scores for the entire request/response cycle
Use the last span (get_last_span_id()) when:
  • The last span represents an LLM invocation
  • You want to annotate the final output or generation step
  • Applying feedback specifically to the model’s response quality
  • Recording model-specific metrics or evaluations

Working with All Captured Spans

You can also access all spans for more complex annotation scenarios:

Working with Multiple Span Types

You can filter spans based on their attributes:

Resources