Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.bitfab.ai/llms.txt

Use this file to discover all available pages before exploring further.

Package: bitfab. Dual ESM/CJS. Node.js ≥ 18 and modern browsers.

Module Exports

// Values
export { Bitfab, BitfabError, BitfabFunction, getCurrentSpan, getCurrentTrace } from "bitfab"
export { BitfabOpenAITracingProcessor } from "bitfab"
export { flushTraces } from "bitfab"
export { __version__, DEFAULT_SERVICE_URL } from "bitfab"

// Types
export type {
  AllowedEnvVars,
  BamlExecutionResult,
  BitfabConfig,
  CurrentSpan,
  CurrentTrace,
  ProviderDefinition,
  ReplayItem,
  ReplayOptions,
  ReplayResult,
  SpanOptions,
  SpanType,
  ActiveSpanContext,
  TraceResponse,
  TracingProcessor,
  WrapBAMLOptions,
  WrappedBamlFn,
} from "bitfab"

Constants

ExportTypeValue
DEFAULT_SERVICE_URLstring"https://bitfab.ai"
__version__stringCurrent package version

class Bitfab

new Bitfab(config: BitfabConfig)

ParamTypeDefaultDescription
config.apiKeystring | undefinedAPI key. Empty/whitespace/undefined disables tracing with a console.warn
config.serviceUrlstring"https://bitfab.ai"Base URL for Bitfab API
config.timeoutnumber120000HTTP request timeout (ms)
config.envVarsAllowedEnvVars{}LLM provider keys for call() (only OPENAI_API_KEY)
config.enabledbooleantrueWhen false, withSpan returns the function unwrapped
config.bamlClientunknownnullGenerated BAML client (for wrapBAML() without explicit client arg)

withSpan

withSpan<TArgs extends unknown[], TReturn>(
  traceFunctionKey: string,
  optionsOrFn: SpanOptions | ((...args: TArgs) => TReturn),
  maybeFn?: (...args: TArgs) => TReturn,
): (...args: TArgs) => TReturn
Wraps a function so that each invocation produces a span. Returns: a function with the same signature as the input. Semantics:
  • If enabled === false, returns the original function unchanged
  • Span name defaults to fn.name || traceFunctionKey
  • Span type defaults to "custom"
  • Input arguments are serialized via superjson (type-preserving)
  • Return value (sync or the resolved Promise value) is serialized as output
  • Thrown errors are recorded (error field) and re-thrown
  • Spans nest automatically via AsyncLocalStorage (Node) or a module-level stack (browser fallback)
  • Browser fallback does not isolate concurrent async chains (Promise.all with independent withSpan calls may see the wrong parent)

getFunction

getFunction(traceFunctionKey: string): BitfabFunction
Returns a BitfabFunction bound to traceFunctionKey.

wrapBAML

Framework integration → see BAML framework guide for examples.
// Form 1 — uses bamlClient from constructor
wrapBAML<TArgs, TReturn>(
  method: (...args: TArgs) => Promise<TReturn>,
  options?: WrapBAMLOptions,
): WrappedBamlFn<TArgs, TReturn>

// Form 2 — explicit client
wrapBAML<TArgs, TReturn>(
  bamlClient: unknown,
  method: (...args: TArgs) => Promise<TReturn>,
  options?: WrapBAMLOptions,
): WrappedBamlFn<TArgs, TReturn>
Returns: a WrappedBamlFn — an async function with a .collector property set after each call. Throws:
  • BitfabError if form 1 is used without bamlClient in constructor
  • BitfabError if the method has no .name
Semantics:
  • If @boundaryml/baml is not installed, the method is called directly; .collector is null
  • Otherwise: creates a BAML Collector, calls the method through a tracked client, then:
    • Calls getCurrentSpan().setPrompt(...) with the rendered messages as JSON
    • Calls getCurrentSpan().addContext({ model, provider, inputTokens, outputTokens, durationMs })
  • onCollector callback fires after each invocation; errors in the callback are swallowed

replay

async replay<TReturn>(
  traceFunctionKey: string,
  fn: (...args: any[]) => TReturn | Promise<TReturn>,
  options?: ReplayOptions,
): Promise<ReplayResult<TReturn>>
OptionTypeDefault
limitnumberunspecified → server default
traceIdsstring[]
maxConcurrencynumber10
Returns: { items, testRunId, testRunUrl }. See ReplayResult. Notes:
  • fn must be the return value of withSpan (so new spans get linked to the test run via async context)
  • Inputs are deserialized from historical spans and passed positionally

call

async call<T = unknown>(
  methodName: string,
  inputs?: Record<string, unknown>,
): Promise<T>
Executes a server-configured BAML function locally using envVars. Throws: BitfabError on lookup failure or execution error.

Framework Integrations

Handlers returned by these methods are framework-native adapters — they plug into each framework’s own callback/processor/hook surface and emit Bitfab spans automatically. For usage examples and semantics, see the per-framework guides; signatures here are canonical.

getLangGraphCallbackHandler

getLangGraphCallbackHandler(traceFunctionKey: string): BitfabLangGraphCallbackHandler
Returns a LangChain/LangGraph BaseCallbackHandler. Pass in config.callbacks when invoking a graph/chain. See LangGraph framework guide.

getOpenAiTracingProcessor

getOpenAiTracingProcessor(): BitfabOpenAITracingProcessor
Returns a processor to pass to @openai/agentssetTraceProcessors. See OpenAI Agents framework guide.

getClaudeAgentHandler

