Metadata-Version: 2.5
Name: yesil-health-ai-api
Version: 0.5.0
Summary: Official Python client for the Yesil Health AI enterprise (B2B) API.
Project-URL: Homepage, https://yesilhealth.com
Author: Yesil Health
License: MIT
License-File: LICENSE
Keywords: ai,health,medical,sse,yesil
Requires-Python: >=3.9
Requires-Dist: httpx>=0.24
Description-Content-Type: text/markdown

# yesil-health-ai-api (Python)

Official Python client for the **Yesil Health AI enterprise (B2B) API**.

Synchronous, built on [httpx](https://www.python-httpx.org/). The hard part of
integrating — parsing the typed Server-Sent Events stream — is handled for you.
Mirror of the TypeScript client `@yesilsci/health-ai-api`.

## Install

```bash
pip install yesil-health-ai-api
```

## Quick start

```python
import uuid
from yesil_health import YesilHealthClient

client = YesilHealthClient(
    base_url="https://api.yesilhealth.com",
    api_key="...",  # sent as X-API-Key
)

for ev in client.chat_stream({
    "question": "Is metformin safe for a patient with stage 3 CKD?",
    "request_id": str(uuid.uuid4()),       # idempotent billing — recommended
    "demographics": {"age": 62, "sex": "female"},
    "health_context": "eGFR 45 mL/min/1.73m². On lisinopril 10mg daily.",
}):
    if ev["type"] == "delta":
        print(ev["content"], end="", flush=True)
```

One-shot (no live rendering):

```python
result = client.chat({"question": "..."})
print(result["text"])
```

The client is a context manager:

```python
with YesilHealthClient(base_url=..., api_key=...) as client:
    ...
```

## Authentication

Every request is authenticated with your enterprise API key via the `X-API-Key`
header. Keep it server-side; never ship it in a client app.

## The event stream

`chat_stream()` yields event dicts. Route on `event["type"]`:

| `type`             | Payload                              | Notes |
|--------------------|--------------------------------------|-------|
| `meta`             | `phase`, `conversation_id`, research preview | Lifecycle + mid-stream research previews. |
| `delta`            | `content`                            | Append to build the answer text. |
| `citation`         | citation fields                      | A literature citation. |
| `graph`            | `data`                               | Structured chart/diagram. |
| `memory_extracted` | `signals`                            | V1 request/account setting; V2 institution module + router decide. |
| `state_patch` | `status`, `operations` | Native V2 action proposals; apply in your system and deduplicate by operation `id`. |
| `reminder_action` / `measurements_extracted` | `status`, `operation_id`, `action` | V2 Compat record proposals; apply once per `operation_id`. |
| `handoff_recommendation` | `status`, `action` | V2 Compat verified institution link; no booking or live transfer. |
| `service_recommendation` | `status`, `action` | V2 Compat approved catalog selection; no purchase or booking. |
| `answer` | `markdown`, `blocks`, `follow_up`, `references` | Native V2 final snapshot of the deltas already streamed. |
| `card` | `card_type`, `payload`, `markdown_fallback` | Native V2 structured card, normalized by this SDK. |
| `done`             | `summary`, `billing`, `usage`         | Terminal event. V2 `billing.cost_usd` is the final customer charge; `usage.worker_summary` contains content-free worker outcomes. |
| `error`            | `message`, `code`                    | Terminal failure event. |

> **Forward compatibility.** The API only ever *adds* fields and event types
> within a contract version. Always ignore unknown `type` values — this client
> yields them as plain dicts rather than raising.

## Errors

Non-2xx responses raise `YesilApiError` with `status`, `code` (server
`error_code`), and message:

```python
from yesil_health import YesilApiError

try:
    client.chat({"question": "..."})
except YesilApiError as e:
    if e.code == "RATE_LIMITED":  # 429
        ...
    if e.status == 402:           # quota exhausted / billing
        ...
```

## Evidence search

Ranked literature retrieval for a query, no LLM answer synthesis. Requires the
`evidence:read` scope on your API key.

```python
res = client.evidence_search({
    "question": "omega-3 and cardiovascular risk reduction",
    "needs_trials": False,
})
print(res["papers"])
```

## Account endpoints

```python
client.billing()  # billing status
client.quota()    # quota / rate-limit status
client.usage()    # usage report
```

## Versioning

Defaults to contract **v1** (`/api/v1`). For V2 chat, change only
`chat_endpoint`; a global version switch also changes billing, evidence and PDF
paths. V1 remains available. V2 access must be enabled for the tenant by Yesil
Health. Kept in lockstep with the TypeScript client — see
`backend/sdk/CONTRACT_SYNC.md`.


### V2 engine with the V1 chat format (local SDK addition)

Pass `chat_endpoint="/api/v2/chat/stream/compat"` to the client constructor and leave the global API version
at its default V1. Only chat uses the adapter; billing/evidence/documents keep
their existing paths. Existing delta/citation/memory handlers work unchanged.
The adapter requires tenant V2 access. Enabled reminder/measurement workers emit
additive `reminder_action` / `measurements_extracted` events; apply their action
once per `operation_id`. Compat also emits `handoff_recommendation` and
`service_recommendation` when a validated link or approved catalog selection is
ready. Markdown deltas still contain a link fallback, so avoid rendering the
same call-to-action twice. Old readers may ignore unknown events.
V2 memory is institution-controlled; extract_memory is accepted but ignored.

For native V2 use `chat_endpoint="/api/v2/chat/stream"`. The SDK exposes
`state_patch`, `answer` and normalized `card` event types. The answer event is a
final snapshot of the text from deltas; replace the current message with it if
needed instead of appending it as a second message.

Both V2 chat endpoints return additive `done.billing` and `done.usage` fields.
Billing lines show the tenant's configured rate, discount, charged amount, and
the worker/result code that triggered an add-on. Worker summaries contain only
module names, status/outcome codes, durations, and result counts; they do not
contain patient text or source titles. Standard research and reminders are part
of chat. Memory and measurement share one add-on line, as do institution search,
approved service matching, and handoff. Deep research and useful structured PDF
results have separate lines. Exact rates come from the tenant's rate card and
are not hardcoded by this client.

V2 document processing is selected independently, leaving billing/evidence on
V1:

```python
v2 = YesilHealthClient(
    base_url="https://api.yesilhealth.com",
    api_key="...",
    chat_endpoint="/api/v2/chat/stream",
    document_endpoint="/api/v2/documents/process",
)
parsed = v2.parse_document(open("lab.pdf", "rb"), document_hint="auto")
# Keep parsed["context_block"] in your own patient context and send it as health_context.
```

The stateless institution loop is documented in
the console API guide (Conversation state): persist memory signals and proposed actions,
then send the institution's current reminders and relevant context on later
turns. PDF `billing.settlement_status` is `settled`, `trial`, or
`not_chargeable`; empty/unusable parse results do not receive a document charge.
Version 0.5.0 adds the V2 endpoint options. Full reference: the API guide in the
Yesil Health console (API Docs).
