Metadata-Version: 2.5
Name: risicare
Version: 0.6.0
Summary: AI agent observability and error diagnosis for Python — trace LLM calls, detect errors, get AI-generated fix suggestions
Project-URL: Homepage, https://risicare.ai
Project-URL: Documentation, https://risicare.ai/docs
Author-email: Risicare <founders@risicare.ai>
License: Copyright (c) 2026 Conscience Labs Pvt. Ltd. All rights reserved.
        Contact: info@consciencelabs.ai
        
        COMMERCIAL END USER LICENSE AGREEMENT (EULA)
        
        This software ("SDK") is the proprietary property of Conscience Labs Pvt. Ltd.
        Your use of this SDK is strictly governed by the commercial subscription agreement
        and terms of service entered into between your organization and Conscience Labs Pvt. Ltd.
        
        LICENSE GRANT & RESTRICTIONS:
        1. Subject to an active, paid subscription, you are granted a limited, non-exclusive,
           non-transferable license to integrate this SDK into your applications solely to
           utilize the AI Observability services hosted by Conscience Labs Pvt. Ltd.
        2. You shall not modify, adapt, alter, translate, or create derivative works from this SDK.
        3. You shall not reverse engineer, decompile, disassemble, or otherwise attempt to
           derive the source code of this SDK.
        4. You shall not distribute, sublicense, lease, rent, or loan this SDK to any third
           party as a standalone tool or product.
        
        WARRANTY DISCLAIMER:
        THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR
        IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
        FITNESS FOR A PARTICULAR PURPOSE.
        
        For licensing inquiries, custom enterprise terms, or support, please contact:
        info@consciencelabs.ai
