Skip to content

Observability · Reference

API reference

The core surface of both packages, side by side. The two libraries mirror each other deliberately — same concepts, same option names in each language's casing — so a mapping written in one reads as a translation of the other.

This page covers the core: configuration, the client, the two wrappers and the session primitive. The framework symbols behind each subpath or submodule are documented with their wiring, in the Console integration guides. The wire-level meaning of every field — event types, section kinds, token semantics, identifier rules — is in Data Model.

Entry points

ts
import {
  init,          // configure the default client (idempotent, safe to call once at boot)
  getClient,     // the resolved CognipeerObservability instance
  resetClient,   // mostly for tests
  observe,       // wrap an async function as a traced span
  trace,         // open a session around a block of work
  TraceSession,  // the session primitive every integration is built on
  flush,         // await before a short-lived process (script, Lambda, CI job) exits
  shutdown,      // end every open session and flush; safe to call more than once
} from '@cognipeer/observability';
python
from cognipeer_observability import (
    init,               # configure the process-wide client (call once at boot)
    get_client,         # the resolved Cognipeer instance
    reset_client,       # mostly for tests
    observe,            # decorator: wrap a function or coroutine as a traced span
    trace,              # context manager: open a session around a block of work
    TraceSession,       # the session primitive every integration is built on
    use_session,        # context manager: bind the active session
    use_span,           # context manager: bind the active parent span
    flush,              # block until every queued trace is delivered
    shutdown,           # end every open session and flush; safe to call more than once
)

Both packages also export their type definitions (TraceEvent / Event, TraceSection / Section, TraceAgent / Agent, TraceToolDefinition / ToolDefinition, TraceSummary / Summary), the environment-variable names (ENV in TypeScript, ENV_API_KEY and friends in Python), and the identifier and redaction helpers used internally (newSessionId, newTraceId, newSpanId, spanIdFrom, traceIdFrom, redactString, stringifyContent in TypeScript). Python additionally exports get_current_session and get_current_span_key.

init() options

Every option falls back to its environment variable, and an explicit value wins. Call it once at boot, before creating agents. Calling it again replaces the client and flushes the previous one.

TypeScriptPythonDefaultMeaning
apiKeyapi_keyCOGNIPEER_API_KEYConsole API token. Absent means tracing disables itself and warns once.
baseUrlbase_urlCOGNIPEER_BASE_URL, else https://console.cognipeer.comConsole host root. A legacy value ending in /api/client/v1 is accepted and trimmed.
agentagentCOGNIPEER_AGENT_NAME / COGNIPEER_AGENT_VERSIONDefault agent identity stamped on every session — {name, version, model, provider}.
metadatametadataDefault attribution tags on every session. Short structured strings, merged with per-session values, never redacted or capped.
threadIdthread_idDefault thread id. Usually set per conversation instead.
enabledenabledCOGNIPEER_TRACING_ENABLED, else trueMaster switch.
capturecaptureCOGNIPEER_CAPTURE_CONTENT, else allall, metadata (structure and tokens, no message bodies) or none.
redactPatternsredact_patternsExtra regexes whose matches are replaced with [redacted], on top of the built-in API-key patterns.
maxContentCharsmax_content_chars50000Per-section content cap, so one oversized message cannot blow the ingest limit.
modemodeCOGNIPEER_TRACING_MODE, else autoauto, stream or batch — see Delivery.
streamAfterMsstream_after_ms2000In auto mode, switch to streaming after this long.
streamAfterEventsstream_after_events25In auto mode, switch to streaming after this many events.
timeouttimeout30 sHTTP timeout per request.
maxRetriesmax_retries3Retry attempts for retryable failures.
headersheadersExtra headers on every request.
debugdebugCOGNIPEER_DEBUG, else falseLog transport activity.
onErroron_errorwarn to the loggerCalled instead of raising when the transport fails.
loggerconsoleTypeScript only: sink for the SDK's own diagnostics.
fetchglobal fetchTypeScript only: custom fetch, for tests, proxies or non-Node runtimes.

init() returns the client, so const client = init({...}) and client = cognipeer.init(...) both work.

The client

CognipeerObservability in TypeScript, Cognipeer in Python. getClient() / get_client() returns the process-wide instance, building it from the environment on first use — so integrations can be wired up unconditionally, and a missing key simply yields a disabled client.

TypeScriptPythonReturnsNotes
client.enabledclient.enabledbooleanTrue when traces are actually being shipped.
client.startSession(options)client.start_session(**options)TraceSessionOpens a session. end() is what delivers it.
client.trace(options, fn)with client.trace(**options) as sessionthe callback's valueSession that closes itself, including on throw.
client.flush()client.flush(timeout)Waits for the queue to drain.
client.shutdown()client.shutdown(timeout)Ends every open session, then flushes.

The module-level flush() and shutdown() are shorthands for the same methods on the default client.

observe

Wraps a function so every call becomes one event. Nesting is automatic — a wrapped function called from inside another becomes its child span — and when no session is active, the outermost call opens one and closes it when it settles.

