Session-Based Observability

Group a multi-turn chatbot's spans into one session you can filter and replay.

📝
TL;DR

Tag every LLM span with using_user() and using_session() so a multi-turn conversation groups into one filterable session in the Future AGI Tracing dashboard, instead of appearing as unrelated spans.

Open in ColabGitHub
TimeDifficultyPackage
15 minBeginnerfi-instrumentation-otel + traceAI-openai
Prerequisites

Install

python3 -m venv .venv
source .venv/bin/activate
python -m pip install fi-instrumentation-otel==1.5.1 traceAI-openai==0.1.16 "openai>=1.69,<3"
export FI_API_KEY="your-api-key"
export FI_SECRET_KEY="your-secret-key"
export OPENAI_API_KEY="your-openai-api-key"
export FI_TRACES_URL="https://api.futureagi.com"

For self-hosting, set FI_TRACES_URL to your trace collector instead. Run the Python blocks below in order in the same notebook or Python session.

Tutorial

Register the tracer and instrument OpenAI

register() creates a tracer provider connected to Future AGI. OpenAIInstrumentor patches the OpenAI client so every chat.completions.create call is captured automatically: model name, messages, token counts, and latency.

from fi_instrumentation import register
from fi_instrumentation.fi_types import ProjectType
from traceai_openai import OpenAIInstrumentor
from openai import OpenAI

trace_provider = register(
    project_type=ProjectType.OBSERVE,
    project_name="chatbot-session-demo",
    verbose=False,
)

OpenAIInstrumentor().instrument(tracer_provider=trace_provider)

client = OpenAI()

Tag a single request with user and session context

An OpenAI call made without any context still gets traced (model, messages, tokens, latency), but the span carries no user.id or session.id. Run one first to see what an untagged span looks like:

# No user/session context: this span is traced but ungrouped
response = client.chat.completions.create(
    model="gpt-4o-mini",
    messages=[{"role": "user", "content": "What should I pack for a rainy day hike?"}],
)
print(response.choices[0].message.content)

The model prints its packing suggestions. The wording will vary.

Go to app.futureagi.com → LLM Tracing (left sidebar under OBSERVE). The span is there, but user.id and session.id are both empty in the attributes panel, and the request doesn’t show up under Sessions at all: there’s no session value to group it by.

Now wrap the same call with using_user() and using_session(). The OpenAI instrumentor copies user.id and session.id from the active context onto its span.

from uuid import uuid4
from fi_instrumentation import using_user, using_session

run_id = uuid4().hex
user_id = f"hiker-{run_id}"
session_id = f"packing-{run_id}"

with using_user(user_id), using_session(session_id):
    response = client.chat.completions.create(
        model="gpt-4o-mini",
        messages=[{"role": "user", "content": "What should I pack for a rainy day hike?"}],
    )
    print(response.choices[0].message.content)

The model prints its packing suggestions. The wording will vary.

Back in LLM Tracing, the span carries the user.id and session.id you just set in the attributes panel.

Run a multi-turn conversation

All three turns run inside the same using_user and using_session block, so they share identical ID values and group together in the dashboard.

from fi_instrumentation import using_user, using_session

def run_conversation(user_id: str, session_id: str) -> None:
    """Run a 3-turn conversation. Every span shares the same user and session IDs."""

    turns = [
        "Which layers would you recommend for a wet day hike?",
        "What if I get too warm on the climb?",
        "Summarize the packing list in one sentence.",
    ]

    conversation_history = []

    with using_user(user_id), using_session(session_id):
        for turn_number, user_message in enumerate(turns, start=1):
            conversation_history.append({"role": "user", "content": user_message})

            # Each call is auto-traced with the same user.id and session.id
            response = client.chat.completions.create(
                model="gpt-4o-mini",
                messages=conversation_history,
            )

            assistant_message = response.choices[0].message.content
            conversation_history.append({"role": "assistant", "content": assistant_message})
            print(f"Turn {turn_number}: {assistant_message[:80]}...")


run_conversation(user_id=user_id, session_id=f"layers-{run_id}")

You should see Turn 1, Turn 2, and Turn 3, each followed by the start of the model’s reply.

