risicare
AI agent observability for Python: traces, errors, cost, evaluations and prompts.
Monitor your AI agents in production. One init() call traces the LLM calls of
the supported providers and frameworks, records errors, and sends the spans to
Risicare. In the Risicare dashboard you see the traces, the errors and the cost.
Risicare is in a free beta: you need no paid subscription. Error diagnosis and
fixes are not available yet (see "Errors and fixes").
Quickstart
pip install risicare
import risicare
from openai import OpenAI
# Initialize. This also instruments the supported LLM providers.
risicare.init(api_key="rsk-...")
client = OpenAI() # Automatically traced by risicare
@risicare.agent(name="research-agent")
def research(query: str) -> str:
response = client.chat.completions.create(
model="gpt-4",
messages=[{"role": "user", "content": query}],
)
return response.choices[0].message.content
result = research("What is quantum computing?")
risicare.shutdown()
The SDK sends one span for the agent function and one span for the LLM call, in the same trace. The LLM span has the model, the latency, the token counts and, by default, the prompt and completion text (see Prompt content is captured by default). You see them in the Risicare dashboard.
Two hosts
The SDK sends data to two hosts:
- Spans go to
endpoint. The default ishttps://ingest.risicare.ai. - Scores and fix reads go to
api_endpoint. The default ishttps://api.risicare.ai.
For the hosted service, set no endpoint. For your own deployment, set
endpoint (or RISICARE_ENDPOINT). Spans go to the endpoint argument, then
RISICARE_ENDPOINT, then the default. Scores and fix reads go to the first of
these that is set:
- the
api_endpointargument; - the
endpointargument, unless it is the default ingest host; - the
RISICARE_API_ENDPOINTenvironment variable; - the
RISICARE_ENDPOINTenvironment variable, if you gave noendpointargument and it is not the default ingest host; - the default,
https://api.risicare.ai.
The SDK ignores the default ingest host (https://ingest.risicare.ai) when it
selects the api host, and goes to the next step. So your key does not go to a
host that you did not name. Only that exact value is ignored (letter case, a
:443 port and slashes at the end do not matter). A different form, for
example http://ingest.risicare.ai or https://ingest.risicare.ai/v1, is a
host that you named, and the SDK uses it. A value that is empty, or that has
ASCII whitespace only, is "not set". RISICARE_ENDPOINT=https://my-host alone sends spans, scores and fix
reads to https://my-host.
Configuration
api_key is the only init() argument that you can give by position. Give
all other arguments by keyword, for example init("rsk-...", endpoint=...).
A second init() call returns the client that the first call made, and it
ignores its arguments.
Without code (Tier 0). When RISICARE_TRACING turns tracing on and
RISICARE_API_KEY is set, import risicare calls init() with the key only.
All other settings come from the environment or the defaults, as for an
explicit init() call: when RISICARE_ENVIRONMENT and
RISICARE_SERVICE_NAME are not set, the environment is development and
there is no service name. A later init() call with at least one argument stops that
client and makes a new one with your arguments. When RISICARE_TRACING is on and
RISICARE_API_KEY is not set, the import logs one WARNING (see "No API key") and makes
no client.
RISICARE_TRACING is trimmed and compared without case:
| Value | Result |
|---|---|
true, 1, yes, on |
tracing on |
false, 0, no, off |
tracing off |
| unset, empty, or whitespace only | the default applies (on for init(); no import-time init()) |
| any other value | tracing off, with one WARNING that names the value |
The other boolean switches. Every RISICARE_* switch that is on or off is read by one
parser, with the same words as RISICARE_TRACING: true, 1, yes, on and false, 0,
no, off, trimmed, in any case. An argument of init() has priority over the variable. Each
WARNING is written once for each variable and value in the process, and it names the variable,
the value read and the value used.
| Switch | Default | Empty value | Any other value |
|---|---|---|---|
RISICARE_TRACING |
on for init() |
the default (as above) | off, with one WARNING |
RISICARE_TRACE_CONTENT |
on | off, with one WARNING | off, with one WARNING |
RISICARE_DEBUG, RISICARE_OTEL_BRIDGE, RISICARE_FIX_RUNTIME, RISICARE_STRICT_INSTRUMENTATION |
off | the default | the default, with one WARNING |
RISICARE_FIX_ENABLED, RISICARE_FIX_AUTO_REFRESH, RISICARE_AB_TESTING, RISICARE_TRACK_EFFECTIVENESS (FixRuntimeConfig.from_env() only) |
on | off, with one WARNING | off, with one WARNING |
RISICARE_FIX_CACHE (from_env() only) |
on | the default | the default, with one WARNING |
RISICARE_FIX_DRY_RUN (from_env() only) |
off | the default | the default, with one WARNING |
RISICARE_STREAM_USAGE, RISICARE_ERROR_TEXT |
auto (also takes auto) |
auto |
auto, with one WARNING |
The exceptions (in bold) have one reason: a switch that sends data or makes requests when it is
on never turns on from a value that is not a recognised "on" word. So an unrecognised value of
such a switch is off. An empty value of such a switch is off too, as it was before this rule: a
blank line such as RISICARE_TRACE_CONTENT= in a .env file turned content capture off before,
and it still does. Remove the variable to get the default. RISICARE_TRACING keeps its own rule
for an empty value (the default), as before. Through 0.15.0, FixRuntimeConfig.from_env() took
only the word true: 1, yes and on read as off, and they now read as on. Through 0.15.0 the
other switches were not trimmed: " true" read as off, and it now reads as on.
No API key: no network. With no API key, the SDK sends nothing to Risicare,
whatever RISICARE_TRACING, enabled or enable() says. init() logs one
WARNING that says so, in plain words (none when tracing is explicitly off). An
import with RISICARE_TRACING=true logs the same WARNING. is_enabled()
returns False, flush() returns False, and nothing is counted as exported.
enable() cannot turn on what has no exporter that can deliver. An exporter
that you name (otlp_endpoint, exporters=[...]) is your own host, not a
Risicare host, so it still delivers without a key: is_enabled() is then
True, flush() reports the delivery of that exporter, and the WARNING does
not appear. The SDK's own HttpExporter never sends a request without a key,
whatever its endpoint, also when it points at your own relay: init() and
add_exporter() leave out an HttpExporter that has no key. It gets the
init() key only when its endpoint is the endpoint of init(); give any other
one api_key=. A key is trimmed of whitespace and of the other characters that
JavaScript's trim() removes (no-break space, ideographic space, byte order
mark and others). A key that is empty after the trim is no key, and an empty or
blank api_key argument counts as "not given", so RISICARE_API_KEY applies.
debug=True with no key still prints the spans to stdout,
unredacted, for local development only. That is display only: the spans are
never sent and never counted, is_enabled() is False and flush() is
False. The same holds with tracing off (enabled=False,
RISICARE_TRACING=false): is_enabled() and flush() return False.
Prompt content is captured by default
trace_content defaults to True. The SDK sends your prompts and
completions to Risicare, and Risicare stores them. The model, the token counts,
the latency, the message roles, the errors and the attributes that you set are
sent in all cases, except that with capture off each content-keyed attribute
(also one that you set) is replaced with <risicare:content-omitted>.
To stop the capture of prompt and completion text, set it off in your code or in the environment:
risicare.init(api_key="rsk-...", trace_content=False)
# or set RISICARE_TRACE_CONTENT=false
The argument wins over the environment variable. You can also turn off content capture in the project settings. The gateway then drops content for that project, also when the SDK still sends it.
The text goes to every exporter of the SDK: the Risicare endpoint, the
exporters that you pass in exporters=[...], an otlp_endpoint, the console
with debug=True, and, with the OTel bridge, the spans of other OpenTelemetry
instrumentations.
With trace_content=False, the SDK also withholds the error text: the
status message, the exception messages, their copies in the stack traces,
error.message, exception.message and error.stack become
<risicare:content-omitted>. An error message can hold part of a prompt or of
the model's output: a provider's 400 answer can repeat the input, a validation
error names the value, a parser error quotes the model's answer. The exception
type, error.code (classified in your process from the full text before it is
withheld) and the status stay. The frame lines of a stack trace stay too: a
File "...", line N, in name line with its ONE source line and its caret
lines, and a JavaScript at name (file:line:column) or at file:line:column
line. Any other line of a stack gets the marker, and a chained cause, an
exception group and a stack that is not the exception's own get the marker
whole. The rule is the rule of the project switch at the gateway (the
error_text section of the content-keys corpus v4), with two more steps that
withhold more, never less.
Known limit. A line that has the exact shape of a frame line is kept, also
when your code wrote it (for example a note or a message that holds
File "x", line 1, in name). The path of a frame line (any text in the quotes),
the one source line after it, and the name before a withheld message
(Name: <risicare:content-omitted>) are kept as they are. The gateway keeps the
source lines in the same way.
risicare.init(trace_content=False) # error text withheld ("auto")
risicare.init(trace_content=False, error_text=True) # error text sent, as in 0.12.0
risicare.init(trace_content=True, error_text=False) # error text withheld, content sent
# or set RISICARE_ERROR_TEXT=true / false / auto
Upgrading with content capture off? This is a behaviour change: the free
text of an error no longer reaches the dashboard. Set error_text=True to get
it back, and only when you accept that an exception message can carry prompt or
model output.
Upgrading from 0.6.3 or earlier? This is a behaviour change. From 0.2.2
to 0.6.3 the default was False: prompts and completions stayed in your
process unless you opted in. Now they are sent unless you stop them. To keep
the old behaviour, add trace_content=False or set
RISICARE_TRACE_CONTENT=false.
The flag covers content that you set by hand too (since 0.2.2). For example,
trace_content=False stops a span.set_attribute("gen_ai.prompt.0.content", ...)
from reaching us. In 0.2.0 and earlier the flag did not do this.
When capture is off, content-bearing attributes are replaced with
<risicare:content-omitted> rather than removed, so "no prompt was sent" stays
distinguishable from "capture is off".
With trace_content=False, the error text is withheld too (see above;
error_text controls it).
Since 0.4.0, the gate also covers the OpenTelemetry GenAI, OpenInference and
CrewAI content keys, for example input.value, output.value,
gen_ai.input.messages and gen_ai.output.messages.
If you want content captured but redacted first, use the mask hook. It runs
on every content-bearing field of every span before export, for every
exporter. It gets the attribute key and the value, and it must return a value
that JSON can encode:
import re
def mask(key, value):
# Replace e-mail addresses in prompts and completions.
if isinstance(value, str):
return re.sub(r"[\w.+-]+@[\w-]+\.[\w.]+", "<email>", value)
return value
risicare.init(api_key="rsk-...", mask=mask)
The span is NOT dropped when the mask returns a value that JSON cannot encode:
the SDK then sends the str() text of that value. So do not return an object
whose str() or repr() shows the original text; return a string, a number, a
boolean, None, or a list or dict of those. When the mask raises, the SDK sends
<risicare:mask-error> in the place of the value.
The request that the OpenAI and Anthropic patches send
For a call through openai or anthropic, the patches send the data that a replay of the call
needs. This is new in 0.9.0 (see the CHANGELOG, "Behaviour change").
With content capture on (the default), each call gets three more attributes:
| Attribute | Content | Cap (UTF-8 bytes) |
|---|---|---|
gen_ai.tool.definitions |
your tools: name, description and parameter schema, in one flat form (input_schema of Anthropic becomes parameters) |
24,576 |
gen_ai.system_instructions |
the Anthropic system prompt, a string or a list of blocks, kept whole (an OpenAI system message stays in the message list) |
16,384 |
gen_ai.input.messages |
the whole messages list, with each tool call and each tool result paired by id (an Anthropic tool result keeps its is_error flag) |
49,152 |
A value above its cap is cut: the longest strings first, each ending in ... [truncated], then a
long list keeps its first and last items. The text stays valid JSON. The three keys are written
last. A key is written only if the strings on the span stay at or below 96,000 bytes (the gateway
refuses a span above 131,072 bytes); a key that does not fit is not written at all. The old keys
(gen_ai.prompt.{i}.* for the first 10 messages and gen_ai.system_prompt) do not change.
With trace_content=False (or RISICARE_TRACE_CONTENT=false) the three keys are not built and not
sent. These request parameters are not content, so they are sent with capture on or off:
gen_ai.request.top_p, gen_ai.request.tool_choice, gen_ai.request.stop_sequences (the stop
of OpenAI) and gen_ai.request.seed (OpenAI only). A parameter that you did not set is not sent.
The cap of the message list is a setting. The three caps above are fixed, except the cap of
gen_ai.input.messages:
| Setting | Default | Range | Effect |
|---|---|---|---|
max_input_messages_bytes (argument of init()) |
49,152 | 1,024 to 65,535 | The cap of gen_ai.input.messages, in UTF-8 bytes. A number outside the range, 0 and a negative number too, is clamped, with one WARNING. A value that is not a number (a string too) is not used: the default stays, with one WARNING. No environment variable. |
The default cuts 24.0 % of the LLM spans of the TRAIL traces (GAIA and SWE Bench) and 0.2 % of the
tau2 airline calls (measured 2026-10-31). If your prompts are long, raise it, for example
risicare.init(max_input_messages_bytes=65535). The ceiling is the gateway's cut of one value
(65,536 bytes), and a cut JSON text is not valid JSON. The limit of 96,000 bytes for the strings
of one span stays whatever the value is: a key that does not fit is not written. The first 10
messages are also in the old keys gen_ai.prompt.{i}.content (up to 10,000 characters each), so a
raised cap helps when those keys leave room for the list.
The OpenAI Responses API writes the same keys: instructions is a system message, and input gives the
other messages (a function_call item is a tool call, a function_call_output item a tool result).
The other providers and the framework integrations are not changed.
The tool calls of the answer
For an OpenAI Chat Completions call and an Anthropic Messages call, the span of the call records the
tool calls of the answer. A streamed answer records the same keys as a non-stream answer:
create(stream=True) of both providers, sync and async, the OpenAI chat.completions.stream()
helper, and the Anthropic messages.stream() helper (anthropic 0.50 and later). In risicare 0.13.1 and earlier, a streamed answer recorded no tool call
and no finish or stop reason. The one exception was messages.stream() on anthropic 0.30 and 0.40,
whose span reads the final message of the stream (it still does).
| OpenAI | Anthropic | |
|---|---|---|
| The number of calls | gen_ai.completion.tool_calls |
gen_ai.completion.tool_uses |
The name of call j (the first 5) |
gen_ai.completion.tool_call.{j}.name |
gen_ai.completion.tool_use.{j}.name |
The arguments of call j (the first 5; content) |
gen_ai.completion.0.tool_calls.{j}.arguments |
the same key: the input, as JSON text |
| Why the answer ended | gen_ai.completion.finish_reason |
gen_ai.response.stop_reason |
- The count and the names are not content: they are sent with capture on or off. The arguments are
content: they are sent only with content capture on, after your
mask. Each argument text is cut at 10,000 characters. - OpenAI: the first choice only. The parts of a streamed call are joined as the
openailibrary joins them; a part that repeats the whole name does not double it. Anthropic: the input of a streamed call is written asjson.dumpswrites the non-streaminput(an input over 1,000,000 characters is written as the raw text that came, cut at 10,000). - A stream that ends early (you stop reading it, an error, a cancel) records what it received: a call whose arguments were cut has the text that came, and there is no finish or stop reason.
- The id of a call is not on the span of the call that made it. With content capture on, it is on
the span of the NEXT call, in
gen_ai.input.messages(the tool call and its result, paired by id), when that list fits its cap. With capture off, no span has the id.
Features
- Auto-instrumentation —
init()instruments the supported LLM providers and frameworks. You do not change your LLM calls - 13 LLM providers — OpenAI, Anthropic, Google Gemini (
google-generativeaiandgoogle-genai), Mistral, Groq, Cohere, Together, Ollama, HuggingFace, Cerebras, Bedrock, Vertex AI. Import them before or afterinit() - OpenAI-compatible APIs — the OpenAI patch traces every API that you call through
openai.OpenAI(base_url=...), and it names 8 hosts (see below) - 10 framework integrations — LangChain, LangGraph, CrewAI, AutoGen, Instructor, LlamaIndex, LiteLLM, DSPy, Pydantic AI, OpenAI Agents
- Errors — the SDK records each error on its span, with an error code; error diagnosis and fixes are not available yet (see "Errors and fixes" below)
- Streaming — see "Streaming" below: it says, for each provider, what a traced stream is
- OpenTelemetry bridge — sends the spans of your OpenTelemetry SDK to Risicare too
- Background export — a worker thread exports the spans in batches;
score()sends on its own thread
LLM Providers
Providers are instrumented by default. You do not set anything.
# auto_patch=False does NOT turn off provider instrumentation. It only stops
# the context patches of ThreadPoolExecutor, ProcessPoolExecutor and asyncio.
risicare.init(api_key="rsk-...", auto_patch=False)
With auto_patch=False, an LLM call that runs in a ThreadPoolExecutor
worker is still traced, but its span has no parent span.
All 13 native providers. A provider is traced when you import it before init() and when you import it after init(), with an import statement. "Measured" is the package version that we measured on 2026-10-03, with real calls to a local test server. The repository tests run the same checks on each version in the table, except: google-generativeai 0.8.6 and mistralai 0.4.2 and 1.2.0 were measured in a separate environment, and the repository tests cover mistralai 0.x and 1.x with synthetic package layouts.
| Provider | Package (module) | Traced calls | Measured |
|---|---|---|---|
| OpenAI | openai |
chat.completions.create, chat.completions.parse (structured outputs; beta.chat.completions.parse before openai 1.92), embeddings.create, and the Responses API: responses.create (also with stream=True and through responses.stream()) and responses.parse (sync and async) |
2.54.0 |
| Anthropic | anthropic |
messages.create, the messages.stream() helper, messages.parse, and beta.messages.create / stream() / parse (sync and async) |
1.11.0; the helpers, parse and beta 2.8.0, 0.75.0, 0.50.0 and 0.40.0 (2026-11-16) |
| Google Gemini | google-generativeai (google.generativeai) |
GenerativeModel.generate_content (sync and async) |
0.8.6 |
| Google Gemini | google-genai (google.genai) |
client.models.generate_content and generate_content_stream, sync and async (client.aio.models), also through client.chats; the Gemini API and Vertex AI (Client(vertexai=True)). One span for each model request (see below) |
1.75.0 and 2.33.0 (2026-11-16); also 1.0.0 and 3.3.0 in a separate environment |
| Mistral | mistralai 0.x, 1.x, 3.x |
chat completions, sync and async. Streaming calls are not traced | 0.4.2, 1.2.0, 3.0.0 |
| Cohere | cohere |
Client / AsyncClient: chat, generate, embed. ClientV2 is not traced |
7.2.0 |
| Groq | groq |
chat.completions.create (sync and async) |
1.7.0 |
| Together AI | together |
chat.completions.create (sync and async) |
2.39.0 |
| Ollama | ollama |
ollama.chat, ollama.generate, and chat / generate on Client and AsyncClient |
0.6.3 |
| AWS Bedrock | boto3 (botocore) |
bedrock-runtime: Converse, ConverseStream, InvokeModel, InvokeModelWithResponseStream (sync) |
1.43.108 |
| Google Vertex AI | google-cloud-aiplatform (vertexai) |
generative_models.GenerativeModel.generate_content (sync and async) |
1.148.1 |
| Cerebras | cerebras-cloud-sdk |
chat.completions.create (sync and async) |
1.91.0 |
| HuggingFace | huggingface-hub |
InferenceClient / AsyncInferenceClient: chat_completion, text_generation |
1.33.0 |
google-genai. One call can send more than one request to the model: the automatic function
calling loop sends one request for each turn, and the automatic continuation (google-genai 2.30.0
and later) one for each hop. Risicare makes one LLM span for each request, with the tokens of that
request. A tool that the loop calls runs between two requests, so its span is not in an LLM span
(in a stream, google-genai runs the tool while the stream of the request is still open). The
provider name (gen_ai.system) is google for the Gemini API and vertexai for a Vertex AI
client. To do this, Risicare wraps private methods of google-genai (_generate_content and
_generate_content_stream). When a google-genai release does not have one of them, Risicare traces
the public method in its place: one span for each call, and a function calling loop is one span
with the tokens of its last request. The state of google.genai in get_instrumented_modules() is
then partially_instrumented, and Risicare logs one WARNING that names the method.
Known limit: a resumed stream. google-genai 2.30.0 and later resume a stream that breaks after
a continuation token. Your code gets the whole answer and no exception, but the request that broke
has an error span: the dashboard shows an error in the trace, and a trace.error webhook fires if
you set one. The run itself is not marked failed.
If you write from ollama import chat before init(), your name keeps the function that is not traced. Use ollama.chat(...) or an ollama.Client.
Bedrock and Vertex AI are patched when your program loads the module that holds the client (botocore.client, which import boto3 loads, and vertexai.generative_models). Risicare does not import these modules itself.
A package that your program imports only with importlib.import_module() after init() is not traced at once. It is traced when the next import statement for that package runs.
Raw responses. A client.<resource>.with_raw_response.create(...) call (OpenAI, Anthropic,
Groq, Cerebras, Together; CrewAI calls OpenAI this way) has the tokens and the model of its answer:
the span reads the answer with parse(), and your own parse() gets the same object. The body of
a with_streaming_response call is not read when the call returns, and Risicare does not read it
before you. So its span stays open: it gets the tokens and the model from your own parse() and
ends there. A block exit or close() before a parse() ends it with no tokens and
stream.end_reason handoff (you read the body with iter_lines(), json() or read(), or not
at all); a drop ends it with garbage. A body read that fails (a dropped connection) ends it with
the error. gen_ai.latency_ms is the time to the response headers.
OpenAI-compatible APIs. The OpenAI patch traces a call to any host that
you reach through openai.OpenAI(base_url=...). It sets the provider name
(gen_ai.system) from the host for 8 hosts: DeepSeek (api.deepseek.com),
Together (api.together.xyz), Groq (api.groq.com), xAI (api.x.ai),
Fireworks (api.fireworks.ai), Baseten (inference.baseten.co), Novita
(api.novita.ai) and BytePlus (ark.cn-beijing.byteplus.com). For every
other host, for example a vLLM server, the provider name is openai.
Cache and reasoning token counts
When the provider gives them, the LLM span also has
gen_ai.usage.cache_read.input_tokens, gen_ai.usage.cache_write.input_tokens
and gen_ai.usage.reasoning.output_tokens: OpenAI (chat and Responses),
Anthropic, Gemini (google.genai, google-generativeai, Vertex AI: the cached and
the thinking tokens), Bedrock Converse (the cache read and write tokens) and
Groq. A count that the provider did not give is not sent: the SDK never derives
or estimates one.
Known limit: a 1-hour cache write. Anthropic and Bedrock can write to the
cache for 5 minutes or for 1 hour, and a 1-hour write costs more. The SDK counts
both in gen_ai.usage.cache_write.input_tokens, so the token total is correct,
but the cost of a 1-hour write is under-counted (priced as a 5-minute write)
until the server knows a key for it (issue #211).
Streaming
- Anthropic stream helpers (
messages.stream(),beta.messages.stream()). The stream manager and theMessageStreamthat you get are the library's own: events,text_stream,get_final_message()anduntil_done()work as without risicare. The span opens when the helper sends the request (atwith), and ends when the stream ends, fails or is closed (the block exit closes it); it has the tokens and the cache counts of the stream. AKeyboardInterruptor a cancel in the block gives the cancel marker; an error of the library's own parse of the answer (output_format) gives the error status, without the output when content capture is off; an error of your own code in the block leaves the span ok. anthropic 0.30 and 0.40 (and a later release that changes the private request of the manager) take a fallback: the span runs from the block's enter to its exit, with the tokens ofcurrent_message_snapshot, andget_instrumented_modules()["anthropic"]["state"]ispartially_instrumented, with a WARNING. - OpenAI, Anthropic, Groq, Cerebras and Together. A traced
stream=Truecall returns a proxy of the provider's stream object.with ... as stream:, iteration,close(),responseand the other attributes work as without risicare. The span ends when the stream is exhausted, when it is closed, when you drop it, or when you leave it through an exception. - Google Gemini (
google-generativeai). A tracedgenerate_content(stream=True)call returns a proxy of the response object. Iteration,resolve(),textandcandidateswork as without risicare. - Google Gemini (
google-genai).generate_content_streamreturns the generator of google-genai, unchanged. Each request of the stream has its span, which ends when the stream of that request ends, fails or is closed, or when it is dropped. The Gemini API sends the tokens of a stream without a request for them, so the span has them. - Ollama and Hugging Face. The provider returns a plain generator, and so does the traced call. Iterate over it.
- Mistral. Streaming calls are not traced.
- Bedrock, Vertex AI and Cohere streams are not described here.
- LlamaIndex (
stream_chat,astream_chat,stream_complete, a streamingFunctionAgent). The call returns the generator of LlamaIndex, unchanged. The LLM span ends when the stream ends, fails or is closed, or when the generator is collected, and it has the tokens and the model of the stream when the provider sends them. The OpenAI API sends the tokens of a stream only when the request asks for them; the LlamaIndexOpenAILLM does not ask. Risicare asks in its place, by the rules ofstream_usage(below): onhttps://api.openai.comby default, and the LlamaIndex LLM gets the same chunks. For another host, setstream_usage=True, or give the LlamaIndex LLMadditional_kwargs={"stream_options": {"include_usage": True}}. - The token counts of an OpenAI stream (
stream_usage). The OpenAI API sends the token counts of a streamed Chat Completions call only when the request asks for them (stream_options.include_usage). When your call does not setstream_options, Risicare asks for them:init(stream_usage="auto")(the default) on a client ofhttps://api.openai.com,Trueon any host (an Azure, proxy or OpenAI-compatible host can refuse the field),Falsenever; orRISICARE_STREAM_USAGE. Your code gets the same chunks as without Risicare: the SDK reads the extra usage chunk and does not pass it on. It acts with openai 1.26.0 and later (the first version withstream_options). A host that refuses the field (an HTTP 400 that names it) fails that one call, with one WARNING, and Risicare does not ask that host again. Awith_raw_responseorwith_streaming_responsecall, and a call under a framework that holds the LLM span (LangChain), is not asked. Under a LlamaIndex stream the call is asked, the LlamaIndex LLM does not see the usage chunk, and the counts go to the LlamaIndex span. The rule:"auto"acts only where every documented read path of the client library stays exact. In Python the documented raw paths arewith_raw_responseandwith_streaming_response; both are known before the request and are never asked, so Python"auto"acts. In JavaScript,.asResponse()is a documented method that cannot be told apart before the request, so JavaScript'auto'does not act. Exception (Python): code that reads the transport of an already parsed stream (stream.response.iter_lines(),iter_bytes(),iter_text()),stream._iteratororcopy.copy(stream)sees theusagefield and the extra usage event; setstream_usage=False(orRISICARE_STREAM_USAGE=false) for such code. When you do not set the option, Risicare logs one INFO line at the first call that it asks.
Framework Integrations
The SDK patches the framework. The framework is not a dependency of
risicare; an extra installs it for you:
pip install risicare[langchain] # LangChain
pip install risicare[langgraph] # LangGraph
pip install risicare[crewai] # CrewAI
pip install risicare[autogen] # AutoGen (autogen-agentchat)
pip install risicare[openai-agents] # OpenAI Agents
pip install risicare[instructor] # Instructor
pip install risicare[litellm] # LiteLLM
pip install risicare[dspy] # DSPy
pip install risicare[pydantic-ai] # Pydantic AI
pip install risicare[llamaindex] # LlamaIndex
pip install risicare[all] # Everything
The agent of each span. In a multi-agent run, an integration makes the agent of each turn the
current agent of the SDK, so the LLM, tool and nested spans of the turn carry that agent. After a
handoff they carry the new agent. The SDK uses the name that the framework gives the agent, and sets
no agent when the framework gives no name. A name marked default below is the agent only when no
agent is current: the agent of @risicare.agent(...) or agent_context(...) around the call, or of
an outer framework agent, stays.
| Framework | The agent | No agent when |
|---|---|---|
| OpenAI Agents | Agent.name, for each turn of the run (handoffs and agents as tools too); the run span has the starting agent (default) |
— |
| Pydantic AI | Agent(name=...), or the name that pydantic-ai takes from your variable |
the agent has no name |
| CrewAI | the agent's role, for each task (a delegation too); the crew span has the crew's name (default; CrewAI's own default is crew) |
— |
| AutoGen (agentchat) | the agent's name, for each turn (Swarm handoffs and AgentTool too) |
— |
| LangGraph | the name of a graph (create_react_agent(name=...), compile(name=...)), while it runs; a graph with no name is the agent LangGraph (default) |
— |
| LlamaIndex | the name of a workflow agent, for its model calls |
the name is the default Agent; a tool call has no agent |
| LangChain | a classic AgentExecutor is the agent AgentExecutor (default), a span of kind agent; its LLM, tool and action spans carry it |
the executor has a name of its own (name= or run_name), or is a subclass: the callbacks of LangChain give only the run name; spans of your own code and provider spans inside a tool do not carry it |
| DSPy | a ReAct module (and a subclass) is the agent of its class name (default), a span of kind agent; the DSPy spans under it carry it |
the module is not a ReAct; spans of your own code inside a DSPy tool do not carry it |
A default name is the same for each object that has it, and the agents page shows one agent for
each name: all unnamed graphs are one agent LangGraph, all unnamed crews one agent crew, and so
on. Give each object a name (name=, compile(name=...), Crew(name=...)) to tell them apart. An
agent that runs inside another agent has it as its parent agent: the named agents of an unnamed graph
have the parent LangGraph, and the agents page shows that link. When default names nest (an
AgentExecutor in a node of an unnamed graph), the outer one is the agent.
LangChain chains other than an AgentExecutor, DSPy modules other than a ReAct, and Instructor
have no agent name: wrap the code in @risicare.agent(name=...) or agent_context(...).
init(service_name=...) (or RISICARE_SERVICE_NAME) gives each span that the SDK makes the
attribute service.name, also a span with an agent (up to 0.15.0, a span with an agent, and each
span of LangChain, DSPy, LlamaIndex and LiteLLM, had none). It replaces a service.name that your
code sets in the attributes of a span. The spans of the OpenTelemetry bridge do not get it.
Tool calls. A tool call of LangChain, LangGraph, CrewAI, the OpenAI Agents SDK (a function
tool) and DSPy is a span of kind tool_call, named <framework>.tool/<tool name>, a child of the
agent or step that called it. It has tool.name; with content capture on, tool.input and
tool.output (JSON, or the text that the tool returned); with it off, tool.input_length and
tool.output_length. A tool that fails is an error span (status error, error.type,
error.message, error.code, one exception record), also when the framework catches the error
and gives its text to the model, as CrewAI and the Agents SDK do. A CrewAI tool that returns a
ToolFailure is an error span too. Through 0.15.0, CrewAI and the Agents SDK made no tool span: the
tool name was only on the LLM span that asked for the call, and a failed tool left every span ok.
DSPy tool spans had the keys gen_ai.request.messages and gen_ai.response.content; they now have
the tool.* keys (framework.dspy.tool_name stays). Limits:
- The Agents SDK: only function tools have a tool span. The hosted tools (web search, file search)
run at OpenAI; computer, shell and apply-patch tools and handoffs have no tool span. A tool call
that a tool input guardrail rejects did not run and has no tool span. A tool timeout is an error
span (
ToolTimeoutorToolTimeoutError), also with your owntimeout_error_function. - CrewAI without native function calling (the text path): CrewAI calls a tool again when it raises (with the arguments as given, then up to two more tries), and each call is a tool span. One failed request can show up to 6 error tool spans; native function calling shows 1.
A guardrail tripwire (OpenAI Agents SDK) ends the run span with status error and one exception
record, as before. Its error.message names the guardrail and its kind:
Guardrail <name> (input) triggered tripwire (input, output, tool input or tool output).
The exception that your code gets is not changed; its own message names only the class of the
guardrail ("Guardrail InputGuardrail triggered tripwire", or "Tool input guardrail
ToolInputGuardrail triggered tripwire"), and through 0.15.0 so did the span. error.message is
error text: when the SDK withholds error text (error_text, by default when content capture is
off), the guardrail name is withheld with it; error.type names the kind of tripwire.
A stream that you stop reading is not an error. A break from LangGraph graph.stream() (or
from LangChain .stream()) ends the spans with the status that they have, with no exception
record. Through 0.15.0 the LangChain span of the graph (langchain.chain/<graph>) was an error
span with GeneratorExit, so the trace was a trace with errors (diagnosis, the trace.error
webhook).
DSPy: one call of a program is one trace. Each module, LM and tool span is the current span
while its DSPy call runs. So a module's LM calls and tool calls are its children, and a span that
your code starts inside a tool (or a module) is a child of that span. A call inside a span of yours
is a child of that span. This holds in the threads of dspy.Parallel too: DSPy 3.4.1 and 3.5 (the
versions checked) carry the DSPy call into them, and the thread pools that init() patches (the
default) carry the context. Through 0.15.0 the DSPy spans had no DSPy parents: with no span around
the call, each module, LM and tool span was a trace of its own (one dspy.ReAct run with three
tool calls gave 10 traces).
Core API
import risicare
risicare.init(api_key="rsk-...") # Initialize (instruments providers)
risicare.flush(timeout_ms=5000) # Wait for delivery; False when a span or a score was lost
risicare.shutdown(timeout_ms=5000) # Deliver what it can in the time, then stop
@risicare.agent(name="my-agent") # Trace a function with agent identity
def my_agent(query): ...
@risicare.trace # Trace any function (also a context manager)
def step(): ...
@risicare.session(session_id="sess-1") # Group traces into a session
def handle_request(): ...
risicare.report_error(ValueError("example")) # Record a caught error as a child error span
risicare.score(name="quality", value=0.92, # A score on a trace: a number, a string or
trace_id="4bf92f3577b34da6a3ce929d0e0e4736") # a boolean (see "Scores, feedback and outcomes")
risicare.disable(); risicare.enable() # Runtime tracing control
risicare.is_enabled() # True only when tracing is on and spans can be delivered
risicare.get_metrics() # Export counters (see "Delivery")
The decorators on generators. @risicare.agent, @risicare.trace, @risicare.session and
the phase decorators (@risicare.trace_think and the others) also work on a generator function
(def f(): yield) and an async generator function (async def f(): yield, for example the
generator of a FastAPI StreamingResponse). The span covers the iteration: it starts at the first
item and ends when the generator is exhausted (ok), raises (error, with the exception), is closed
early (a break, close(): not an error), or is cancelled (error, with the cancel marker); an
error in the close (a finally that raises) is an error. Each iteration has a context of its own:
the span and the agent, session or phase are current for the body of the generator (also a with
block of the body that spans a yield), and not for your code between two items. So the LLM calls
in the body are its children, and a sampled-out generator drops its whole trace, as a call does.
The parent is the span that is current at the first item, not at the call. The decorated function
is still a generator function (inspect.isgeneratorfunction and
inspect.isasyncgenfunction hold). Through 0.15.0 the span ended at once with status ok when the
generator was made: the body ran outside it, its LLM calls were traces of their own with no agent
or session, and its error was recorded nowhere.
Identity: user, session, release and tags
import risicare
risicare.init(api_key="rsk-...", service_version="2026.10.24") # service.version on every span
with risicare.trace("handle-request"):
risicare.set_user("user-42")
risicare.set_session("conv-7")
risicare.set_release("2026.10.24-rc1")
risicare.add_tags(["beta", "eu"])
with risicare.trace("step"):
pass # this span gets all four values when it ends
Each helper writes one span attribute that the Risicare backend reads into a dashboard column:
set_user(id)writesuser.id.set_session(id)writessession.id.set_release(version)writesrisicare.release.add_tags([...])writestag.tags, a list. A later call adds to the earlier tags, in order, with no repeats.
The current span gets the attribute at once. Each other span of the same trace that ends after the
call gets it when it ends, unless that span has the attribute already: the spans that are open (for
example the root span) and the spans that start later, in any thread or task. A span of another
trace never gets it, so a value cannot pass from one request to the next. A helper returns True
when it set the value. Outside a span there is no trace: it sets nothing, returns False, and the
first such call logs one WARNING. For a value that must apply before the first span, use
session_context(session_id=..., user_id=...). With no code at the call site, init(service_version=...)
or RISICARE_SERVICE_VERSION puts service.version on every span, and the Release column uses it
when no span of the trace has risicare.release. The values of the last 10,000 traces are kept.
Prompt version
import risicare
from openai import OpenAI
risicare.init(api_key="rsk-...")
client = OpenAI()
with risicare.prompt_context("support", "2.1.0.5"):
client.chat.completions.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": "Where is my order?"}],
)
prompt_context(name, version) tells Risicare which version of which prompt a call used. Each LLM
span that starts inside the block gets three attributes:
risicare.prompt.nameis the name.risicare.prompt.versionis the version as text.llm.prompt_template.versionis the same text. It is the OpenInference name for the version. OpenInference has no key for the name, so the name has no mirror.
prompt_context(name, version, hash=None, label=None) takes two more optional values, with the same
rules: the content hash of the version (risicare.prompt.hash) and the label of the pull
(risicare.prompt.label). A prompt that you pull with get_prompt sets them for you (see
Pull a prompt).
The dashboard shows them as a chip in the span panel (support@2.1.0.5). A click on the chip opens
the traces that carry the same keys.
- The scope is the call, not the trace. A trace that calls two prompts holds two pairs, one on each LLM span. A nested block replaces the outer block as a whole; it does not merge.
- Only LLM spans get the keys. An agent, tool or function span gets none. An embeddings span
gets none. A key that you set yourself with
attributes=is not overwritten. - A value is a non-empty string or an integer, at most 200 characters. Any scheme is valid:
integer, semantic, date, hash, four-part (
2.1.0.5). A bool, a float or an empty value does nothing and logs one WARNING. Give at least one of the two values. - The prompt text is not sent. The keys are names, not content: they are sent with
trace_content=Falsetoo. Keep the text where you keep it now (git, or a store you use). Do not put a credential in a name or a version. - A stream keeps the keys. They are written when the span is created, so a stream that you read after the block ends has them.
- The block reaches asyncio tasks and the thread pools that
init()patches (they copy the context). A thread that you start with a barethreading.Threaddoes not inherit it. - Framework spans get the keys too (since 0.12.0). The LLM spans of LangChain (and of the LLM calls of LangGraph), DSPy, LlamaIndex and LiteLLM are written in the context of the call, so the block reaches them. Their embeddings spans get none.
- Known limits. Spans that the OpenTelemetry bridge converts are not stamped. For those, set
the attribute by hand, or use OpenInference
using_prompt_templateon the other side: the dashboard readsllm.prompt_template.versiontoo. The filter termattr.risicare.prompt.version:2.1.0.5matches any span of a trace, so the name term and the version term can match two different spans of one trace. The keys ofrisicare.prompt.*,llm.prompt_template.versionandgen_ai.prompt.*do not join: a trace sent with one family is not found by a chip of another family.
For a number by version, add a tag as well: risicare.add_tags(["prompt:support@2.1.0.5"]), then
group by tag.
Pull a prompt
A prompt is a named text with versions. Your team edits it in the dashboard and moves a label
(production, staging) from one version to another. Your code pulls it by name and by label or
version. Each LLM call that uses the pulled prompt carries its name, version, hash and label on the
span, so the dashboard can show the numbers of each version.
import risicare
from openai import OpenAI
risicare.init(api_key="rsk-...")
client = OpenAI()
prompt = risicare.get_prompt(
"support",
label="production", # or version=4; with neither, label="production" (or RISICARE_PROMPT_LABEL)
fallback=risicare.PromptContent( # used only when the pull fails and nothing is cached
messages=[{"role": "system", "content": "You help with {{topic}}."}],
version="3",
),
)
body = prompt.openai_body(topic="billing") # model, messages and parameters of the version
client.chat.completions.create(**body) # the span of this call carries the four prompt keys
# Any other path: a framework, or a message list that you copied.
with prompt.context():
run_my_framework(prompt.compile(topic="billing"))
# A run that binds to the stored version (see "Runs, trials and the gate").
evals.run(dataset="support-regressions", function=my_agent, checks=checks, prompt=prompt)
- The pull.
get_prompt(name, label=, version=, fallback=, cache_ttl_s=, timeout_s=)sendsGET /v1/prompts/resolveto the api host with the key ofinit(). The key needs the scopeprompts:read. A key of the default class has it. With a key that does not, the api answers 403 and the SDK writes one WARNING that names the scope. Givelabelorversion, not both. With neither, the label is the value ofRISICARE_PROMPT_LABEL(for examplestaging) or, when that is not set,production. A label or version in the call always wins. The SDK pulls nothing at import time or atinit(). - The object.
prompt.name,prompt.version,prompt.hash,prompt.label, andprompt.source:server(this call pulled it),cache,staleorfallback. The content isprompt.messages,model,parameters,tools,output_schemaandvariables.repr(prompt)shows the identity and not the text. - The values.
prompt.compile(topic="billing")gives the messages with the values put in. A placeholder is{{name}}or{{ name }}; any other{{is plain text. A value that is not a string goes in as compact JSON. A missing value raisesrisicare.MissingVariable. A value is never read again as a template.prompt.openai_body(**values)gives a dict forclient.chat.completions.create(**body), andprompt.anthropic_body(**values)gives a dict forclient.messages.create(**body). Both leave out the keys the prompt does not set. Neither adds a default. - Anthropic.
anthropic_bodynever putstemperatureortop_pin the body: the current Anthropic API version refuses them on every model. It also leaves outseedand the output schema. It writes one WARNING that says so. It adds nomax_tokens; the Anthropic API needs one, so setbody["max_tokens"]when the prompt does not. - OpenAI.
openai_bodywritesmax_output_tokensasmax_completion_tokens, the current field of the OpenAI chat completions API.max_tokensis the legacy name, and newer models refuse it. A server that takes onlymax_tokens(some OpenAI-compatible hosts) gets it from you: rename the key in the dict. - The cache. One cache in memory for each process, at most 500 entries, no disk. A version pin
never expires. A label is fresh for
cache_ttl_s(default 60, from 5 to 3,600). After that the next call gets the cached value at once, and one background refresh asks withIf-None-Match: the api answers 304 when the label did not move. A promotion in the dashboard reaches a running process within that time. Only the first call for a key waits for the network, and never longer thantimeout_s(default 1, from 0.1 to 10). - A failure. When a refresh fails (a network error, a 5xx, a timeout, 401, 403, 404 or 410), the
SDK keeps the last good value, sets
sourcetostale, and writes one WARNING for each key each minute. A removed label or an archived prompt does not take the prompt away from a running process. When the first pull fails and nothing is cached,get_promptreturns thefallback(sourceisfallback), or raisesrisicare.PromptUnavailablewith thereasonand the HTTPstatus. A failed key is asked again after onecache_ttl_s, so a down api does not add a timeout to every call. - The fallback hash.
risicare.PromptContent(messages, model=, parameters=, tools=, output_schema=, version=)has the shape of a stored version. The SDK computes its hash here, with the same canonical form (RFC 8785) and the same SHA-256 as the api. A fallback with the same content as stored version 3, key for key, has the hash of version 3, so its calls count as version 3. A fallback with other content shows on the version page as "Calls with an unknown hash". A key that you leave out is absent; a key that you set toNoneisnull. They give different hashes. - The span keys.
compile(),openai_body()andanthropic_body()return a message list that carries a hidden reference to the prompt. The list is alistsubclass; it compares equal to a plain list and its JSON does not change. The OpenAI and Anthropic patches read the reference and writerisicare.prompt.name,risicare.prompt.version(text),risicare.prompt.hashandrisicare.prompt.labelon the span of that call, also withtrace_content=False. A fallback has a hash and no label. The list that goes to the call replaces an enclosingprompt_contextblock as a whole: all keys of the span come from the list, and none from the block. So a version pin, which has no label, gets no label from the block. A copy of the list (list(messages), a slice, a new list) does not keep the reference. For such a path usewith prompt.context():orprompt.run(fn, *args); both use the scope rules ofprompt_context. - Runs.
evals.run(..., prompt=prompt)sendsprompt = {name, version, hash}with the run and runs each trial insideprompt.context(). The api binds the run to the stored version when the hash equals the hash of that version. A hash that differs gives a 422prompt_hash_mismatch, and the run stops before any trial, with words. The pairprompt=("support", "4")still works and binds to nothing. - What is never sent. No template text and no variable value goes on a span. The SDK holds no
provider key for Risicare.
get_promptnever writes a version and never moves a label; only the commandrisicare prompts pushdoes (see "Prompts in git"). - Environment.
RISICARE_PROMPT_CACHE_TTL_S(5 to 3,600) andRISICARE_PROMPT_TIMEOUT_S(0.1 to 10) set the defaults. A value out of range is ignored with one WARNING.RISICARE_PROMPT_LABELis the default label (see "The pull"). - Known limits. The spans of the framework integrations (LangChain, LangGraph, DSPy, LlamaIndex,
LiteLLM) get no keys from a list, because the framework copies the messages. Use
prompt.context()for them (since 0.12.0). Spans that the OpenTelemetry bridge converts get no keys from a list or from a block: set the attributes by hand. The refresh is a thread of the SDK that starts on first use, and again after afork.
Prompts in git
Teams that keep prompts in code type each change twice, and the two copies drift. The command
risicare prompts keeps the files of your repository and the prompts in Risicare in step. It has
three commands and no other host than the api host.
risicare prompts pull # write the version that production holds, one file for each prompt
risicare prompts status # compare the files with production: exit 0 or 100
risicare prompts push --note-from-git --label staging # save the files as versions and move staging
- The files. One file for each prompt:
prompts/<name>.json, pretty printed with sorted keys. It has four keys and no other:format(risicare-prompt/1),name,description(optional) andcontent.contentis the content of a version:template,messages, and the optionalmodel,parameters,toolsandoutput_schema. It has novariables: the api derives them from the messages. A file withvariablesis read and the key is dropped. A file withouttemplategetsmustache_basic, the one syntax. Put the files in git. - The hash. A file and a stored version compare by hash. The hash of a file is the hash of its
contentin the canonical form of RFC 8785 (the same form as the api andPromptContent). The layout of the file (key order, spaces,1or1.0, the description) never changes the hash. - The lock file.
.risicare/prompts.lock.jsonrecords, for each prompt, the version and the hash that the file was last synced with.pushsends the version asparent_version.statususes it to say which side moved. It names the api host, because version numbers belong to one project: a lock file for another host is not used. Use--lock FILEfor one lock file for each project. The file holds no key. - pull.
risicare prompts pull [NAME ...] [--label LABEL | --version N]writes the prompts thatLABELholds (defaultproduction; the command does not readRISICARE_PROMPT_LABEL), or one version of one prompt, withGET /v1/prompts/export(at most 100 prompts for a call; the command follows the cursor). A file that has changes which are not in the store is kept and the exit code is 1;--forceoverwrites it. A file that is exactly the last sync is replaced. A pull that changes nothing writes nothing. The api allows 60 export calls in 5 minutes for each key.pullmakes one call for eachNAMEyou give (and one for each 100 prompts when you give none), so apullwith more than 60 names stops at the limit (rate_limited, exit 1). To pull many prompts, give no names. - push.
risicare prompts push [NAME ...] (--note TEXT | --note-from-git)saves each file as a new version withPOST /v1/prompts/push. The api compares the hash with the stored versions: a file that equals a stored version is not a new version (unchanged), so a repeat changes nothing. A note of 1 to 500 characters is required.--note-from-gitisgit <short id> · <first line of the newest commit>. The command reads every file before it sends anything, then pushes the prompts in the order of their names, and stops at the first failure. If someone saved a newer version than the parent, the push still saves and printsSomeone saved v6 after v4.;--require-lateststops it instead (exit 1). - Labels.
--label NAME(repeat for more) moves a label to the pushed version, only where the rule of that label lets a key do it. A key never movesproduction: the command refuses--label productionbefore it sends anything.--request-promotion LABELopens a request in the same call; a person approves it in the app. The api does not take such a request yet: it answers 422promotion_request_unavailableand the command exits 1. When the api takes it, this is the loop: merge, push, request, approve. - status.
risicare prompts status [NAME ...] [--label LABEL]compares each file with the version that the label holds (GET /v1/prompts/resolve) and writes nothing. For each file it prints one state:equal,files_ahead(the file changed since the last sync),store_ahead(the label moved since the last sync),not_promoted(the label does not hold the version of the file yet),both_changed,differs(no lock entry),not_in_storeorlabel_not_set. - Dry run and diff.
--dry-runwrites nothing. Forpullit writes no file and no lock file. Forpushit sendsdry_runand the api saves nothing, so a dry run needs no note.--diff(and--dry-run) prints a unified diff of the text of each change: the text of each message on its own lines, the other keys as JSON.--jsonprints one JSON object and nothing else. - The key and the host.
RISICARE_API_KEYholds a key of classci. The key needsprompts:read(statusand the diff),prompts:write(push) andprompts:export(pull). A key of classsecretcanpulland runstatus. It cannotpush: only classciholdsprompts:write.RISICARE_API_URLis the api host (defaulthttps://api.risicare.ai; without it the command uses the hosts ofinit():RISICARE_API_ENDPOINT, thenRISICARE_ENDPOINT). The command keeps the scheme, host, port and path of the URL, removes userinfo, a query and a fragment, and writes one warning. A value that is not an http or https URL is exit 1, and the message names the variable. The command calls the api host and no other host, and never prints or writes the key. A key of classcican save versions and request a promotion. It cannot moveproduction.
| Exit code | Meaning |
|---|---|
| 0 | done: every prompt pulled, pushed or unchanged; status: every file equals the store |
| 1 | the command could not finish: no key, a network error, 401, 403, 404, 409, 422, a 5xx, an answer it cannot read, a file it cannot write, or a file that pull kept |
| 2 | a usage error: a bad option or name, a prompt file that is not valid, no prompt files, a missing note |
| 100 | status only: at least one file differs from the store |
A pipeline (GitHub Actions) that ships a change:
- run: pip install risicare
- run: risicare prompts push --note-from-git --label staging
env: { RISICARE_API_KEY: "${{ secrets.RISICARE_CI_KEY }}" }
status exits 100 when the files differ from the store, and a step fails on any exit code that is not 0.
Do not put status before push in a pipeline. If you must, accept the 100:
risicare prompts status || [ $? -eq 100 ].
The CI canary. Three commands change nothing and prove that the key, the host and the edge are in
order: risicare prompts status NAME, risicare prompts pull NAME --dry-run and
risicare prompts push NAME --dry-run. Exit 0 (or 100 for status) on all three means the key reaches
the store, the export route and the push route. Exit 1 with 401 says the key is wrong. Exit 1 with
"not public on this host" says that the edge of the api host does not forward the path.
What each dashboard column reads
The backend takes the first value that is set, in this order, from the attributes of each span.
| Column | Read from (first that is set) | Set it with the SDK |
|---|---|---|
| User | session.user_id, user_id, user.id, enduser.id, llm.user, ai.telemetry.metadata.userId (at most 256 characters) |
set_user(id) (user.id); session_context(user_id=...) writes session.user_id, which comes first |
| Session | the span's session field, then session.id, gen_ai.conversation.id, gcp.vertex.agent.session_id, ai.telemetry.metadata.sessionId |
session_context(session_id=...) (the session field, first); set_session(id) (session.id) |
| Release | risicare.release; then service.version (the OpenTelemetry resource attribute, then the span attribute); then the deployment id; then the first 12 characters of the git commit |
set_release(version) (risicare.release); init(service_version=...) or RISICARE_SERVICE_VERSION (service.version, no other code) |
| Environment | deployment.environment.name, deployment.environment (resource attribute, then span attribute); else the environment of the request |
init(environment=...) or RISICARE_ENVIRONMENT (default development) |
| Tags | framework.langchain.tags, framework.llamaindex.tags, tag.tags, langsmith.span.tags, ai.telemetry.metadata.tags, merged in this order: each tag is cut at 200 characters, a repeat is dropped, and the first 50 tags are kept, so on a LangChain or LlamaIndex span the tags of the framework come first; a list, a JSON array text or a comma-separated text |
add_tags([...]) (tag.tags) |
| Prompt | the chip of the span panel: risicare.prompt.name then gen_ai.prompt.name for the name; risicare.prompt.version, then llm.prompt_template.version, then gen_ai.prompt.version for the version |
prompt_context(name, version) (risicare.prompt.name, risicare.prompt.version, and llm.prompt_template.version as a mirror of the version); a pulled prompt (get_prompt) also writes risicare.prompt.hash and risicare.prompt.label |
| Experiment | risicare.experiment.id, the id of the run a trial belongs to (the trace takes the id of its earliest span that has one). A trace that has one is left out of release numbers and of the default trace list |
evals.run and the pytest plugin write it on every span of a trial. Do not set it by hand |
| Agent | the span's agent fields (id and name), then agent.name and gen_ai.agent.name for the name |
@risicare.agent(name=...) or agent_context(...); a framework integration sets them (see Framework Integrations) |
An application that uses another OpenTelemetry SDK sets the same attributes on its spans, and
service.version as a resource attribute, with no Risicare code.
Check the setup: risicare doctor
risicare doctor checks, one line each, that spans from this host can reach Risicare. Run it
with the same environment as your application (RISICARE_API_KEY, RISICARE_ENDPOINT,
RISICARE_SERVICE_NAME, and the proxy variables):
$ risicare doctor
risicare doctor <version> (Python 3.12.13, httpx 0.28.1)
[PASS] SDK version: risicare <version> is installed; <version> is the newest on PyPI.
[PASS] API key: set: prefix "rsk-", 36 characters.
[INFO] Endpoint: https://ingest.risicare.ai (spans go here; environment production).
[INFO] Proxy: no proxy variable is set. No proxy applies to https URLs: the connection to the endpoint is direct.
[PASS] Reachable: https://ingest.risicare.ai answered HTTP 200 in 84 ms.
[PASS] Clock: this host and the endpoint differ by 0 s (limit 300 s).
[PASS] Key accepted: POST /v1/spans with no span: HTTP 200. The gateway takes the key.
[PASS] Test span: the gateway accepted 1 span: risicare.doctor, trace 4f1c… (service checkout-api, environment production). It shows in Traces of the project of this key within a short time.
[INFO] Instrumentations: installed in this Python environment, and patched when your application calls init(): openai 3.57.0.
Result: the gateway accepted the test span. Exit code 0.
-
Each line starts with PASS, FAIL, WARN or INFO. A FAIL or WARN line ends with "Next:" and the next step. A refused key gets the same texts as the WARNING of the SDK (the table in "Delivery during a gateway outage").
-
Options:
--endpoint URL: the ingest gateway (default:RISICARE_ENDPOINT, then the default gateway);--timeout SECONDS: the time for each request (default 10);--no-version-check: do not read the newest version on PyPI;--no-send: send no test span (nothing is written to the project); stop after the key check, with exit code 3.
-
Exit codes:
- 0: the gateway accepted the test span; this is the only proof of delivery;
- 1: a check failed;
- 3:
--no-send(the key is accepted, and no span was sent); - 2: a usage error.
-
The checks:
- Reachable:
GET <endpoint>/health, with no key. Any HTTP answer means that the host is reachable. ItsDateheader gives the clock check. - Key accepted:
POST <endpoint>/v1/spanswith no span, so nothing is stored. Any 2xx answer means that the gateway takes the key. - Test span:
POST <endpoint>/v1/spanswith one span, through the SDK's own exporter.
- Reachable:
-
The test span goes to the real project of the key. It is as small as possible:
- one span of kind INTERNAL, named
risicare.doctor, with the attributerisicare.doctor= true; service.namefromRISICARE_SERVICE_NAME, and the environment ofinit()(RISICARE_ENVIRONMENT, elsedevelopment), so that you find it where your spans are;- no LLM data, no tokens, no LLM cost, no content. It counts as one event toward the quota of the organization.
With
--no-sendno span is sent. - one span of kind INTERNAL, named
-
The output is safe to paste in a support thread. It shows only the prefix and the length of the key. It never shows the user name or the password of a URL or of a proxy value (a proxy value that cannot be read with certainty shows only " is set"). It shows no content. The log lines of the SDK during the two requests are kept out of the report; a rejection reason goes into the Test span line, with the key removed.
-
The key is read as
init()reads it: white space at an end is removed (a WARN line says so), and white space inside the key, or a character that is not ASCII, is a FAIL. -
The proxy line names the variables that are set, and the rule that httpx (the HTTP client of the SDK) applies to the endpoint: a proxy, NO_PROXY, or a direct connection.
-
Requests: only to your endpoint, plus one read of
https://pypi.org/pypi/risicare/jsonfor the newest version (--no-version-checkturns it off). -
Instrumentations:
doctorruns in its own process, so it names the libraries that are installed in this Python environment and that the SDK patches when your application callsinit(). -
An
init()at import: withRISICARE_TRACING=true,import risicarerunsinit()in the doctor process too. An INFO line says so: the doctor does not use that client, and that client can make requests of its own (for example fix reads withRISICARE_FIX_RUNTIME=true).
Delivery: flush, shutdown and metrics
You usually need neither call: init() registers an exit handler and a
SIGTERM handler that deliver the queued spans.
Child processes are the exception. A forked child (a multiprocessing
worker, a worker of a pre-fork server) does not get the SIGTERM handler of
the parent, and a multiprocessing child that calls init() itself gets
none. A multiprocessing child of the fork or forkserver start method also
ends without the exit handler (a spawn child runs it). Such a child delivers
its spans on the normal export tick (1 s by default), so call
risicare.flush() at the end of each task. A child that is stopped before
that does not deliver the spans made since the last tick.
A forked child does not hang on a lock of its parent. fork() copies each
lock as it is, and a lock that another thread of the parent held has no owner in
the child. The SDK gives every lock of its own, and the risicare-core locks that
it takes, a fresh lock in the child before the child runs any code of yours. A
SIGTERM in the first instant of a child (before that step) does what SIGTERM did
before init(): the default stops the child, an ignored SIGTERM stays ignored,
your own handler runs; the SDK drains nothing there. (That instant is inside
CPython's fork hooks, and CPython discards an exception that a fork hook raises:
a handler that calls sys.exit() there does not stop the child. 0.15.0 is the
same.) After that instant the SDK's handler drains in the child as in the parent. Through 0.15.0 a child could
hang for ever at its first span, flush(), init() or shutdown() when a parent
thread was inside one of those locks at the fork, and a worker that got SIGTERM
right after its fork could hang in the SDK's drain (seen as a pool.terminate()
that never returned).
Known limit: a SIGTERM in the first milliseconds of a forked child can be
lost. The SDK installs a Python-level SIGTERM handler, and the child inherits
it. A Python-level handler does not run in the C signal handler: the C handler
only sets a flag. CPython clears those flags in a new child before the fork
hooks run (_PySignal_AfterFork), so a SIGTERM that reaches the child between
fork() and that step is lost: the child keeps running. With the default
disposition (no Python-level handler), the kernel would have ended the child.
Who can see it: a supervisor that sends SIGTERM to a worker in its first
milliseconds and then waits for ever, with no second SIGTERM and no SIGKILL.
Supervisors that send SIGTERM again or escalate to SIGKILL after a grace period
(gunicorn, systemd, Kubernetes, docker stop) are not affected. In the tests,
every fork pool stops as such a supervisor does, and a second SIGTERM that was
needed is counted (FORK-WINDOW-HIT).
Known limit: CrewAI with fork pools. With CrewAI (1.15.41) in the parent process, a forked worker can fail to end on SIGTERM; a supervisor that escalates to SIGKILL is not affected.
Process pools: in a pool worker, call risicare.flush() at the end of each
task (multiprocessing.Pool, concurrent.futures.ProcessPoolExecutor), for
example in a finally: of the task function. A pool ends its workers with
SIGTERM (pool.terminate(), and the end of with Pool() as pool:), and a
worker has no SIGTERM flush from the SDK: without that call, the spans that a
worker made since its last export tick are lost. Up to 0.4.0 the worker had a
SIGTERM flush, and a pool could then hang for ever in terminate(). The main
process is not changed: it keeps its exit handler and its SIGTERM flush, so a
container stop still delivers its spans.
flush(timeout_ms=5000)only waits. It does not stop a request that is already sent, and it does not send a span again. It returnsTrueonly when every span and every score that the SDK accepted since the previousflush()returned (or sinceinit(), for the first call) was acknowledged, and nothing is still queued or in flight. With one exporter that is the gateway. With more than one exporter, see the last item of this list. The SDK stays usable after it. It returnsFalseat its deadline. It also returnsFalsewhen the SDK is not active: beforeinit(), with tracing off, and with no API key and no exporter of your own. There is no evidence of delivery then.- A loss is reported one time. A loss is a span that was dropped for any
reason (
shutdown_residueincluded), a span that the backend rejected, a score that failed, and a score thatscore()refused at the call. A loss makes the nextflush()returnFalse, one time, also when it occurred while no flush ran, and also aftershutdown(). The flush after that returnsTruewhen nothing new was lost. Each loss also raises a counter with a named reason:dropped_spans_by_reason,rejected_spansorfailed_scores. - "Lost" and "still in flight" are different. A
flush()that returnsFalseat its deadline, while none of these three counters went up since the previousflush(), means that the spans are still in flight. The outcome arrives later, as a delivery or as a loss. - A drain that runs, and after
shutdown(). Aflush()that overlaps a drain (ashutdown()on another thread, or the SDK's own drain at SIGTERM) waits for it inside its own deadline, and then reports the real outcome with the same rule. So does aflush()aftershutdown(). The order in which your program and the SDK install their SIGTERM handlers does not change this. What the SDK's handler does depends on what SIGTERM had beforeinit():- A handler of yours or of your server (gunicorn's sync worker installs
it before it imports your app; uvicorn's workers load your app inside
their own signal capture): that handler runs at once. Then the SDK flushes
(it does not shut down) for at most 1 s, and a background thread goes on
flushing until the process ends or
shutdown_timeout_spasses. The SDK stays active, so your requests in flight keep running and their spans are sent; the SDK's exit handler drains the rest when it runs. The 1 s flush is for servers that end with no exit handler: uvicorn's workers restore SIGTERM's default and raise it again right after their graceful stop. Known limits: a span that ends in the last instant before such a re-raise can still be lost (as in 0.15.0), and a handler of yours that ends the process itself at once (os._exit) leaves the queue unsent. - SIGTERM ignored (
SIG_IGN): nothing stops; the SDK stays active and the background thread sends the queue. - The default (no handler before
init()): the SDK drains (at mostshutdown_timeout_s) and then the process stops, as SIGTERM's default does. A handler that you install afterinit()replaces the SDK's handler; yourflush()then exports the queue itself. Through 0.15.0 the SDK drained BEFORE a handler that was installed beforeinit(), on your server's thread: with gunicorn's sync worker the request in flight lost its span (measured), the server's handler ran late behind a slow export, and an ignored SIGTERM stopped the SDK in a process that went on. uvicorn's single process installs its handler after your app and was not affected. Theflush()path never waits for a lock of the SDK, so it is safe in a signal handler. A span that was open at the drain or atshutdown()and ends after it is not sent. It counts at once asopen_at_shutdown, with one WARNING for the first one, and the nextflush()returnsFalse. A span that starts after the drain or aftershutdown(), before a newinit(), is not made. It counts asafter_shutdown, with one WARNING for the first one, and the nextflush()returnsFalse. This holds for a span that you start with the tracer in an exit handler of yours that runs after the SDK's own, and for a call to a traced provider there: it makes no span, and it counts asafter_shutdown(see "Serverless functions").
- A handler of yours or of your server (gunicorn's sync worker installs
it before it imports your app; uvicorn's workers load your app inside
their own signal capture): that handler runs at once. Then the SDK flushes
(it does not shut down) for at most 1 s, and a background thread goes on
flushing until the process ends or
- A new
init()starts a new count. The losses thatflush()has not reported yet belong to the old client, and the new client does not report them. Report them withflush()orget_metrics()before you callinit()again. - More than one exporter. With more than one exporter that counts as
delivery (
otlp_endpoint, an exporter of your own, the Risicare exporter), a batch counts as delivered when the first exporter that succeeds takes it.flush()Truethen means that at least one of them acknowledged each span. Another exporter, also the Risicare one, can refuse the batch, andflush()still returnsTrue. Its WARNING andfailed_exportsshow that an export call failed.failed_exportsis not a loss counter.
- A loss is reported one time. A loss is a span that was dropped for any
reason (
shutdown()is the call that ends a process in a fixed time. The exports stop withintimeout_ms; when you give none, within theshutdown_timeout_sofinit()(default 10 s). It also is the budget of the SDK's own exit handler and SIGTERM handler. A batch that waits for a retry gets one more attempt at once, and a failed attempt is not retried. Spans that it cannot deliver in that time (still queued, or in an export that did not finish) are counted asshutdown_residue, and one WARNING gives both numbers. The bound does not cover theshutdown()method of an exporter that you wrote.docker stopwaits 10 s by default: when your application needs time for its own cleanup, setshutdown_timeout_slower or raise the grace period.get_metrics()returns the counters:exported_spans(spans the backend accepted),rejected_spans(spans the backend acknowledged and rejected),failed_scores,failed_exports,attempts,oldest_pending_age_s,dropped_spans,dropped_spans_by_reason(queue_full,transport_refused,retry_exhausted,too_large,shutdown_residue,unacknowledged,quota_exceeded,after_shutdown,open_at_shutdown),queue_size,queue_capacity,queue_utilizationandsdk_state. See "Delivery during a gateway outage" for each drop reason. Afterinit()there is alsomask_errors.unacknowledgedcounts spans that were sent, or that could not be serialized, and that the backend's answer did not account for.failed_exportscounts export calls that failed as a whole. A later round can still deliver those spans, so it is not a loss counter. The loss counters aredropped_spans_by_reason,rejected_spansandfailed_scores.
ok = risicare.flush(timeout_ms=2000)
if not ok:
print("not delivered:", risicare.get_metrics()["dropped_spans_by_reason"])
score() sends on a background thread and never raises. A score that gets an
HTTP status of 300 or more, raises, or times out adds 1 to failed_scores. A
score that the SDK refuses at the call (a value that is not a finite number, a string of 1 to
256 characters or a boolean; an empty name or one longer than 128 characters; no trace and no
session; an unknown kind; the other rules of "Scores, feedback and outcomes") logs a WARNING,
sends no request, and also adds 1 to failed_scores, so the next flush() returns False. It does not
count when the SDK is not active (no API key, tracing off, or before init()).
The first failure logs one WARNING at once. Failures in the next 10 seconds
are counted, and the next WARNING gives their number. The SDK does not follow
a redirect. At most 50 score requests run at one time. Up to 1,000 scores wait for a
free slot (running and waiting scores together); a waiting score has no timer, and
the request bound starts when its request starts. A score that comes when 1,000
are pending fails at once and is counted. flush() waits for pending scores. A
normal exit waits for them for at most 2.5 seconds. When the bound of flush() or
of the exit ends, the scores that still wait fail and are not sent.
Serverless functions: flush() for each invocation, shutdown() only at the end
A warm serverless runtime (AWS Lambda, Google Cloud Functions, Vercel and similar) runs many invocations in one process. The rule:
- Call
risicare.flush()at the end of each invocation. It waits for the spans of that invocation and returns True only when they were delivered. - Call
risicare.shutdown()only where the process ends. Aftershutdown(), tracing is shut down in this process.
What happens to a span after shutdown() (measured):
- Through 0.14.0: a span that started after
shutdown()was not made and was in no counter.flush()returned True, and nothing was logged. In a handler that calledshutdown()at the end of each invocation, only the first invocation was traced, with no signal. - Now:
- A span that starts after
shutdown()(and before a newinit()) is not made. It is counted asafter_shutdowninget_metrics()["dropped_spans_by_reason"]. Counted: the tracer API, the decorators, thesession.endmarker of@sessionandsession_context, the provider patches (each LLM call, once even when one patched call calls another) andreport_error()outside a span (inside a span the error goes on that span, so it is not a span of its own), the framework integrations and the OpenTelemetry bridge.- A framework call (CrewAI, LangGraph, AutoGen, Instructor, OpenAI Agents, Pydantic AI, LiteLLM) counts once for the outermost call: a nested framework call and the LLM calls inside it do not count again. A callback integration (LangChain, LlamaIndex, DSPy) counts its root run once, not its child runs. It gets events and wraps no call, so a patched LLM call inside the run counts too: a count that is too high, never too low.
- The OpenTelemetry bridge counts each local root span (no parent, or a parent from an
incoming
traceparent), and a child span once for each trace (its root can have been sent beforeshutdown(), or dropped by a sampler): asafter_shutdownwhen the span started aftershutdown(), asopen_at_shutdownwhen it started before. A trace with a child and a root aftershutdown()counts two. - Your function, and the framework call, run as before; a fault of the count never reaches
them.
The count is made before sampling: with
sample_ratebelow 1 it also counts spans that sampling would have dropped, so read it as spans not sent, not as lost traces.
- A span that was open when
shutdown()ran and ends after it is counted asopen_at_shutdown. It is not queue residue (shutdown_residue), and it did not start after the shutdown. - The next
flush()returns False (a loss is reported once, at the next call). - At most one WARNING of each reason for each shutdown (so at most two lines) says what happened and what to call instead.
- A span that starts after
init()aftershutdown()is supported: it starts a new client, and tracing works again. The SDK never restarts by itself.
Decision Phases
Structure your traces to see how your agent thinks, decides, and acts:
@risicare.agent(name="planner")
def plan(query: str):
@risicare.trace_think
def analyze():
return llm.chat("Analyze this query...")
@risicare.trace_decide
def choose_action(analysis):
return llm.chat("Pick the best action...")
@risicare.trace_act
def execute(action):
return run_tool(action)
analysis = analyze()
action = choose_action(analysis)
return execute(action)
Errors and fixes
Not available yet: error diagnosis and fixes. In the beta, the Risicare service does not diagnose errors and does not suggest or give fixes. The SDK records each error, and the dashboard shows it in its trace.
When your agent fails:
- The SDK records the exception on the span and gives it an error code
(
error.code). Therisicare-coretaxonomy has 154 codes in 10 modules (TOOL, MEMORY, REASONING, OUTPUT and others). The SDK's own rules give 18 of them. An error that no rule matches gets a 19th,TOOL.EXECUTION.CRASHED. - The span goes to Risicare with the rest of the trace, and the dashboard shows the error in its trace.
try:
result = my_agent(user_input)
except Exception as e:
risicare.report_error(e) # A child error span under the current span
report_error() on an error that your code recovers from. Inside a span, report_error(e)
makes a child span error:<ExceptionType> (or the name= that you give) under the current span,
and ends it at once. It has status error, one exception record, error, error.type,
error.message, error.code and risicare.reported_error, and your attributes=. The current
span does not change. So the trace is a trace with errors (it goes to diagnosis and to the
trace.error webhook), and a run that recovers and returns normally does not read "ended in
error": the error is a child step. Outside any span it makes the same span as the root of a trace
of its own (the same error again within 5 minutes is not sent again). Through 0.15.0, inside a span
the error went on the current span; when that span was the root (an @agent function that catches
and reports), the run read "ended in error". The JavaScript reportError already makes the child
span.
One exception record on a failed span. A span that an integration ends with an error has one exception record. Through 0.15.0 the LangGraph graph span, the CrewAI crew and agent spans, the OpenAI Agents run span and the provider spans had two records of the same exception. Two different exceptions with the same text still give two records.
Fix application is off by default
Since 0.4.0, FixRuntime starts only when you opt in. During the beta, the Risicare service does not give fixes to customer projects, so FixRuntime has no effect for them. Through 0.3.0, FixRuntime started automatically when you set an API key.
When FixRuntime is on, it reads the active fixes for your project from Risicare.
The fix interceptor enforces guard fixes on these paths only: FixRuntime.wrap_call,
wrap_async_call, intercept_call, intercept_response, and the input guards
of the direct, synchronous OpenAI chat call. The guards do not run for the async
OpenAI client, or when a framework integration suppresses provider
instrumentation. A failed input guard raises risicare.GuardRejectedError
before the LLM call. A failed output guard raises it after the call, and the SDK
does not retry it. The input guards check messages that have text content: a
string, or the text parts of a list. A guard pattern that is not usable (not a
string, empty, longer than 500 characters, or it does not compile) rejects the
call. The provider path does not apply prompt, parameter or fallback fixes.
Each SDK uses its own regular-expression engine. These constructs can give a
different result in Python and JavaScript: $ before a final newline, Unicode
case folding, \d and \w on non-ASCII text, \N{...}, \U........, and a
] first in a class. A pattern has no time bound: a pattern with nested repeats
can take a very long time on a long input.
When FixRuntime is off, the SDK does not request /fixes/active, and it does
not change your LLM calls. Tracing, error reporting and scores are not affected.
To opt in:
risicare.init(api_key="rsk-...", fix_runtime=True)
# or set RISICARE_FIX_RUNTIME=true
When FixRuntime is on, the SDK requests the active fixes during init() and
then every 60 seconds. The fix_runtime argument has priority over the environment variable.
Scores, feedback and outcomes
import risicare
risicare.init(api_key="rsk-...")
with risicare.trace("answer-question"):
trace_id = risicare.get_current_trace_id()
# A person's judgment of the answer
risicare.score(name="quality", value=0.92, trace_id=trace_id, kind="annotation")
# The verdict of an evaluator (a model or a rule)
risicare.score(name="groundedness", value="partly_grounded", trace_id=trace_id, kind="eval")
# The end user's reaction
risicare.score(name="thumbs_up", value=False, trace_id=trace_id, kind="feedback",
comment="The answer missed the refund policy")
# A result that your own system knows
risicare.score(name="ticket_resolved", value=True, session_id="conv-7", kind="outcome")
A score is a named value on a trace, a span or a session. kind says what the judgment is:
kind |
Use it for | Example |
|---|---|---|
annotation (the default) |
the judgment of a person who reviewed the trace | a reviewer rates an answer 4 of 5 |
eval |
the verdict of an evaluator: a model (LLM as a judge) or a rule | a groundedness check returns "partly_grounded" |
feedback |
the reaction of your end user | a thumbs-down, a star rating, a comment |
outcome |
a result that your own system knows: resolved, refunded, goal met | the support ticket of the session was resolved |
An outcome is a result that your own system knows, and no model infers it. Send it from the
code that knows the result (the ticket system, the payment, the order), when it knows it; it can
come minutes or days after the trace.
The type of value decides how the score is stored: a finite number (any range, for example a
rating from 1 to 5) is numeric, a string of 1 to 256 characters is categorical, True or False
is boolean. name is 1 to 128 characters. Give trace_id (32 lowercase hex characters, for
example from get_current_trace_id()), session_id (1 to 255 characters), or both; span_id
needs trace_id. comment is at most 4,096 characters, and a mask of init() sees it under
the key score.comment. A score that does not meet these rules is refused at the call with a
WARNING and counted in failed_scores.
Seven more fields are optional. A field that you do not set is not sent. The api applies the same
rules and answers 422, so the SDK refuses a score that breaks one at the call, with a WARNING that
names the rule, and counts it in failed_scores. A mask of init() does not see these fields:
they are identifiers, not free text.
| Field | Applies to | What it holds | Rule |
|---|---|---|---|
failure_class |
any kind |
the coarse class of the failure: a key of the failure-class vocabulary, for example fabrication, tool_contract or loop_runaway |
2 to 63 characters: lowercase letters, digits and underscores, the first a letter. The api answers 422 unknown_failure_class for a key that is not in the vocabulary of the project; the SDK cannot check that |
judge_model |
kind="eval" only |
the model id that the judge used. Leave it out for a rule or a person | 1 to 128 characters |
judge_version |
kind="eval" only |
your own version of the judge; a judge that is code has one too | 1 to 64 characters |
judge_prompt_hash |
kind="eval" only |
the SHA-256 of the judge prompt template, taken before the variables are filled. Risicare never sees the prompt | 64 lowercase hex characters |
judge_failed |
kind="eval" only |
True when the judge or the check ran and gave no result: an error, a timeout, a refusal, an output that it could not parse. Default False |
send no value with it |
trial |
any kind |
the number of this result among the trials of one experiment | an integer from 1 to 1000; needs experiment_id |
experiment_id |
any kind |
your id of the experiment or CI run. Risicare does not check it against another table | 1 to 128 characters |
- The judge fields need
kind="eval".judge_model,judge_version,judge_prompt_hashandjudge_failed=Trueon a score of another kind are refused:judge_fields_need_eval. The default kind isannotation, so passkind="eval"with them. The SDK does not change the kind for you. - A failed judge result has no value.
score(name="groundedness", trace_id=trace_id, kind="eval", judge_failed=True, comment="the judge timed out")posts a result of kindevalwith no value. Risicare stores it and counts it as failed. It is never read as 0 or 1, it stays out of the mean and of the pass rate, and it is not billed. Avaluewithjudge_failed=Trueis refused:failed_has_no_value. The judge fields may go with it. - A trial needs an experiment.
trialwithoutexperiment_idis refused:trial_needs_experiment.
The positional form of 0.7.0 and earlier, score(trace_id, name, value), still sends the score,
and the first such call in the process logs one WARNING. score() sends the score to the api host
(see "Two hosts"). For what happens when a score fails, see "Delivery".
Post the result of a judge
A judge is code that you run to grade an answer: a model or a rule. Post its result with
kind="eval". The default kind is annotation, and Risicare stores a judge result that you post
with the default as the label of a person. Add the identity of the judge with judge_model,
judge_version and judge_prompt_hash. Use the same name as the labels of your reviewers, and
post on the same trace, span or session.
import hashlib
import risicare
risicare.init(api_key="rsk-...")
JUDGE_PROMPT = "Is the answer grounded in the context? Reply pass or fail.\n\nContext: {context}\n\nAnswer: {answer}"
with risicare.trace("answer-question"):
trace_id = risicare.get_current_trace_id()
# The result of your judge. Without kind="eval", Risicare stores it as the label of a person.
risicare.score(
name="groundedness",
value=True,
trace_id=trace_id,
kind="eval",
judge_model="gpt-4o-mini",
judge_version="2026-11-01",
judge_prompt_hash=hashlib.sha256(JUDGE_PROMPT.encode("utf-8")).hexdigest(),
)
The judge validation card in the dashboard compares the results of a judge with the labels of
people. A label is a score of kind annotation: a person adds it in the dashboard, or your code
posts it. The card needs at least 50 pass labels and 50 fail labels that the judge also scored.
With fewer, the card shows counts and no rates. The card reads each identity on its own, so a new
prompt template (a new judge_prompt_hash) is a new identity. A result with judge_failed=True
is never a pass and never a fail.
Runs, trials and the gate
Run the cases of a dataset version through your function, with trials, and ask if the new build is worse. Your code runs the function and the checks. Risicare stores the run, the results and the check scores, and the api computes the verdict, with the noise of the trials in it.
from risicare import evals
def my_agent(case: evals.Case) -> str:
return answer(case.input) # your own code; it may be async
def exact_match(case: evals.Case, output: str) -> bool:
return output == case.expected
run = evals.run(
dataset="support-regressions", # a name or an id
function=my_agent,
checks=[evals.Check("correct", exact_match)],
trials=4,
release="2.4.1",
)
print(run.summary)
- What a run does. It creates the run, reads the cases (
GET /v1/evaluations/{id}/inputs), runs each casetrialstimes, each trial under its own trace, posts one score for each check and trial, posts the results, and closes the run (completed;cancelledonKeyboardInterrupt;failedon any other exception, which is raised again). It writesrisicare-run.json(the run id, the api host, the project id and the release; no key) or the path inRISICARE_EVAL_STATE. - A dataset name or an id. A name is looked up with
GET /v1/datasets?name=, an exact match (a name is unique in a project); an id (a uuid) skips the lookup. - A repeat of
external_id. The same key with the same dataset, version, split and trials gives the first run back, and the helper goes on with it if it is still running. If it is closed, or the key belongs to a run with other settings, the helper stops before it runs a trial. - What a trial writes. The root span
risicare.eval.trialand, on every span of the trial trace,risicare.experiment.id(the run id) and, when you giverelease,risicare.release. The root span also hasrisicare.experiment.case_idandrisicare.experiment.trial. A prompt pair (prompt=("support", "4")) wraps the function inprompt_context. A prompt object fromget_prompt(prompt=prompt) also sends its hash with the run and wraps the function inprompt.context()(see Pull a prompt). Nothing else is written. A trace with an experiment id is left out of release numbers and of the default trace list. - Checks.
evals.Check(name, fn, value_type="boolean", required=True, threshold=None, judge=None, score_kind="eval").fn(case, output)(orfn(case, output, trace_id)) returns a bool, a number, a string orevals.CheckResult(value, comment=None, failed=False). A boolean check passes when its value is true; a numeric check passes when its value is at leastthreshold; a categorical check never decides and cannot be required. A trial passes when every required check passes. At least one check must be required.score_kind="outcome"is for a result that your own system knows.judge=evals.Judge(model=..., version=..., prompt_hash=...)copies your judge identity to the score. The helper runs no judge and no model of its own. - A failure is not a fail. A function that raises, or a required check that raises, gives a
failed result: no pass and no fail. It is counted, and it stays out of every rate. A failed
optional check gives a score row with
judge_failedand no value, and the trial keeps its decision. If more than 10 percent of the planned trials of a run fail or are missing, the api gives no verdict. - Write a whole threshold as an int. The pass rule text is
all of:and the sorted items (correct is true; tone >= 0.7). Python writes a number withrepr, so1.0gives1.0; writethreshold=1to get the same rule text as the JavaScript helper. - Retries. A post that meets a connection error or a 5xx is tried again three times, after 1, 2
and 4 seconds. A 4xx raises
evals.RisicareEvalError. A 403 that comes from the load balancer of the host and not from the api (the body is not the api's JSON error, theserverheader isawselb, or theerror.codeispath_not_public, which the edge of the api host sends) raises the same error with thecodepath_not_public; its text says that the path is not public on this host and names the path. A check score that still cannot be posted is counted inrun.summary.score_post_failedand logged once; it does not changepassed. A score post that is tried again after a 5xx or a lost answer can reach the api twice, and then the check counts twice for that trial, until the api makesPOST /v1/scoresidempotent. A result is not affected: the api keeps the first row of a case and a trial. - Tracing must be on. If you did not call
init(), the helper does it withRISICARE_API_KEY. Asample_ratebelow 1.0 is refused, because a result needs a trace id. The checks run inside the trial trace, so the calls of a judge carry the experiment id too. - The holdout. A dataset can set a share of its cases aside as a holdout (a hash of the case
id; the api keeps it hidden from keys). Use
split="holdout"for a run on the holdout. The cases of a holdout run can be read only while the run is open, and each run counts as a look. The helper reads the cases into memory, writes them nowhere, and refuses a case of the wrong split. It cannot stop your function from logging what it reads.
pytest
from risicare import evals
def test_case(risicare_case, risicare_eval):
res = risicare_eval.run_case(
risicare_case, my_agent, [evals.Check("correct", exact_match)]
)
assert res.pass_fraction >= 0.5 # or: res.assert_passed_all()
pytest --risicare-dataset support-regressions --risicare-trials 4 --risicare-release 2.4.1
The plugin is installed with the package (entry point pytest11) and does nothing unless
--risicare-dataset (or RISICARE_EVAL_DATASET) is set; -p no:risicare turns it off. It makes
the run when the session starts, gives every test with an argument risicare_case one call for each
case (the case id is the test id), and closes the run at the end. The other options are
--risicare-version N (default: the head), --risicare-split dev|holdout, --risicare-trials K,
--risicare-release LABEL, --risicare-prompt NAME@VERSION and --risicare-external-id KEY. With
--collect-only it lists the cases of the export and makes no run. A CaseResult has trials,
pass_fraction (None when no trial was decided), passed_all, flipped and failed_trials.
Your test decides what to assert; pytest decides its exit code; the gate decides the gate. The exit
code of pytest is not the gate: a test that does not assert on the result passes even when its case
passed no trial. At the end of the session the plugin prints a WARNING for each test that passed while
its case did not pass all its trials and that did not read the result. Assert on the result, or run
risicare eval gate. The run
is made before a test gives its checks, so the pass rule of the first checks that a test gives
travels with the first batch of results. One run has one pass rule: use the same required checks in
every test of the session. pytest-xdist is not supported (pytest.UsageError).
Fail CI when your agent got worse
Since risicare 0.13.1. With fewer cases than the table below gives for your line, fail the build
(exit 100) when the observed pass rate is under your line. A trial with no result (it failed, or it
was never sent) counts as not passed. The output gives the number of cases and says that the result
is observed, not proven:
risicare eval gate --fail-under 0.9
With enough cases, fail only on proof, against your last release:
risicare eval gate --min-pass-rate 0.9 --baseline release:2.3.0. A line is proven met only from
this many cases (at that size, only when every case passes); a miss can be proven from fewer:
| Line | 0.8 | 0.9 | 0.95 |
|---|---|---|---|
| Cases | 16 | 35 | 73 |
--baseline needs 20 cases that both runs decided; with fewer, the comparison has no verdict and
the gate exits 101 (100 when a line is proven missed). On your first release no baseline run exists
and the gate exits 1, so leave --baseline out.
The gate
risicare eval gate --baseline release:2.3.0 --min-pass-rate 0.6
This example needs a completed run with the release label 2.3.0 and 20 or more cases that both
runs decided and that did not change between the two runs; see "Few cases" below.
risicare eval gate [--run ID] [--fail-under T] [--baseline RUN_ID|release:LABEL] [--max-drop X] [--min-pass-rate T] [--min-pass-all T] [--require-holdout] [--strict] [--allow-no-verdict] [--json]
reads the verdict
of the run (default: the run in risicare-run.json) with one call and exits with the code of the
answer: the command rewrites no code. The one exception is --fail-under: the command exits 1 when
the api did not apply the line, or when the answer does not agree with itself. It has no statistics
code. With none of --fail-under,
--baseline, --min-pass-rate, --min-pass-all and --require-holdout, the api passes the run (exit 0),
also a run that is not closed. The command then prints a WARNING on
stderr, because such a gate does not look at the results; the exit code does not change.
| Exit code | Meaning |
|---|---|
| 0 | the gate passed |
| 1 | the command could not decide: a network error, 401, 403, a 5xx, an unknown run, a body it cannot read, an api that did not apply --fail-under, or a --fail-under answer that does not agree with itself |
| 2 | a usage error (a bad option) |
| 100 | at least one criterion is missed: proven (a regression, or a pass rate provably below the line), or observed with --fail-under (gate.basis says which) |
| 101 | no verdict: the evidence is missing or cannot be compared; or an unclear criterion under --strict |
Each criterion of the proof mode has a state from the 95 percent interval of the number it tests:
met (the whole interval is on the passing side of the line), missed (the whole interval is on the
failing side) or unclear (the interval holds the line). The gate blocks on proof: only missed exits
100. An unclear criterion prints a line that says on which side of the line the value is, and exits
0, unless --strict is set. A missed line exits 100 also when the comparison has no verdict: only a
run that lost more than 10 percent of its trials (too_many_failed_candidate) or that is not closed
(run_not_closed) hides it. A no-verdict never passes, unless --allow-no-verdict is set: the api
then answers 0 for a no-verdict that has a reason. An unclear criterion under --strict stays 101
with it. A baseline compare is missed only when the run is provably
worse than the baseline by more than --max-drop (default 0). --json prints the verdict object
and nothing else. For a script, read the exit code and --json: the words of the table and of
stderr can change in a PATCH release.
The plain mode (since risicare 0.13.1). --fail-under T fails the gate (exit 100) when the observed pass rate of the run
is under T, and passes it (exit 0) when the rate is on T or over it. The rate is the passed trials over
all the planned trials of the run: a trial with no result (it failed, or it was never sent) counts as
not passed. It is an observed result, not a proof: the output says so and gives the number of cases.
The api compares exact fractions, so a rate on the line passes. T is a decimal from 0 to 1, with
no sign and at most 9 decimals as typed (exit 2 for more), so the api uses exactly that number. --fail-under cannot be used with
--min-pass-rate, --min-pass-all, --baseline, --max-drop, --strict or --allow-no-verdict
(exit 2). --require-holdout and --json are accepted: with --require-holdout, a dev run under the
line exits 100 and one on or over the line exits 101. A run that is not closed exits 101. In the table,
the Pass rate line is the mean over the decided cases only, the Pass^k line is over the complete
cases only, and the fail_under row gives the observed rate. --json prints gate.basis:
observed or proven. With --json, read the observed rate from the fail_under criterion
(criteria[].value), not from run.pass_rate. In the plain mode the table cuts the pass rate, its
interval and pass^k to the decimals it prints (it does not round them), as the api cuts the rate in
its words. The command needs an api that knows fail_under (an older api
ignores it), and an answer that agrees with itself (the line, the state, the value and the exit code): else it exits 1 and says so.
Few cases. The interval of the pass rate is the 95 percent Wilson interval of the case mean, over
the cases that have a decision, for every run. With few cases the interval is wide, so a line is
often unclear: by default it passes (exit 0), and under --strict it gives 101, also for a rate
over the line. With 1 trial per case, a run in which every case passes is met only from this many
cases:
Line (--min-pass-rate or --min-pass-all) |
Cases for met when every case passes |
|---|---|
| 0.8 | 16 |
| 0.9 | 35 |
| 0.95 | 73 |
--baseline compares the cases that both runs decided and that did not change between the two runs:
with fewer than 20 such cases, the comparison has no verdict (too_few_cases), and the answer is
101, also with --strict (0 with --allow-no-verdict). A line that is proven missed still exits
100, also with --allow-no-verdict. A first release has no baseline: --baseline release:LABEL for a label with
no completed run of the same dataset and split (other than this run) exits 1 (404
baseline_not_found), and --allow-no-verdict does not change that; the command then says to leave
out --baseline. For the first release, leave out --baseline: use --fail-under on a small
dataset, or --min-pass-rate or --min-pass-all with enough cases, and add --baseline from the
second release.
The key and the limits
The helper needs a project key of the Secret class. Only an owner or an admin can make a key (Settings > API keys).
An Ingest key, the class that the dashboard selects first, reaches POST /v1/scores, GET /v1/fixes/active and the prompt pull, and gets 403 on the other paths of the helper.
A CI key holds the scopes of the api paths of the helper but not ingest:write: the run and the gate work, and the ingest gateway refuses the spans of the trials (HTTP 401).
Scopes the helper uses: ingest:write, evaluations:read, evaluations:write, datasets:read, scores:write.
This list shows what the helper uses. The api enforces the scopes of a key: a key that lacks one gets a 403 that names the missing scope. Use a key of its own for CI and rotate it if it leaks.
The helper calls the api host and the ingest host that init() or the environment names, and no
other host. It sends no telemetry about you and no update check. It sends no function output and no
case input, except inside the spans of the trial, under your content switch. A run holds at most
10,000 cases and 50,000 results, and a run has at most 100 trials. Runs and results stay until you
delete them.
OpenTelemetry
pip install risicare[otel]
risicare.init(api_key="rsk-...", otel_bridge=True)
With otel_bridge=True, the SDK adds a span processor to the global
OpenTelemetry TracerProvider when your program imports opentelemetry. The
spans of your OpenTelemetry SDK then also go to Risicare. Set the
TracerProvider before you call init().
The bridge works with opentelemetry-sdk 1.20.0 (the minimum of the otel
extra) and later; it is tested on 1.20.0 and on 1.45.2. With the SDK installed,
its processor and exporter subclass the SDK's SpanProcessor and
SpanExporter, and no hook of the bridge raises into your code. Through 0.14.0 the processor did not have the _on_ending hook that
opentelemetry-sdk 1.40.0 and later call from Span.end(). With
otel_bridge=True, or with RisicareSpanProcessor added by hand, every
span.end() then raised AttributeError. With 0.14.0 or earlier, use
opentelemetry-sdk<1.40.0, or turn the bridge off, until you upgrade.
Attribute names the bridge reads
OpenTelemetry renamed some GenAI attributes. A new emitter writes the current names. The Anthropic
SDK (beta), Strands, Microsoft Agent Framework and @ai-sdk/otel do this. An older emitter writes
the older names. The bridge reads both. For each pair, it reads the current name first and the older
name second. A span that has both names keeps the current one. The bridge removes both names from the
span attributes and puts the value in the Risicare field.
| Risicare field | Current name (read first) | Older name (read second) |
|---|---|---|
provider |
gen_ai.provider.name |
gen_ai.system |
prompt_tokens |
gen_ai.usage.input_tokens |
gen_ai.usage.prompt_tokens |
completion_tokens |
gen_ai.usage.output_tokens |
gen_ai.usage.completion_tokens |
stop_reason |
gen_ai.response.finish_reasons |
gen_ai.response.finish_reason |
- A name that has no usable value does not hide the other name. An empty text, a count that is not a number and an empty list have no usable value. The count 0 is a usable value.
gen_ai.response.finish_reasonsis a list of strings. The first item is the stop reason.gen_ai.response.finish_reason(one string) is not in the OpenTelemetry registry. The bridge read it before, and it still does.- These names did not change, and the bridge reads them as before:
gen_ai.response.model(thengen_ai.request.model),gen_ai.request.temperature,gen_ai.request.max_tokens,gen_ai.usage.total_tokensandgen_ai.usage.cost. - The bridge does not read
gen_ai.operation.name,gen_ai.input.messages,gen_ai.output.messages,gen_ai.tool.*andgen_ai.response.id. They stay on the span under the name that the span carries. - The bridge does not change a value. A provider value that the span carries is the value that Risicare stores.
- Source, read on 2026-10-31: the deprecated registry of
open-telemetry/semantic-conventionsv1.44.0 (the older names), andopen-telemetry/semantic-conventions-genaiat commit6f98aef(the current names). That repository has no release tag, and its attributes have the status "development". A name can change again.
What happens at the Free quota
Each plan has a monthly event quota. When your organisation has used it, the Risicare backend discards new spans until the quota resets (the first day of the next UTC month), or until you upgrade or buy an event pack. Nothing raises in your application, and tracing continues.
The SDK treats this as a state, not an error (0.6.1 and later). It writes one WARNING
that names the reset time, and it stops sending. It sends one batch again every 5 minutes (the
retryAfterSeconds that the backend returns; it does not wait for the reset time). Spans that
end in the meantime wait in the SDK queue, which has a fixed size: when it is full, the oldest
spans are dropped and the most recent are kept. flush() returns false at once in this time, and
does not wait for its timeout. When the backend accepts a batch again, the SDK writes one INFO and sends the queued spans, so an upgrade takes effect
within minutes and nothing new is lost unless the queue overflows. While the quota stays used
up, it writes at most one WARNING an hour. A batch that the backend discards, and a span that
the full queue drops in the pause, are counted in get_metrics()["dropped_quota"] (the same number as
dropped_spans_by_reason["quota_exceeded"]). They are also in the flat dropped total, and not in rejected_spans. They are not stored. With more than one exporter, the queue holds spans only when every
exporter that delivers is paused; beside an exporter that is not paused, a paused one still drops
the batches that it gets.
Delivery during a gateway outage (retry policy)
The SDK's HTTP exporter keeps a batch and sends it again while the gateway is down, for a fixed time. The JavaScript SDK has the same policy, with the same numbers.
| Case | What the SDK does | Drop reason |
|---|---|---|
| HTTP 408, 429, 500, 502, 503 or 504, a connection error, a timeout | It sends the batch again. The wait before retry n (0 for the first retry) is a random part of min(30 s, 1 s × 2^n) (full jitter). A Retry-After header (seconds or an HTTP date) replaces the wait when it is more than 0 s. |
— |
The batch is still not delivered at the retry horizon: retry_horizon_s, default 300 s, from its first attempt |
It stops and drops the batch. No wait goes past the horizon. | retry_exhausted |
| HTTP 413 (the request is too large) | It splits the batch in two, one time, and sends both halves. A half that gets 413 again is dropped. One WARNING, one time. | too_large |
| HTTP 400, 401, 403, 404, 422 and every other status; a redirect; a 2xx that is not a Risicare ack; an ack of 0 and 0 | It sends the batch once. A retry cannot change the answer. | transport_refused |
The queue is full: 10,000 spans, or 64 MiB of estimated span bytes (max_queue_bytes of BatchSpanProcessor) |
It drops the oldest queued spans and keeps the new one. Memory stays bounded by the queue. Nothing is written to disk. Through 0.15.0 only the count was bounded: with content capture on, 10,000 large LLM spans could hold about 1 GB. | queue_full |
| 5 export calls in a row fail (a batch sent once and refused, or a batch that used up its retries; not when the last answer was 429 or 503) | The circuit breaker opens for 60 s. A batch is then dropped with no request. After 60 s, the next batch is the probe. | transport_refused |
shutdown() |
It sends for at most shutdown_timeout_s (default 10 s). A retry wait ends at once, and a failed attempt is not retried. Spans that it cannot send are counted. |
shutdown_residue |
A span that starts after shutdown() (or after the SDK's own SIGTERM drain), before a new init() |
It makes no span and counts it. Your function, and a patched LLM call, run as before; a fault of the count never reaches them. The next flush() returns False, and one WARNING for the shutdown says what to do (see "Serverless functions"). The count is made before sampling. |
after_shutdown |
A span that was open when shutdown() ran and ends after it |
It cannot send the span. It counts it, with one WARNING for the shutdown. | open_at_shutdown |
A gateway outage that is longer than the retry horizon loses spans. The oldest batch is
dropped when it reaches the horizon, and a full queue drops its oldest spans. Nothing raises
in your application. The SDK writes a WARNING, flush() returns False, and
get_metrics()["dropped_spans_by_reason"] counts each lost span under its reason. To wait
longer, raise retry_horizon_s in init(); the queue still holds at most 10,000 spans and
64 MiB.
While the exporter is paused for the monthly quota, a span that ends keeps no content. The
pause can last until the month ends, and the content (prompts, completions, tool arguments) is what
makes a span large. Such a span is queued with the content gate's marker in each content key
(<risicare:content-omitted>), as with content capture off; its timing, tokens, model and errors
stay. A span that was queued before the pause keeps its content.
While the SDK retries, get_metrics()["oldest_pending_age_s"] grows: it is the age of the
oldest span that is queued or in an export. attempts counts the HTTP requests (each retry and
each half of a split included) of an export call when that call ends, so the requests of a batch
that is still retrying are added when it is delivered or dropped. flush() does not stop a
retry: it returns False at its deadline while the batch waits. A retry can send a span a second time when the gateway stored it but
its answer did not arrive.
A 401 or 403 answer is sent once in each export call: a retry gets the same answer. The
WARNING "spans are NOT reaching ..." comes at the first failure of an outage (at most once in 5
minutes): for a retryable answer after the third failed attempt of a batch, or when its retries
end before that. It gives the HTTP status of the last answer, or the error class when there was no
answer. For a 401 or 403 it says who refused. It reads the error.code of the JSON answer (the
code only; it never logs the body) and writes one of these texts after the status:
| Answer | Who refused | The WARNING says |
|---|---|---|
403, code path_not_public |
the edge (the load balancer) of a host that does not forward spans | this host does not forward spans. The endpoint is probably the API host or the dashboard. Set endpoint (or RISICARE_ENDPOINT) to the ingest gateway, https://ingest.risicare.ai. |
403, code AUTHORIZATION_FAILED |
the api, for a key that does not hold the scope | this key cannot write spans. Create an Ingest key or a Secret key in Settings > API keys. |
401, code UNAUTHORIZED or no code |
the ingest gateway, for a missing or wrong key, or for a key without the scope ingest:write (a CI key) |
The endpoint refused the API key. Check the api_key (or RISICARE_API_KEY) and the project it belongs to. A CI key cannot send spans: use an Ingest key or a Secret key. |
| 401 or 403, another code; 403, no code | not known | The endpoint refused the API key. Check the api_key (or RISICARE_API_KEY) and the project it belongs to. Another code comes first, for example (code SOME_CODE), and a 401 also gets the sentence about a CI key. |
A code is printed only when it is 1 to 40 letters or underscores. A failed score() names the
same causes in its WARNING; for path_not_public it says to set api_endpoint (or
RISICARE_API_ENDPOINT) to the api host. When the kind of failure changes in one outage (for
example a 401, then no answer), the SDK writes one more WARNING. A batch that is dropped as retry_exhausted gets one
more WARNING (at most once in 5 minutes) that names the attempts and the last answer.
For the other answers it writes the next step after the status:
| Answer | The WARNING says |
|---|---|
| 404 | The endpoint has no route for spans (POST /v1/spans). Set endpoint= (or RISICARE_ENDPOINT) to the base URL of your ingest gateway, without /v1 (the default is https://ingest.risicare.ai). |
| 429 | The gateway limits the request rate (for this IP address, for this project, or while it is busy). To send fewer requests, raise batch_timeout_ms (and batch_size at a high span rate) or lower sample_rate. |
| 400 | The gateway refused the request body. Upgrade the SDK (pip install --upgrade risicare); if the answer stays, send this WARNING to Risicare support. |
| 408 | The request took too long. Check the network between this host and the endpoint. |
| 502, 504 | A load balancer or a proxy in front of the gateway got no answer from it. If this stays, check the status of the endpoint. |
| 503 | The gateway, or a service behind it, cannot take spans now. |
| another 5xx | The gateway had an error. If this stays, check the status of the endpoint. |
| another 4xx | Check the endpoint (endpoint= or RISICARE_ENDPOINT). |
| no answer | Check that the endpoint (endpoint= or RISICARE_ENDPOINT) is right and that this host can reach it: DNS, the firewall, the proxy variables (HTTPS_PROXY, HTTP_PROXY, NO_PROXY), and for a TLS error the CA bundle (SSL_CERT_FILE). |
A short program can end before the third attempt. Then shutdown() ends the retries, and the
WARNING comes at that point, with the same next step. The shutdown_residue WARNING that follows
says that a longer shutdown timeout does not help while the endpoint refuses or cannot be reached.
init() prints one line to stderr: [risicare] Tracing configured — endpoint: <url>, service: <name>. Delivery is not checked yet: a WARNING follows if the endpoint refuses the key or cannot be reached. init() sends nothing, so the line says what is configured, not that spans arrive. It
names no project: the gateway takes the project from the key. With debug=True a DEBUG log takes
its place. With no API key there is no line, and a WARNING says that nothing is sent.
The exporter that otlp_endpoint adds (your own collector) keeps its own retry rules; this
policy is the Risicare HTTP exporter's.
The SDK removes its API key from each text that it logs: in any case of letters, and also when the key is percent-encoded. An endpoint is logged without its user name, password and query. A secret that you put in another place of a URL (for example in its path) is logged as you gave it.
A note on debug=True
debug=True attaches a console exporter in addition to any HTTP exporter.
That exporter writes every span attribute to stdout, with no redaction of
its own. It gets the same spans as the HTTP exporter: when trace_content is
on (the default), your prompts and completions go to your console (after your
mask). It is
a local-development switch, not a diagnostic one.
If you are debugging a delivery problem ("spans are NOT reaching ..."), raise the SDK's logger instead. This prints the HTTP status and transport error and does not print span payloads:
import logging
logging.getLogger("risicare").setLevel(logging.DEBUG)
Measured for a failing export: the logger WARNING shows the HTTP status and no
span payload, with and without debug=True. debug=True adds the spans on the
console; the console lines themselves have no HTTP status.
Requirements
- Python 3.10+
Documentation
Support
- Email: support@risicare.ai
- Docs: risicare.ai/docs
During the beta, please send detailed reproduction steps for any SDK or platform issue.
License
Proprietary. See LICENSE.
Conscience Labs Pvt. Ltd. owns this SDK. You may use it with the Risicare service under the terms in LICENSE. Risicare is in a free beta: you need no paid subscription. You may not change the SDK, make derivative works from it, reverse engineer it, or redistribute it. Contact info@consciencelabs.ai.
Metadata
Release files for risicare 0.16.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| risicare-0.16.0.tar.gz | 674.3 kB | With provenance | Details for risicare-0.16.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| risicare-0.16.0-py3-none-any.whl | Python 3 | none | any | Details for risicare-0.16.0-py3-none-any.whl |
Total release size: 1.4 MB
Release files / risicare-0.16.0.tar.gz
| Download URL | risicare-0.16.0.tar.gz |
|---|---|
| Size | 674.3 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
cd277b7a13012f16586e67038add68f550d733a9d7b3a7508cdb7e0bfc5d96bb
|
|
BLAKE2b-256 checksum How to use checksums |
04cde01b81dafa83c7a1abe25845a8253a8b043c8ae8002f60cfdd9d401c1c70
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.14
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 22, 2026.
Transparency logRelease files / risicare-0.16.0-py3-none-any.whl
| Download URL | risicare-0.16.0-py3-none-any.whl |
|---|---|
| Size | 712.1 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
3d78e8f9cffd85dd6b55fd14aa8d62fe658a609a7999324b7807968aee568c6e
|
|
BLAKE2b-256 checksum How to use checksums |
c15352d4146cfdc558d716fdecf9e19268c9b9917a0d606d9a5c6cfa3e01e314
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.14
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 22, 2026.
Transparency logSecurity for risicare 0.16.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for risicare-0.16.0.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 22, 2026.
Transparency logA note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.