TypeScriptPythonDefaultMeaning
namenamethe function's nameEvent label.
typetypespanai_call, tool_call, retrieval, embedding, summarization, guardrail, span.
toolNametool_nameRenders the event as a tool invocation.
captureInputcapture_inputtrueRecord the arguments as an Input section.
captureOutputcapture_outputtrueRecord the return value as an Output section.
metadatametadataExtra key/values on the event.

In TypeScript it is a wrapper: observe(fn, options). In Python it is a decorator, usable bare or with arguments, and it handles sync, async def, generator and async-generator functions — see the four forms.

trace

Opens a session, binds it as the ambient one, and closes it at the end of the block. On an exception the session is marked error and the exception is re-raised untouched — tracing never swallows an application error.

ts
await trace({ name: 'research-agent', threadId: 'conv-42' }, async (session) => { /* … */ });
python
with trace(name="research-agent", thread_id="conv-42") as session:
    ...

It accepts every session option below, plus name — a shorthand for agent: {name}, which is what the Agents screen and cost reports group by.

Session options

Passed to startSession / start_session and to trace.

TypeScriptPythonMeaning
sessionIdsession_idFixed session id. Re-posting the same one updates that session instead of creating another.
threadIdthread_idConversation key, grouping runs in Tracing → Threads.
agentagent{name, version, model, provider}, merged over the client default.
metadatametadataAttribution tags, merged over the client default.
configsession_configFree-form run configuration, shown on the session header.
traceIdtrace_idW3C trace id, when you already have one.
rootSpanIdroot_span_idParent of every top-level event.
modemodeOverrides the client delivery mode for this session.
startedAtstarted_atBackdate the session start.

Ids you do not supply are generated. Ids you do supply are folded to W3C shape deterministically — 32 hex for a trace id, 16 for a span id — by hashing anything that is not already the right length. See Identifiers for why truncation is not used.

TraceSession

The primitive every shipped integration is built on. A span is opened under a key of your choosing and closed later; the key links a child to its parent and is folded into a span id, so a child can name a parent it never held a reference to.

TypeScriptPythonNotes
session.sessionId / traceId / rootSpanIdsession.session_id / trace_id / root_span_idIdentity, readable for correlation.
openSpan(key, init)open_span(key, **init)Nothing is sent yet.
hasSpan(key)has_span(key)Lets an integration stay idempotent.
updateSpan(key, patch)update_span(key, **patch)Amend an open span before it closes.
closeSpan(key, close)close_span(key, **close)Emits the event, with the duration measured for you.
record(event)record(event)Emit a complete event directly, for a step with no duration to measure.
end({status, error})end(status=…, error=…)Delivers the session. Still-open spans are closed automatically.
setThreadId(id) / setAgent(agent)set_thread_id(id) / set_agent(agent)Fill in identity discovered mid-run.
getSummary()get_summary()Running totals — tokens, duration, event counts.
flush()flush(timeout)Wait for this session's deliveries.
disableddisabledTrue when the transport is off, so an integration can skip the mapping work entirely.

The event is emitted on close, not on open, so one framework start/end pair becomes exactly one Console event carrying both sides.

Opening a span

TypeScriptPythonMeaning
typetypeEvent type; defaults to span.
labellabelTimeline row title — node name, tool name or model name.
parentKeyparent_keyKey of the parent span. Resolves to the root span when unknown.
modelmodelThe provider's model id, not a nickname — cost resolution matches on it.
actoractor{scope, name}, where scope is agent, model, tool, retriever or user.
toolNametool_name
toolExecutionIdtool_execution_idCorrelates the span with the model's tool-call id that requested it.
sectionssectionsRenderable blocks — messages, tool calls, tool results.
toolDefinitionstool_definitionsThe tool menu the model was offered on this call.
responseFormatresponse_formatThe structured-output contract enforced on this call.
metadatametadataFree-form; rendered as a key/value block.
startedAtstarted_atBackdate the span start.

Closing a span

TypeScriptPythonMeaning
statusstatussuccess or error; an error argument implies error.
errorerrorAttach the exception. The step is marked failed and the session collects it.
sectionssectionsAppended to whatever the open call recorded.
inputTokensinput_tokens
outputTokensoutput_tokens
cachedInputTokenscached_input_tokensA subset of the input tokens — see Tokens.
reasoningTokensreasoning_tokensA subset of the output tokens; never billed on top.
totalTokenstotal_tokens
finishReasonfinish_reasonWhy the model stopped: stop, tool_calls, length, content_filter.
label / model / toolNamelabel / model / tool_nameOverride what the open call recorded.
toolDefinitions / responseFormat / metadatatool_definitions / response_format / metadataSame fields as on open, for what you only learn at the end.
endedAtTypeScript only: backdate the span end.
toolExecutionIdTypeScript only on close; Python sets it on open.

Absent, not zero

Leave a token field unset when the framework did not report one. A zero silently under-reports spend, while an absent value shows up in Console as unknown and can be chased.

See also

Studio · Pulse · Console · Agent SDK and more — the Cognipeer documentation hub