Node.js / TypeScript SDK 开发指南
Habitaxx 官方提供的 Node.js / TypeScript 服务端 SDK,封装了开放平台的全量 AI 能力与管理能力,提供完整的 TypeScript 类型定义、Promise 异步封装及统一的响应与错误处理机制。
SDK 源码目录:sdk/habitaxx-node
1. 安装与准备
安装方式
bash
# 从 npm 或私有源安装
npm install habitaxx
# 或使用 pnpm
pnpm add habitaxx
# 或使用 yarn
yarn add habitaxx依赖环境
- Node.js 18.0.0 及以上版本
- 具备原生 Fetch / Node 现代 HTTP 环境,天然支持 TypeScript
2. 认证体系与调用规范
开放平台采用两阶段凭证安全模型:
- 第一阶段(换取 Access Token):使用开发者 API Key(持久凭据)和项目/终端用户标识,调用
/v1/auth/token接口换取短效access_token(JWT,有效期通常为 24 小时)。 - 第二阶段(调用业务能力):使用获取到的
access_token初始化业务客户端,调用具体 AI 能力接口。网关将对 Token 进行鉴权与限流计量。
统一响应与错误排查
开放平台对外接口统一响应 HTTP 200 状态码,实际调用结果由响应体的 code 与业务字段呈现:
json
{
"code": 200,
"message": "success",
"data": { ... },
"call_id": "call_6a96d6bda27ff05dee01244b314e5662"
}当接口鉴权失败、参数错误或限流时,HTTP 状态码依然保持 200,并返回平台标准错误码结构:
json
{
"code": 10002,
"error_code": "INVALID_API_KEY",
"message": "API Key 无效",
"data": null,
"call_id": "call_6a96d6bda27ff05dee01244b314e5662"
}所有系统级与业务级异常均已收敛脱敏,客户端可直接通过 call_id 向平台技术支持反馈追踪。
3. 完整调用示例
typescript
import { Habitaxx } from 'habitaxx';
import * as fs from 'fs';
// 开发者凭据(示例已脱敏)
const API_KEY = 'qj_live_your_api_key_here';
const PROJECT_NO = 'prj_your_project_no_here';
const USER_ID = 'user_unique_identifier_123';
async function main() {
// 1. 初始化认证客户端
const authClient = new Habitaxx({
apiKey: 'placeholder',
baseURL: 'https://open-api.habitaxx.com',
});
// 2. 换取短效 Access Token
const tokenResp = await authClient.auth.token({
xApiKey: API_KEY,
body: {
project_no: PROJECT_NO,
user_id: USER_ID,
},
});
const accessToken = tokenResp.data.access_token;
console.log('成功获取 Access Token:', accessToken);
// 3. 使用 Access Token 初始化业务客户端
const client = new Habitaxx({
apiKey: accessToken,
baseURL: 'https://open-api.habitaxx.com',
});
// 4. 调用 IMU 行为分析能力
const imuResult = await client.imu.predict({
samples: [
[-0.322, -0.498, -0.657, -32.217, -21.967, 1.33],
// 推荐连续传入 100 组 6 轴采样点 (1 秒时序数据)
],
top_k: 5,
});
console.log('IMU 预测结果:', imuResult.data.prediction);
// 5. 调用鸟类多模态识别
const birdResult = await client.bird.detect({
file: fs.createReadStream('./sample_bird.jpg'),
});
console.log('鸟类检测结果:', birdResult.data.detections);
}
main().catch(console.error);4. 模块详细参考 (API Reference)
Habitaxx 客户端实例 client 包含以下资源模块对象:
| 模块属性 | 对应资源类 | 描述 |
|---|---|---|
client.auth | Auth | 凭证交换与鉴权管理 |
client.imu | IMU | 智能项圈 IMU 行为时序多轴传感器算法识别 |
client.bird | Bird | 鸟类与野生动物多模态目标检测与细粒度物种识别 |
client.petProfiles | PetProfiles | 宠物档案管理(增删改查、品种列表与基本信息) |
client.consultation | Consultation | 智能健康问诊与问答交互全流程 |
client.imageRecognition | ImageRecognition | 宠物图像病症多模态识别与诊断总结 |
client.multimedia | Multimedia | 宠物视频行为理解、吠声意图翻译与音频多模态分析 |
client.oss | Oss | 开放平台媒体资源直传与转存对象存储服务 |
4.1 认证模块 (client.auth)
用于凭据转换与短效令牌签发。
方法:auth.token(params, options?)
- 方法签名:
token(params: { xApiKey: string; body: { project_no: string; user_id: string } }, options?: RequestOptions): Promise<any> - 参数说明:
参数名 类型 是否必填 描述 params.xApiKeystring是 平台颁发的永久 API Key(以 qj_live_开头)params.body.project_nostring是 关联的项目编号(例如 prj_xxx)params.body.user_idstring是 终端用户或设备唯一标识字符串 - 返回值:typescript
{ code: number; message: string; data: { access_token: string; token_type: string; expires_in: number; }; call_id: string; }
4.2 IMU 行为预测模块 (client.imu)
处理来自穿戴设备(如智能宠物项圈)的高频时序 6 轴加速度计与陀螺仪传感器数据,智能识别趴卧、行走、奔跑、玩耍等精细行为姿态。
方法 1:imu.predict(body, options?)
通用 IMU 时序数据姿态预测。
- 方法签名:
predict(body: { samples: number[][]; top_k?: number; part?: string }, options?: RequestOptions): Promise<any> - 参数说明:
参数名 类型 是否必填 描述 body.samplesnumber[][]是 6 轴传感器采样矩阵,格式为 [[ax, ay, az, gx, gy, gz], ...],通常建议 100 组(1 秒窗口)body.top_knumber否 返回置信度前 K 个分类概率,默认 5body.partstring否 佩戴部位(如 neck、back),默认neck - 返回值说明: 包含输入统计
input_statistics、主预测类别prediction(class_index,name,name_zh,confidence)、top_k概率列表及计算延迟等。
方法 2:imu.predictForDevice(deviceId, body, options?)
指定硬件设备 ID 的 IMU 数据推理。
- 方法签名:
predictForDevice(deviceId: string, body: { samples: number[][]; top_k?: number; part?: string }, options?: RequestOptions): Promise<any> - 参数说明:
参数名 类型 是否必填 描述 deviceIdstring是 硬件设备标识(如设备出厂 SN 码) bodyobject是 同 imu.predict参数
4.3 鸟类多模态识别模块 (client.bird)
支持对野外或家庭环境拍摄的鸟类图像进行目标检测、边界框定位、物种精细分类(支持数百种常见鸟类)与 top-5 置信度评估。
方法:bird.detect(params, options?)
上传并识别鸟类图像。
- 方法签名:
detect(params: { file: Uploadable }, options?: RequestOptions): Promise<any> - 参数说明:
参数名 类型 是否必填 描述 params.fileUploadable是 图像文件输入(支持 fs.ReadStream、Blob、File或文件二进制流),格式为 JPEG / PNG - 返回值说明:typescript
{ code: 200, message: "success", data: { annotated_image: string; // 标注并绘制候选框的 Base64 图像 width: number; height: number; device: string; detections: Array<{ box: [number, number, number, number]; // [ymin, xmin, ymax, xmax] 像素坐标 class_id: number; class_en: string; class_zh: string; class_key: string; detector_confidence: number; classification_confidence: number; top5: Array<{ class_en: string; class_zh: string; class_key: string; confidence: number; }>; uncertain: boolean; }>; }, call_id: string; }
4.4 宠物档案模块 (client.petProfiles)
管理用户名下的宠物健康与基础生物档案(支持犬、猫及其他常见品种)。
| 方法名 | 签名与参数 | 描述 |
|---|---|---|
create | create(body: PetProfileCreateParams): Promise<any> | 创建新宠物档案(含姓名、物种、品种、出生日期、绝育状态、体重等) |
list | list(params?: { page?: number; page_size?: number }): Promise<any> | 分页查询当前用户/项目绑定的宠物列表 |
retrieve | retrieve(petId: string): Promise<any> | 获取指定宠物的详细健康资料与档案 |
update | update(petId: string, body: PetProfileUpdateParams): Promise<any> | 修改并更新指定宠物档案字段 |
delete | delete(petId: string): Promise<any> | 软删除或注销指定宠物档案 |
listBreeds | listBreeds(params?: { pet_type?: string }): Promise<any> | 查询系统支持的标准宠物物种与细分品种字典 |
getPetInfo | getPetInfo(petId: string): Promise<any> | 便捷获取宠物精简基础信息 |
4.5 智能问诊模块 (client.consultation)
全流程智能宠物健康咨询与多轮对话系统。
| 方法名 | 签名与参数 | 描述 |
|---|---|---|
createSession | createSession(body: { pet_id?: string; initial_symptom?: string }): Promise<any> | 开启新的问诊会话,获取 session_id |
analysis | analysis(body: { session_id: string; message: string }): Promise<any> | 主会话深度分析与问答回复 |
keywords | keywords(body: { session_id: string }): Promise<any> | 提取症状核心关键词与关联特征 |
preQuestion | preQuestion(body: { session_id: string }): Promise<any> | 会话初期的预设追问与引导问题生成 |
reasonInfo | reasonInfo(body: { session_id: string }): Promise<any> | 获取 AI 推理逻辑、鉴别诊断思路及医学依据 |
relatedQuestion | relatedQuestion(body: { session_id: string }): Promise<any> | 生成用户可能感兴趣的延伸就诊建议与相关问题 |
ifContinueAsk | ifContinueAsk(body: { session_id: string }): Promise<any> | 评估当前病情描述是否完备,判断是否需要继续追问 |
ifNeedImage | ifNeedImage(body: { session_id: string }): Promise<any> | 判断当前体征是否需要引导用户拍摄并上传患处图像 |
picResult | picResult(body: { session_id: string; image_url: string }): Promise<any> | 结合患处图像进行多模态综合病情判定 |
summary | summary(body: { session_id: string }): Promise<any> | 生成咨询阶段总结与初步病情研判 |
report | report(body: { session_id: string }): Promise<any> | 生成结构化完整电子病历与诊疗建议报告 |
getTask | getTask(taskId: string): Promise<any> | 轮询异步问诊报告生成任务的执行进度 |
getMedicalRecord | getMedicalRecord(recordId: string): Promise<any> | 获取归档病历报告的详情内容 |
saveMessage | saveMessage(body: { session_id: string; role: string; content: string }): Promise<any> | 手动持久化问诊过程中的历史消息记录 |
listMessages | listMessages(params: { session_id: string }): Promise<any> | 检索指定问诊会话的历史完整对话记录 |
4.6 图像病症识别模块 (client.imageRecognition)
面向宠物皮肤病、眼科、口腔及常见体表异状的多模态图像识别能力。
| 方法名 | 签名与参数 | 描述 |
|---|---|---|
summary | summary(body: { image_url: string; symptom_desc?: string }): Promise<any> | 针对上传病灶图像生成多模态诊断与风险评估总结 |
summaryStream | summaryStream(body: { image_url: string; symptom_desc?: string }): Promise<any> | 以流式(Server-Sent Events)逐步输出诊断与病理分析文本 |
createReportTask | createReportTask(body: { image_url: string; pet_id?: string }): Promise<any> | 提交深度图像识别与结构化病症报告异步生成任务 |
getReportTask | getReportTask(taskId: string): Promise<any> | 轮询异步图像识别任务的执行状态 |
getMedicalRecord | getMedicalRecord(recordId: string): Promise<any> | 获取由图像识别生成的完整医疗报告记录 |
4.7 多媒体与音频模块 (client.multimedia)
覆盖宠物视频动作识别、吠叫意图音频分析与长音频多模态理解。
| 方法名 | 签名与参数 | 描述 |
|---|---|---|
understandVideo | understandVideo(body: { video_url: string; prompt?: string }): Promise<any> | 提交宠物长/短视频行为理解与事件抽取异步任务 |
getVideoResult | getVideoResult(taskId: string): Promise<any> | 获取视频理解任务分析结果与关键帧事件段落 |
translateSound | translateSound(body: { audio_url: string }): Promise<any> | 提交犬吠、猫鸣等音频意图分析与情绪翻译任务 |
getVoiceResult | getVoiceResult(taskId: string): Promise<any> | 查询宠物叫声翻译分析任务的执行结果 |
streamVoiceAnalysis | streamVoiceAnalysis(body: { audio_url: string }): Promise<any> | 流式获取音频声学特征识别与情绪反馈结果 |
4.8 资源直传模块 (client.oss)
为多模态识别、音频分析和图像诊断提供便捷的对象存储凭据与文件直传。
| 方法名 | 签名与参数 | 描述 |
|---|---|---|
uploadImage | uploadImage(params: { file: Uploadable }): Promise<any> | 上传图片文件并返回合规的公网或签名访问 URL |
uploadAudio | uploadAudio(params: { file: Uploadable }): Promise<any> | 上传音频文件并返回可用访问 URL |
uploadVideo | uploadVideo(params: { file: Uploadable }): Promise<any> | 上传视频文件并返回可用访问 URL |
5. 错误处理与规范
SDK 将所有响应体统一按规范映射。若网络层面断开或服务端出现非 200 HTTP 响应,SDK 将抛出相应异常:
typescript
import { Habitaxx, APIError } from 'habitaxx';
try {
const result = await client.imu.predict({ samples: [] });
// 业务状态码判断
if (result.code !== 200) {
console.error(`业务异常 [${result.error_code}]: ${result.message} (call_id: ${result.call_id})`);
}
} catch (error) {
if (error instanceof APIError) {
console.error(`HTTP 异常状态: ${error.status}, 信息: ${error.message}`);
} else {
console.error('网络或未知异常:', error);
}
}