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
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';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.
| TypeScript | Python | Default | Meaning |
|---|---|---|---|
apiKey | api_key | COGNIPEER_API_KEY | Console API token. Absent means tracing disables itself and warns once. |
baseUrl | base_url | COGNIPEER_BASE_URL, else https://console.cognipeer.com | Console host root. A legacy value ending in /api/client/v1 is accepted and trimmed. |
agent | agent | COGNIPEER_AGENT_NAME / COGNIPEER_AGENT_VERSION | Default agent identity stamped on every session — {name, version, model, provider}. |
metadata | metadata | — | Default attribution tags on every session. Short structured strings, merged with per-session values, never redacted or capped. |
threadId | thread_id | — | Default thread id. Usually set per conversation instead. |
enabled | enabled | COGNIPEER_TRACING_ENABLED, else true | Master switch. |
capture | capture | COGNIPEER_CAPTURE_CONTENT, else all | all, metadata (structure and tokens, no message bodies) or none. |
redactPatterns | redact_patterns | — | Extra regexes whose matches are replaced with [redacted], on top of the built-in API-key patterns. |
maxContentChars | max_content_chars | 50000 | Per-section content cap, so one oversized message cannot blow the ingest limit. |
mode | mode | COGNIPEER_TRACING_MODE, else auto | auto, stream or batch — see Delivery. |
streamAfterMs | stream_after_ms | 2000 | In auto mode, switch to streaming after this long. |
streamAfterEvents | stream_after_events | 25 | In auto mode, switch to streaming after this many events. |
timeout | timeout | 30 s | HTTP timeout per request. |
maxRetries | max_retries | 3 | Retry attempts for retryable failures. |
headers | headers | — | Extra headers on every request. |
debug | debug | COGNIPEER_DEBUG, else false | Log transport activity. |
onError | on_error | warn to the logger | Called instead of raising when the transport fails. |
logger | — | console | TypeScript only: sink for the SDK's own diagnostics. |
fetch | — | global fetch | TypeScript 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.
| TypeScript | Python | Returns | Notes |
|---|---|---|---|
client.enabled | client.enabled | boolean | True when traces are actually being shipped. |
client.startSession(options) | client.start_session(**options) | TraceSession | Opens a session. end() is what delivers it. |
client.trace(options, fn) | with client.trace(**options) as session | the callback's value | Session 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.
| TypeScript | Python | Default | Meaning |
|---|---|---|---|
name | name | the function's name | Event label. |
type | type | span | ai_call, tool_call, retrieval, embedding, summarization, guardrail, span. |
toolName | tool_name | — | Renders the event as a tool invocation. |
captureInput | capture_input | true | Record the arguments as an Input section. |
captureOutput | capture_output | true | Record the return value as an Output section. |
metadata | metadata | — | Extra 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.
await trace({ name: 'research-agent', threadId: 'conv-42' }, async (session) => { /* … */ });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.
| TypeScript | Python | Meaning |
|---|---|---|
sessionId | session_id | Fixed session id. Re-posting the same one updates that session instead of creating another. |
threadId | thread_id | Conversation key, grouping runs in Tracing → Threads. |
agent | agent | {name, version, model, provider}, merged over the client default. |
metadata | metadata | Attribution tags, merged over the client default. |
config | session_config | Free-form run configuration, shown on the session header. |
traceId | trace_id | W3C trace id, when you already have one. |
rootSpanId | root_span_id | Parent of every top-level event. |
mode | mode | Overrides the client delivery mode for this session. |
startedAt | started_at | Backdate 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.
| TypeScript | Python | Notes |
|---|---|---|
session.sessionId / traceId / rootSpanId | session.session_id / trace_id / root_span_id | Identity, 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. |
disabled | disabled | True 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
| TypeScript | Python | Meaning |
|---|---|---|
type | type | Event type; defaults to span. |
label | label | Timeline row title — node name, tool name or model name. |
parentKey | parent_key | Key of the parent span. Resolves to the root span when unknown. |
model | model | The provider's model id, not a nickname — cost resolution matches on it. |
actor | actor | {scope, name}, where scope is agent, model, tool, retriever or user. |
toolName | tool_name | |
toolExecutionId | tool_execution_id | Correlates the span with the model's tool-call id that requested it. |
sections | sections | Renderable blocks — messages, tool calls, tool results. |
toolDefinitions | tool_definitions | The tool menu the model was offered on this call. |
responseFormat | response_format | The structured-output contract enforced on this call. |
metadata | metadata | Free-form; rendered as a key/value block. |
startedAt | started_at | Backdate the span start. |
Closing a span
| TypeScript | Python | Meaning |
|---|---|---|
status | status | success or error; an error argument implies error. |
error | error | Attach the exception. The step is marked failed and the session collects it. |
sections | sections | Appended to whatever the open call recorded. |
inputTokens | input_tokens | |
outputTokens | output_tokens | |
cachedInputTokens | cached_input_tokens | A subset of the input tokens — see Tokens. |
reasoningTokens | reasoning_tokens | A subset of the output tokens; never billed on top. |
totalTokens | total_tokens | |
finishReason | finish_reason | Why the model stopped: stop, tool_calls, length, content_filter. |
label / model / toolName | label / model / tool_name | Override what the open call recorded. |
toolDefinitions / responseFormat / metadata | tool_definitions / response_format / metadata | Same fields as on open, for what you only learn at the end. |
endedAt | — | TypeScript only: backdate the span end. |
toolExecutionId | — | TypeScript 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
- Data Model — what each field does to the UI and to cost accounting
- Manual instrumentation — the same API as a worked example, plus the plain-HTTP route
- Tracing API reference — the raw endpoint shapes underneath

