Cogitator
Deployment

Observability

Trace agent executions with Langfuse and OpenTelemetry, with GenAI semantic conventions, one trace across runs, cost tracking and content capture.

Overview

Cogitator ships two observability exporters in @cogitator-ai/core: Langfuse for AI-native tracing with cost tracking, and OpenTelemetry (OTLP) for standard distributed tracing. Neither is attached automatically: pass them to a runtime's observers, register them for the whole process with registerTelemetry, or connect them to the run callbacks (onRunStart, onToolCall, onToolResult, onSpan, onRunComplete, onRunError) that cog.run() accepts.

Spans follow the OpenTelemetry GenAI semantic conventions, so any GenAI-aware backend reads them without custom mapping, and runs that belong together (an agent called as a tool, the agents of a workflow or a swarm) share one trace.

Both exporters are off unless you pass enabled: true; a disabled exporter accepts every call and does nothing, which makes it easy to toggle per environment.

Spans

Every run produces spans, returned in result.trace.spans and streamed one by one to onSpan as they finish:

SpanKindAttributes
agent.runinternalagent.id, agent.name, agent.model, run.id, run.thread_id, run.iterations, run.tool_calls, run.input_tokens, run.output_tokens
llm.chatclientllm.model, llm.iteration, llm.input_tokens, llm.output_tokens, llm.cost, llm.cached_input_tokens, llm.reasoning_tokens, llm.finish_reason
tool.<name>internaltool.name, tool.call_id, tool.arguments, tool.success, tool.error
agent.handoffinternalhandoff.from, handoff.to

