@yesilsci/health-ai-api
v0.5.3
Published
Official TypeScript client for the Yesil Health API: evidence-grounded health chat with modules, institution knowledge and PDF processing, streamed as typed SSE.
Downloads
79
Maintainers
Readme
@yesilsci/health-ai-api
Official TypeScript client for the Yesil Health API (B2B).
What the API gives you: streaming health answers grounded in scientific evidence and in your institution's own content. Answers come with inline citations, structured proposals your system applies (reminders, measurements), memory records to store, appointment/service links, and billing on every turn.
Endpoints
Point the client at the chat and document endpoints you use:
| Option | Endpoint |
|---|---|
| chatEndpoint | /api/v2/chat/stream/compat (classic delta/citation events plus module events) or /api/v2/chat/stream (native: final answer, cards, state proposals) |
| documentEndpoint | /api/v2/documents/process (structured lab rows, quality metadata, context_block) |
| evidenceEndpoint | /api/v2/evidence/search (ranked sources with relevance, no AI answer) |
The router picks the modules each message needs (memory, measurements, reminders, scientific evidence, institution knowledge, appointment handoff and service matching) and returns them as additive events. Unknown events stay safe to ignore. The full reference is the API guide in the Yesil Health console.
Zero runtime dependencies: uses the platform fetch + ReadableStream
(Node ≥ 18, modern browsers, edge runtimes). The hard part of integrating,
parsing the typed Server-Sent Events stream, is handled for you.
Install
npm install @yesilsci/health-ai-apiQuick start
import { YesilHealthClient } from '@yesilsci/health-ai-api';
import { randomUUID } from 'node:crypto';
const client = new YesilHealthClient({
baseUrl: 'https://api.yesilhealth.com',
apiKey: process.env.YESIL_API_KEY!, // sent as X-API-Key
chatEndpoint: '/api/v2/chat/stream/compat',
});
for await (const ev of client.chatStream({
question: 'Is metformin safe for a patient with stage 3 CKD?',
request_id: randomUUID(), // idempotent billing — strongly recommended
demographics: { age: 62, sex: 'female' },
health_context: 'eGFR 45 mL/min/1.73m². On lisinopril 10mg daily.',
})) {
if (ev.type === 'delta') process.stdout.write(ev.content);
}One-shot (no live rendering):
const { text, events } = await client.chat({ question: '...' });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 browser bundle or mobile app.
The event stream
chatStream() yields typed events. Route on event.type:
| type | Payload | Notes |
|--------------------|--------------------------------------|-------|
| meta | phase, conversation_id, research preview fields | Lifecycle + mid-stream research previews. |
| delta | content: string | Append content to build the answer text. |
| citation | citation fields | A literature citation for the answer. |
| memory_extracted | signals: MemorySignal[] | Records to store; send them back in memory. |
| state_patch | status, operations | Native action proposals; apply in your system and deduplicate by operation id. |
| reminder_action / measurements_extracted | status, operation_id, action | Compat record proposals; apply once per operation_id. |
| handoff_recommendation | status, action | Compat: verified institution link; no booking or live transfer. |
| service_recommendation | status, action | 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; stream ends. |
Forward compatibility. The API only ever adds fields and event types within a contract version — it never renames, removes, or retypes existing ones. Always include a
defaultbranch in yourswitchand ignore unknown event types. This client surfaces them asUnknownEventrather than throwing.
Request fields
| Field | Required | Description |
|------------------------|----------|-------------|
| question | ✅ | The end-user's question. |
| request_id | — | Client UUID for idempotent billing. Strongly recommended. |
| demographics | — | Small structured profile (≤ 12 KB JSON). |
| health_context | — | Free-form clinical context (vitals, EHR summary, wearable rollups). |
| conversation_history | — | Last turns only (max 8), role ∈ user/assistant. |
| memory | — | Raw memory signals to replay. |
| tenant_id | — | Optional hint; must match the key's tenant. |
| reminders | — | V2 current list; omit/null if unknown, [] if known empty. |
| timezone | — | V2 IANA timezone; institution default is used when omitted. |
| research_mode | — | V2 standard (default) or deep. |
| state.reminders | — | Accepted V2 legacy alias; use top-level reminders. |
Errors
Non-2xx HTTP responses throw YesilApiError with status, code
(server error_code), and message:
import { YesilApiError } from '@yesilsci/health-ai-api';
try {
await client.chat({ question: '...' });
} catch (e) {
if (e instanceof YesilApiError) {
if (e.code === 'RATE_LIMITED') { /* back off */ }
if (e.status === 402) { /* quota exhausted / billing */ }
}
}Common codes: RATE_LIMITED (429), quota/billing (402), INVALID_API_KEY
(401). In-stream failures arrive as an error event (see table above), not an
exception, unless you use the chat() convenience wrapper which re-throws them.
Evidence search
Ranked literature retrieval for a query, no LLM answer synthesis. Requires the
evidence:read scope on your API key.
const res = await client.evidenceSearch({
question: 'omega-3 and cardiovascular risk reduction',
needs_trials: false,
});
console.log(res.papers);Account endpoints
await client.billing(); // billing status
await client.quota(); // quota / rate-limit status
await client.usage(); // usage reportCancellation
Pass an AbortSignal to stop a stream early:
const ac = new AbortController();
setTimeout(() => ac.abort(), 5_000);
for await (const ev of client.chatStream({ question: '...' }, { signal: ac.signal })) { /* … */ }Compat and native
Compat (/api/v2/chat/stream/compat) streams delta and citation events
with [n] markers, plus reminder_action / measurements_extracted proposals
(apply once per operation_id) and handoff_recommendation /
service_recommendation links. The answer text also contains the link, so don't
render the same call-to-action twice.
Native (/api/v2/chat/stream) adds state_patch proposals, card events
and a final answer snapshot. Replace the streamed message with the snapshot if
you need it; don't append it as a second message.
Both chat endpoints end each turn with done.billing (charged lines, each with
the module and result that triggered it) and done.usage (module names,
outcome codes, durations and counts; never patient text or source titles).
Exact rates come from your institution's rate card.
Your system owns patient state: store memory_extracted records and applied
proposals, and send the current reminders and relevant context on later turns.
See Conversation state in the console API guide. Document processing returns a
context_block to send as health_context; unusable results are not charged.
const client = new YesilHealthClient({
baseUrl: 'https://api.yesilhealth.com',
apiKey: process.env.YESIL_API_KEY!,
chatEndpoint: '/api/v2/chat/stream',
documentEndpoint: '/api/v2/documents/process',
});
const parsed = await client.parseDocument({ file: pdfBlob, documentHint: 'auto' });
// Keep parsed.context_block in your own patient context and send it as health_context.Full reference: the API guide in the Yesil Health console (API Docs).
