Skip to content

Tracing API

The SDK supports tracing in three complementary ways:

  1. Direct ingestion via client.tracing.ingest(...)
  2. LangChain middleware/callback integrations for automatic event capture
  3. OpenTelemetry exporter for OTLP-native pipelines

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 }>;

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://api.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.

Released under the MIT License.