Skip to main content

uselemma-tracing

HTTP tracing SDK for AI agents. The primary API sends trace payloads directly to Lemma over HTTP.

Installation

pip install uselemma-tracing

Quick Start

from uselemma_tracing import Lemma

lemma = Lemma(release="1.8.3")  # or set LEMMA_RELEASE

def run(trace):
    docs = search_docs(user_message)
    trace.record_tool(
        name="search_docs",
        input={"query": user_message},
        output=docs,
        tool_parameters={"query": "string"},
    )

    response = call_model(user_message, docs)
    trace.record_generation(
        name="draft-reply",
        input=response.messages,
        output=response.text,
        model="gpt-4o",
        llm_input_messages=[{"role": "user", "content": user_message}],
        llm_invocation_parameters={"temperature": 0.2},
    )

    return response.text

answer = lemma.trace(
    "support-agent",
    run,
    input=user_message,
    thread_id=conversation_id,
    user_id=user.id,
)

lemma.trace() measures the trace from callback start to completion. Use async_trace() for async callbacks.

Pass release (or set LEMMA_RELEASE) to stamp the running app version on every ingest payload. An explicit constructor value wins. Empty or invalid values are omitted.

Live Spans

def run(trace):
    span = trace.start_span(name="retrieve-context", input=query)
    try:
        docs = retrieve(query)
        span.end(output={"count": len(docs)})
        return docs
    except Exception as error:
        span.end(status="ERROR", error=error)
        raise

Live handles know their start time when created and their end time when .end() is called, so you usually do not pass duration_ms. Pass duration_ms only when replaying historical work or overriding the measured duration with a value from another timer.

For one-off records where you already measured the work, pass duration_ms on the record call:

trace.record_generation(
    name="answer",
    output=text,
    model="gpt-4o",
    duration_ms=measured_model_ms,
)

User-facing messaging tools

When a tool delivers the agent's response to the end user, pass the exact display text as user_facing_message. Lemma renders that text as an assistant message while preserving the complete tool input and output in the span detail:

tool_input = {
    "message": "Your order arrives Friday.",
    "send_as_voice_note": False,
    "should_terminate": True,
}

trace.record_tool(
    name="send_whatsapp",
    input=tool_input,
    output={"delivered": True},
    user_facing_message=tool_input["message"],
)

The tool's own schema can call the value message, text, body, or anything else. Lemma never guesses which input field the user saw. Omit user_facing_message for internal tools; their payload and rendering are unchanged.

The same handle pattern is available for tool calls and generations:

tool = trace.start_tool(name="search_docs", input={"query": query})
docs = search_docs(query)
tool.end(output=docs)

generation = trace.start_generation(name="answer", input=messages)
response = call_model(messages)
generation.end(output=response.text)

Sending a Trace You Built Yourself

trace() assumes the client owns the trace lifecycle within a single process. When the producer lives elsewhere — a cross-process buffer, a queue worker, a batch backfill — build a TraceContext yourself and deliver it with ingest():

from uselemma_tracing import Lemma, TraceContext

lemma = Lemma()

context = TraceContext(
    id=turn_id,  # stable id for this execution (use for retries)
    name=prompt,
    input=prompt,
    thread_id=conversation_id,
)
context.record_tool(name="search_docs", input=query, output=docs, duration_ms=25)
context.record_generation(name="answer", model="gpt-4o", output=final_answer)
context.output(final_answer)

lemma.ingest(context, started_at=started_at)

ingest() POSTs one payload. Deliver one complete trace when the execution (agent turn) finishes: root input/output, thread/user, and all child spans in one call. This is required — patching a trace over time is not currently supported.

ingest() is not an incremental merge API: omitted root fields do not preserve prior values, and after Lemma processes the trace once, a later re-delivery does not re-run issue extraction (occasional late child spans may still append to the tree for display). Retries of the same complete payload are safe — already-stored span IDs are skipped — so a failed send can be retried as-is. It raises on a non-2xx response and never mutates the trace's status.

Automatic delivery (trace / async_trace) fails open: a Lemma ingest 4xx/5xx or network error is logged in debug mode and dropped so it cannot fail the caller's application. LangChain and OpenAI Agents flush through this path. Use ingest() when you need a failed send to raise so you can retry.

Cross-process turns

When a user turn spans a host and a sandbox such as E2B, record one trace. Export a context token on the host. The child records a journal with no API key. The host applies the journal and ingest()s once.

import json
from uselemma_tracing import Lemma, attach_turn

