TypeScript SDK
Node.js / TypeScript instrumentation for TrailAI.
Maturity: the TypeScript SDK covers a narrower set of providers than the Python SDK and has no guardrail module. If you have a choice of runtime for AI workloads, Python currently gets more from TrailAI. The TS SDK is production-usable for tracing, prompts, and vault.
Installation
npm install trailai
Requires Node.js ^18.19.0 || >=20.6.0 (OpenTelemetry JS 2.x). Install the provider SDKs you use (openai v4–v7, @anthropic-ai/sdk,
cohere-ai, ollama); they're optional peer dependencies, not bundled with TrailAI.
The package is trailai — same name as the Python package, different registry.
Initialisation
import Trail from 'trailai';
// Reads TRAIL_URL, TRAIL_PUBLIC_KEY and TRAIL_SECRET_KEY
Trail.init({
applicationName: 'support-bot',
environment: 'production',
});
Or pass them explicitly: Trail.init({ url, publicKey, secretKey, ... }). Spans are exported to
<TRAIL_URL>/v1/traces with the key headers.
On
trailaiolder than 1.1.0 you had to build the exporter config yourself:otlpEndpoint: 'https://your-trail-host/api/sdk/v1/traces'andotlpHeaders: { 'X-Public-Key': …, 'X-Secret-Key': … }. Both options still work and take precedence.
Call it before importing or constructing any AI provider client — instrumentation patches libraries at init time.
TrailOptions
| Option | Type | Default | Purpose |
|---|---|---|---|
url |
string |
TRAIL_URL |
TrailAI SDK URL (…/api/sdk/v1, …/api/sdk or …/api) |
publicKey |
string |
TRAIL_PUBLIC_KEY |
|
secretKey |
string |
TRAIL_SECRET_KEY |
TRAIL_PRIVATE_KEY is accepted too |
applicationName |
string |
'default' |
→ service.name |
environment |
string |
'default' |
→ deployment.environment |
otlpEndpoint |
string |
OTEL_EXPORTER_OTLP_ENDPOINT, else from url |
Full OTLP traces URL; takes precedence over url |
otlpHeaders |
object |
from the keys | Extra/override export headers |
disableBatch |
boolean |
false |
true exports each span immediately (debugging only) |
consoleExporter |
boolean |
false |
Also print spans to stdout (or set TRAIL_DEBUG=true). Includes prompt content |
traceContent |
boolean |
— | Whether prompts/completions are captured |
disabledInstrumentations |
string[] |
— | Instrumentations to skip |
tracer |
tracer | — | Supply your own NodeTracerProvider (OpenTelemetry JS 2.x); TrailAI instruments onto it |
pricing_json |
string | object |
— | Custom pricing table |
Spans are batched. Pending spans flush when the event loop drains; in serverless handlers or before
process.exit(), callawait Trail.flush()(orawait Trail.shutdown()). Before 1.1.0disableBatchdefaulted totrueand every span was also printed to stdout.
Environment variables
| Variable | Used by |
|---|---|
TRAIL_URL |
Tracing, prompt hub and vault — same value as the Python SDK |
TRAIL_PUBLIC_KEY |
Tracing, prompt hub and vault |
TRAIL_SECRET_KEY |
Tracing, prompt hub and vault (TRAIL_PRIVATE_KEY also accepted) |
TRAIL_DEBUG |
true to also print spans to stdout |
OTEL_EXPORTER_OTLP_ENDPOINT / OTEL_EXPORTER_OTLP_HEADERS |
Standard OTel settings, used when no TrailAI URL is configured |
Explicit options win over environment variables.
On
trailaiolder than 1.1.0,TRAIL_URLhad to be the API base (https://your-host/api), the secret key was read only fromTRAIL_PRIVATE_KEY, and environment variables overrode explicit options.
Auto-instrumentation
| Provider | Instrumentation |
|---|---|
| OpenAI | ✅ |
| Anthropic | ✅ |
| Cohere | ✅ |
| Ollama | ✅ |
Far narrower than Python's 40+. Anything else needs manual tracing.
import Trail from 'trailai';
Trail.init({ applicationName: 'support-bot', environment: 'production' });
import OpenAI from 'openai'; // after init
const client = new OpenAI();
const response = await client.chat.completions.create({
model: 'gpt-4o-mini',
messages: [{ role: 'user', content: 'Hello' }],
}); // traced automatically
Manual tracing
The same role model as Python, so traces from mixed-language systems render consistently.
Trail.trace(fn, options)
import Trail from 'trailai';
const searchWeb = Trail.trace(
async (query: string) => {
const res = await fetch(`https://api.example.com/search?q=${query}`);
return res.text();
},
{ role: 'tool' }
);
const researchAgent = Trail.trace(
async (topic: string) => {
const results = await searchWeb(topic);
return summarize(results);
},
{ role: 'agent' }
);
Trail.startTrace(name, options, fn)
await Trail.startTrace('iteration_1', { role: 'agent step' }, async (span) => {
const decision = await decideNextAction(state);
span.setAttribute('agent.decision', decision);
return decision;
});
Roles
Identical semantics to Python — Manual Tracing:
role |
Kind | gen_ai.operation.name |
|---|---|---|
'agent' |
agent |
agent |
'agent step' / contains step or task |
agent |
execute_task |
'tool' |
tool |
execute_tool |
'llm' |
llm |
— |
'memory' |
memory |
— |
'api' / 'external' |
external |
— |
| unset | function |
— |
Agent context propagates to nested steps and tools, so Agent Analytics works the same way.
TraceOptions also accepts an optional goal?: string — what this agent run is trying to accomplish.
It only applies when role classifies as 'agent' (sets gen_ai.agent.goal); on any other role it's
silently ignored.
Helpers are exported directly too:
import { trace, startTrace, classifySpan, genaiOperationFor, AISpanKind } from 'trailai';
Prompt hub
import Trail from 'trailai';
const prompt = await Trail.getPrompts({
name: 'support-answer',
version: '3',
shouldCompile: true,
variables: { company: 'Acme', language: 'English' },
metaProperties: { requestId },
});
| Option | Purpose |
|---|---|
name / promptId |
Which prompt |
version |
Pin a version |
shouldCompile |
Substitute variables server-side |
variables |
Values for substitution |
metaProperties |
Extra metadata recorded with the fetch |
url / pKey / sKey |
Per-call credential overrides |
Errors are returned, not thrown — check for an err field:
const prompt = await Trail.getPrompts({ name: 'support-answer' });
if ('err' in prompt) {
console.error('Prompt fetch failed:', prompt.err);
// use a fallback
}
See Prompt Management for authoring.
Vault
const secrets = await Trail.getSecrets({
tags: ['llm-provider'],
shouldSetEnv: true, // writes values into process.env
});
| Option | Purpose |
|---|---|
key |
One secret by name |
tags |
Every secret with these tags |
shouldSetEnv |
Populate process.env under the vault names |
url / pKey / sKey |
Per-call credential overrides |
Same err-field error convention as the prompt hub.
See Vault.
Not available in TypeScript
| Feature | Alternative |
|---|---|
| Guardrails | Call the REST endpoint directly |
| 40+ instrumentations | Wrap unsupported libraries with Trail.trace |
Calling a guardrail directly is straightforward:
// TRAIL_URL is the same …/api/sdk/v1 value used by Trail.init()
const res = await fetch(`${process.env.TRAIL_URL}/guardrail/detect`, {
method: 'POST',
headers: {
'X-Public-Key': process.env.TRAIL_PUBLIC_KEY!,
'X-Secret-Key': process.env.TRAIL_SECRET_KEY!,
'Content-Type': 'application/json',
},
body: JSON.stringify({ prompt: userText, isInput: true, promptUserId: userId }),
});
const { data } = await res.json();
if (data.result.verdict === 'yes') {
// blocked
}
Remember to implement fail-closed handling yourself — the Python SDK does it for you, this does not.
Complete example
import Trail from 'trailai';
Trail.init({
applicationName: 'support-bot',
environment: process.env.NODE_ENV || 'development',
otlpHeaders: {
'X-Public-Key': process.env.TRAIL_PUBLIC_KEY!,
'X-Secret-Key': process.env.TRAIL_SECRET_KEY!,
},
disableBatch: false,
});
import OpenAI from 'openai';
const client = new OpenAI();
const retrieveContext = Trail.trace(
async (question: string) => '…retrieved passages…',
{ role: 'tool' }
);
export const supportAgent = Trail.trace(
async (question: string) => {
const context = await retrieveContext(question);
const response = await client.chat.completions.create({
model: 'gpt-4o-mini',
messages: [
{ role: 'system', content: `You are a support agent. Context: ${context}` },
{ role: 'user', content: question },
],
});
return response.choices[0].message.content;
},
{ role: 'agent' }
);
Related
- Manual Tracing — the role model in depth
- REST API — for features the TS SDK doesn't wrap
- Configuration — the Python equivalents