> ## Documentation Index
> Fetch the complete documentation index at: https://traceroot.ai/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# TypeScript SDK

> Full API reference for the traceroot TypeScript SDK

The traceroot TypeScript SDK provides automatic and manual instrumentation for AI agents using OpenTelemetry.

## Instrumentation

Pass module instances to `initialize()` to instrument all calls automatically:

```typescript theme={null}
import OpenAI from 'openai';
import { TraceRoot } from '@traceroot-ai/traceroot';

TraceRoot.initialize({
  instrumentModules: { openAI: OpenAI },
});

const openai = new OpenAI();
```

## The Observe Wrapper

Wrap any async function to create a span:

```typescript theme={null}
import { observe } from '@traceroot-ai/traceroot';

const result = await observe({ name: 'my_function', type: 'tool' }, async () => {
  return doWork('your input here');
});
```

### Parameters

| Parameter | Type | Default | Description |
| - | - | - | - |
| `name` | `string` | function name | Span name |
| `type` | `'span' \| 'agent' \| 'tool' \| 'llm'` | `'span'` | Span kind — `'agent'` for multi-step agents, `'tool'` for function calls, `'llm'` for model inference, `'span'` for generic |
| `metadata` | `Record<string, unknown>` | — | Static metadata to attach |
| `tags` | `string[]` | — | Tags to attach |
| `captureInput` | `boolean` | `true` | Capture the function arguments as span input |
| `captureOutput` | `boolean` | `true` | Capture the return value as span output |

See [Data Capture and Privacy](https://traceroot.ai/docs/tracing/data-capture.md) for `captureInput` and `captureOutput` examples that keep sensitive values off spans.

To rewrite personal data in every span before export, pass a `redact` function to `TraceRoot.initialize()`. It may be async. See [Data Capture and Privacy](https://traceroot.ai/docs/tracing/data-capture.md#redact-personal-data-before-export).

## Setting Trace Context

Use `usingAttributes()` to set user and session context for all spans created within a block:

```typescript theme={null}
import { usingAttributes } from '@traceroot-ai/traceroot';

await usingAttributes(
  {
    sessionId: 'conv-123',
    userId: 'user-456',
    tags: ['production', 'v2'],
    metadata: { feature: 'chat' },
  },
  async () => {
    // All spans here inherit the attributes above
    await runAgent('What is the weather?');
  },
);
```

### Parameters

| Parameter | Type | Description |
| - | - | - |
| `sessionId` | `string` | Session / conversation ID |
| `userId` | `string` | User identifier |
| `tags` | `string[]` | Tags to attach to all spans |
| `metadata` | `Record<string, unknown>` | Arbitrary metadata |

## Updating Spans and Traces

Update the current span or trace programmatically:

```typescript theme={null}
import { observe, updateCurrentSpan, updateCurrentTrace } from '@traceroot-ai/traceroot';

await observe({ name: 'my_agent', type: 'agent' }, async () => {
  updateCurrentSpan({
    input: { query: userInput },
    output: { response: agentOutput },
    model: 'gpt-4o',
    usage: { input: 100, output: 50 },
  });

  updateCurrentTrace({
    userId: 'user-123',
    sessionId: 'sess-456',
    tags: ['prod'],
    metadata: { plan: 'pro' },
  });
});
```

### `updateCurrentSpan` Parameters

| Parameter | Type | Description |
| - | - | - |
| `name` | `string` | Rename the span after creation |
| `input` | `unknown` | Input data |
| `output` | `unknown` | Output data |
| `metadata` | `Record<string, unknown>` | Custom metadata |
| `model` | `string` | LLM model name |
| `modelParameters` | `Record<string, unknown>` | LLM model parameters |
| `usage` | `TokenUsage` | Token usage (`{ input, output, cacheRead, cacheWrite, total }`) |
| `cost` | `number` | Total cost of this call in USD, for an LLM call or a paid tool or API call. Replaces traceroot's computed price for the span |
| `prompt` | `unknown` | Prompt or messages sent to the LLM |
| `attributes` | `Record<string, string \| number \| boolean>` | Arbitrary span attributes |

### `updateCurrentTrace` Parameters

| Parameter | Type | Description |
| - | - | - |
| `userId` | `string` | User identifier |
| `sessionId` | `string` | Session identifier |
| `tags` | `string[]` | Tags for the trace |
| `metadata` | `Record<string, unknown>` | Trace-level metadata |

## Flushing and Shutdown

By default, the TypeScript SDK batches spans to optimize performance, flushing them every 5 seconds or when 100 spans are accumulated.

**Important:** The SDK's only automatic shutdown flush is a `beforeExit` hook. Node.js does not emit `beforeExit` on `process.exit()`, unhandled exceptions, or signals like SIGINT/SIGTERM. Serverless runtimes that freeze the process (e.g. AWS Lambda, Cloud Functions) skip it too. In any of these cases, buffered spans will be lost if you exit without flushing explicitly.

To ensure all spans are exported before your script terminates, await `shutdown()` (or `flush()`):

```typescript theme={null}
import { TraceRoot } from '@traceroot-ai/traceroot';

TraceRoot.initialize();

async function main() {
  try {
    // ... your application logic ...
  } finally {
    // Ensure all batched spans are exported before exiting, even on failure
    await TraceRoot.shutdown();
  }
}
main();
```

Alternatively, for tests or short scripts, you can disable batching:

```typescript theme={null}
TraceRoot.initialize({ disableBatch: true });
```

**Note:** Disabling batching does not make the network request synchronous. You still must await `flush()` or `shutdown()` before terminating the process with `process.exit()`.

*(Note: The Python SDK registers an `atexit` handler that flushes spans automatically in most environments. However, `atexit` does not run when a serverless runtime freezes the process — Python handlers there still need `traceroot.flush()` before returning.)*

## Environment Variables

| Variable | Default | Description |
| - | - | - |
| `TRACEROOT_API_KEY` | (required) | API key |
| `TRACEROOT_HOST_URL` | `https://app.traceroot.ai` | API endpoint |
| `TRACEROOT_ENABLED` | `true` | Enable/disable tracing |
| `TRACEROOT_ENVIRONMENT` | — | Deployment environment tag (e.g. `production`, `staging`) |
| `TRACEROOT_GIT_REPO` | auto-detected | Git repository (`owner/repo`) |
| `TRACEROOT_GIT_REF` | auto-detected | Git reference |


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.