The root agent.run span is emitted last (when the run ends). A failed run emits it with status error, an error attribute and error.type (the Cogitator error code, such as RUN_TIMEOUT, else the error's class).

Trace and span ids are W3C ids: 32 hex characters for a trace, 16 for a span.

GenAI Semantic Conventions

Next to the attributes above, which stay for compatibility, every span carries the gen_ai.* attributes of the OpenTelemetry GenAI conventions. The GEN_AI constant in @cogitator-ai/core names them all.

Spangen_ai.operation.nameAttributes
agent.runinvoke_agentgen_ai.agent.id, gen_ai.agent.name, gen_ai.agent.description, gen_ai.request.model, gen_ai.conversation.id, gen_ai.usage.*
llm.chatchatgen_ai.provider.name, gen_ai.request.model, gen_ai.request.temperature, gen_ai.request.top_p, gen_ai.request.max_tokens, gen_ai.request.stop_sequences, gen_ai.request.stream, gen_ai.response.id, gen_ai.response.finish_reasons, gen_ai.response.time_to_first_chunk, gen_ai.usage.input_tokens, gen_ai.usage.output_tokens, gen_ai.usage.cache_read.input_tokens, gen_ai.usage.cache_write.input_tokens, gen_ai.usage.reasoning.output_tokens, gen_ai.conversation.id
tool.<name>execute_toolgen_ai.tool.name, gen_ai.tool.call.id, gen_ai.tool.type, gen_ai.conversation.id, error.type when the tool failed
llm.decidechatgen_ai.provider.name, gen_ai.request.model, gen_ai.response.id, gen_ai.usage.*
workflow.runinvoke_workflowgen_ai.workflow.name, workflow.id
swarm.runinvoke_workflowgen_ai.workflow.name, swarm.id, swarm.strategy

gen_ai.provider.name uses the convention's names where it has one (openai, anthropic, gcp.gemini for Google, azure.ai.openai, aws.bedrock, mistral, groq, deepseek) and the backend's own name otherwise (ollama, vllm, openrouter, a custom backend). gen_ai.response.time_to_first_chunk is the time in seconds from the request to the first chunk of a streamed answer, recorded on streamed calls only.

Recording Prompts and Answers

What the model was sent and answered is sensitive and often large, so it is off by default. Turn it on for a runtime:

const cog = new Cogitator({ telemetry: { captureContent: true } });

Model call spans then carry gen_ai.system_instructions, gen_ai.input.messages, gen_ai.output.messages and gen_ai.tool.definitions, and tool spans gen_ai.tool.call.arguments and gen_ai.tool.call.result, as JSON strings in the convention's shapes:

[{ "role": "user", "parts": [{ "type": "text", "content": "What is the weather in Paris?" }] }]

An observer can also ask for content for itself with captureContent: true. Content is then recorded while it watches, and only the observers that asked for it receive it: the others, the run's own onSpan and result.trace.spans get the spans without those attributes. This is how Cogitator Studio shows the prompt and the answer of every model call without sending them to your OTLP backend.

One Trace Across Runs

A run started inside a tool of another run (an agent used as a tool, or any cog.run() in your tool's code) joins that run's trace, its agent.run span a child of the tool's span. Workflows and swarms do the same for their agents:

  • a workflow puts each agent run under its node span when a workflow tracer is on, else under a workflow.run span it reports to the runtime's observers
  • a swarm reports a swarm.run span and runs its agents under it, also on workers of a distributed swarm
  • a paused run reports its agent.run span with status unset and run.status: paused, and cog.resume() continues the same trace under it

To put a run into a trace that started elsewhere, such as an incoming HTTP request, pass its parent:

import { parseTraceparent } from '@cogitator-ai/core';

const parent = parseTraceparent(request.headers.get('traceparent') ?? '');
const result = await cog.run(agent, { input, ...(parent && { trace: parent }) });

formatTraceparent(traceId, spanId) writes the header for a call going out, and withTraceContext(parent, work) makes every run started inside work join parent.

Every Runtime of a Process

registerTelemetry watches the runs of every Cogitator in the process, whoever builds it (a server adapter, a workflow, a swarm), until the function it returns is called. Decisions and the spans of workflows and swarms reach it too:

import { createOTLPExporter, registerTelemetry } from '@cogitator-ai/core';

const otlp = createOTLPExporter({ endpoint: 'http://localhost:4318/v1/traces', enabled: true });
otlp.start();
const unregister = registerTelemetry(otlp.observer());

cog.close() does not close a registered observer: whoever registers it flushes and stops it. Register an exporter in one place only: otlp.observer() makes a new observer each call, so the same exporter in a runtime's observers and in registerTelemetry exports every span twice. cog.recordSpan(span, { runId }) reports a span of your own orchestration to everything watching a runtime, the same way. Langfuse keeps one trace per run, so it shows the agent runs of a workflow or a swarm, not the workflow.run and swarm.run spans around them.

Langfuse Integration

Langfuse provides purpose-built observability for LLM applications: traces, generations, cost analysis, and evaluation scores. The langfuse SDK is an optional peer dependency:

pnpm add langfuse
import { createLangfuseExporter } from '@cogitator-ai/core';

const langfuse = createLangfuseExporter({
  publicKey: process.env.LANGFUSE_PUBLIC_KEY!,
  secretKey: process.env.LANGFUSE_SECRET_KEY!,
  baseUrl: 'https://cloud.langfuse.com',
  flushAt: 10,
  flushInterval: 5000,
  enabled: true,
});

await langfuse.init(); // throws when `langfuse` is not installed

Every Run of a Runtime

langfuse.observer() turns every run of a runtime into a trace with its spans, output and usage, and cog.close() shuts the exporter down after flushing:

await langfuse.init();
const cog = new Cogitator({ observers: [langfuse.observer()] });

Wiring a Run

To trace one run with tool calls as their own spans, wire its callbacks. Each run becomes a Langfuse trace (id = run id, session = thread id, tagged cogitator and the agent name), and tool calls become tool:<name> spans on it:

let currentRunId = '';

const result = await cog.run(agent, {
  input: 'Summarize recent papers on chain-of-thought reasoning',
  onRunStart: ({ runId, agentId, input, threadId }) => {
    currentRunId = runId;
    langfuse.onRunStart({
      runId,
      agentId,
      agentName: agent.name,
      input,
      threadId,
      model: agent.model,
    });
  },
  onToolCall: (call) => langfuse.onToolCall(currentRunId, call),
  onToolResult: (toolResult) => langfuse.onToolResult(currentRunId, toolResult),
  onRunComplete: (runResult) => langfuse.onRunComplete(runResult),
});

onToolCall and onToolResult do not carry the run id, so keep the one from onRunStart in a variable scoped to the run. onRunComplete writes the output, token usage and tool-call count to the trace and releases its state.

Generations and Custom Spans

For LLM calls you make yourself (or to record finished onSpan spans), use the lower-level hooks:

const generationId = langfuse.onLLMCall({
  runId,
  model: 'openai/gpt-5.5',
  messages: [{ role: 'user', content: 'Summarize recent papers...' }],
  temperature: 0.7,
  maxTokens: 4096,
});

langfuse.onLLMResponse({
  generationId,
  output: 'Here is a summary...',
  inputTokens: 150,
  outputTokens: 820,
});

const span = {
  id: 'span_rerank',
  traceId: 'trace_abc123',
  name: 'rerank',
  kind: 'internal' as const,
  startTime: Date.now(),
  attributes: { candidates: 20 },
};
langfuse.onSpanStart(runId, span);
langfuse.onSpanEnd({
  ...span,
  status: 'ok',
  endTime: Date.now(),
  duration: 0,
  attributes: { ...span.attributes, output: ['doc-3', 'doc-7'] },
}); // the span's output is `attributes.output`

onLLMCall and onSpanStart take an optional parent (spanId / span.parentId) and fall back to the trace. Hooks for a run that was never started return quietly (onLLMCall returns '').

OpenTelemetry (OTLP)

For teams using Jaeger, Grafana Tempo, Honeycomb or Datadog, the OTLP exporter sends spans as OTLP/HTTP JSON.

import { createOTLPExporter } from '@cogitator-ai/core';

const otlp = createOTLPExporter({
  endpoint: 'http://localhost:4318/v1/traces',
  serviceName: 'cogitator-production', // default 'cogitator'
  serviceVersion: '1.0.0', // default '1.0.0'
  headers: { Authorization: `Bearer ${process.env.OTLP_TOKEN}` },
  enabled: true,
});

otlp.start(); // flush every 5 seconds

To export every span of every run of a runtime, pass the exporter's observer in the config. cog.close() stops the exporter and flushes what is pending:

const cog = new Cogitator({ observers: [otlp.observer()] });

cog.observe(otlp.observer()) attaches it to a runtime that is already built. For one run only, wire the run callbacks:

let runId = '';
await cog.run(agent, {
  input: 'Hello',
  onRunStart: (data) => {
    runId = data.runId;
  },
  onSpan: (span) => otlp.exportSpan(runId, span),
});

You can also export spans after the fact, with result.trace.spans.forEach((span) => otlp.exportSpan(result.runId, span)), or build your own Span objects:

import { newSpanId, newTraceId } from '@cogitator-ai/core';

otlp.exportSpan('run_abc123', {
  id: newSpanId(),
  traceId: newTraceId(),
  name: 'agent.run',
  kind: 'internal',
  status: 'ok',
  startTime: Date.now() - 1500,
  endTime: Date.now(),
  duration: 1500,
  attributes: { 'agent.name': 'researcher', 'llm.model': 'openai/gpt-5.5' },
});

await otlp.flush();

Spans are batched and flushed every 5 seconds after start(), or as soon as 100 spans are pending.

Cogitator ids already are the hex ids OTLP needs (16 bytes for a trace, 8 for a span) and are sent as they are. Ids of another shape, such as those in traces saved by older versions, are turned into OTLP ids with SHA-256, so parent links stay intact. The original ids, the run id and the span's Cogitator name are kept as the cogitator.trace_id, cogitator.span_id, cogitator.run_id and cogitator.span_name attributes.

Spans are exported under the convention's names, {operation} {target}: chat gpt-5.5, execute_tool search, invoke_agent researcher, invoke_workflow onboarding. Spans that are not GenAI operations, such as agent.handoff, keep their own name. Numbers, booleans and strings keep their types as OTLP attribute values, arrays are sent as arrays, and objects as JSON strings.

A batch the collector refuses with a 4xx status is dropped and logged; on network errors, 408, 429 and 5xx it is kept and sent again with the next flush, up to 10,000 pending spans.

OTLPExporter also has onRunStart, onRunComplete and onRunError hooks. They do nothing (ids come from the spans themselves) and exist so you can wire both exporters to the same callbacks.

Span Kinds

Cogitator KindOTLP KindEmitted by
internalINTERNALagent.run, tool.<name>, agent.handoff, workflow.run, swarm.run
clientCLIENTllm.chat, llm.decide
serverSERVERAvailable for your own spans (e.g. an API call)
producerPRODUCERAvailable for your own spans (e.g. queue jobs)
consumerCONSUMERAvailable for your own spans (e.g. worker jobs)

Span status maps to OTLP OK, ERROR or UNSET.

Cost Tracking

Every run reports its cost in result.usage.cost (USD, from the model registry prices) alongside inputTokens, outputTokens, cachedInputTokens and reasoningTokens. The llm.chat spans carry per-call token counts, so any OTLP backend can aggregate them by llm.model.

Langfuse computes cost from the token usage of generations; with onRunComplete the run's usage (including cost) is attached to the trace metadata. Group costs by agent (trace name), model, or session (thread) in the Langfuse dashboard.

Shutdown

With the exporters in observers, await cog.close() flushes them. Wired by hand, flush them before the process exits to avoid losing buffered data:

process.on('SIGTERM', async () => {
  await langfuse.flush();
  await langfuse.shutdown();
  otlp.stop();
  await otlp.flush();
});

On this page