Get the Current Span/Context and Tracer
Sometimes it's helpful to access whatever the current span is at a point in time so that you can enrich it with more information.
from opentelemetry import trace
current_span = trace.get_current_span()
# enrich 'current_span' with some information
Get Active Context
Example to grab the active context:
import { context, trace } from '@opentelemetry/api';
// Function to demonstrate context usage
function demonstrateActiveContext() {
// Get the active context
const activeContext = context.active();
// Example of using the active context to set and get a value
const ctxWithValue = context.with(activeContext, () => {
context.setValue('key', 'value');
});
// Accessing the current span if tracing is set up
const currentSpan = trace.getSpan(activeContext);
}
Get the current span Sometimes it’s helpful to do something with the current/active span at a particular point in program execution.
const activeSpan = opentelemetry.trace.getActiveSpan();
// do something with the active span, optionally ending it if that is appropriate for your use case.
Get a span from context It can also be helpful to get the span from a given context that isn’t necessarily the active span.
const ctx = context.active();
const span = opentelemetry.trace.getSpan(ctx);
// do something with the acquired span, optionally ending it if that is appropriate for your use case.
Get Current Tracer
The tracer in OTEL can be used to create spans.
The following is used to get the tracer:
tracer = trace.get_tracer(__name__)
# Start a new span for the tool function handling
with tracer.start_as_current_span("HandleFunctionCall", attributes={
SpanAttributes.OPENINFERENCE_SPAN_KIND: OpenInferenceSpanKindValues.TOOL.value,
ToolCallAttributes.TOOL_CALL_FUNCTION_NAME: function_call_name,
ToolCallAttributes.TOOL_CALL_FUNCTION_ARGUMENTS_JSON: str(arguments),
SpanAttributes.INPUT_VALUE: function_call_name
})
The following is how to get tracer in TS/JS:
import { trace, context } from '@opentelemetry/api';
import { SpanKind, SpanStatusCode } from '@opentelemetry/api';
// Get the tracer
const tracer = trace.getTracer('your-service-name');
// Start a new span for the tool function handling
const span = tracer.startSpan('HandleFunctionCall', {
kind: SpanKind.INTERNAL,
attributes: {
'openinference.span_kind': 'TOOL',
'tool.call_function_name': functionCallName,
'tool.call_function_arguments_json': JSON.stringify(arguments),
'input.value': functionCallName
}
});
The
Last updated