# risicare

AI agent observability and self-healing 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: MIT](https://img.shields.io/pypi/l/risicare.svg)](https://opensource.org/licenses/MIT)

Monitor your AI agents in production. Trace every LLM call, detect errors automatically, and get AI-generated fixes — with a single `init()`.

## Quickstart

```bash
pip install risicare
```

```python
import risicare
from openai import OpenAI

# Initialize — auto-instruments all detected LLM providers
risicare.init(
    api_key="rsk-...",
    endpoint="https://app.risicare.ai",
)

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

**That's it.** Your agent's LLM calls, latency, token usage, and costs now appear in the [Risicare dashboard](https://app.risicare.ai).

## Features

- **Auto-instrumentation** — Detects and patches LLM providers on `init()`, zero code changes
- **12 LLM providers** — OpenAI, Anthropic, Google, Mistral, Groq, Cohere, Together, Ollama, HuggingFace, Cerebras, Bedrock, Vertex AI
- **8 host-detected** — DeepSeek, xAI, Fireworks, Baseten, Novita, BytePlus, vLLM, and any OpenAI-compatible API via `base_url`
- **10 framework integrations** — LangChain, LangGraph, CrewAI, AutoGen, Instructor, LlamaIndex, LiteLLM, DSPy, Pydantic AI, OpenAI Agents
- **Self-healing** — Automatic error diagnosis and AI-generated fix suggestions
- **13 built-in scorers** — Faithfulness, relevance, toxicity, hallucination, and more
- **Streaming support** — Full streaming trace enrichment with token counts
- **OpenTelemetry bridge** — Compatible with existing OTel pipelines
- **Non-blocking** — All telemetry is async, never slows your app

## LLM Providers

```python
# Auto-patching (default) — detects installed providers automatically
risicare.init(api_key="rsk-...", endpoint="https://app.risicare.ai")

# Disable auto-patching if needed
risicare.init(api_key="rsk-...", endpoint="https://app.risicare.ai", auto_patch=False)
```

All 12 native providers:

| Provider | Package | Provider | Package |
|----------|---------|----------|---------|
| OpenAI | `openai` | Anthropic | `anthropic` |
| Google Gemini | `google-generativeai` | Mistral | `mistralai` |
| Cohere | `cohere` | Groq | `groq` |
| Together AI | `together` | Ollama | `ollama` |
| AWS Bedrock | `boto3` | Google Vertex AI | `google-cloud-aiplatform` |
| Cerebras | `cerebras-cloud-sdk` | HuggingFace | `huggingface-hub` |

Plus 8 auto-detected via OpenAI `base_url`: DeepSeek, xAI, Fireworks, Baseten, Novita, BytePlus, vLLM, and any OpenAI-compatible API.

## Framework Integrations

```bash
pip install risicare[langchain]    # LangChain + LangGraph
pip install risicare[crewai]       # CrewAI
pip install risicare[autogen]      # AutoGen
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, endpoint)            # Initialize (auto-patches providers)
risicare.shutdown(timeout_ms=5000)          # Flush pending spans and close

@risicare.agent(name="my-agent")            # Trace a function with agent identity
@risicare.trace                             # Trace any function (decorator or CM)
@risicare.session(session_id="sess-1")      # Group traces into user sessions

risicare.report_error(exception)            # Report caught errors for diagnosis
risicare.score(trace_id, "quality", 0.92)   # Record evaluation score [0.0-1.0]

risicare.enable() / risicare.disable()      # Runtime tracing control
risicare.is_enabled()                       # Check tracing status
```

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

## Self-Healing

When your agent fails, Risicare automatically:

1. **Classifies** the error (154 codes across TOOL, MEMORY, REASONING, OUTPUT, etc.)
2. **Diagnoses** the root cause using AI analysis
3. **Generates** a fix you can review and apply

```python
try:
    result = my_agent(user_input)
except Exception as e:
    risicare.report_error(e)  # Triggers automatic diagnosis pipeline
```

## Scoring & Evaluation

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

# 13 built-in scorers available in the dashboard:
# faithfulness, answer_relevance, context_precision, context_recall,
# hallucination, toxicity, bias, coherence, conciseness,
# fluency, g_eval, goal_accuracy, summarization
```

## OpenTelemetry

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

```python
risicare.init(api_key="rsk-...", otel_bridge=True)
# Compatible with any OTel-instrumented application
```

## 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)
- [Self-healing](https://risicare.ai/docs/heal)
- [Evaluations](https://risicare.ai/docs/observe/evaluations)
- [JS/TS SDK](https://www.npmjs.com/package/risicare)

## License

[MIT](LICENSE)