In LLM Tracing, click the Sessions tab. The session appears as a row with trace count, duration, and first/last messages. Click the row to view all three turns together in a conversation view.

Note

The Sessions tab shows an auto-generated UUID as the session identifier, not the string you passed to using_session(). Your string (e.g. the value starting with layers-) is stored as the session name and used for grouping: every trace that shares the same using_session() value within a project links to the same session.

Add per-turn metadata

Nest using_metadata() around the OpenAI call inside the turn loop. That call’s span inherits the turn number, conversation stage, and total turn count; other turns do not inherit its metadata.

from fi_instrumentation import using_user, using_session, using_metadata

def run_conversation_with_metadata(user_id: str, session_id: str) -> None:
    """Same conversation loop, with per-turn metadata attached to each span."""

    turns = [
        {"message": "Which layers would you recommend for a wet day hike?", "stage": "opening"},
        {"message": "What if I get too warm on the climb?", "stage": "deepening"},
        {"message": "Summarize the packing list in one sentence.", "stage": "closing"},
    ]

    conversation_history = []

    with using_user(user_id), using_session(session_id):
        for turn_number, turn in enumerate(turns, start=1):
            conversation_history.append({"role": "user", "content": turn["message"]})

            # Per-turn metadata is scoped to this span only
            turn_metadata = {
                "turn_number": turn_number,
                "conversation_stage": turn["stage"],
                "total_turns": len(turns),
            }

            with using_metadata(turn_metadata):
                response = client.chat.completions.create(
                    model="gpt-4o-mini",
                    messages=conversation_history,
                )

            assistant_message = response.choices[0].message.content
            conversation_history.append({"role": "assistant", "content": assistant_message})
            print(f"Turn {turn_number} [{turn['stage']}]: {assistant_message[:80]}...")


run_conversation_with_metadata(user_id=user_id, session_id=f"stages-{run_id}")

The three lines now include [opening], [deepening], and [closing].

Each span in Tracing now carries a metadata attribute with turn_number, conversation_stage, and total_turns, visible in the span detail panel. Filter by userId in the LLM Tracing tab to see every span from one user across sessions.

Tip

Combine using_user(), using_session(), using_metadata(), and using_tags() into a single using_attributes() call. Import it from fi_instrumentation.

Flush and verify the grouped session

Short scripts can exit before the batch span processor sends its final spans. Call trace_provider.force_flush() at the end to wait for pending exports.

if not trace_provider.force_flush():
    raise TimeoutError("Timed out while flushing spans")
print(f"Look for stages-{run_id} in chatbot-session-demo")

Open Sessions in the chatbot-session-demo project and look for the printed session name. Its trace count should be three. A completed flush alone does not confirm that the spans are visible in the dashboard.

Troubleshooting

SymptomCauseFix
No traces appear in the dashboardThe script exited before trace_provider.force_flush() ran, so the batch span processor never sent its bufferCall trace_provider.force_flush() at the end of the script, as in Step 5
A span is missing user.id or session.idThe chat.completions.create() call ran outside the using_user/using_session with blockMove the call inside the context manager, or wrap the whole request handler
Every turn creates its own session instead of groupingA new session_id was generated per turn instead of reusing one value for the whole conversationGenerate session_id once per conversation, outside the turn loop
The Sessions tab shows a UUID, not the string passed to using_session()This is expected: the platform assigns its own session ID and stores your string as the session nameMatch on the session name field, not the displayed ID, when reconciling sessions with your own database
metadata attribute is missing from a spanusing_metadata() wrapped the wrong call, or was closed before the request ranConfirm the chat.completions.create() call sits inside the using_metadata() block, as in Step 4
userId filter in LLM Tracing returns no resultsSpans were traced before using_user() was added to the code, or the filter uses a different user ID stringRe-run the script with the current user_id and confirm it matches the value passed to using_user()
ModuleNotFoundError: No module named 'traceai_openai'traceAI-openai isn’t installed, or a different virtualenv is activeRun python -m pip install fi-instrumentation-otel==1.5.1 traceAI-openai==0.1.16 "openai>=1.69,<3" in the environment you’re executing from

Score a turn inside a grouped session with Inline Evals in Tracing.

Was this page helpful?

Questions & Discussion