JavaScript SDK
Complete JavaScript/TypeScript SDK reference.
Complete reference for the Risicare JavaScript/TypeScript SDK (v0.3.0).
Installation
npm install risicareCore Functions
init
Initialize the SDK.
import { init } from 'risicare';
init(config?: RisicareConfig): voidenable / disable / isEnabled
Runtime control.
import { enable, disable, isEnabled } from 'risicare';
enable(): void
disable(): void
isEnabled(): booleanflush / shutdown
Export control.
import { flush, shutdown } from 'risicare';
flush(): Promise<void>
shutdown(): Promise<void>getMetrics
Returns processor metrics for monitoring export health.
import { getMetrics } from 'risicare';
getMetrics(): {
exportedSpans: number;
droppedSpans: number;
failedExports: number;
queueSize: number;
queueCapacity: number;
queueUtilization: number;
}getTraceContent
Returns whether content tracing is enabled.
import { getTraceContent } from 'risicare';
getTraceContent(): booleanreportError
Report a caught exception to the self-healing pipeline. Creates an error span that triggers diagnosis. Never throws.
import { reportError } from 'risicare';
try {
const result = await llm.invoke(query);
} catch (error) {
reportError(error); // Triggers diagnosis → fix generation
return fallbackResponse;
}| Parameter | Type | Default | Description |
|---|---|---|---|
error | Error | string | (required) | The caught exception |
options.name | string | error class name | Custom span name |
options.attributes | Record | {} | Additional span attributes |
score
Record a custom evaluation score on a trace. Non-blocking — sends in background via fetch(). Never throws.
import { score } from 'risicare';
score('trace-abc123', 'factual_accuracy', 0.92, {
comment: 'Verified against source documents',
});| Parameter | Type | Default | Description |
|---|---|---|---|
traceId | string | (required) | The trace to score |
name | string | (required) | Score name |
value | number | (required) | Score between 0.0 and 1.0 |
options.spanId | string | undefined | Specific span within the trace |
options.comment | string | undefined | Human-readable explanation |
Values outside [0.0, 1.0] are rejected with a warning and not sent.
Provider Patches
12 native provider patches, each imported from a sub-path export. All return a transparent ES Proxy wrapper — the original client is unchanged.
| Provider | Import | Patch Function |
|---|---|---|
| OpenAI | risicare/openai | patchOpenAI(client) |
| Anthropic | risicare/anthropic | patchAnthropic(client) |
| Vercel AI | risicare/vercel-ai | patchVercelAI(client) |
| Google Gemini | risicare/google | patchGoogleAI(client) |
| Mistral | risicare/mistral | patchMistral(client) |
| Groq | risicare/groq | patchGroq(client) |
| Cohere | risicare/cohere | patchCohere(client) |
| Together AI | risicare/together | patchTogether(client) |
| Ollama | risicare/ollama | patchOllama(client) |
| HuggingFace | risicare/huggingface | patchHuggingFace(client) |
| Cerebras | risicare/cerebras | patchCerebras(client) |
| AWS Bedrock | risicare/bedrock | patchBedrock(client) |
import { patchOpenAI } from 'risicare/openai';
import { patchAnthropic } from 'risicare/anthropic';
import { patchGroq } from 'risicare/groq';
import OpenAI from 'openai';
const openai = patchOpenAI(new OpenAI());
// All chat.completions.create and embeddings.create calls are now tracedHost Detection (OpenAI-Compatible)
When using patchOpenAI() with a client pointing to an OpenAI-compatible API, the SDK automatically detects the real provider from the base URL and sets gen_ai.system correctly:
| Provider | Base URL |
|---|---|
| DeepSeek | api.deepseek.com |
| Together AI | api.together.xyz |
| Groq | api.groq.com |
| xAI (Grok) | api.x.ai |
| Fireworks | api.fireworks.ai |
| Baseten | inference.baseten.co |
| Novita | api.novita.ai |
| BytePlus | api.byteplus.com |
import { patchOpenAI } from 'risicare/openai';
import OpenAI from 'openai';
// DeepSeek via OpenAI-compatible API — auto-detected as "deepseek"
const deepseek = patchOpenAI(new OpenAI({
baseURL: 'https://api.deepseek.com/v1',
apiKey: process.env.DEEPSEEK_API_KEY,
}));patchVercelAI
Returns higher-order wrapper functions for Vercel AI SDK:
import { generateText, streamText, generateObject } from 'ai';
import { patchVercelAI } from 'risicare/vercel-ai';
const { tracedGenerateText, tracedStreamText, tracedGenerateObject } = patchVercelAI();
const generate = tracedGenerateText(generateText);
const stream = tracedStreamText(streamText);
const genObject = tracedGenerateObject(generateObject);Framework Integrations
4 framework integrations, each imported from a sub-path export:
LangChain.js
import { RisicareCallbackHandler } from 'risicare/langchain';
const handler = new RisicareCallbackHandler();
const result = await chain.invoke(input, { callbacks: [handler] });LangGraph.js
import { instrumentLangGraph } from 'risicare/langgraph';
const tracedGraph = instrumentLangGraph(compiledGraph);
const result = await tracedGraph.invoke(input);Instructor
import { patchInstructor } from 'risicare/instructor';
const patchedClient = patchInstructor(instructorClient);
const result = await patchedClient.create({ /* ... */ });LlamaIndex.TS
import { RisicareLlamaIndexHandler } from 'risicare/llamaindex';
const handler = new RisicareLlamaIndexHandler();
// Register with LlamaIndex's event systemStreaming
Trace async iterables with automatic span lifecycle management:
import { tracedStream } from 'risicare';
const stream = tracedStream(asyncIterable, { name: 'llm-stream' });
for await (const chunk of stream) {
process(chunk);
}
// Span automatically records stream.chunk_count and stream.completedDedup
Framework integrations can suppress provider-level tracing to prevent double-tracing:
import { suppressProviderInstrumentation, isProviderInstrumentationSuppressed } from 'risicare';
suppressProviderInstrumentation(() => {
// Provider patches are suppressed inside this scope
await client.chat.completions.create(/* ... */);
});Higher-Order Functions
agent
import { agent } from 'risicare';
agent<T extends (...args: any[]) => any>(
options: {
name?: string;
role?: string; // orchestrator, worker, supervisor, specialist, router, etc.
agentType?: string;
version?: number;
metadata?: Record<string, unknown>;
},
fn: T
): Tsession
import { session } from 'risicare';
session<T extends (...args: any[]) => any>(
optionsOrResolver: SessionOptions | ((...args: any[]) => SessionOptions),
fn: T
): T
interface SessionOptions {
sessionId: string;
userId?: string;
}Phase Functions
Phase decorators accept either a bare function or a name + function (added in 0.2.1):
import { traceThink, traceDecide, traceAct, traceObserve } from 'risicare';
// Bare form — span named after the function
const analyze = traceThink(async () => { /* ... */ });
// Named form — explicit span name
const analyze = traceThink('analyze-query', async () => { /* ... */ });
// All four phases support both forms
traceDecide('choose-action', async () => { /* ... */ });
traceAct('execute-tool', async () => { /* ... */ });
traceObserve('check-result', async () => { /* ... */ });Multi-Agent Functions
import { traceMessage, traceDelegate, traceCoordinate } from 'risicare';
traceMessage<T extends (...args: any[]) => any>(
options: { to: string },
fn: T
): T
traceDelegate<T extends (...args: any[]) => any>(
options: { to: string },
fn: T
): T
traceCoordinate<T extends (...args: any[]) => any>(
options: { participants: string[] },
fn: T
): TContext Functions
getCurrentContext
import { getCurrentContext } from 'risicare';
getCurrentContext(): ContextState | undefined
interface ContextState {
session?: { sessionId: string; userId?: string };
agent?: { name: string; role?: string; agentId?: string };
span?: Span;
phase?: SemanticPhase;
}Individual Getters
import {
getCurrentTraceId,
getCurrentSpanId,
getCurrentAgentId,
getCurrentSessionId,
} from 'risicare';
getCurrentTraceId(): string | undefined
getCurrentSpanId(): string | undefined
getCurrentAgentId(): string | undefined
getCurrentSessionId(): string | undefinedW3C Trace Context
import { injectTraceContext, extractTraceContext } from 'risicare';
injectTraceContext(headers: Record<string, string>): void
extractTraceContext(headers: Record<string, string>): TraceContext | undefinedSpan Registry
import {
registerSpan,
getSpanById,
unregisterSpan,
} from 'risicare';
registerSpan(span: Span, ttlMs?: number): void
getSpanById(spanId: string): Span | undefined
unregisterSpan(spanId: string): voidTypes
RisicareConfig
interface RisicareConfig {
apiKey?: string;
projectId?: string; // DEPRECATED — emits console.warn. Will be removed in v1.0.
endpoint?: string;
environment?: string;
serviceName?: string;
serviceVersion?: string;
enabled?: boolean;
traceContent?: boolean;
compress?: boolean;
sampleRate?: number;
batchSize?: number;
batchTimeoutMs?: number;
maxQueueSize?: number;
debug?: boolean;
metadata?: Record<string, unknown>;
}TraceContext
interface TraceContext {
traceId: string;
spanId: string;
sessionId?: string;
agentId?: string;
}Span
class Span {
traceId: string;
spanId: string;
name: string;
kind: SpanKind;
startTime: number;
endTime?: number;
attributes: Record<string, unknown>;
events: SpanEvent[];
status: SpanStatus;
setAttribute(key: string, value: unknown): this;
addEvent(name: string, attributes?: Record<string, unknown>): this;
setStatus(status: SpanStatus): this;
end(): void;
}SpanKind
enum SpanKind {
INTERNAL = 'internal',
SERVER = 'server',
CLIENT = 'client',
PRODUCER = 'producer',
CONSUMER = 'consumer',
AGENT = 'agent',
LLM_CALL = 'llm_call',
TOOL_CALL = 'tool_call',
RETRIEVAL = 'retrieval',
DECISION = 'decision',
DELEGATION = 'delegation',
COORDINATION = 'coordination',
MESSAGE = 'message',
THINK = 'think',
DECIDE = 'decide',
OBSERVE = 'observe',
REFLECT = 'reflect',
}SpanStatus
enum SpanStatus {
UNSET = 'unset',
OK = 'ok',
ERROR = 'error',
}