Skip to main content
GitHub

Python SDK

Complete Python SDK reference.

Complete reference for the Risicare Python SDK.

Installation

pip install risicare

Exports

The risicare package exports 70 public symbols organized by category:

Core

ExportDescription
initInitialize the SDK and return a RisicareClient
shutdownGraceful shutdown with optional timeout
disableDisable tracing at runtime
enableRe-enable tracing at runtime
is_enabledCheck if tracing is active
RisicareClientMain client class
RisicareConfigConfiguration dataclass
get_clientGet the current client instance
__version__SDK version string

Tracer

ExportDescription
TracerLow-level tracer for creating spans
get_tracerGet the current tracer instance

Decorators

ExportDescription
agentMark a function as an agent
sessionBind a function to a user session
traceGeneric trace decorator with customizable kind
trace_thinkMark a thinking phase
trace_decideMark a decision phase
trace_actMark an action phase
trace_observeMark an observation phase
trace_messageMark inter-agent messaging
trace_delegateMark task delegation
trace_coordinateMark multi-agent coordination

Context Managers

ExportDescription
session_contextSync context manager for sessions
async_session_contextAsync context manager for sessions
agent_contextSync context manager for agent identity
async_agent_contextAsync context manager for agent identity
phase_contextContext manager for semantic phases
restore_trace_contextRestore a saved trace context

Context Accessors

ExportDescription
get_current_sessionGet active session context
get_current_agentGet active agent context
get_current_spanGet active span
get_current_phaseGet active semantic phase
get_current_contextGet full context state
get_trace_contextGet W3C trace context
get_current_session_idGet active session ID
get_current_trace_idGet active trace ID
get_current_span_idGet active span ID
get_current_agent_idGet active agent ID
get_current_parent_span_idGet parent span ID

Span Registry

ExportDescription
register_spanRegister a span for ID-based lookup
get_span_by_idRetrieve a span by its ID
unregister_spanRemove a span from the registry

Streaming

ExportDescription
traced_streamWrap an async stream with tracing
traced_stream_syncWrap a sync stream with tracing

W3C Trace Context

ExportDescription
inject_trace_contextInject trace context into headers
extract_trace_contextExtract trace context from headers

Types

ExportDescription
SpanSpan data class
SpanKindSpan kind enum
SpanStatusSpan status enum
SessionContextSession context dataclass
AgentContextAgent context dataclass
TraceContextTrace context for W3C propagation
SemanticPhasePhase enum (THINK, DECIDE, ACT, REFLECT, OBSERVE, COMMUNICATE, COORDINATE)
AgentRoleAgent role enum
MessageTypeMessage type enum

Fix Runtime

ExportDescription
FixRuntimeMain fix runtime class
FixLoaderLoads fix configurations
FixApplierApplies fixes to spans
FixCacheCaches fix configs locally
FixRuntimeConfigFix runtime configuration
FixInterceptorIntercepts and applies fixes
get_runtimeGet fix runtime instance
init_runtimeInitialize fix runtime
shutdown_runtimeShutdown fix runtime

Auto-Instrumentation

ExportDescription
install_import_hooksInstall auto-instrumentation hooks
remove_import_hooksRemove auto-instrumentation hooks
instrument_already_importedInstrument already-loaded modules
is_instrumentedCheck if a module is instrumented
get_instrumented_modulesList instrumented modules
get_supported_modulesList all supported modules

Exporters

ExportDescription
OTLPExporterOTLP/HTTP span exporter

risicare.init

Initialize the SDK.

risicare.init(
    api_key: str | None = None,
    endpoint: str | None = None,
    environment: str = "development",
    service_name: str | None = None,
    service_version: str | None = None,
    enabled: bool = True,
    trace_content: bool = True,
    sample_rate: float = 1.0,
    batch_size: int = 100,
    batch_timeout_ms: int = 1000,
    auto_patch: bool = True,
    debug: bool = False,
    exporters: list | None = None,
    metadata: dict | None = None,
    otlp_endpoint: str | None = None,
    otlp_headers: dict | None = None,
    otel_bridge: bool = False,
) -> RisicareClient
ParameterTypeDefaultDescription
api_keystrenvAPI key (or RISICARE_API_KEY). Each key is scoped to one project.
endpointstr"https://app.risicare.ai"Gateway endpoint URL
environmentstr"development"Environment name (within-project org)
service_namestrNoneService name (within-project org)
service_versionstrNoneService version for traces
enabledboolTrueEnable tracing
trace_contentboolTrueCapture prompts/completions
sample_ratefloat1.0Trace sampling rate (0.0-1.0)
batch_sizeint100Spans per batch
batch_timeout_msint1000Milliseconds between flushes
auto_patchboolTrueAuto-instrument supported libraries
debugboolFalseEnable debug logging
exporterslistNoneCustom span exporters
metadatadictNoneGlobal metadata for all spans
otlp_endpointstrNoneOTLP exporter endpoint
otlp_headersdictNoneOTLP exporter headers
otel_bridgeboolFalseBridge spans to OpenTelemetry