License-File: LICENSE
Keywords: agent,agentic-ai,ai,ai-agent,anthropic,claude,error-diagnosis,gemini,gpt,langchain,llm,llm-observability,monitoring,observability,openai,opentelemetry,tracing
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: License :: Other/Proprietary License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Topic :: System :: Monitoring
Requires-Python: >=3.10
Requires-Dist: httpx>=0.27.0
Requires-Dist: risicare-core>=0.1.8
Requires-Dist: wrapt>=1.16.0
Provides-Extra: all
Requires-Dist: autogen-agentchat>=0.4.0; extra == 'all'
Requires-Dist: boto3>=1.34.0; extra == 'all'
Requires-Dist: cerebras-cloud-sdk>=1.0.0; extra == 'all'
Requires-Dist: crewai>=0.50.0; extra == 'all'
Requires-Dist: dspy>=2.5.0; extra == 'all'
Requires-Dist: google-cloud-aiplatform>=1.40.0; extra == 'all'
Requires-Dist: groq>=0.4.0; extra == 'all'
Requires-Dist: huggingface-hub>=0.20.0; extra == 'all'
Requires-Dist: instructor>=1.0.0; extra == 'all'
Requires-Dist: langchain-core>=0.2.0; extra == 'all'
Requires-Dist: langgraph>=0.2.0; extra == 'all'
Requires-Dist: litellm>=1.30.0; extra == 'all'
Requires-Dist: llama-index-core>=0.10.20; extra == 'all'
Requires-Dist: ollama>=0.1.0; extra == 'all'
Requires-Dist: openai-agents>=0.1.0; extra == 'all'
Requires-Dist: opentelemetry-api>=1.20.0; extra == 'all'
Requires-Dist: opentelemetry-sdk>=1.20.0; extra == 'all'
Requires-Dist: pydantic-ai>=0.1.0; extra == 'all'
Requires-Dist: together>=1.0.0; extra == 'all'
Provides-Extra: autogen
Requires-Dist: autogen-agentchat>=0.4.0; extra == 'autogen'
Provides-Extra: bedrock
Requires-Dist: boto3>=1.34.0; extra == 'bedrock'
Provides-Extra: cerebras
Requires-Dist: cerebras-cloud-sdk>=1.0.0; extra == 'cerebras'
Provides-Extra: crewai
Requires-Dist: crewai>=0.50.0; extra == 'crewai'
Provides-Extra: dev
Requires-Dist: langchain-classic>=1.0.0; extra == 'dev'
Requires-Dist: mypy>=1.8.0; extra == 'dev'
Requires-Dist: pytest-asyncio>=0.21.0; extra == 'dev'
Requires-Dist: pytest-cov>=4.1.0; extra == 'dev'
Requires-Dist: pytest>=7.4.0; extra == 'dev'
Requires-Dist: ruff>=0.1.0; extra == 'dev'
Provides-Extra: dspy
Requires-Dist: dspy>=2.5.0; extra == 'dspy'
Provides-Extra: frameworks
Requires-Dist: autogen-agentchat>=0.4.0; extra == 'frameworks'
Requires-Dist: crewai>=0.50.0; extra == 'frameworks'
Requires-Dist: dspy>=2.5.0; extra == 'frameworks'
Requires-Dist: instructor>=1.0.0; extra == 'frameworks'
Requires-Dist: langchain-core>=0.2.0; extra == 'frameworks'
Requires-Dist: langgraph>=0.2.0; extra == 'frameworks'
Requires-Dist: litellm>=1.30.0; extra == 'frameworks'
Requires-Dist: llama-index-core>=0.10.20; extra == 'frameworks'
Requires-Dist: openai-agents>=0.1.0; extra == 'frameworks'
Requires-Dist: pydantic-ai>=0.1.0; extra == 'frameworks'
Provides-Extra: groq
Requires-Dist: groq>=0.4.0; extra == 'groq'
Provides-Extra: huggingface
Requires-Dist: huggingface-hub>=0.20.0; extra == 'huggingface'
Provides-Extra: instructor
Requires-Dist: instructor>=1.0.0; extra == 'instructor'
Provides-Extra: langchain
Requires-Dist: langchain-core>=0.2.0; extra == 'langchain'
Provides-Extra: langgraph
Requires-Dist: langchain-core>=0.2.0; extra == 'langgraph'
Requires-Dist: langgraph>=0.2.0; extra == 'langgraph'
Provides-Extra: litellm
Requires-Dist: litellm>=1.30.0; extra == 'litellm'
Provides-Extra: llamaindex
Requires-Dist: llama-index-core>=0.10.20; extra == 'llamaindex'
Provides-Extra: ollama
Requires-Dist: ollama>=0.1.0; extra == 'ollama'
Provides-Extra: openai-agents
Requires-Dist: openai-agents>=0.1.0; extra == 'openai-agents'
Provides-Extra: otel
Requires-Dist: opentelemetry-api>=1.20.0; extra == 'otel'
Requires-Dist: opentelemetry-sdk>=1.20.0; extra == 'otel'
Provides-Extra: providers
Requires-Dist: boto3>=1.34.0; extra == 'providers'
Requires-Dist: cerebras-cloud-sdk>=1.0.0; extra == 'providers'
Requires-Dist: google-cloud-aiplatform>=1.40.0; extra == 'providers'
Requires-Dist: groq>=0.4.0; extra == 'providers'
Requires-Dist: huggingface-hub>=0.20.0; extra == 'providers'
Requires-Dist: ollama>=0.1.0; extra == 'providers'
Requires-Dist: together>=1.0.0; extra == 'providers'
Provides-Extra: pydantic-ai
Requires-Dist: pydantic-ai>=0.1.0; extra == 'pydantic-ai'
Provides-Extra: together
Requires-Dist: together>=1.0.0; extra == 'together'
Provides-Extra: vertexai
Requires-Dist: google-cloud-aiplatform>=1.40.0; extra == 'vertexai'
Description-Content-Type: text/markdown

# risicare

AI agent observability and error diagnosis for Python.

