Configuration
Configure the Risicare SDK for your application.
Configure the Risicare SDK to connect to your project and customize tracing behavior.
JavaScript SDK?
Basic Setup
import risicare
risicare.init( # reads RISICARE_API_KEY from the environment
service_name="my-agent", # Identify your service
environment="production", # Environment name
)API Key = Project
Your API key is scoped to the project it was created under (visible in Settings → General). No separate project_id is needed — the gateway resolves it from your key.
project_id is deprecated
Passing project_id to init() emits a DeprecationWarning in Python (or console.warn in JavaScript). The parameter is ignored by the gateway and will be removed in v1.0. Use service_name and environment for within-project organization instead.
Configuration Options
Required
| Option | Type | Description |
|---|---|---|
api_key | str | Your Risicare API key, from the dashboard. Paste it exactly as the dashboard shows it. Each key is scoped to one project. Set it as RISICARE_API_KEY in the environment. Do not write a key in your code or commit one. |
With no API key the SDK sends nothing
With no key (also a key of only whitespace; the SDK trims the key) and no exporter of your own, tracing is off. The SDK sends nothing to Risicare, is_enabled() and flush() return False, and nothing is counted as exported. init() logs one WARNING that says so and names the RISICARE_API_KEY environment variable (none when you turned tracing off on purpose). Since 0.16.1, the WARNING names the environment variable only: keep the key out of your code. Through 0.16.0 it also said to pass api_key to init(), and it named debug=True. RISICARE_TRACING=true and enable() cannot turn tracing on without a key. An empty api_key argument counts as not given, so RISICARE_API_KEY applies. An exporter that you name yourself (otlp_endpoint, exporters=[...]) still delivers without a key: then is_enabled() is True and flush() reports the delivery of that exporter, with no WARNING. In 0.5.1 and earlier, is_enabled() and flush() returned True with no key.
Optional
| Option | Type | Default | Description |
|---|---|---|---|
endpoint | str | "https://ingest.risicare.ai" | Ingest gateway URL. The SDK sends spans to this host. |
api_endpoint | str | "https://api.risicare.ai" | API URL. The SDK sends scores, prompt pulls, evaluation runs and fix reads to this host. If you pass endpoint (not the default ingest host) and no api_endpoint, these requests go to endpoint, also when RISICARE_API_ENDPOINT is set. |
project_id | str | None | Deprecated. Ignored by the gateway. See the warning above. |
environment | str | "development" | Environment name (development, staging, production) |
service_name | str | None | Service name for within-project organization. The SDK writes it as service.name on every span that it makes, also on a span inside @agent(...) and on the spans of LangChain, DSPy, LlamaIndex and LiteLLM (since 0.16.0; before, a span with an agent and those spans had none). The spans of the OpenTelemetry bridge do not get it |
service_version | str | None | Service version. The SDK puts it on every span as service.version |
enabled | bool | True | Enable/disable tracing globally |
trace_content | bool | True | Capture prompt and completion content, and the arguments of tool calls. On by default since 0.7.0. Pass trace_content=False (or set RISICARE_TRACE_CONTENT=false) to keep content in your process. With it off, the text of an error is withheld too (see error_text). You can also turn content off in the project settings. The gateway then drops the content of that project, but the text has already left your process |
sample_rate | float | 1.0 | Sampling rate (0.0-1.0, clamped) |
batch_size | int | 500 | Spans per batch export. Values outside [1, 10000] are clamped and a WARNING risicare.exporters.batch log line is emitted on each init() call that triggers a clamp. |
batch_timeout_ms | int | 1000 | Milliseconds between batch exports |
auto_patch | bool | True | Patch ThreadPoolExecutor, ProcessPoolExecutor, and asyncio.create_task for automatic context propagation |
debug | bool | False | Echo every span to stdout via a console exporter. Prints span attributes as they are exported (after mask, if one is set), including prompt and completion text when content capture is on — see the warning below before enabling. |
exporters | list[SpanExporter] | None | Custom span exporters. Import the base class with from risicare.exporters import SpanExporter, ExportResult, and implement export(self, spans) -> ExportResult. When you pass exporters, the SDK does not add its HTTP exporter (it logs a WARNING). Default: the HTTP exporter when api_key is provided |
metadata | dict | {} | Global metadata attached to all spans |
otlp_endpoint | str | None | OTLP/HTTP export endpoint |
otlp_headers | dict | None | OTLP export headers |
otel_bridge | bool | False | Bring the spans of your OpenTelemetry SDK into Risicare. It does not send Risicare spans out: use otlp_endpoint for that. See OpenTelemetry |
mask | Callable[[str, Any], Any] | None | Function mask(key, value) that returns the value to export. It runs on content-bearing fields before export. It has no environment variable. See Production & Failure Modes. |
fix_runtime | bool | False | Start the fix runtime. It is off by default since 0.4.0. During the beta the Risicare service gives no fixes to customer projects, so keep it off. |
retry_horizon_s | float | 300 | How long the HTTP exporter retries one batch, in seconds from its first attempt. A batch that the gateway does not take in that time is dropped (retry_exhausted). 0 sends each batch once. It has no environment variable. See Span Delivery. |
shutdown_timeout_s | float | 10 | The budget of shutdown(), in seconds. It is also the budget of the SDK's own teardown at interpreter exit and, when no handler of your application owns SIGTERM, at SIGTERM. Spans that the SDK cannot send in that time are counted as shutdown_residue. It has no environment variable. Through 0.7.0 the budget was 5 s. |
max_input_messages_bytes | int | 49152 | The cap of gen_ai.input.messages (the whole message list of an OpenAI or Anthropic call), in UTF-8 bytes. A value below 1,024 or above 65,535 is clamped, with one WARNING. A list above the cap is cut: the first and last messages stay. Raise it for long prompts. It has no environment variable. See OpenAI. |
stream_usage | bool or str | "auto" | Whether the SDK asks OpenAI for the token counts of a streamed Chat Completions call, when your call does not set stream_options. "auto" asks on a call to https://api.openai.com, True on any host, False never. Or set RISICARE_STREAM_USAGE. See OpenAI. |
error_text | bool or str | "auto" | Whether the text of an error leaves your process. The error text is the status message, the exception messages and their copies in the stack traces, error.message, exception.message and error.stack. "auto" follows trace_content: with content capture off, each such value is replaced with <risicare:content-omitted>. True sends it also with content capture off. Use it only when you need the messages and accept that an exception message can carry prompt or model output. False withholds it also with content capture on. The exception type, error.code, the status and the frame lines of a stack stay. Or set RISICARE_ERROR_TEXT. A second init() with another value warns, and the first value stays. |
Content truncation
When trace_content is on, captured text is truncated. Provider integrations cut each prompt and completion field at 10,000 characters, with no marker. The older gen_ai.system_prompt key of the Anthropic patch holds the first 5,000 characters of a string system. The whole system prompt is in gen_ai.system_instructions (see Anthropic). Framework integrations cut at a limit between 500 and 10,000 characters and append ... [truncated]. These limits are not configurable — they are hardcoded safety bounds to prevent oversized spans. The one setting is max_input_messages_bytes, for the whole message list of an OpenAI or Anthropic call.
auto_patch does not control provider instrumentation
When tracing is enabled, init() installs the import hooks that patch LLM provider libraries (OpenAI, Anthropic, etc.), whatever the value of auto_patch. auto_patch controls only the ThreadPoolExecutor, ProcessPoolExecutor and asyncio.create_task patches. With auto_patch=False, providers are still instrumented.
What debug=True enables
- Console exporter: Adds a
ConsoleExporterthat prints every span to stdout as it's exported — including span attributes. With no API key it still prints the spans, but they are not counted as exported and not delivered, andflush()returnsFalse - Debug log messages: Messages about an LLM call with no parent span (each such call becomes its own trace — a common Tier 1 mistake) and about initialization go to the
risicarelogger atDEBUGlevel. You see them only if you set that logger toDEBUG - No startup line: The
[risicare] Tracing configuredline is not printed whendebug=True. A DEBUG log takes its place
debug=True prints prompt and completion content unredacted
The console exporter writes span attributes to stdout as they are exported (after mask, if one is set), including
gen_ai.prompt and gen_ai.completion when content capture is on. Content capture is on by default, so a default
init(debug=True) prints this text. Any customer data in a prompt is
printed to your terminal and container logs. Attribute values are truncated at
~80 characters, which is not redaction — a value that begins with an SSN
or card number is printed in full.
Do not enable it against production traffic. init() also accepts a mask
callable for redacting attribute values before export.
debug=True does not show more about export failures
A failed span export logs a WARNING that names the endpoint and the HTTP status (or
the error, when there is no answer). debug=True adds nothing on that path. To see each
attempt, raise the SDK logger:
import logging
logging.getLogger("risicare").setLevel(logging.DEBUG)Span Delivery
When you pass an api_key, init() installs the HTTP exporter. This is the
default path — if you have not configured exporters or an OTLP endpoint, this
is what is sending your spans.
The exporter keeps a batch through a gateway outage for up to retry_horizon_s seconds
(default 300). It retries HTTP 408, 429, 500, 502, 503 and 504, a connection error and a
timeout, with full-jitter backoff (base 1 s, cap 30 s). A Retry-After header replaces
the wait when it is more than 0 s. It sends every other answer once, and it drops that
batch (transport_refused). On 413 it splits the batch in two, one time. A batch that the
gateway does not take within the horizon is dropped (retry_exhausted). A gateway outage
that is longer than the horizon loses spans. When the queue (10,000 spans, or 64 MiB of
estimated span bytes: the option max_queue_bytes of BatchSpanProcessor, since 0.16.0) is full, the
SDK drops the oldest queued span (queue_full) and keeps the new one. Through 0.7.0, the
exporter gave up after a few seconds, and a full queue dropped the new span.
The exporter has a circuit breaker
After 5 consecutive failed export calls the exporter opens a circuit and stops
attempting exports for a 60-second cooldown. A call is one batch, with all its
retries. For the default HTTP exporter, a call that ends with 429 or 503 as its last answer does not count. With the
default horizon, a dead gateway opens the circuit only after five batches in a row were each
retried for 300 s. Spans created during the cooldown are dropped. This bounds the damage a
gateway outage does to your application's latency, but delivery does not resume the
moment the gateway returns.
Tracing never raises: an export failure is logged, not thrown. The SDK logs a
WARNING that names the endpoint and the HTTP status when spans stop arriving. To see
each attempt, raise the SDK logger as shown above.
The OTLPExporter also opens after 5 failed calls and stays open for 60 seconds.
After the cooldown it lets one call through; if that call fails, it opens again at once.
It counts a 429 or a 503 as a failure — see OpenTelemetry.
For the measured behaviour — how the threshold counts, which spans survive, and how long delivery really stays stopped — see Production & Failure Modes.
Environment Variables
You can set these options with environment variables:
export RISICARE_API_KEY="rsk-..."
export RISICARE_ENVIRONMENT="production"
export RISICARE_SERVICE_NAME="my-agent"
export RISICARE_TRACING="true"
export RISICARE_TRACE_CONTENT="true"
export RISICARE_SAMPLE_RATE="1.0"
export RISICARE_SERVICE_VERSION="1.0.0"
export RISICARE_DEBUG="false"
export RISICARE_OTLP_ENDPOINT="https://otel-collector:4318"
export RISICARE_OTLP_HEADERS="key1=value1,key2=value2"
export RISICARE_OTEL_BRIDGE="false"| Variable | Maps To |
|---|---|
RISICARE_API_KEY | api_key |
RISICARE_ENDPOINT | endpoint |
RISICARE_API_ENDPOINT | api_endpoint |
RISICARE_PROJECT_ID | project_id (deprecated) |
RISICARE_ENVIRONMENT | environment |
RISICARE_SERVICE_NAME | service_name |
RISICARE_SERVICE_VERSION | service_version |
RISICARE_TRACING | enabled |
RISICARE_TRACE_CONTENT | trace_content |
RISICARE_SAMPLE_RATE | sample_rate |
RISICARE_DEBUG | debug |
RISICARE_OTLP_ENDPOINT | otlp_endpoint |
RISICARE_OTLP_HEADERS | otlp_headers |
RISICARE_OTEL_BRIDGE | otel_bridge |
RISICARE_FIX_RUNTIME | fix_runtime |
risicare.init() reads these fifteen variables. The import hooks read one more,
RISICARE_STRICT_INSTRUMENTATION — see
Production & Failure Modes.
batch_size, batch_timeout_ms, auto_patch, exporters, metadata, mask,
retry_horizon_s, shutdown_timeout_s and max_input_messages_bytes have
no environment variable.
Since 0.16.0, one parser reads every boolean variable: RISICARE_TRACING, RISICARE_TRACE_CONTENT, RISICARE_DEBUG, RISICARE_OTEL_BRIDGE, RISICARE_FIX_RUNTIME and RISICARE_STRICT_INSTRUMENTATION. The words for on are true, 1, yes and on. The words for off are false, 0, no and off. The SDK trims the value and ignores the case. Before 0.16.0, the SDK did not trim some values: true with a space read as off.
A value that is not one of these words writes one WARNING. For a switch that sends data or makes requests when it is on, such a value means off (RISICARE_TRACING and RISICARE_TRACE_CONTENT). For the other switches, it keeps the default. An empty RISICARE_TRACE_CONTENT is off, as before, now with one WARNING. An empty RISICARE_TRACING is the same as no value. Each WARNING is written one time for each value.
FixRuntimeConfig.from_env() reads the same words as init(): 1, yes and on turn its switches on. Before 0.16.0, it read only the word true.
Do not set RISICARE_ENDPOINT to the dashboard address
https://app.risicare.ai is the dashboard. It is not the ingest gateway. Leave both
variables unset to use the defaults. The SDK finds the host for scores, prompt pulls,
evaluation runs and fix reads in this order: the
api_endpoint option; the endpoint option, unless it is the default ingest host;
RISICARE_API_ENDPOINT; RISICARE_ENDPOINT, when no endpoint option is given and it is
not the default ingest host; https://api.risicare.ai. So a custom endpoint alone also
receives these requests, and https://ingest.risicare.ai never does.
Single-Import Instrumentation
Add import risicare to your entrypoint and set RISICARE_API_KEY and
RISICARE_TRACING=true to enable auto-instrumentation without calling init() or
changing your agent logic. The import itself is required — these variables are read
when the SDK is imported. This path uses the same defaults as init(): the environment
development and no service name, when RISICARE_ENVIRONMENT and
RISICARE_SERVICE_NAME are not set.
Advanced Configuration
Custom Endpoint
Override the default gateway endpoint (https://ingest.risicare.ai) — for example, to send
spans through an outbound proxy your network requires:
risicare.init( # reads RISICARE_API_KEY from the environment
endpoint="https://llm-egress-proxy.internal.example.com",
)endpoint sets where the SDK sends spans. If you do not also pass api_endpoint, the SDK
sends scores, prompt pulls, evaluation runs and fix reads to the same host as endpoint. To send them to a different host, pass
api_endpoint: when endpoint is passed as an option, RISICARE_API_ENDPOINT does not
override it.
Risicare is a hosted service
Risicare runs as a managed service. There is no self-hosted or on-premise Risicare
instance to point this at — endpoint and api_endpoint retarget where the SDK sends
its requests (a proxy or a non-default host), not where Risicare itself runs.
Sampling
Control trace sampling rate:
risicare.init( # reads RISICARE_API_KEY from the environment
sample_rate=0.1, # Sample 10% of traces
)Programmatic Control
Check Status
if risicare.is_enabled():
print("Tracing is active")is_enabled() is False before init(), with tracing off, with no API key (and no exporter of your own), and after the SDK's own SIGTERM drain.
Flush Pending Spans
# Send the spans queued so far. The SDK stays usable afterwards.
risicare.flush(timeout_ms=5000) # default: 5000msflush() returns a bool. True means that the gateway (in Python, also an exporter that you named) acknowledged every span and every score that the SDK accepted since the previous flush() returned, and that nothing is in the queue or in flight. This holds also in a signal handler and after shutdown().
A loss (a span dropped, rejected or not acknowledged, or a score that failed) makes the next flush() return False one time, and the one after it True again. flush() also returns False before init(), with tracing off, and with no API key (and no exporter of your own).
With more than one exporter, a batch counts as delivered when the first exporter that succeeds takes it, so True means that at least one exporter acknowledged each span; a failure of another exporter shows only in its own WARNING and in failed_exports. A span that you start after shutdown() has returned is not made. The SDK counts it as after_shutdown, and the next flush() returns False.
When it is False, read risicare.get_metrics(): dropped_spans_by_reason, rejected_spans and failed_scores name the loss; a False at the deadline with none of them raised means that the spans are still in flight. See the flush() reference for every case.
metrics = risicare.get_metrics()
print(metrics["exported_spans"], metrics["failed_exports"], metrics["dropped_spans"])See the Python SDK reference for every field.
Shutdown
# Graceful shutdown - flushes and closes connections
risicare.shutdown() # budget: shutdown_timeout_s of init(), default 10 s
risicare.shutdown(timeout_ms=1000) # or give a budget in millisecondsshutdown() waits up to timeout_ms (not given: the shutdown_timeout_s of init(), default 10 s) for the batch processor thread to drain, then performs a final flush and closes HTTP connections. An atexit handler calls shutdown() automatically on normal exit, so a normal program needs no explicit call. After shutdown() returns, the SDK makes no more spans until you call init() again. To send the queued spans mid-process and keep tracing (for example at the end of each invocation of a serverless function, or before a long non-tracing phase), call risicare.flush() and not shutdown(). See flush() and Serverless functions.
At SIGTERM, the handler of your application runs first when it owned the signal before init(). Then the SDK flushes for at most 1 s, and in the background (since 0.16.0). See SIGTERM and SIGINT and the known limits.
Shutdown may block on network issues
If the exporter is mid-request when shutdown() runs, the thread join blocks for up to timeout_ms. A batch that waits for a retry gets one more attempt at once, and a failed attempt in the drain is not retried, so a dead gateway costs one attempt for each batch, not the whole budget. In latency-sensitive paths, reduce the timeout: risicare.shutdown(timeout_ms=1000). docker stop waits 10 s by default, so set shutdown_timeout_s lower when your application needs time for its own cleanup.
Auto-Instrumentation Management
Control which libraries are automatically instrumented:
from risicare import (
install_import_hooks,
remove_import_hooks,
instrument_already_imported,
is_instrumented,
get_instrumented_modules,
get_supported_modules,
)
# See which libraries can be auto-instrumented
get_supported_modules()
# {'openai', 'anthropic', 'cohere', 'google.generativeai', 'mistralai', ...}
# Check what's currently instrumented — returns a per-module state record
get_instrumented_modules()
# {'openai': {'state': 'instrumented', 'hooks_landed': 4, ...},
# 'anthropic': {'state': 'instrumented', 'hooks_landed': 2, ...}}
# A patched provider reports "instrumented"; "failed" if its patch raised;
# "pending" if the module that holds its patch points is not imported yet.
# Check a specific library: True when at least one hook landed.
is_instrumented("openai") # True
# Instrument libraries that were imported before risicare.init()
count = instrument_already_imported()
# Returns number of newly instrumented modules
# Remove all import hooks (stops future auto-instrumentation)
remove_import_hooks()
# Re-install import hooks
install_import_hooks()Configuration Precedence
Configuration is resolved in this order (highest to lowest priority):
- Explicit
init()parameters - Environment variables
- Default values