Context helpers
Attach session, user, metadata, and tags to spans, and suppress tracing.
Attach metadata, tags, session IDs, and user IDs to spans. These apply to all spans created within the scope.
from fi_instrumentation import (
using_session, using_user, using_metadata,
using_tags, using_prompt_template, using_attributes,
suppress_tracing
)
# Individual context managers
with using_session("session-abc-123"):
with using_user("user-456"):
response = client.chat.completions.create(...)
with using_metadata({"environment": "production", "version": "2.1"}):
response = client.chat.completions.create(...)
with using_tags(["rag-pipeline", "v2"]):
response = client.chat.completions.create(...)
# Prompt template tracking
with using_prompt_template(
template="Answer {question} using {context}",
label="production",
version="v1.2",
variables={"question": "...", "context": "..."}
):
response = client.chat.completions.create(...)
# Combined - set everything at once
with using_attributes(
session_id="session-abc",
user_id="user-456",
metadata={"env": "prod"},
tags=["rag", "v2"],
prompt_template="Answer {question}",
prompt_template_version="v1.2",
):
response = client.chat.completions.create(...)
# Suppress tracing for a block
with suppress_tracing():
# These calls won't be traced
result = client.chat.completions.create(...) import {
setSession, getSession, clearSession,
setUser, getUser, clearUser,
setMetadata, setTags,
setPromptTemplate,
getAttributesFromContext
} from "@traceai/fi-core";
import { context } from "@opentelemetry/api";
// Build up context with multiple attributes
let ctx = context.active();
ctx = setSession(ctx, { sessionId: "session-abc-123" });
ctx = setUser(ctx, { userId: "user-456" });
ctx = setMetadata(ctx, { environment: "production" });
ctx = setTags(ctx, ["rag-pipeline", "v2"]);
ctx = setPromptTemplate(ctx, {
template: "Answer {{question}} using {{context}}",
variables: { question: "...", context: "..." },
version: "v1.2",
});
// All spans created in this context inherit these attributes
context.with(ctx, async () => {
const response = await openai.chat.completions.create({
model: "gpt-4o-mini",
messages: [{ role: "user", content: "Hello" }],
});
});
// Read attributes back from context
const attrs = getAttributesFromContext(ctx); Java uses AutoCloseable scopes with try-with-resources:
import ai.traceai.ContextAttributes;
// Session tracking
try (var ignored = ContextAttributes.usingSession("session-abc-123")) {
// All spans here get session.id and gen_ai.conversation.id
var response = tracedClient.createChatCompletion(params);
}
// User tracking
try (var ignored = ContextAttributes.usingUser("user-456")) {
var response = tracedClient.createChatCompletion(params);
}
// Metadata
try (var ignored = ContextAttributes.usingMetadata(Map.of(
"environment", "production",
"version", "2.1"
))) {
var response = tracedClient.createChatCompletion(params);
}
// Tags
try (var ignored = ContextAttributes.usingTags(List.of("rag-pipeline", "v2"))) {
var response = tracedClient.createChatCompletion(params);
}
// Nest them for combined context
try (var s = ContextAttributes.usingSession("session-abc");
var u = ContextAttributes.usingUser("user-456");
var m = ContextAttributes.usingMetadata(Map.of("env", "prod"))) {
var response = tracedClient.createChatCompletion(params);
}
// Read current attributes
Map<String, Object> attrs = ContextAttributes.getAttributesFromContext(); C# uses IDisposable scopes with using statements:
using FIInstrumentation.Context;
// Session and user tracking
using (ContextAttributes.UsingSession("session-abc-123"))
using (ContextAttributes.UsingUser("user-456"))
{
tracer.Llm("llm-call", span =>
{
// span automatically gets session.id and user.id
span.SetInput("Hello!");
});
}
// Metadata and tags
using (ContextAttributes.UsingMetadata(new Dictionary<string, object>
{
["environment"] = "production",
["version"] = "2.1"
}))
using (ContextAttributes.UsingTags(new List<string> { "rag-pipeline", "v2" }))
{
tracer.Chain("pipeline", span => { /* ... */ });
}
// Prompt template tracking
using (ContextAttributes.UsingPromptTemplate(
template: "Answer {question} using {context}",
label: "production",
version: "v1.2",
variables: new Dictionary<string, object>
{
["question"] = "...",
["context"] = "..."
}
))
{
tracer.Llm("templated-call", span => { /* ... */ });
}
// Combined - set everything at once
using (ContextAttributes.UsingAttributes(
sessionId: "session-abc",
userId: "user-456",
metadata: new Dictionary<string, object> { ["env"] = "prod" },
tags: new List<string> { "rag", "v2" }
))
{
tracer.Chain("full-context", span => { /* ... */ });
} Suppress Tracing
Temporarily disable tracing for a block of code. Useful for health checks, internal calls, or operations you don’t want in your traces. Available in Python and C# only - Java and TypeScript don’t have this API.
Warning
suppress_tracing drops spans created in its block, it does not move them anywhere else. If a LangChain call inside the block is one you still want traced, but into a different project (for example a linter or internal tool that shares a process with your main agent), suppressing it makes those calls disappear entirely rather than showing up somewhere else. Use a separate tracer_provider/project for that code path instead if you need it observable.
In Python, only use the synchronous form, even inside an async def:
with suppress_tracing():
result = await client.chat.completions.create(...)suppress_tracing does not support async with. Its __aenter__/__aexit__ methods are plain (non-async def), so async with suppress_tracing(): raises a TypeError on entry. Because __aenter__ already attaches the suppression context before that error, the TypeError also skips the matching __aexit__/detach, so the suppression can leak into code that runs after the failed block.
from fi_instrumentation import suppress_tracing
with suppress_tracing():
# Nothing in this block is traced
result = client.chat.completions.create(...) using FIInstrumentation.Context;
using (new SuppressTracing())
{
// Nothing in this block is traced
} Questions & Discussion