neosigma
Trace your AI agents and ship the results to NeoSigma. Add a
few lines, run your agents as usual, and every run's model calls, tool calls, and
token usage lands in NeoSigma as a structured OpenTelemetry trace.
- Dark by default: with no API key (and
NEOSIGMA_CONSOLE_EXPORT=false) the SDK is
a complete no-op and never touches your application's own OpenTelemetry setup, so it's
safe to leave in place.
- Provider-agnostic: a small core with thin adapters that wrap the agent
framework you already use, with no hard dependency on any provider SDK.
Using JavaScript or TypeScript? See the TypeScript SDK.
Use cases
- Agent observability. See every model call, tool call, and token count from a run
as one trace, without hand-instrumenting each call.
- Product analytics joined to agent behavior.
capture() events and agent traces
share one turn_id, so a product signal (a click, a conversion) links to the exact
run behind it.
- Keep your existing stack. Dual-export the same traces to LangSmith, Braintrust,
or Langfuse, and mirror PostHog or Mixpanel events, with no migration.
- Move history in bulk. Import past traces from another provider, or export your own.
How it works
The SDK runs inside your application process. It builds spans on a private
OpenTelemetry provider (never the global one, unless you opt in), stamps each with the
ambient turn_id, and ships them to NeoSigma over OTLP/HTTP with your API key. Product
events take a parallel path through a background event sink. Both are bounded and
fail-open, so telemetry never blocks or breaks your app, and with no API key the SDK is
a complete no-op. The sections below cover each piece in detail.
Install
pip install neosigma
# or: uv add neosigma
Quickstart
import neosigma
neosigma.init() # reads NEOSIGMA_API_KEY from the environment
# ... trace your agent with the decorators or an adapter (below) and run as usual ...
neosigma.shutdown() # flush before exit (long-running servers flush in the background)
Managed agents
Running a Harbor benchmark? See the Harbor integration
for the optional plugin, Python API example, and a three-tool-call smoke task.
The same pip install neosigma distribution includes the Managed Agents API
client. Python packages do not use npm-style scoped names such as
@neosigma/managed-agents; import this client as neosigma.agents or
from the neosigma package root.
Set the API key once:
export NEOSIGMA_API_KEY="ns_live_..."
Then create the three durable resources and send work to the session:
from neosigma import NeoSigma
client = NeoSigma()
environment = client.environments.create(
project_id="YOUR_PROJECT_ID",
name="python-dev",
)
agent = client.agents.create(
workspace_id="YOUR_WORKSPACE_ID",
name="Coding assistant",
instructions="Make focused changes and run the relevant tests.",
model={"provider": "anthropic", "id": "sonnet"},
)
# Agent listings must be scoped to one workspace or project.
agents = client.agents.list(workspace_id="YOUR_WORKSPACE_ID")
session = client.sessions.create(
agent_id=agent.agent.id,
environment_id=environment.environment.id,
)
client.sessions.events.send(
session_id=session.session.id,
messages=[{"content": "Fix the failing unit test."}],
)
events = client.sessions.events.list(session_id=session.session.id)
for event in events.items:
print(event.type, event.payload)
New agents use Pi when harness is omitted. Set harness="claude" for Claude
Code or harness="codex" for Codex. The selected model must support that harness.
agents.update requires an explicit harness and creates a new immutable version.
Existing sessions keep their pinned version.
Use the server catalogs to discover compatible models and execution limits:
models = client.models.list(limit=25)
for model in models.items:
print(model.id, model.provider, model.harnesses)
harnesses = client.harnesses.list(limit=25)
for harness in harnesses.items:
print(harness.id, harness.supports_mcp_tool_filters)
Both methods return items and next_cursor. Pass next_cursor as cursor to
read the next page until it is None. The same methods are available on
AsyncNeoSigma with await. Choose a harness from the selected model's
harnesses list. Native harnesses reject per-server MCP tool filters before
execution; use Pi when those filters are required.
Creating an agent also creates its backing project and trace project. Managed session runs are
traced automatically to that project. Open Traces in NeoSigma and select the
project named after the agent. Your application does not initialize tracing or
configure a trace project.
The resource layout follows the API operation names:
client.models.list and client.harnesses.list
client.agents.create, update, get, list, and versions.list
client.environments.create, update, get, list, and versions.list
client.sessions.create, get, list, interrupt, events.list, and
events.send. Pass vault_ids to sessions.create when the session needs
credentials from workspace vaults.
List methods return items and an optional next_cursor. Send that cursor back
unchanged to get the next page. AsyncNeoSigma exposes the same resource layout
with await. The production API is the default. To test against the development
contract, pass base_url="https://api.dev.neosigma.ai" or set
NEOSIGMA_MANAGED_AGENTS_BASE_URL.
Agent skills are typed references. For a workspace skill, pass
AgentCustomSkill(name="my-skill"). You can pin a version with
AgentCustomSkill(name="my-skill", version=3).
Updating the generated API layer
api/agents.json at the repository root is the committed source for the private generated models
and endpoint functions under neosigma.agents._generated. The public resource
classes are thin, stable argument-shaping wrappers over those functions. Do not
edit generated files directly.
Refresh the scoped snapshot from the live specification and regenerate:
uv run python scripts/generate_agents_sdk.py \
--source https://api.dev.neosigma.ai/openapi.json
Check for generated drift without writing files:
uv run python scripts/generate_agents_sdk.py --check
The refresh keeps only agents.*, environments.*, and sessions.* paths and
their transitively referenced schemas. CI generates from the committed snapshot,
not the network, and fails when generated files are stale.
Tracing your agents
A few ways to produce spans, and they compose: anything traced while an interaction is
active nests under it, so one run is one trace.
-
Decorators mark a run and its steps, with no framework required. @interaction is
the run; @tool is a step inside it.
@neosigma.tool()
def search(query: str) -> list[str]:
...
@neosigma.interaction()
def answer(question: str) -> str:
hits = search(question) # nested under the interaction
...
-
turn() / finish() track a run whose lifecycle spans multiple functions, where a
single decorator cannot wrap the whole thing. One user message is one trace: turn()
always opens a fresh root, tied to a session_id and a turn_id (minted, or supplied)
that is also the join key for capture() events below.
t = neosigma.turn(session_id="sess_123", user_message=question, distinct_id="user_123")
t.set_attributes({"plan": "pro"}) # attach metadata/tags to the run
reply = run_agent(question) # tool and LLM calls nest under this run
t.finish(output=reply)
With NEOSIGMA_CAPTURE_CONTENT=false, set_attributes() and the attributes= option
of neosigma.span() write nothing, since the values are your data.
-
Auto-instrumentation traces raw LLM clients (Anthropic, OpenAI) with no per-call
code: install the instrumentation extra and call neosigma.init(tracing_enabled=True).
import anthropic
neosigma.init(tracing_enabled=True) # turn on the off-the-shelf instrumentors
client = anthropic.Anthropic()
client.messages.create(...) # this call is now a traced span
See the documentation for the full API and configuration.
Product events and the turn_id spine
Agent traces tell you what the model did. Product events tell you what the user did
(a button click, a feature used, a conversion). NeoSigma joins the two streams on a
single id, the turn_id, so you can go from "this user clicked rewind" to "here is
the exact agent trace behind it" without stitching timestamps.
turn_id is the durable correlation key. One turn is one user message plus
everything the agent did in response; a session is a series of turns. You supply
the id, bind it once, and from then on:
- every span opened inside the turn carries it (stamped by the
CorrelationSpanProcessor,
so adapters, auto-instrumented LLM clients, and your own spans all pick it up with no
per-framework code), and
- every product event you
capture() inside the turn carries the same value.
Both land in NeoSigma keyed on turn_id, and join there.
Binding the turn
Use trace() when the span is produced elsewhere (an adapter or auto-instrumented
client), or turn() / @interaction to also open a root span. Both bind the same
ambient ids:
import neosigma
neosigma.init()
with neosigma.trace(turn_id="turn_abc", distinct_id="user_123"):
reply = run_agent(question) # any spans here carry turn_abc
neosigma.capture("agent_answered", # this event carries turn_abc too
{"helpful": True, "latency_ms": 820})
Contextvars propagate across await within a task, but not across a process or queue
hop. Across such a boundary, thread the turn_id into the job payload and re-bind it on
the far side (with neosigma.trace(turn_id=...) or neosigma.turn(turn_id=...)).
Routing a turn to a project
Declare a project on the turn and every span in it carries neosigma.project, which
takes precedence over the process-wide project set at init(). Use it when one process
serves several projects.
with neosigma.turn(project="acme-support", session_id=session_id) as current:
reply = run_agent(question)
# Or when the project is only known after the turn opens:
with neosigma.turn(session_id=session_id) as current:
current.set_project(resolve_project(question))
Four things worth knowing:
- A trace has one project, and the first declaration wins. A second, differing one is a
conflict rather than an update, so it warns and the first one stands. This keeps a
framework default from silently overwriting a project you declared yourself.
- A nested
turn() inside a trace that has no project yet declares for the whole trace,
which is how you declare when a framework or middleware owns the outer turn. Inside a
trace that already has one it warns and inherits.
- Spans that started before the declaration stay unlabelled. They cannot be re-stamped
once open, and labelling them later would leave one trace disagreeing with itself. The
trace root is still open, so it does take the project. Prefer
turn(project=...) when
you can.
set_attributes refuses neosigma.project. Routing comes from a declaration, never
from forwarded metadata, so user-supplied data cannot pick the project.
Across a process or queue hop, thread the resolved project alongside the turn_id and
pass it back in (neosigma.trace(turn_id=..., project=...)). Pass the value you were
given rather than recomputing it on the far side, whose configuration may differ.
Serving many projects from one HTTP service? The FastAPI middleware owns the turn, so
declare the project there rather than in the handler:
app.add_middleware(
NeosigmaTurnMiddleware,
project_resolver=lambda request: request.headers.get("x-tenant", ""),
)
project_resolver takes precedence over the static project= argument, and falls back to
it when the resolver returns "" or raises. A failing tenant lookup costs the label, never
the request.
An adapter that opens its own traces takes a project too, for a process that
runs several agents belonging to different projects:
async for message in neosigma.trace_claude(query(prompt=...), project="agent-one"):
...
client = neosigma.wrap_managed_agents(anthropic_client, project="agent-two")
That binds the project for every trace the adapter opens, so it fits one agent
per project, not one project per request. For a multi-tenant service sharing a
client, declare on the enclosing turn instead. Omitted, an adapter inherits
whatever turn encloses it.
Product events carry the project too. capture() stamps the ambient turn's
project, and takes an explicit project= for a caller that knows the routing
without being inside the turn that owns it. An event emitted outside any turn
(telemetry-only mode, a wrapped analytics client, identify() at login) names
no project and resolves to the default.
Work handed to a thread follows the usual contextvar rules. asyncio.to_thread copies the
context, so the work stays in the turn. A bare threading.Thread or a
ThreadPoolExecutor.submit does not, so spans there are unlabelled. Re-bind explicitly
with neosigma.trace(turn_id=..., project=...) inside the worker if you need them
attributed.
A turn that is never finished releases its project once it is unreachable, so later spans
are unlabelled rather than mislabelled. One exception: an adapter stream abandoned
mid-iteration (a bare for ... break rather than with) does not release its turn, and
spans opened afterwards in that context can still carry it. Use with / async with
around adapter streams, which is the documented pattern anyway.
An unlabelled span is not an error. It routes to the default project, which is
recoverable in a way a wrong label is not.
Session metadata
Pass session_metadata to turn() to attach details about the session, such as a plan
or a customer tier. Each entry is stamped on the turn's root span as
neosigma.session.<key>.
with neosigma.turn(
session_id=session_id,
session_metadata={"plan": "pro", "seats": 3, "cohort": {"name": "beta"}},
):
reply = run_agent(question)
- At most 50 keys. A key may have at most 128 characters, and a value at most 1,000
characters once it is text. An entry over a limit is dropped, and the SDK warns the
first time and then once per 100 drops.
- Strings, numbers, booleans, and lists of one of those (
None entries allowed) stay
typed. A mapping or a mixed list is stored as JSON text. A None value is skipped.
Any other object, such as a datetime, UUID, Decimal, or set, is dropped, and
counts toward the drop warning. set_attributes follows the same rules.
- Lengths count characters (code points), so an emoji counts as one.
- With
NEOSIGMA_CAPTURE_CONTENT=false, no session metadata is recorded, plain strings
and numbers included. The SDK drops it without a warning.
- Only the root turn reads
session_metadata. A nested turn() ignores it and warns,
the same as it does for a different turn_id or session_id.
Uploading files
Call upload_artifact() inside the span that produced a local file or in-memory
bytes. The SDK records the managed artifact on that exact span right away, then
uploads the data to NeoSigma storage on background threads, up to four at a time.
It uses the active turn's project, or the project passed to init().
with neosigma.turn(project="acme-support", session_id=session_id):
report_path = build_report()
uploaded = neosigma.upload_artifact(
report_path,
name="Support report.csv",
)
print(uploaded.location)
In-memory bytes use the same operation and require a filename. A bytearray or
memoryview is copied when you call:
uploaded = neosigma.upload_artifact(
b"report contents",
name="Support report.txt",
)