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-py (imported as bitfab). Python ≥ 3.10.

Module Exports

from bitfab import (
    AllowedEnvVars,
    Bitfab,
    BitfabFunction,
    BitfabTracingProcessor,   # only if openai-agents is installed
    CurrentSpan,
    CurrentTrace,
    ReplayItem,
    ReplayResult,
    SpanType,
    flush_traces,
    get_current_span,
    get_current_trace,
)
BitfabTracingProcessor is only exported when openai-agents is installed. from bitfab import BitfabTracingProcessor will raise ImportError otherwise.

Type Aliases

SpanType = Literal["llm", "agent", "function", "guardrail", "handoff", "custom"]

class Bitfab

__init__

Bitfab(
    api_key: str,
    service_url: Optional[str] = None,
    env_vars: Optional[AllowedEnvVars] = None,
    enabled: bool = True,
    baml_client: Any = None,
)
ParamTypeDefaultDescription
api_keystrrequiredEmpty/whitespace disables tracing with a warning
service_urlOptional[str]"https://bitfab.ai"Base URL
env_varsAllowedEnvVars{}LLM provider keys for call()
enabledboolTrueWhen False, @span decorator returns the function unwrapped
baml_clientAnyNoneGenerated BAML client for wrap_baml() without explicit client arg

span

def span(
    trace_function_key: str,
    *,
    name: Optional[str] = None,
    type: SpanType = "custom",
    test_run_id: Optional[str] = None,
) -> Callable[[Callable[P, T]], Callable[P, T]]
Decorator. Wraps the decorated function (sync or async) with a span. Returns: a decorator that returns a function with the same signature. Semantics:
  • When enabled=False, returns the function unchanged
  • name defaults to the function’s __name__
  • Nested spans propagate via contextvars.ContextVar — safe across asyncio.gather, threads, and sync/async boundaries
  • Exceptions are recorded on the span and re-raised
  • test_run_id is rarely set directly; replay() injects it via a replay context

get_function

def get_function(trace_function_key: str) -> BitfabFunction

wrap_baml

Framework integration → see BAML framework guide for examples.
# Form 1 — uses baml_client from constructor
def wrap_baml(method: Callable[..., Any]) -> Callable[..., Any]

# Form 2 — explicit client
def wrap_baml(
    baml_client: Any,
    method: Callable[..., Any],
) -> Callable[..., Any]
Returns: an async wrapper with the same signature as method. Raises:
  • ValueError if form 1 is used without baml_client in constructor
  • ValueError if the method has no __name__
Semantics:
  • If baml-py is not installed, the method is called directly without instrumentation
  • Otherwise calls get_current_span().set_prompt(...) and get_current_span().add_context({...}) with extracted metadata
  • Must be invoked inside a @span-decorated function for the prompt/context to attach to anything

replay

def replay(
    fn: Callable,
    *,
    limit: int = 5,
    trace_ids: Optional[list[str]] = None,
    max_concurrency: Optional[int] = 10,
) -> ReplayResult
fn must be decorated with @span. max_concurrency=None means unlimited; 1 means sequential.

call

def call(method_name: str, **kwargs: Any) -> Any
Executes a server-configured BAML function locally using env_vars. Raises: ValueError on lookup failure or execution error.

Framework Integrations

Handlers returned by these methods plug into each framework’s callback/processor/hook surface and emit Bitfab spans automatically. For usage examples and semantics, see the per-framework guides.

get_langgraph_callback_handler

def get_langgraph_callback_handler(trace_function_key: str) -> BitfabLangGraphCallbackHandler
Returns a LangChain/LangGraph BaseCallbackHandler. Pass via config={"callbacks": [handler]} when invoking. See LangGraph framework guide.

get_openai_tracing_processor

def get_openai_tracing_processor() -> BitfabOpenAITracingProcessor
Raises: ImportError if openai-agents is not installed. See OpenAI Agents framework guide.

get_claude_agent_handler

def get_claude_agent_handler(trace_function_key: str) -> BitfabClaudeAgentHandler
Returns a handler exposing instrument_options(options), wrap_response(stream), and wrap_query(stream) for the Claude Agent SDK. See Claude Agent SDK framework guide.

wrap_baml

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

class BitfabFunction

Returned from client.get_function(key).
def span(
    *,
    name: Optional[str] = None,
    type: SpanType = "custom",
) -> Callable[[Callable[P, T]], Callable[P, T]]

def wrap_baml(
    method_or_client: Any,
    method: Optional[Callable] = None,
) -> Callable[..., Any]
Delegates to the parent Bitfab instance with the bound trace_function_key.

Module Functions

get_current_span()

def get_current_span() -> CurrentSpan | _NoOpCurrentSpan
Returns a no-op object when called outside a span context. The no-op’s methods do nothing and never raise.

get_current_trace()

def get_current_trace() -> CurrentTrace | _NoOpCurrentTrace
Returns a no-op object when called outside a span context.

flush_traces(timeout: float = 30.0)

def flush_traces(timeout: float = 30.0) -> None
Waits for pending trace threads to join, up to timeout seconds. Use before process exit in short-lived scripts.

Classes (Context Handles)

CurrentSpan

class CurrentSpan:
    @property
    def trace_id(self) -> str
    def add_context(self, context: dict[str, Any]) -> None
    def set_prompt(self, prompt: str) -> None
MethodSemantics
trace_idUUID string
add_contextAppends the dict as one entry to span_data.contexts. Non-dict input ignored. Never raises
set_promptOverwrites span_data.prompt. Non-string input ignored. Never raises

CurrentTrace

class CurrentTrace:
    def set_session_id(self, session_id: str) -> None
    def set_metadata(self, metadata: dict[str, Any]) -> None
    def add_context(self, context: dict[str, Any]) -> None
set_metadata shallow-merges with later keys winning. add_context accumulates entries.

TypedDicts & Dataclasses

AllowedEnvVars

class AllowedEnvVars(TypedDict, total=False):
    OPENAI_API_KEY: str

ReplayItem

@dataclass
class ReplayItem:
    input: list[Any]
    result: Any
    original_output: Any
    error: str | None

ReplayResult

@dataclass
class ReplayResult:
    items: list[ReplayItem]
    test_run_id: str
    test_run_url: str

Error Behavior Summary

SituationBehavior
Empty api_keyWarning logged, enabled forced to False
@span transport failureSwallowed. User’s return value / exception passes through
Decorated function raisesSpan records error, exception re-raised
add_context / set_prompt with invalid inputSilently ignored
call() — function not foundValueError with URL to /functions
call() — no promptValueError with URL to /functions/{id}
wrap_baml — missing clientValueError
replay()fn not decoratedSpans are not linked to the test run (not an error)
Import BitfabTracingProcessor without openai-agentsImportError