# SDK

> Dart / Flutter (anpheros_sdk) 和 TypeScript (@anpheros/sdk) 客户端：形状相同，幂等创建，重试，令牌刷新和同意流程。

Source: https://developers.anpheros.com/zh/guides/sdks

> 适用于 FHIR R4 医疗保健 API 的官方客户端库，提供免费的 FHIR 沙盒：患者、观察结果、实验室结果、病症、药物、国际患者摘要、患者同意和 AI 上下文，支持 TypeScript 和 Dart / Flutter。

**Anpheros 是用于构建医疗保健应用程序、医疗软件和 AI 服务的可互操作的医疗数据基础设施。** 每位患者都有一个由其控制的 HL7 FHIR R4 记录；应用程序、诊所、实验室和 AI 代理通过 Anpheros Platform API 读取和写入该记录——需获得患者同意（OAuth 2.1 / SMART on FHIR），每次写入都有出处记录，并且患者可以看到访问日志。本仓库包含官方客户端库和可运行的示例。

| 语言 | 包 | 安装 | 源码 |
|---|---|---|---|
| Dart / Flutter | [`anpheros_sdk`](https://pub.dev/packages/anpheros_sdk) | `dart pub add anpheros_sdk` | [`dart/anpheros_sdk`](https://github.com/anpheros/anpheros-sdk/tree/main/dart/anpheros_sdk) |
| TypeScript (Node 18+, 浏览器, Deno, Bun) | [`@anpheros/sdk`](https://www.npmjs.com/package/@anpheros/sdk) | `npm install @anpheros/sdk` | [`ts`](https://github.com/anpheros/anpheros-sdk/tree/main/ts) |

## 2分钟快速入门

1. **获取免费沙盒密钥：** 登录 [dashboard](https://platform.anpheros.com/dashboard/)，然后点击 **Get a sandbox key** (`sk_test_…`)。您的沙盒包含 30 位合成患者。
2. **验证是否正常工作：**

   ```bash
   curl -H "Authorization: Bearer $ANPHEROS_KEY" "https://platform.anpheros.com/fhir/R4/Patient?_count=3"
   ```

3. **安装 SDK 并读取记录：** `npm install @anpheros/sdk` 或 `dart pub add anpheros_sdk`，然后运行 [Connect](#connect) 下方的代码，或克隆 [quickstart-ts](https://github.com/anpheros/anpheros-sdk/tree/main/examples/quickstart-ts)。

## 适用人群

为构建患者和家属健康应用、医疗应用后端、诊所和实验室集成，以及需要患者结构化医疗上下文（而无需从头设计医疗数据库、同意系统和审计日志）的 AI 助手或代理的开发者。

## 获取沙盒密钥

沙盒是免费且自助服务的。在[仪表板](https://platform.anpheros.com/dashboard/)上使用 Google 登录，然后按**获取沙盒密钥**：您将立即获得一个沙盒项目和一个密钥。每个沙盒项目都包含 30 名合成患者——六个月的病史、用药、过敏、实验室结果和生命体征——您可以随时自由更改和重置。沙盒密钥 (`sk_test_…`) 永远不会接触到真实的患者数据。

当您上线时，生产环境是为已验证的组织提供数据处理协议，生产环境起价为每月 49 欧元，第一个月免费（[定价](https://developers.anpheros.com/zh/guides/pricing)）。

## 连接

```ts
import { Anpheros, apiKey } from '@anpheros/sdk';

const anpheros = new Anpheros({ auth: apiKey(process.env.ANPHEROS_KEY!) });   // sk_test_… in the sandbox
const { data: patients } = await anpheros.patients.list();
const labs = await anpheros.observations.list(patients[0].id, { category: 'laboratory', limit: 10 });
const ctx = await anpheros.context.build({ patient: patients[0].id, task: 'weekly check-in', budget_tokens: 1500, format: 'text' });
```

```dart
import 'package:anpheros_sdk/anpheros_sdk.dart';

final anpheros = Anpheros(auth: AnpherosAuth.apiKey('sk_test_…'));
final patients = await anpheros.patients.list();
final labs = await anpheros.observations.list(patients.data.first.id, category: 'laboratory', limit: 10);
```

API 密钥应放在服务器端。代表用户操作的应用应使用 OAuth：SDK 都实现了授权码 + PKCE 的同意流程，并自动刷新令牌。

## SDK 涵盖内容

两者都涵盖了完整的公共接口（`/v1`、`/fhir/R4`、`/oauth/token`、`/oauth/revoke`），具有相同的结构：`patients`、`observations`、`conditions`、`medications`、`documents`、`timeline`、`provenance`、`context`、`grants`、`terminology` 和原始 `fhir`。当任一 SDK 缺少公共路由，或 SDK 调用了服务器上不存在的路由时，测试将导致构建失败。

两个 SDK 都支持：创建时的自动 `Idempotency-Key`、在遇到 429/5xx 错误时的带回退重试、一次 401 错误时的令牌刷新、带有请求 ID 的类型化错误，以及 PKCE 辅助和同意流程。

## 医疗数据与 FHIR

记录由标准的 FHIR R4 资源构成 — 共 26 种类型，包括 `Observation`、`Condition`、`MedicationStatement`、`DocumentReference`、`Immunization` 和 `AllergyIntolerance` — 并使用 LOINC、ICD-10、ATC 和 UCUM 进行编码。REST API (`/v1`) 和 FHIR API (`/fhir/R4`) 使用相同的 ID 读取和写入相同的资源；两个 SDK 中的 `fhir` 均提供原始 FHIR 访问（搜索、事务、`$everything`、`$summary`、`$validate`）。

## 示例

| 示例 | 展示 |
|---|---|
| [quickstart-ts](https://github.com/anpheros/anpheros-sdk/tree/main/examples/quickstart-ts) | 写入和读取记录：测量值、实验室结果、诊断、药物、时间线、FHIR 搜索、IPS、AI 上下文 |
| [quickstart-dart](https://github.com/anpheros/anpheros-sdk/tree/main/examples/quickstart-dart) | 使用 Dart / Flutter 实现相同功能 |
| [consent-app-ts](https://github.com/anpheros/anpheros-sdk/tree/main/examples/consent-app-ts) | 一个请求同意（OAuth 2.1 + PKCE）并读取个人记录的 Web 应用 |
| [ai-context-llm](https://github.com/anpheros/anpheros-sdk/tree/main/examples/ai-context-llm) | 关于记录的问题，由您选择的模型（本地或托管）回答 |
| [fhir-transaction](https://github.com/anpheros/anpheros-sdk/tree/main/examples/fhir-transaction) | 一个 FHIR R4 事务包和生成的国际患者摘要 |

这些示例在免费沙箱环境中运行，每个沙箱项目都有自己的 30 个合成患者 — 请参阅 [获取沙箱密钥](#get-a-sandbox-key)。

## 相关仓库

| 仓库 | 作用 |
|---|---|
| [fhir-api-openapi](https://github.com/anpheros/fhir-api-openapi) | API 的 OpenAPI 3.1 规范和 Postman 集合 |
| [mcp-server](https://github.com/anpheros/mcp-server) | 面向 AI 代理的托管 FHIR MCP 服务器：Claude、Cursor、VS Code 的配置 |
| [agent-skills](https://github.com/anpheros/agent-skills) | Agent Skill、Claude 代码插件、Cursor 规则和 AGENTS.md |
| [fhir-synthetic-patients](https://github.com/anpheros/fhir-synthetic-patients) | 30 个合成患者的 FHIR R4 Bundles 和 NDJSON |
| [ips-examples](https://github.com/anpheros/ips-examples) | FHIR R4 格式的国际患者摘要 (International Patient Summary) 文档 |
| [fhir-validate-action](https://github.com/anpheros/fhir-validate-action) | 在 CI 中验证 FHIR R4 JSON 的 GitHub Action |
| [lab-results-to-fhir](https://github.com/anpheros/lab-results-to-fhir) | 命令行工具：CSV / HL7 v2 实验室报告 → FHIR Observations |
| [healthcare-app-starters](https://github.com/anpheros/healthcare-app-starters) | Next.js 和 Flutter 健康应用模板 |

## 一致性

原始测试结果，已发布以便进行检查（测试结果，非认证）：[conformance/](https://github.com/anpheros/anpheros-sdk/tree/main/conformance)。于 2026 年 9 月 28 日，Inferno SMART App Launch STU2 测试套件（v1.0.3）的 Standalone Launch 组在平台上通过了 22 项测试中的 22 项。不支持 EHR 启动。

## 文档

- [开发者指南](https://developers.anpheros.com/guides/)
- [入门](https://developers.anpheros.com/zh/guides/getting-started)
- [FHIR 沙盒](https://developers.anpheros.com/zh/guides/fhir-sandbox)
- [医疗保健 API](https://developers.anpheros.com/zh/guides/healthcare-api)
- [医疗保健 API 平台](https://developers.anpheros.com/zh/guides/healthcare-api-platform)
- [FHIR 平台](https://developers.anpheros.com/zh/guides/fhir)
- [SDK 指南](https://developers.anpheros.com/zh/guides/sdks)
- [API 参考 (OpenAPI)](https://developers.anpheros.com/docs)
- [面向 AI 助手](https://developers.anpheros.com/llms.txt)
- [Anpheros](https://anpheros.com/)

## 问题与安全

请在此仓库的 issues 中报告 bug。切勿在 issue 中包含 API 密钥、令牌或患者数据。安全报告：contact@anpheros.com。

## 许可

Apache License 2.0 — 请参阅每个软件包的 `LICENSE` 文件。Copyright 2026 Anpheros。

## @anpheros/sdk

**Anpheros Platform** 的 TypeScript 客户端：每个患者一个 FHIR R4 健康记录，项目隔离，患者同意（OAuth 2.1 / SMART on FHIR），每次写入都有溯源，以及一个 AI 上下文 API。可在任何支持 `fetch` 的地方运行（Node 18+、浏览器、Deno、Bun）。

```ts
import { Anpheros, apiKey } from '@anpheros/sdk';

const anpheros = new Anpheros({ auth: apiKey(process.env.ANPHEROS_KEY!) });
const { data: patients } = await anpheros.patients.list();
const labs = await anpheros.observations.list(patients[0].id, { category: 'laboratory', limit: 10 });
const ctx = await anpheros.context.build({ patient: patients[0].id, task: 'weekly check-in', budget_tokens: 1500, format: 'text' });
```

代表某人操作：

```ts
import { OAuthFlow, OAuthAuth, generatePkce } from '@anpheros/sdk';

const flow = new OAuthFlow({ baseUrl: BASE, clientId: 'client_…', redirectUri: 'https://myapp.example/callback' });
const pkce = await generatePkce();
location.href = flow.authorizeUrl({ scopes: ['patient/Observation.rs?category=laboratory', 'offline_access'], state, pkce, lang: 'ro' });
// on the callback:
const tokens = await flow.exchange(code, pkce);
const anpheros = new Anpheros({ auth: new OAuthAuth({ tokens, onRefresh: flow.refresh, onTokens: persist }) });
```

错误是 `AnpherosError`（`status`、`type`、`message`、`field`、`requestId`）。创建操作会发送一个 `Idempotency-Key`；429/5xx 会重试；过期的令牌会刷新一次并重试调用。

## anpheros_sdk

Dart / Flutter 客户端，用于 **Anpheros Platform**：一个健康数据后端，每个患者都有一个 FHIR R4 记录，支持项目隔离、患者同意（OAuth 2.1 / SMART on FHIR）、每次写入的溯源以及 AI 上下文 API。

```dart
import 'package:anpheros_sdk/anpheros_sdk.dart';

final anpheros = Anpheros(auth: AnpherosAuth.apiKey('sk_test_…'));      // server / sandbox

final patients = await anpheros.patients.list();
final elena = patients.data.first;
final labs = await anpheros.observations.list(elena.id, category: 'laboratory', limit: 10);
final ctx = await anpheros.context.build(ContextRequest(patient: elena.id, task: 'weekly check-in', budgetTokens: 1500));
```

## 代表个人（应用）

```dart
final flow = OAuthFlow(baseUrl: 'https://…', clientId: 'client_…', redirectUri: 'myapp://callback');
final pkce = Pkce.generate();
final url = flow.authorizeUrl(scopes: ['patient/Observation.rs?category=laboratory', 'patient/MedicationStatement.r', 'offline_access'],
                              state: 'abc', pkce: pkce, lang: 'ro');
// open `url`; on return with ?code=…:
final tokens = await flow.exchange(code: code, pkce: pkce);
final anpheros = Anpheros(auth: AnpherosAuth.oauth(
  accessToken: tokens.accessToken, refreshToken: tokens.refreshToken, expiresAt: tokens.expiresAt,
  onRefresh: flow.refresh, onTokens: persist));
final meds = await anpheros.medications.listMedications(tokens.patient!);
```

每个对象都带有 `fhir`（其 `/fhir/R4` 引用）；`anpheros.fhir` 提供原始 FHIR 访问权限
（读取、搜索、创建、事务、`$everything`、`$summary`、`$validate`）。

错误通过 `AnpherosException`、`status`、`type`、`message` 和 `field` 进行 `requestId`。
创建会自动发送一个 `Idempotency-Key`；429/5xx 错误会进行指数退避重试；过期的 OAuth
令牌会刷新一次并重试调用。