risicare.shutdown

Graceful shutdown — flushes pending spans and closes connections.

risicare.shutdown(timeout_ms: int = 5000) -> None

@risicare.agent

Decorator for agent functions.

@risicare.agent(
    name: str | None = None,
    role: str | None = None,
    agent_type: str | None = None,
    version: int | None = None,
)
def my_agent():
    ...
ParameterTypeDefaultDescription
namestrFunction nameHuman-readable agent name (optional)
rolestrNoneAgent role (orchestrator, worker, reviewer)
agent_typestrNoneType identifier for filtering
versionintNoneAgent version number

@risicare.session

Decorator for session-bound functions.

@risicare.session(
    session_id_arg: str = "session_id",
    user_id_arg: str | None = "user_id",
)
def handle_request(session_id: str, user_id: str, query: str):
    ...
ParameterTypeDefaultDescription
session_id_argstr"session_id"Name of the function parameter containing the session ID
user_id_argstr"user_id"Name of the function parameter containing the user ID

@risicare.trace_think

Decorator for thinking phase.

@risicare.trace_think
def analyze():
    ...

@risicare.trace_decide

Decorator for decision phase.

@risicare.trace_decide
def plan():
    ...

@risicare.trace_act

Decorator for action phase.

@risicare.trace_act
def execute():
    ...

@risicare.trace_observe

Decorator for observation phase (state reading).

@risicare.trace_observe
def check_memory(key: str):
    """Read state from memory."""
    return memory.get(key)

@risicare.trace_message

Decorator for inter-agent message passing.

@risicare.trace_message(
    name: str | None = None,
    target: str | None = None,
    target_name: str | None = None,
)
def send_to_reviewer(message: str):
    """Send a message to another agent."""
    return response
ParameterTypeDefaultDescription
namestrFunction nameSpan name
targetstrNoneTarget agent ID
target_namestrNoneTarget agent name

@risicare.trace_delegate

Decorator for task delegation.

@risicare.trace_delegate(
    name: str | None = None,
    target: str | None = None,
    target_name: str | None = None,
)
def assign_research_task(task: str):
    """Delegate a research task to a worker agent."""
    return researcher.execute(task)
ParameterTypeDefaultDescription
namestrFunction nameSpan name
targetstrNoneTarget agent ID
target_namestrNoneTarget agent name

@risicare.trace_coordinate

Decorator for multi-agent coordination.

@risicare.trace_coordinate(
    name: str | None = None,
)
def sync_agents(agent_ids: list):
    """Coordinate state between multiple agents."""
    return sync_result

@risicare.trace

Generic trace decorator with customizable kind.

from risicare import SpanKind
 
@risicare.trace(
    name: str | None = None,
    kind: SpanKind = SpanKind.INTERNAL,
    attributes: dict | None = None,
)
def custom_operation():
    ...
ParameterTypeDefaultDescription
namestrFunction nameSpan name
kindSpanKindINTERNALSpan kind
attributesdictNoneStatic attributes to attach to the span

risicare.session_context

Context manager for sessions.

with risicare.session_context(
    session_id: str,
    user_id: str | None = None,
    metadata: dict | None = None,
    parent_session_id: str | None = None,
    turn_number: int = 1,
):
    ...

risicare.agent_context

Context manager for agents.

with risicare.agent_context(
    agent_id: str,
    agent_name: str | None = None,
    agent_role: str | None = None,
    agent_type: str | None = None,
    version: str | None = None,
    metadata: dict | None = None,
):
    ...

risicare.phase_context

Context manager for phases.

from risicare import SemanticPhase
 
with risicare.phase_context(phase: SemanticPhase):
    # Example: phase_context(SemanticPhase.THINK)
    ...

