Skip to content

Tracing API ​

The SDK supports tracing in four complementary ways:

  1. Bulk ingestion via client.tracing.ingest(...) (one full session per call).
  2. Streaming ingestion via startStream / appendEvent / endStream for long-running agents that emit events incrementally.
  3. Direct OTLP ingest via client.tracing.ingestOtlp(payload) when you already have an ExportTraceServiceRequest payload.
  4. LangChain middleware/callback integrations + OpenTelemetry exporter for automatic capture.

Resource ​

client.tracing.ingest(data) ​

Ingest a full tracing session payload.

typescript
import { ConsoleClient } from '@cognipeer/console-sdk';

const client = new ConsoleClient({
  apiKey: process.env.COGNIPEER_API_KEY!,
  baseURL: process.env.COGNIPEER_BASE_URL,
});

await client.tracing.ingest({
  sessionId: 'sess_abc123',
  threadId: 'thread_order-workflow-42',
  traceId: '4bf92f3577b34da6a3ce929d0e0e4736',
  rootSpanId: '00f067aa0ba902b7',
  source: 'custom',
  status: 'success',
  startedAt: new Date(Date.now() - 2000).toISOString(),
  endedAt: new Date().toISOString(),
  durationMs: 2000,
  agent: {
    name: 'support-agent',
    version: '1.2.0',
    model: 'gpt-4o-mini',
  },
  summary: {
    totalInputTokens: 450,
    totalOutputTokens: 180,
    totalCachedInputTokens: 20,
    totalBytesIn: 9000,
    totalBytesOut: 4200,
    eventCounts: {
      ai_call: 1,
      tool_call: 1,
    },
  },
  events: [
    {
      id: 'evt_1',
      type: 'ai_call',
      label: 'Assistant response',
      sequence: 1,
      timestamp: new Date().toISOString(),
      status: 'success',
      traceId: '4bf92f3577b34da6a3ce929d0e0e4736',
      spanId: 'b7ad6b7169203331',
      parentSpanId: '00f067aa0ba902b7',
      inputTokens: 450,
      outputTokens: 180,
      model: 'gpt-4o-mini',
      actor: { scope: 'agent', name: 'support-agent', role: 'assistant' },
      data: {
        sections: [
          {
            kind: 'message',
            label: 'User Message',
            role: 'user',
            content: 'Help me reset my password',
          },
        ],
      },
    },
  ],
  errors: [],
});

Returns

typescript
Promise<{ success: boolean; sessionId: string; eventsStored: number }>;

client.tracing.startStream(sessionId, data?) ​

Open a streaming session. The server creates (or refreshes) the row in agent_tracing_sessions and returns { success, sessionId, status: 'in_progress' }.

typescript
await client.tracing.startStream('sess_stream_42', {
  agent: { name: 'support-bot', model: 'gpt-4o-mini', version: '1.0.0' },
  threadId: 'thread_xyz',
});

client.tracing.appendEvent(sessionId, event) ​

Append a single event to a streaming session. The server merges token/byte totals and modelsUsed / toolsUsed into the parent session.

typescript
await client.tracing.appendEvent('sess_stream_42', {
  type: 'llm_end',
  label: 'Final response',
  inputTokens: 320,
  outputTokens: 96,
  model: 'gpt-4o-mini',
  actor: { scope: 'agent', name: 'support-bot' },
});

client.tracing.endStream(sessionId, data?) ​

Close a streaming session. Optional status, summary, and errors are merged with the live aggregates already on the row.

typescript
await client.tracing.endStream('sess_stream_42', { status: 'success' });

client.tracing.ingestOtlp(payload) ​

POST an OTLP/HTTP JSON payload directly. Identical to what CognipeerOTelSpanExporter does internally — useful if you already have an ExportTraceServiceRequest from another exporter.

typescript
await client.tracing.ingestOtlp({
  resourceSpans: [
    {
      resource: { attributes: [{ key: 'service.name', value: { stringValue: 'my-agent' } }] },
      scopeSpans: [{ scope: { name: 'cognipeer-sdk' }, spans: [/* ... */] }],
    },
  ],
});

LangChain Integration ​

For LangChain v1 agents, use middleware for automatic tracing:

typescript
import { createAgent } from 'langchain';
import { ConsoleClient, createCognipeerTracingMiddleware } from '@cognipeer/console-sdk';

const client = new ConsoleClient({
  apiKey: process.env.COGNIPEER_API_KEY!,
  baseURL: process.env.COGNIPEER_BASE_URL,
});

const tracing = createCognipeerTracingMiddleware({
  client,
  agent: {
    name: 'my-agent',
    model: 'gpt-4o-mini',
  },
  threadId: 'thread_checkout-17',
  debug: true,
});

const agent = createAgent({
  model: 'gpt-4o-mini',
  tools: [],
  middleware: [tracing.middleware],
});

await agent.invoke({
  messages: [{ role: 'user', content: 'Hello!' }],
});

await tracing.end('success');

Middleware Options ​

NameTypeDescription
clientConsoleClient | ConsoleClientOptionsSDK client or client config
sessionIdstringOptional custom session ID
agentTracingAgentAgent metadata (name, model, version)
threadIdstringOptional workflow thread correlation ID
configRecord<string, unknown>Optional custom config snapshot
debugbooleanEnables verbose tracing logs
loggerfunctionOptional custom logger

OpenTelemetry Exporter ​

Use CognipeerOTelSpanExporter when your runtime already emits OTel spans.

typescript
import { NodeTracerProvider } from '@opentelemetry/sdk-trace-node';
import { SimpleSpanProcessor } from '@opentelemetry/sdk-trace-base';
import { CognipeerOTelSpanExporter } from '@cognipeer/console-sdk';

const exporter = new CognipeerOTelSpanExporter({
  apiKey: process.env.COGNIPEER_API_KEY!,
  baseURL: process.env.COGNIPEER_BASE_URL || 'https://console.cognipeer.com',
});

const provider = new NodeTracerProvider();
provider.addSpanProcessor(new SimpleSpanProcessor(exporter));
provider.register();

The exporter converts spans to OTLP/HTTP JSON and sends them to:

  • POST /api/client/v1/traces

Exporter Options ​

NameTypeDescription
apiKeystringBearer token used for auth
baseURLstringCognipeer gateway base URL
headersRecord<string, string>Extra headers for each export request
timeoutnumberRequest timeout in ms (default 30000)
fetchtypeof fetchCustom fetch implementation

Correlation Fields ​

FieldScopeDescription
traceIdSession + EventW3C trace ID
rootSpanIdSessionRoot span ID for the session
spanIdEventSpan ID for the event
parentSpanIdEventParent span for hierarchy
sourceSessionIngestion source (custom or otlp)

Thread Correlation ​

Set threadId to group related sessions (including multi-agent workflows):

typescript
const tracing = createCognipeerTracingMiddleware({
  client,
  threadId: 'thread_order-workflow-42',
  agent: { name: 'planner-agent' },
});

All sessions that share the same threadId appear together in Tracing → Threads.

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