[![PyPI version](https://img.shields.io/pypi/v/risicare.svg)](https://pypi.org/project/risicare/)
[![Downloads](https://img.shields.io/pypi/dm/risicare.svg)](https://pypi.org/project/risicare/)
[![Python](https://img.shields.io/pypi/pyversions/risicare.svg)](https://pypi.org/project/risicare/)
[![License: Proprietary](https://img.shields.io/badge/license-proprietary-red.svg)](LICENSE)

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. Risicare then diagnoses the errors and suggests fixes.

## Quickstart

```bash
pip install risicare
```

```python
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 and the token
counts. You see them in the [Risicare dashboard](https://app.risicare.ai).

## Two hosts

The SDK sends data to two hosts:

- **Spans** go to `endpoint`. The default is `https://ingest.risicare.ai`.
- **Scores and fix reads** go to `api_endpoint`. The default is `https://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:

1. the `api_endpoint` argument;
2. the `endpoint` argument, unless it is the default ingest host;
3. the `RISICARE_API_ENDPOINT` environment variable;
4. the `RISICARE_ENDPOINT` environment variable, if you gave no `endpoint`
   argument and it is not the default ingest host;
5. 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 |

**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 NOT captured by default

**`trace_content` defaults to `False`** (since 0.2.2, the first published version with this default). Your prompts and
completions stay in your process. The model, the token counts, the latency,
the message roles, the errors and the attributes that you set are still sent.

To send prompt and completion text as well, opt in:

```python
risicare.init(api_key="rsk-...", trace_content=True)
# or set RISICARE_TRACE_CONTENT=true
```

**Upgrading from 0.2.0 or earlier?** This is a behaviour change: content that
used to be sent is no longer sent unless you opt in. In those versions the flag
also did not work for content you set by hand — `trace_content=False` did not
stop a `span.set_attribute("gen_ai.prompt.0.content", ...)` from reaching us.
Both are fixed together.

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".

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:

```python
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-...", trace_content=True, 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.


## Features

- **Auto-instrumentation** — `init()` instruments the supported LLM providers and frameworks. You do not change your LLM calls
- **12 LLM providers** — OpenAI, Anthropic, Google Gemini (`google-generativeai`), Mistral, Groq, Cohere, Together, Ollama, HuggingFace, Cerebras, Bedrock, Vertex AI. Import them before or after `init()`
- **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
- **Error Diagnosis (beta)** — the Risicare service finds the root cause and suggests a fix; it does not apply fixes (see "Error Diagnosis" 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.

```python
# 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 12 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`, `embeddings.create` (sync and async) | 2.54.0 |
| Anthropic | `anthropic` | `messages.create` (sync and async) | 1.11.0 |
| Google Gemini | `google-generativeai` (`google.generativeai`) | `GenerativeModel.generate_content` (sync and async) | 0.8.6 |
| 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` (module `google.genai`) is a different package. It is not instrumented.

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.

**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`.

### Streaming

- **OpenAI, Anthropic, Groq, Cerebras and Together.** A traced `stream=True`
  call returns a proxy of the provider's stream object. `with ... as stream:`,
  iteration, `close()`, `response` and 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 traced
  `generate_content(stream=True)` call returns a proxy of the response object.
  Iteration, `resolve()`, `text` and `candidates` work as without risicare.
- **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.

## Framework Integrations

The SDK patches the framework. The framework is not a dependency of
`risicare`; an extra installs it for you:

```bash
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
```

## Core API

```python
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"))     # Report a caught error for diagnosis
risicare.score("trace-id", "quality", 0.92)      # Record an evaluation score in [0.0, 1.0]

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")
```

## 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.

**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 returns `True` only when
  every span and every score that the SDK accepted since the previous
  `flush()` returned (or since `init()`, 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 returns `False` at its deadline. It also
  returns `False` when the SDK is not active: before `init()`, 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_residue` included), a span that the backend rejected, a
    score that failed, and a score that `score()` refused at the call. A loss
    makes the next `flush()` return `False`, one time, also when it occurred
    while no flush ran, and also after `shutdown()`. The flush after that
    returns `True` when nothing new was lost. Each loss also raises a counter
    with a named reason: `dropped_spans_by_reason`, `rejected_spans` or
    `failed_scores`.
  - **"Lost" and "still in flight" are different.** A `flush()` that returns
    `False` at its deadline, while none of these three counters went up since
    the previous `flush()`, 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()`.** A `flush()` that overlaps a
    drain (a `shutdown()` 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 a `flush()` after `shutdown()`. The order in
    which your program and the SDK install their SIGTERM handlers does not
    change this: a handler that you install before `init()` runs after the SDK
    has drained, and its `flush()` reports what the drain lost. A handler that
    you install after `init()` replaces the SDK's handler, and the SDK does not
    drain; your `flush()` then exports the queue itself. The `flush()` path
    never waits for a lock of the SDK, so it is safe in a signal handler.
    A span that ends after the drain or after `shutdown()` is not sent. It
    counts at once as `shutdown_residue`, with one WARNING for the first one,
    and the next `flush()` returns `False`. This holds for a span that started
    while the SDK was active, and for a span that you start with the tracer in
    your own SIGTERM handler after the SDK's drain. A span that you start after
    `shutdown()` has returned is not made, and nothing counts it. A call to a
    traced provider in your handler after the drain makes no span and is not
    counted.
  - **A new `init()` starts a new count.** The losses that `flush()` has not
    reported yet belong to the old client, and the new client does not report
    them. Report them with `flush()` or `get_metrics()` before you call
    `init()` 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()` `True` then means that at least one of them acknowledged each
    span. Another exporter, also the Risicare one, can refuse the batch, and
    `flush()` still returns `True`. Its WARNING and `failed_exports` show that
    an export call failed. `failed_exports` is not a loss counter.
- `shutdown(timeout_ms=5000)` is the call that ends a process in a fixed time.
  The exports stop within `timeout_ms`. Spans that it cannot deliver in that
  time (still queued, or in an export that did not finish) are counted as
  `shutdown_residue`, and one WARNING gives both numbers. The bound does not
  cover the `shutdown()` method of an exporter that you wrote.
- `get_metrics()` returns the counters: `exported_spans` (spans the backend
  accepted), `rejected_spans` (spans the backend acknowledged and rejected),
  `failed_scores`, `failed_exports`, `dropped_spans`, `dropped_spans_by_reason`
  (`queue_full`, `transport_refused`, `shutdown_residue`, `unacknowledged`),
  `queue_size`, `queue_capacity`, `queue_utilization` and `sdk_state`. After
  `init()` there is also `mask_errors`. `unacknowledged` counts spans that were sent, or that could not
  be serialized, and that the backend's answer did not account for.
  `failed_exports` counts 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 are
  `dropped_spans_by_reason`, `rejected_spans` and `failed_scores`.

```python
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 outside [0.0, 1.0] or not a
number, an empty trace id or name) 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.

## Decision Phases

Structure your traces to see how your agent thinks, decides, and acts:

```python
@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)
```

## Error Diagnosis

> **Beta.** The Risicare service detects an error, diagnoses it and suggests a
> fix. The diagnosis runs on the service, with Together.AI Llama-3.3-70B.
> Suggested fixes land in your dashboard as `status=draft` for human review.
> Automatic deployment, A/B rollout and learning from outcomes are not
> available. Treat this as **AI-assisted error diagnosis**.

When your agent fails:

1. The SDK records the exception on the span and gives it an error code
   (`error.code`). The `risicare-core` taxonomy 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`.
2. The Risicare service diagnoses the root cause.
3. The service writes a fix suggestion that you can review in the dashboard
   and apply manually.

```python
try:
    result = my_agent(user_input)
except Exception as e:
    risicare.report_error(e)  # Records the error for diagnosis; the fix lands as a draft for review
```

## 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:

```python
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.

## Scoring

```python
# Custom scores
risicare.score(trace_id="tr-123", name="quality", value=0.92)
```

`score()` sends the score to the api host (see "Two hosts"). For what happens
when a score fails, see "Delivery".

## OpenTelemetry

```bash
pip install risicare[otel]
```

```python
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()`.

## Known limitation — span loss during a backend outage

The SDK does **not** keep spans through a long outage of the Risicare backend.
Nothing raises in your application. The SDK logs a WARNING, `flush()` returns
`False`, and `get_metrics()` counts the lost spans under `transport_refused`.

The HTTP exporter opens a circuit breaker after **5 consecutive failed export
calls** and holds it open for **60 seconds**. While it is open, an export
returns failure at once and does not use the network. A batch that fails is
put back in the queue at most 3 times. Against an open breaker these 3
attempts fail at once, so the spans are dropped. For the rest of the cooldown
the SDK does not send, also when your backend is healthy again.

The thresholds count **failed calls, not seconds**. When the 5th consecutive
failure occurs depends on your span rate and on how fast your endpoint fails.
A batch is lost when 4 export calls for it fail (the first call, and 3 calls
from the queue). The breaker can still be closed at that time. A failure that
ends before the 4th call loses no span.

One export call sends a batch at most 3 times. A 401 or 403 answer is sent
once in each export call: the endpoint refused the API key, and the same key
gets the same answer. The WARNING "spans are NOT reaching ..." gives the HTTP
status of the last answer, or the error class when there was no answer. For a
401 or 403 it tells you to check the API key. When the kind of failure changes in
one outage (for example a 401, then no answer), the SDK writes one more WARNING.

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, 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:

```python
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

- [Full docs](https://risicare.ai/docs)
- [Quickstart guide](https://risicare.ai/docs/start/quickstart)
- [Python SDK reference](https://risicare.ai/docs/reference/sdk)
- [LLM providers](https://risicare.ai/docs/instrument/providers)
- [Error Diagnosis](https://risicare.ai/docs/heal)
- [Evaluations](https://risicare.ai/docs/observe/evaluations)
- [JS/TS SDK](https://www.npmjs.com/package/risicare)

## Support

- **Email**: support@risicare.ai
- **Docs**: [risicare.ai/docs](https://risicare.ai/docs)

During the public beta, please file detailed reproduction steps for any
SDK or platform issue — fast feedback shapes GA.

## License

**Proprietary. You need a commercial licence.** See [LICENSE](LICENSE).

Conscience Labs Pvt. Ltd. owns this SDK. You need an active, paid
subscription to use it. You may not change it, make derivative works from
it, reverse engineer it, or redistribute it. Contact <info@consciencelabs.ai>.