risicare.is_enabled

Check if tracing is enabled.

risicare.is_enabled() -> bool

risicare.get_current_trace_id

Get current trace ID.

trace_id = risicare.get_current_trace_id() -> str | None

risicare.get_current_span_id

Get current span ID.

span_id = risicare.get_current_span_id() -> str | None

risicare.get_current_session_id

Get current session ID.

session_id = risicare.get_current_session_id() -> str | None

risicare.get_current_agent_id

Get current agent ID.

agent_id = risicare.get_current_agent_id() -> str | None

risicare.get_current_parent_span_id

Get the parent span ID from the current context.

parent_span_id = risicare.get_current_parent_span_id() -> str | None

risicare.get_current_session

Get the active SessionContext, or None if no session is active.

session = risicare.get_current_session() -> SessionContext | None

Returns the full SessionContext dataclass with session_id, user_id, metadata, parent_session_id, and turn_number.

risicare.get_current_agent

Get the active AgentContext, or None if no agent context is active.

agent = risicare.get_current_agent() -> AgentContext | None

Returns the full AgentContext dataclass with agent_id, agent_name, agent_role, agent_type, version, and metadata.

risicare.get_current_span

Get the current active span, or None if no span is active.

span = risicare.get_current_span() -> Span | None

Async generators

In async generators, contextvars may lose the span reference after the first yield. Use the span registry (get_span_by_id) instead for async generator contexts.

risicare.get_current_phase

Get the active SemanticPhase, or None if no phase is active.

phase = risicare.get_current_phase() -> SemanticPhase | None

Returns one of: SemanticPhase.THINK, DECIDE, ACT, REFLECT, OBSERVE, COMMUNICATE, COORDINATE.

risicare.get_current_context

Get the full trace context state.

ctx = risicare.get_current_context() -> TraceContext

Returns a TraceContext object containing the current session, agent, span, phase, and trace/span IDs in a single call.

risicare.get_trace_context

Get W3C trace context for distributed tracing propagation.

trace_ctx = risicare.get_trace_context() -> TraceContext

risicare.get_tracer

Get the global Tracer instance. Use this for low-level span creation.

tracer = risicare.get_tracer() -> Tracer
tracer = risicare.get_tracer()
span = tracer.start_span("my-operation")
span.set_attribute("key", "value")
span.end()

risicare.enable

Re-enable tracing after it was disabled.

risicare.enable() -> None

risicare.disable

Temporarily disable all tracing. Instrumented calls become no-ops with zero overhead.

risicare.disable() -> None
# Disable tracing for a sensitive operation
risicare.disable()
result = do_sensitive_work()
risicare.enable()

risicare.get_client

Get the current RisicareClient instance, or None if not initialized.

client = risicare.get_client() -> RisicareClient | None

Span Registry

The span registry provides ID-based span lookup, which is essential for contexts where contextvars may not propagate reliably (async generators, thread pools).

risicare.register_span

Register a span in the global registry for later retrieval by ID.

risicare.register_span(span: Span) -> None

Spans created by decorators and context managers are registered automatically. Use this for manually created spans.

risicare.get_span_by_id

Retrieve a span by its ID from the global registry.

span = risicare.get_span_by_id(span_id: str) -> Span | None
# Useful in async generators where contextvars may be lost
async def stream_results(span_id: str):
    span = risicare.get_span_by_id(span_id)
    async for chunk in source:
        span.add_event("chunk", {"size": len(chunk)})
        yield chunk

risicare.unregister_span

Remove a span from the global registry.

risicare.unregister_span(span_id: str) -> None

Spans are unregistered automatically when they end. Use this only for manual cleanup.


Streaming

Utilities for tracing streaming responses from LLM providers.

risicare.traced_stream

Wrap an async iterator with tracing. Each chunk emits an event on the span, and the span is ended when the stream completes.

risicare.traced_stream(
    span_id: str,
    stream: AsyncIterator,
    event_name: str = "chunk",
) -> AsyncIterator
span = tracer.start_span("stream-response")
async for chunk in risicare.traced_stream(span.span_id, response.stream()):
    print(chunk)

risicare.traced_stream_sync

Synchronous version of traced_stream.

risicare.traced_stream_sync(
    span_id: str,
    stream: Iterator,
    event_name: str = "chunk",
) -> Iterator
span = tracer.start_span("stream-response")
for chunk in risicare.traced_stream_sync(span.span_id, response.stream()):
    print(chunk)