getClaudeAgentHandler(traceFunctionKey: string): BitfabClaudeAgentHandler
Returns a handler exposing instrumentOptions(options), wrapResponse(stream), and wrapQuery(stream) for the Claude Agent SDK. See Claude Agent SDK framework guide.

wrapBAML

See the BAML framework guide for examples; full signature under wrapBAML above.

class BitfabFunction

Fluent wrapper binding a traceFunctionKey. Obtained via client.getFunction(key).

withSpan

withSpan<TArgs, TReturn>(
  optionsOrFn: SpanOptions | ((...args: TArgs) => TReturn),
  maybeFn?: (...args: TArgs) => TReturn,
): (...args: TArgs) => TReturn
Delegates to client.withSpan(boundKey, optionsOrFn, maybeFn).

wrapBAML

Identical signature and semantics to Bitfab#wrapBAML.

class BitfabError

Extends Error.
class BitfabError extends Error {
  constructor(message: string, url?: string)
  readonly url?: string
}
Thrown for SDK-originated failures (missing function, missing prompt, misconfiguration). Never thrown for transport errors on withSpan paths — those are swallowed.

class BitfabLangGraphCallbackHandler

Extends LangChain’s BaseCallbackHandler. Obtained via client.getLangGraphCallbackHandler(key). No direct instantiation needed for normal use. Full callback surface documented in LangGraph framework guide.

class BitfabOpenAITracingProcessor

Implements the OpenAI Agents SDK TracingProcessor interface. Obtained via client.getOpenAiTracingProcessor(). No direct instantiation needed for normal use. See OpenAI Agents framework guide.

class BitfabClaudeAgentHandler

Handler for the Claude Agent SDK. Obtained via client.getClaudeAgentHandler(key). Exposes instrumentOptions, wrapResponse, and wrapQuery. See Claude Agent SDK framework guide for method signatures and usage.

Functions

getCurrentSpan()

function getCurrentSpan(): CurrentSpan
Returns the innermost active span. Outside a span context, returns a no-op whose traceId is "".

getCurrentTrace()

function getCurrentTrace(): CurrentTrace
Returns a handle to the active trace. Outside a span context, returns a no-op.

flushTraces(timeoutMs?: number)

async function flushTraces(timeoutMs?: number): Promise<void>
Waits for pending trace dispatches to complete. Default timeoutMs: 5000. Use before process.exit() in short-lived scripts. Resolves after timeoutMs or when all pending sends finish, whichever comes first.

Interfaces

BitfabConfig

See constructor table.

SpanOptions

interface SpanOptions {
  name?: string    // defaults to fn.name || traceFunctionKey
  type?: SpanType  // defaults to "custom"
}

SpanType

type SpanType = "llm" | "agent" | "function" | "guardrail" | "handoff" | "custom"

CurrentSpan

interface CurrentSpan {
  readonly traceId: string
  addContext(context: Record<string, unknown>): void
  setPrompt(prompt: string): void
}
MethodSemantics
traceIdUUID string. Empty when outside a span
addContextPushes the object as a single entry onto span_data.contexts. Non-object input is ignored. Never throws
setPromptOverwrites span_data.prompt. Non-string input is ignored. Never throws

CurrentTrace

interface CurrentTrace {
  setSessionId(sessionId: string): void
  setMetadata(metadata: Record<string, unknown>): void
  addContext(context: Record<string, unknown>): void
}
MethodSemantics
setSessionIdStored on the trace’s session_id DB column
setMetadataShallow-merges with existing metadata. Later keys overwrite
addContextAppends an entry to rawData.contexts. Accumulates across calls

WrapBAMLOptions

interface WrapBAMLOptions {
  onCollector?: (collector: unknown) => void
}

WrappedBamlFn<TArgs, TReturn>

interface WrappedBamlFn<TArgs extends unknown[], TReturn> {
  (...args: TArgs): Promise<TReturn>
  collector: unknown | null
}
collector is null before the first call or when @boundaryml/baml is unavailable. After each successful call, it holds the BAML Collector instance from that invocation.

ReplayOptions

interface ReplayOptions {
  limit?: number
  traceIds?: string[]
  maxConcurrency?: number  // default 10
}

ReplayResult<T>

interface ReplayResult<T> {
  items: ReplayItem<T>[]
  testRunId: string
  testRunUrl: string
}

interface ReplayItem<T> {
  input: unknown[]
  result: T | undefined
  originalOutput: unknown
  error: string | null
}

AllowedEnvVars

interface AllowedEnvVars {
  OPENAI_API_KEY?: string
}
Only OPENAI_API_KEY is currently whitelisted.

ActiveSpanContext

interface ActiveSpanContext {
  traceId: string
  spanId: string
}
Passed to the OpenAI tracing processor’s span-linking hook.

Error Behavior Summary

SituationBehavior
Empty / missing apiKeyconsole.warn, enabled forced to false
withSpan transport failureSwallowed. User’s return value / exception passes through
User function throwsSpan records error, error re-thrown
addContext / setPrompt with invalid inputSilently ignored. Never throws
call() — function not foundBitfabError with URL to /functions
call() — no prompt configuredBitfabError with URL to /functions/{id}
wrapBAML — missing clientBitfabError
replay()fn not wrapped by withSpanSpans are not linked to the test run (not an error)

Module Resolution

  • Node.js ESM: dist/index.js
  • Node.js CJS: dist/index.cjs
  • Browser: works, but AsyncLocalStorage-dependent features degrade (see withSpan semantics)