lemma = Lemma()
turn = lemma.start_turn(
    "agent-turn",
    input=user_message,
    thread_id=conversation_id,
)
sandbox = turn.start_span(name="e2b-sandbox")
token = json.dumps(turn.export(parent_span_id=sandbox.id))
# pass token to the child on the existing channel, then:
turn.apply(child_journal)
sandbox.end()
turn.end(output=answer)  # strict ingest

In the child, do not construct Lemma and do not call /traces/ingest:

import json
import os
from uselemma_tracing import attach_turn

local = attach_turn(os.environ["LEMMA_TURN"])
local.record_tool(name="search_docs", input=query, output=docs)
print(json.dumps(local.records()))

The journal uses the same camelCase schema as the TypeScript SDK, so a TypeScript host can apply a Python child's journal. assemble_turn(token, journal) builds a TraceContext when you already have the journal; then call ingest() once. Re-applying the same journal is idempotent (stable span ids). If the sandbox dies before a clean journal, end the host sandbox span as ERROR. Tools that started and never ended stay incomplete.

OpenAI Agents SDK

Install the OpenAI Agents extra and register the Lemma processor:

pip install "uselemma-tracing[openai-agents]" openai-agents
from agents import Agent, Runner
from uselemma_tracing import instrument_openai_agents

instrument_openai_agents()

agent = Agent(
    name="support-agent",
    instructions="Answer customer questions clearly and concisely.",
)

async def call_agent(user_message: str):
    result = await Runner.run(agent, user_message)
    return result.final_output

The processor creates one Lemma trace for each OpenAI Agents trace with root current-turn input, final output or terminal error, promoted thread_id / user_id, and wall-clock bounds from child spans. Generation/response spans become Lemma generations, function spans become Lemma tool spans, and parent IDs are preserved so tools stay nested under the generation or agent span that called them.

Pass OpenAI Agents group_id for thread_id and metadata user_id / userId for user_id. Call force_flush() / shutdown() to finalize open traces once.

Enable debug mode to validate live span shape while developing:

from uselemma_tracing import enable_debug_mode

enable_debug_mode()

Prompts, tool inputs, outputs, generated text, and error messages are always recorded — Lemma cannot show what a run consumed, produced, or why it failed without them.

LangChain and LangGraph

Install the optional integration dependency and pass langchain() as a callback handler. Each root run owns one Lemma trace with current-turn input, final output or root error, promoted thread_id / user_id, typed nested generations/tools/spans, and real wall-clock bounds. Call flush() / shutdown() to finalize open traces immediately. On long-lived hosts, traces that stay idle (no child start/end) past open_trace_ttl (default 2 hours) are finalized and sent, swept from every on_*_start at most every eviction_interval (default 5 minutes). A still-active long run is not evicted. Pass open_trace_ttl=None to disable. Stale traces are sent (same payload as flush()), not dropped.

pip install "uselemma-tracing[langchain]" langchain-openai
from langchain_openai import ChatOpenAI
from uselemma_tracing import langchain

handler = langchain(
    agent_name="support-agent",
    thread_id_key="conversation_id",
    user_id_key="user_id",
)
model = ChatOpenAI(model="gpt-4o", callbacks=[handler])
response = model.invoke(
    user_message,
    config={"metadata": {"conversation_id": thread_id, "user_id": user_id}},
)
handler.flush()

langgraph() is the same LangChain callback adapter with a LangGraph default trace name (langgraph-agent):

pip install "uselemma-tracing[langgraph]"
from uselemma_tracing import langgraph

result = graph.invoke(
    {"input": user_message},
    {"callbacks": [langgraph(agent_name="support-graph")]},
)

LangGraph middleware hooks often receive the full graph state, so one turn can POST megabytes of duplicated history. Drop hook nodes by exact name, fnmatch pattern, or predicate. Children nest under the nearest included ancestor. before_send, max_payload_bytes, and deduplicate_span_content are forwarded when the handler constructs Lemma:

handler = langgraph(
    exclude_span_names=["*.awrap_model_call"],
    # or include_span=lambda name: "awrap_model_call" not in name,
    max_payload_bytes=256_000,
)

Prompts, tool inputs, outputs, generated text, and error messages are recorded unless you drop the span or redact them in before_send.

Supported Contract Fields

Use native SDK keyword arguments for OpenInference-style fields:

  • LLM: llm_model_name, llm_provider, llm_system, llm_invocation_parameters, llm_input_messages, llm_output_messages, llm_tools, usage / input_tokens / output_tokens / cache and reasoning kwargs (omit when the provider did not supply them — never invent zeros), and prompt template fields
  • provenance: every span includes lemma.sdk.language and lemma.sdk.integration (manual by default; framework integrations override)
  • tools: tool_description, tool_parameters, user_facing_message
  • embeddings and rerankers: embedding_model_name, embedding_invocation_parameters, embedding_embeddings, reranker_model_name, reranker_input_documents, reranker_output_documents