W3C Trace Context

Functions for propagating trace context across service boundaries using W3C traceparent and tracestate headers.

risicare.inject_trace_context

Inject W3C traceparent and tracestate headers into a headers dict.

risicare.inject_trace_context(headers: dict) -> dict
headers = {"Content-Type": "application/json"}
risicare.inject_trace_context(headers)
# headers now includes "traceparent" and "tracestate"
response = httpx.post(url, headers=headers)

risicare.extract_trace_context

Extract trace context from incoming W3C headers.

ctx = risicare.extract_trace_context(headers: dict) -> TraceContext | None
# In your HTTP handler
ctx = risicare.extract_trace_context(request.headers)
with risicare.restore_trace_context(ctx):
    process_request()

Auto-Instrumentation

Functions to control which modules are auto-instrumented.

risicare.install_import_hooks

Install Python import hooks for auto-instrumentation. Called automatically by risicare.init() when auto_patch=True.

risicare.install_import_hooks() -> None

risicare.remove_import_hooks

Remove auto-instrumentation import hooks. Modules already instrumented remain instrumented.

risicare.remove_import_hooks() -> None

risicare.instrument_already_imported

Instrument modules that were imported before risicare.init() was called. Called automatically by init().

risicare.instrument_already_imported() -> None

risicare.is_instrumented

Check if a specific module is currently instrumented.

risicare.is_instrumented(module_name: str) -> bool
if risicare.is_instrumented("openai"):
    print("OpenAI is being traced")

risicare.get_instrumented_modules

Get the set of module names currently instrumented.

modules = risicare.get_instrumented_modules() -> set[str]

risicare.get_supported_modules

Get the set of all module names supported for auto-instrumentation.

supported = risicare.get_supported_modules() -> set[str]
# e.g. {"openai", "anthropic", "cohere", "langchain", ...}

Exporters

OTLPExporter

Export spans via OTLP/HTTP protocol. Use this when sending traces to an OpenTelemetry-compatible backend alongside Risicare.

from risicare import OTLPExporter
 
exporter = OTLPExporter(
    endpoint="http://localhost:4318/v1/traces",
    headers={"Authorization": "Bearer token"},
)
 
risicare.init(exporters=[exporter])

Fix Runtime

The fix runtime loads, caches, and applies fixes at the SDK level. It runs inside your agent process and intercepts matching errors to apply the configured fix strategy.

FixRuntimeConfig

Configuration for the fix runtime.

from risicare import FixRuntimeConfig
 
config = FixRuntimeConfig(
    enabled=True,
    poll_interval_s=30,
    cache_ttl_s=300,
)

risicare.init_runtime

Initialize the fix runtime with a configuration.

risicare.init_runtime(config: FixRuntimeConfig) -> FixRuntime

risicare.get_runtime

Get the current fix runtime instance.

runtime = risicare.get_runtime() -> FixRuntime | None

risicare.shutdown_runtime

Shutdown the fix runtime gracefully.

risicare.shutdown_runtime() -> None

FixRuntime

Main fix runtime class. Coordinates FixLoader, FixCache, FixApplier, and FixInterceptor.

FixLoader

Loads fix configurations from the Risicare API.

FixCache

Caches fix configurations locally with configurable TTL to minimize API calls.

FixApplier

Applies a fix configuration to an error span (e.g., retry, fallback, parameter change).

FixInterceptor

Intercepts errors matching a fix rule and applies the configured fix before the error propagates.


Async Context Managers

risicare.async_session_context

Async version of session_context for use in async code.

async with risicare.async_session_context(
    session_id: str,
    user_id: str | None = None,
    metadata: dict | None = None,
    parent_session_id: str | None = None,
    turn_number: int = 1,
):
    await handle_request()

risicare.async_agent_context

Async version of agent_context for use in async code.

async with risicare.async_agent_context(
    agent_id: str,
    agent_name: str | None = None,
    agent_role: str | None = None,
    agent_type: str | None = None,
    version: str | None = None,
    metadata: dict | None = None,
):
    await run_agent()

risicare.restore_trace_context

Restore a previously saved or extracted TraceContext. Use this to re-establish context in a new scope, such as after extracting from W3C headers or restoring in a background task.

with risicare.restore_trace_context(ctx: TraceContext):
    process_request()

