Skip to main content

yesil-health-ai-api (Python)

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

Synchronous, built on httpx. 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

pip install yesil-health-ai-api

Quick start

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

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

The client is a context manager:

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:

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

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

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

Account endpoints

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:

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

Metadata

Release files for yesil-health-ai-api 0.5.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for yesil-health-ai-api 0.5.0
File Size Uploaded Provenance
yesil_health_ai_api-0.5.0.tar.gz 11.2 kB Without provenance Details

Built distribution (wheel)

Table of built distributions (wheels) for yesil-health-ai-api 0.5.0
File Interpreter ABI Platform
yesil_health_ai_api-0.5.0-py3-none-any.whl Python 3 none any Details

Total release size: 23.9 kB

Release files / yesil_health_ai_api-0.5.0.tar.gz

Download URL yesil_health_ai_api-0.5.0.tar.gz
Size 11.2 kB
Tags Source
SHA-256 checksum
How to use checksums
e01c2a269dfed7f56721196efe04444433c908f463d5349979d59eede9cb6232
BLAKE2b-256 checksum
How to use checksums
a4199415a7c6556b59b43f0d70ffdc660e95786f56ccbe60934e54d5e8f49444
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.7

Release files / yesil_health_ai_api-0.5.0-py3-none-any.whl

Download URL yesil_health_ai_api-0.5.0-py3-none-any.whl
Size 12.7 kB
Tags Python 3
SHA-256 checksum
How to use checksums
73013a2a5194777d7f5abc6b1a2eef154d9df99764cf9760f2bdc2ab66ce0257
BLAKE2b-256 checksum
How to use checksums
970f60c2072d76fcf7f34759db003f7c1756857c38cf99a2489fda4711c0f2ef
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.7

Security for yesil-health-ai-api 0.5.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.

No provenance found

None of the files in this release were uploaded with provenance metadata.

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

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page