Use attributes for raw attributes that do not yet have a native SDK keyword.

Configuration

Option Environment variable Default
api_key LEMMA_API_KEY Required
project_id LEMMA_PROJECT_ID Required
base_url none https://api.uselemma.ai
before_send none none
max_payload_bytes none none (no cap)
deduplicate_span_content none False

The SDK sends to {base_url}/traces/ingest.

You can pass configuration directly to the constructor instead of using environment variables:

lemma = Lemma(
    api_key="sk_...",
    project_id="proj_...",
    base_url="https://api.uselemma.ai",
)

Redacting, dropping, and shrinking payloads

before_send runs on the assembled ingest dict after optional SDK shaping (content dedup and payload cap) and before JSON serialization. Return a payload to send, or None to drop the request. Transport, User-Agent, and error handling stay with the SDK — you do not need a fake transport to scrub PHI.

from uselemma_tracing import STRUCTURAL_PAYLOAD_KEYS, Lemma

def scrub(payload):
    # Drop a trace you must not export:
    # return None
    payload["trace"]["input"] = "[redacted]"
    return payload

lemma = Lemma(before_send=scrub)

If before_send raises, ingest() raises so you can retry; automatic delivery (trace / LangChain flush) fails open and does not send. Returning None is a successful drop on both paths.

Structural keys identify, time, and classify the tree. Redactors must keep them (and should leave __lemma_truncated__ / __lemma_deduplicated__ markers in place, scrubbing only preview text if needed):

  • envelope: project_id
  • identities: id, parent_id, thread_id, user_id
  • names: name, model, tool_name, release
  • timing: started_at, ended_at, duration_ms
  • classification: type, status, message role

max_payload_bytes replaces the largest input / output / error fields and oversized metadata / attributes values with an explicit marker (__lemma_truncated__, kind, original_bytes, plus preview or item_count / key_count). Structural keys are never replaced.

deduplicate_span_content=True replaces a span input that is byte-identical to its parent's input with {__lemma_deduplicated__: true, identical_to: "parent.input", parent_id: ...}. Outputs are left alone so a rewritten hook result is not discarded.

Debug Mode

Debug mode logs trace starts, span starts, span completions, send attempts, and send results as they happen:

from uselemma_tracing import enable_debug_mode

enable_debug_mode()

You can also set LEMMA_DEBUG=1 (true also works). Use this when validating that spans are created in the expected order and the SDK is sending to the intended URL.

Examples

Runnable docs-chat agents for every Python stack live in examples/python/. See Runnable examples.

This package also ships SDK API snippets in examples/.

License

MIT

Metadata

Release files for uselemma-tracing 7.12.2

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for uselemma-tracing 7.12.2
File Size Uploaded Provenance Actions
uselemma_tracing-7.12.2.tar.gz 42.2 kB Without provenance Details for uselemma_tracing-7.12.2.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for uselemma-tracing 7.12.2
File Interpreter ABI Platform Actions
uselemma_tracing-7.12.2-py3-none-any.whl Python 3 none any Details for uselemma_tracing-7.12.2-py3-none-any.whl

Total release size: 91.4 kB

Release files / uselemma_tracing-7.12.2.tar.gz

Download URL uselemma_tracing-7.12.2.tar.gz
Size 42.2 kB
Tags Source
SHA-256 checksum
How to use checksums
05ce120117f51cfed7d0a39975b7379ed959c58e9447c7583e6336e717f77900
BLAKE2b-256 checksum
How to use checksums
7178aadc430e4863fbc09d516012a8c2a4198f0f0a118e434c22f27adb7536f6
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.12.16 {"installer":{"name":"uv","version":"0.12.16","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Release files / uselemma_tracing-7.12.2-py3-none-any.whl

Download URL uselemma_tracing-7.12.2-py3-none-any.whl
Size 49.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
7a4fdff0852ebf9620e766be9de5dc1af80cabb1c114b7eaf03af8e8ec15271a
BLAKE2b-256 checksum
How to use checksums
c9fabb009dea3842b50730d05e56f6028d3daa7b19f70159eb79101bbba13819
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.12.16 {"installer":{"name":"uv","version":"0.12.16","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Security for uselemma-tracing 7.12.2

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

7.12.2 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page