Decorators
Reference for all Risicare SDK decorators.
Risicare provides decorators for adding rich observability context to your agent code.
JavaScript SDK?
Agent Decorators
@agent
Marks a function as an agent entry point. All spans created within the function are associated with this agent.
from risicare import agent
@agent(
name="planner", # Agent name (optional, defaults to function name)
role="orchestrator", # See AgentRole for all 12 values: /docs/reference/sdk#agentrole
agent_type="custom", # Type identifier
version=1, # Agent version number
)
def plan_task(objective: str):
# All spans here are associated with this agent
return resultParameters:
| Parameter | Type | Default | Description |
|---|---|---|---|
name | str | Function name | Human-readable agent name (optional) |
role | str | None | Agent role (orchestrator, worker, supervisor, critic — see AgentRole for all 12 values) |
agent_type | str | None | Type identifier for filtering |
version | int | None | Agent version number |
Async Support:
@agent(name="async-planner")
async def async_plan_task(objective: str):
result = await some_async_operation()
return resultContext always propagates, even when tracing is off
@agent and phase decorators (@trace_think, @trace_decide, @trace_act, @trace_observe) always set their ContextVars regardless of whether tracing is enabled. This means get_current_agent() and get_current_phase() return values even when tracing is disabled. Only span creation is no-op'd — context propagation always runs.
Session Decorators
@session
Creates a session context. Can extract the session ID from function arguments, use a fixed ID, or auto-generate one.
from risicare import session
# Extract session_id from function argument (default behavior)
@session
def handle_request(session_id: str, user_id: str, query: str):
return agent.run(query)
# Fixed session ID (no arg inspection needed)
@session(session_id="AAPL-analysis")
def analyze(ticker: str):
return agent.run(ticker)
# Auto-generate a new UUID each call
@session(auto_generate=True)
def process(query: str):
return agent.run(query)
# Custom argument names
@session(session_id_arg="sid", user_id_arg="uid")
def handle(sid: str, uid: str, query: str):
return agent.run(query)Parameters:
| Parameter | Type | Default | Description |
|---|---|---|---|
session_id | str | None | Fixed session ID (skips arg inspection) |
session_id_arg | str | "session_id" | Name of the function parameter containing session ID |
user_id_arg | str | "user_id" | Name of the function parameter containing user ID |
auto_generate | bool | False | Generate a new UUID session ID per call |
Session ID Resolution Priority
session_idkwarg (fixed value)session_id_argfound in function argumentsauto_generate=Truegenerates a fresh UUID- No match found — runs without session context
Phase Decorators
Track semantic decision phases:
@trace_think
Marks a function as a THINK phase (reasoning, planning).
from risicare import trace_think
@trace_think
def analyze_problem(context: dict):
"""Analyze the problem and identify key factors."""
# Reasoning logic here
return analysis@trace_decide
Marks a function as a DECIDE phase (decision-making).
from risicare import trace_decide
@trace_decide
def choose_action(options: list):
"""Select the best action from available options."""
# Decision logic here
return selected_action@trace_act
Marks a function as an ACT phase (action execution).
from risicare import trace_act
@trace_act
def execute_tool(tool_name: str, args: dict):
"""Execute a tool with the given arguments."""
# Action execution here
return resultThe span has the kind tool_call and the phase act. It does not record the arguments or the return value. See Trace your own tool function.
@trace_observe
Marks a function as an OBSERVE phase (state reading).
from risicare import trace_observe
@trace_observe
def check_memory(key: str):
"""Read state from memory."""
return memory.get(key)All phase decorators accept an optional name parameter to customize the span name (defaults to <phase>:<function name>, for example think:analyze):
@trace_think(name="strategic-analysis")
def analyze(context: dict):
...Multi-Agent Decorators
@trace_message
Tracks inter-agent message passing.
from risicare import trace_message
@trace_message
def send_to_reviewer(message: str):
"""Send a message to another agent."""
return reviewer.receive(message)
@trace_message(target="reviewer-001", target_name="Code Reviewer")
def send_review_request(code: str):
"""Send a review request to the reviewer agent."""
return reviewer.review(code)Parameters:
| Parameter | Type | Default | Description |
|---|---|---|---|
name | str | communicate:<function name> | Custom span name |
target | str | None | Target agent ID for the message recipient |
target_name | str | None | Human-readable name of the target agent |
@trace_delegate
Tracks task delegation to other agents.
from risicare import trace_delegate
@trace_delegate
def assign_research_task(task: str):
"""Delegate a research task to a worker agent."""
return researcher.execute(task)
@trace_delegate(target="research-agent", target_name="Research Specialist")
def delegate_analysis(topic: str):
"""Delegate analysis to a specialist."""
return specialist.analyze(topic)Parameters:
| Parameter | Type | Default | Description |
|---|---|---|---|
name | str | coordinate:<function name> | Custom span name. A delegate span carries the coordinate phase |
target | str | None | Target agent ID that work is delegated to |
target_name | str | None | Human-readable name of the target agent |
@trace_coordinate
Tracks coordination between multiple agents.
from risicare import trace_coordinate
@trace_coordinate
def sync_agents(agent_ids: list):
"""Coordinate state between multiple agents."""
# Synchronization logic
return sync_resultGeneric Decorator
@trace
Creates a span with customizable kind and attributes. Works as both a decorator and a context manager.
As a decorator:
from risicare import trace
from risicare import SpanKind
# Bare decorator (uses function name as span name)
@trace
def process_data(data: dict):
return transform(data)
# With parameters
@trace(name="custom-operation", kind=SpanKind.INTERNAL)
def custom_operation(data: dict):
return process(data)As a context manager:
from risicare import trace
def complex_pipeline(data):
with trace("step-1"):
intermediate = preprocess(data)
with trace("step-2", attributes={"batch_size": len(data)}):
result = transform(intermediate)
return resultParameters:
| Parameter | Type | Default | Description |
|---|---|---|---|
name | str | Function name | Span name |
kind | SpanKind | INTERNAL | Span kind |
attributes | dict | None | Static attributes to add to the span |
Trace your own tool function
JavaScript and TypeScript
traceAct(), or getTracer().startSpan() with SpanKind.TOOL_CALL), see Trace your own tool function in JavaScript.The OpenAI and Anthropic patches trace the model call. They record on its span that the model asked for a tool: the name, and the arguments when content capture is on. They do not trace the function of yours that runs the tool. In an agent loop that you write yourself, wrap that function. Then each run of the tool is a span of its own, with its time, its status and its exception.
The Tools column of the trace list counts the spans of kind tool_call. A trace in which you wrap no tool function shows 0 tools.
import risicare
from risicare import SpanKind, agent, trace, trace_act
risicare.init()
@trace(name="get_weather", kind=SpanKind.TOOL_CALL)
def get_weather(city: str) -> str:
return fetch_weather(city)
@trace_act
def lookup_order(order_id: str) -> dict:
return find_order(order_id)
@agent(name="support-agent") # one trace for the whole loop
def run(question: str):
... # your loop: call the model, run get_weather or lookup_order, call the model again| Decorator | Name of the span | Kind | Phase |
|---|---|---|---|
@trace(name="get_weather", kind=SpanKind.TOOL_CALL) | The name that you give. Without name, the name of the function | tool_call | None |
@trace_act | act:<function name>, for example act:lookup_order. @trace_act("name") and @trace_act(name="name") choose another name | tool_call | act |
Both decorators work on sync and async functions, and as a with block. Put the loop in @agent(...) or in @trace, so that the model calls and the tool calls are in one trace.
A tool that fails. When the tool raises, its span has the status error and the exception, and the exception goes on to your code. You do not call report_error() for it. See When to call report_error.
The input and the output. The two decorators do not record the arguments or the return value of your function, and the SDK has no option that does. To show them, open the span with with trace(...) as span: and set the keys tool.input and tool.output:
import json
from risicare import SpanKind, trace
def lookup_order(order_id: str) -> dict:
with trace("lookup_order", kind=SpanKind.TOOL_CALL) as span:
span.set_attribute("tool.input", json.dumps({"order_id": order_id}))
order = find_order(order_id)
span.set_attribute("tool.output", json.dumps(order))
return orderThe span panel of a tool call shows these two keys in Input / Output. They are content: with trace_content=False, the SDK replaces both with <risicare:content-omitted>.
Context Managers
For fine-grained control, use context managers instead of decorators:
agent_context
from risicare import agent_context, async_agent_context
# Sync
with agent_context("planner-001", agent_name="planner", agent_role="worker"):
do_work()
# Async
async def main():
async with async_agent_context("planner-001", agent_name="planner", agent_role="worker"):
await do_work()session_context
from risicare import session_context, async_session_context
# Sync
with session_context("sess-123", user_id="u-456"):
agent.run(query)
# Async
async def main():
async with async_session_context("sess-123", user_id="u-456"):
await agent.run(query)Put the session outside the run: open session_context() first, and the run (@agent, @trace or with risicare.trace(...)) inside it. See Session outside, run inside.
phase_context
from risicare import phase_context
from risicare import SemanticPhase
with phase_context(SemanticPhase.THINK):
# This code is in THINK phase
analyze()Best Practices
Decorator Stacking
Decorators can be stacked. Apply them in order from outermost (first) to innermost (last):
@agent(name="planner")
@trace_think
def planning_phase():
passAsync Support
All decorators support both sync and async functions automatically.
Generator Functions
Since Python 0.16.0, @agent, @trace, @session and the phase decorators work on a generator function and on an async generator function. An example is the generator of a FastAPI StreamingResponse.
from fastapi import FastAPI
from fastapi.responses import StreamingResponse
from risicare import agent
app = FastAPI()
@agent(name="writer")
async def write(prompt: str):
stream = await client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": prompt}],
stream=True,
)
async for chunk in stream:
yield chunk.choices[0].delta.content or ""
@app.get("/story")
async def story(prompt: str):
return StreamingResponse(write(prompt), media_type="text/plain")The decorator makes a span that covers the iteration:
- The LLM calls of the body are the children of this span. They have its agent and its session.
- The span ends when the generator is exhausted (status
ok), raises (statuserror), is closed early or is cancelled. A close and a cancel are not errors (since Python 0.16.1). See A close and a cancel are not errors. - The span, the agent, the session or the phase are current for the body, also across a
yield. They are not current for your code between two items. - The parent of the span is the span that is current at the first item, not at the call.
- A generator that sampling drops loses its whole trace.
- The decorated function is still a generator function.
Before 0.16.0, such a decorator closed its span at once with the status ok, so the span lasted 0 s. The body ran outside it. The LLM calls of the body were traces of their own with no agent and no session, and nothing recorded the error of the body.
A stream that you build yourself
To record the chunks of a stream as events on a span, use the streaming utilities — see Streaming:
from risicare import traced_stream, get_tracer
async def generate(prompt):
with get_tracer().start_span("llm_stream") as span:
async for chunk in traced_stream(span_id=span.span_id, stream=llm.stream(prompt)):
yield chunkRead a generator like this to its end, or close it with contextlib.aclosing() where you stop early. A generator that is dropped part-way and closed later, in another task or thread, can leave its ended span as the current span, so the next span becomes its child (a known issue that the release does not fix).
FastAPI: a streaming response
Call risicare.init() once, in the module of your app, before the first request. Put @agent(...) (or @trace(...)) on the generator that the StreamingResponse reads, as in the example above.
- Where the trace goes. Each request is one trace. Its root is the span of the decorated generator. The span starts at the first item and ends when the stream ends. The LLM calls of the body are its children, also the calls after a
yield. - A client that disconnects. Starlette stops the stream: it closes the generator (
GeneratorExit) or cancels its task (asyncio.CancelledError). Since Python 0.16.1, the span then ends with no error status, no exception record and noerror.code. It getsrisicare.cancelled = true,risicare.cancel_type(GeneratorExitorCancelledError) andrisicare.lifecycle.status = "cancelled". So a request that the client stopped is not a failed trace. Through Python 0.16.0, the span had the statuserror(for a close, with the messageGeneratorExit:), so a disconnect looked like a failed run with no reason. - An error. An exception that your generator raises is an error, as before. An exception that your code raises while it handles the close or the cancel (for example in a
finallyblock) is an error too. - When the server stops. uvicorn owns
SIGTERM. See SIGTERM and SIGINT.
A close and a cancel are not errors
Since Python 0.16.1, a close and a cancel of a decorated function or of a with risicare.trace(...) block are not errors. This applies to @agent, @trace, @session (its session.end marker), the phase decorators and with risicare.trace(...):
- A close:
GeneratorExit, when the consumer closes a generator early (abreak,close(), or the client of aStreamingResponsethat stops reading). - A cancel:
asyncio.CancelledError(for example when Starlette cancels a request on a disconnect),KeyboardInterruptandSystemExit.
The span then has no error status, no exception record and no error.code. It has these three attributes:
| Attribute | Value |
|---|---|
risicare.cancelled | true |
risicare.cancel_type | The type name, for example GeneratorExit or CancelledError |
risicare.lifecycle.status | cancelled |
A filter on risicare.lifecycle.status can see this new value, cancelled. An exception that your code raises while it handles the close or the cancel is an error. A TimeoutError from asyncio.wait_for is an error on the span that waited. Through Python 0.16.0, a close gave the status error with the message GeneratorExit: , and a cancel gave the status error with the cancel marker. For JavaScript, see An abort is not an error.