npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@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

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

Quick 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 default branch in your switch and ignore unknown event types. This client surfaces them as UnknownEvent rather 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 report

Cancellation

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