Types

Span

Core span data class representing a single unit of work.

from risicare import Span
 
span.trace_id       # str — 32 hex characters
span.span_id        # str — 16 hex characters
span.parent_span_id # str | None
span.name           # str
span.kind           # SpanKind
span.status         # SpanStatus
span.start_time     # float (epoch seconds)
span.end_time       # float | None
span.attributes     # dict
span.events         # list

SpanKind

from risicare import SpanKind
 
# Standard (OpenTelemetry compatible)
SpanKind.INTERNAL       # Default, internal operation
SpanKind.SERVER         # Server-side of RPC
SpanKind.CLIENT         # Client-side of RPC
SpanKind.PRODUCER       # Message producer
SpanKind.CONSUMER       # Message consumer
 
# Agent-specific
SpanKind.AGENT          # Agent lifecycle span
SpanKind.LLM_CALL       # LLM API call
SpanKind.TOOL_CALL      # Tool/function execution
SpanKind.RETRIEVAL      # RAG retrieval operation
SpanKind.DECISION       # Agent decision point
SpanKind.DELEGATION     # Delegation to another agent
SpanKind.COORDINATION   # Multi-agent coordination
SpanKind.MESSAGE        # Inter-agent message
 
# Phase-specific
SpanKind.THINK          # Reasoning/planning phase
SpanKind.DECIDE         # Decision-making phase
SpanKind.OBSERVE        # Environment observation phase
SpanKind.REFLECT        # Self-evaluation phase

SpanStatus

from risicare import SpanStatus
 
SpanStatus.OK       # Successful
SpanStatus.ERROR    # Error occurred
SpanStatus.UNSET    # Status not set

SemanticPhase

from risicare import SemanticPhase
 
SemanticPhase.THINK       # Reasoning / analysis
SemanticPhase.DECIDE      # Decision making
SemanticPhase.ACT         # Action execution
SemanticPhase.REFLECT     # Self-evaluation
SemanticPhase.OBSERVE     # State reading
SemanticPhase.COMMUNICATE # Inter-agent messaging
SemanticPhase.COORDINATE  # Multi-agent coordination

AgentRole

from risicare import AgentRole
 
# Primary roles
AgentRole.ORCHESTRATOR   # Coordinates other agents
AgentRole.WORKER         # Executes assigned tasks
AgentRole.SUPERVISOR     # Monitors and validates
AgentRole.SPECIALIST     # Domain expert
 
# Communication roles
AgentRole.ROUTER         # Routes messages/tasks
AgentRole.AGGREGATOR     # Aggregates results
AgentRole.BROADCASTER    # Broadcasts to multiple agents
 
# Specialized roles
AgentRole.CRITIC         # Reviews and critiques
AgentRole.PLANNER        # Creates execution plans
AgentRole.EXECUTOR       # Executes plans
AgentRole.RETRIEVER      # Retrieves information
AgentRole.VALIDATOR      # Validates outputs

MessageType

from risicare import MessageType
 
# Control messages
MessageType.TASK         # Task assignment
MessageType.RESULT       # Task result
MessageType.STATUS       # Status update
MessageType.ERROR        # Error notification
 
# Communication messages
MessageType.QUERY        # Information request
MessageType.RESPONSE     # Information response
MessageType.BROADCAST    # Broadcast to all
MessageType.DIRECT       # Direct message
 
# Coordination messages
MessageType.PROPOSAL     # Propose action
MessageType.VOTE         # Vote on proposal
MessageType.CONSENSUS    # Consensus reached
MessageType.CONFLICT     # Conflict detected
 
# Lifecycle messages
MessageType.HEARTBEAT    # Agent alive signal
MessageType.SHUTDOWN     # Shutdown signal
MessageType.HANDOFF      # Handoff to another agent

SessionContext

from risicare import SessionContext
 
session.session_id          # str
session.user_id             # str | None
session.metadata            # dict | None
session.parent_session_id   # str | None
session.turn_number         # int

AgentContext

from risicare import AgentContext
 
agent.agent_id    # str
agent.agent_name  # str | None
agent.agent_role  # str | None
agent.agent_type  # str | None
agent.version     # str | None
agent.metadata    # dict | None

TraceContext

from risicare import TraceContext
 
ctx.trace_id      # str
ctx.span_id       # str
ctx.trace_flags   # int
ctx.trace_state   # str | None

Next Steps