@happyrobot-ai/ sdk (英语)
TypeScript SDK用于HappyRobot公共API.
安装
npm install @happyrobot-ai/sdk
# or
pnpm add @happyrobot-ai/sdk
# or
yarn add @happyrobot-ai/sdk
可选 : 如果你计划使用 HappyRobotVoiceClient (进口自 @happyrobot-ai/sdk/voice)用于浏览器侧语音调用,也安装 livekit-client数字 :
npm install livekit-client
# or
pnpm add livekit-client
# or
yarn add livekit-client
这只用于语音——所有其他SDK特性都没有它的工作.
快速启动
import { HappyRobotClient } from "@happyrobot-ai/sdk";
const client = new HappyRobotClient({ apiKey: "sk_live_..." });
// List workflows
const { data } = await client.workflows.list();
// Trigger a run
const { run_id } = await client.workflows.triggerRun("my-workflow", {
payload: { phone: "+1234567890" },
});
配置
const client = new HappyRobotClient({
apiKey: "sk_live_...", // Required. API key (sk_live_... or sk_test_...)
cluster: "eu", // Optional. "us" (default) or "eu"
timeout: 30_000, // Optional. Request timeout in ms. Defaults to 30000
maxRetries: 2, // Optional. Retries on 429/5xx with exponential backoff. Defaults to 2
fetch: customFetch, // Optional. Custom fetch implementation
});
帮助者
通过下列途径提供的高级便利功能: @happyrobot-ai/sdk/helpers。 。 。 .
triggerAndWait
触发工作流程运行和民意调查直至达到终端状态.
import { triggerAndWait } from "@happyrobot-ai/sdk/helpers";
const { run, sessions } = await triggerAndWait(client, {
workflowId: "my-workflow",
payload: { phone: "+1234567890" },
timeoutMs: 300_000, // Optional. Defaults to 5 minutes
pollIntervalMs: 2_000, // Optional. Defaults to 2 seconds
fetchSessions: true, // Optional. Fetch sessions on completion. Defaults to true
environment: "production", // Optional. Defaults to "production"
});
console.log(run.status); // "completed" | "failed" | "canceled" | ...
createVoiceAgent
从可选出版的模板创建语音代理工作流程.
import { createVoiceAgent } from "@happyrobot-ai/sdk/helpers";
const { workflow, publishResult } = await createVoiceAgent(client, {
name: "Sales Agent",
template: "voice-agent", // "voice-agent" (outbound) or "inbound-voice-agent"
prompt: "You are a helpful sales assistant...",
initialMessage: "Hi, how can I help you today?",
publish: true,
environment: "production",
folderId: "folder-id", // Optional
});
createFromTemplate
从自定义输入的模板创建任何工作流程 .
import { createFromTemplate } from "@happyrobot-ai/sdk/helpers";
const { workflow } = await createFromTemplate(client, {
template: "voice-agent",
name: "My Agent",
inputs: { agent_name: "My Agent" },
publish: false,
});
资源
| 财产 | 类 | 说明 |
|---|---|---|
client.workflows | WorkflowsResource | 工作流程 CRUD、出版、运行和模板 |
client.versions | VersionsResource | 版本管理(分叉、发布、锁定、测试) |
client.nodes | NodesResource | 节点 CRUD, 配置计划, 以及可用的变量 |
client.runs | RunsResource | 运行细节、 取消和说明 |
client.sessions | SessionsResource | 会话细节、消息和 SSE 流线 |
client.messages | MessagesResource | 信件质量旗帜 |
client.variables | VariablesResource | 工作流范围变量 |
client.phoneNumbers | PhoneNumbersResource | 电话号码管理 |
client.sipTrunks | SipTrunksResource | SIP干线管理 |
client.integrations | IntegrationsResource | 综合与事件发现 |
client.contacts | ContactsResource | 联系人查询和历史 |
client.knowledgeBases | KnowledgeBasesResource | 知识库文件管理 |
client.workflowFolders | WorkflowFoldersResource | 工作流程文件夹组织 |
client.mcp | MCPResource | MCP 服务器管理 |
client.billing | BillingResource | 账单使用详情和总数 |
client.apiKey | ApiKeyResource | API 密钥回顾 |
client.artifacts | ArtifactsResource | 解析授权的文物下载 URL |
client.adversarialSuites | AdversarialSuitesResource | 保留对抗性套房的历史 |
client.adversarialTests | AdversarialTestsResource | 保留对抗试验历史 |
client.northstars | NorthstarsResource | 北星质量标准管理 |
client.customEvals | CustomEvalsResource | 自定义电子邮件管理和执行 |
client.nodeTests | NodeTestsResource | 保存节点测试并运行历史 |
client.issues | IssuesResource | 质量问题(旗)状况管理 |
client.auditRemarks | AuditRemarksResource | 审计意见反馈管理 |
client.chat | ChatResource | 聊天会话管理、消息和文件上传 |
client.voice | VoiceResource | 语音目录查询和调用符号创建 |
client.workflows
// List workflows (paginated)
const { data, pagination } = await client.workflows.list({ page: 1, limit: 20 });
// Iterate all workflows across pages
for await (const wf of client.workflows.listAll()) { ... }
// Create a workflow
const wf = await client.workflows.create({ name: "My Workflow" });
// Get by ID or slug
const wf = await client.workflows.get("my-workflow");
// Update
await client.workflows.update("my-workflow", { name: "New Name" });
// Delete
await client.workflows.delete("my-workflow");
// Duplicate
await client.workflows.duplicate("my-workflow", { name: "Copy" });
// Publish / unpublish
await client.workflows.publish("my-workflow");
await client.workflows.unpublish("my-workflow");
// Cancel current and queued runs. By default, this also unpublishes the workflow.
await client.workflows.cancelRuns("my-workflow");
await client.workflows.cancelRuns("my-workflow", { unpublish_workflow: false });
// List templates
const { data } = await client.workflows.listTemplates();
// List versions
const { data } = await client.workflows.listVersions("my-workflow");
// List runs
const { data } = await client.workflows.listRuns("my-workflow");
// List sessions across all runs
const { data: sessions } = await client.workflows.listSessions("my-workflow");
// Trigger a run
const { run_id } = await client.workflows.triggerRun("my-workflow", { payload: { phone: "+1..." } });
| 方法 | HTTP 密码 | 路径 | 说明 |
|---|---|---|---|
list(query?) | 获取 | /workflows | 列表工作流程,分解 |
listAll(query?) | 获取 | /workflows | 所有页面的自动生成器 |
create(body) | 邮政 | /workflows | 创建新工作流程 |
get(workflowId) | 获取 | /workflows/:id | 通过 ID 或 swit 获取工作流程 |
update(workflowId, body) | 帕齐 | /workflows/:id | 更新名称,描述等. |
delete(workflowId) | 迪莱特 | /workflows/:id | 删除工作流程 |
duplicate(workflowId, body?) | 邮政 | /workflows/:id/duplicate | 复制工作流程 |
publish(workflowId, body?) | 邮政 | /workflows/:id/publish | 发布最新版本 |
unpublish(workflowId) | 邮政 | /workflows/:id/unpublish | 解开工作流程 |
cancelRuns(workflowId, body?) | 邮政 | /workflows/:id/cancel-runs | 取消当前和队列运行 |
listTemplates(query?) | 获取 | /workflows/templates | 列表工作流程模板 |
listVersions(workflowId, query?) | 获取 | /workflows/:id/versions | 工作流程的列表版本 |
listRuns(workflowId, query?) | 获取 | /workflows/:id/runs | 工作流程列表运行 |
listSessions(workflowId, query?) | 获取 | /workflows/:id/sessions | 为工作流程列出会话 |
triggerRun(workflowId, body?) | 邮政 | /workflows/:id/runs | 触发新运行 |
client.versions
const version = await client.versions.get("version-id");
await client.versions.update("version-id", { name: "v2" });
await client.versions.fork("version-id");
await client.versions.publish("version-id");
await client.versions.unpublish("version-id");
await client.versions.lock("version-id");
await client.versions.unlock("version-id");
await client.versions.testAll("version-id");
const issues = await client.versions.getPromptIssues("version-id");
| 方法 | HTTP 密码 | 路径 | 说明 |
|---|---|---|---|
get(versionId) | 获取 | /versions/:id | 获取带有节点摘要和更改日志的版本 |
update(versionId, body) | 帕齐 | /versions/:id | 更新名称或说明 |
fork(versionId) | 邮政 | /versions/:id/fork | 克隆一个版本 |
publish(versionId, body?) | 邮政 | /versions/:id/publish | 发布一个版本 |
unpublish(versionId) | 邮政 | /versions/:id/unpublish | 解开版本 |
lock(versionId) | 邮政 | /versions/:id/lock | 锁定一个版本( 防止编辑) |
unlock(versionId) | 邮政 | /versions/:id/unlock | 解锁版本 |
testAll(versionId) | 邮政 | /versions/:id/test-all | 运行全部测试验证 |
getPromptIssues(versionId) | 获取 | /versions/:id/prompt-issues | 为所有快速节点获取快速质量问题 |
client.nodes
节点总是被瞄准一个版本.
const nodes = await client.nodes.list("version-id");
await client.nodes.addBatch("version-id", { nodes: [...] });
const node = await client.nodes.get("version-id", "node-id");
await client.nodes.update("version-id", "node-id", { config: { ... } });
await client.nodes.delete("version-id", "node-id");
const schema = await client.nodes.getConfigSchema("version-id", "node-id");
const vars = await client.nodes.getAvailableVars("version-id", "node-id");
const result = await client.nodes.test("version-id", "node-id");
返回的团体 getAvailableVars 可包含 is_list: true。这意味着组中的变量作为环外的数组进行解析。 顺序循环和平行循环两个还原数组;单迭代返回一个单项数组.
| 方法 | HTTP 密码 | 路径 | 说明 |
|---|---|---|---|
list(versionId) | 获取 | /versions/:vId/nodes | 在版本中列出所有节点 |
addBatch(versionId, body) | 邮政 | /versions/:vId/nodes | 分批添加节点 (1-50) |
get(versionId, nodeId) | 获取 | /versions/:vId/nodes/:nId | 获得一个单一节点 |
update(versionId, nodeId, body) | 点 | /versions/:vId/nodes/:nId | 更新节点 |
delete(versionId, nodeId) | 迪莱特 | /versions/:vId/nodes/:nId | 删除节点 |
getConfigSchema(versionId, nodeId) | 获取 | /versions/:vId/nodes/:nId/config-schema | 获取字段类型和要求 |
getAvailableVars(versionId, nodeId) | 获取 | /versions/:vId/nodes/:nId/available-vars | 获取此节点的上游变量 |
test(versionId, nodeId, body?) | 邮政 | /versions/:vId/nodes/:nId/test | 测试单个节点( 不得发布版本) |
client.runs
const run = await client.runs.get("run-id");
const sessions = await client.runs.getSessions("run-id");
const recordings = await client.runs.getRecordings("run-id");
const flags = await client.runs.getFlags("run-id");
await client.runs.cancel("run-id");
await client.runs.mark("run-id", { annotation: "correct" });
| 方法 | HTTP 密码 | 路径 | 说明 |
|---|---|---|---|
get(runId) | 获取 | /runs/:id | 获取运行细节 |
getSessions(runId, query?) | 获取 | /runs/:id/sessions | 获取会话运行 |
getRecordings(runId) | 获取 | /runs/:id/recordings | 跑步要录音 |
getFlags(runId, query?) | 获取 | /runs/:id/flags | 为运行获取质量旗 |
cancel(runId) | 邮政 | /runs/:id/cancel | 取消运行 |
mark(runId, body) | 邮政 | /runs/:id/mark | 注释运行( 正确/ 不正确/ 关键) |
client.sessions
const session = await client.sessions.get("session-id");
const { data } = await client.sessions.getMessages("session-id");
// SSE streaming
for await (const event of await client.sessions.stream("session-id")) {
if (event.event === "message")
console.log(event.data.role, event.data.content);
if (event.event === "session_ended") break;
}
| 方法 | HTTP 密码 | 路径 | 说明 |
|---|---|---|---|
get(sessionId) | 获取 | /sessions/:id | 获取会话细节 |
getMessages(sessionId, query?) | 获取 | /sessions/:id/messages | 获取一个会话的 pazized 信件 |
stream(sessionId, query?) | 获取 | /sessions/:id/stream | 打开会话消息的 SSE 流 |
client.messages
const { data } = await client.messages.listFlags("message-id");
await client.messages.createFlag("message-id", {
type: "incorrect",
note: "...",
});
| 方法 | HTTP 密码 | 路径 | 说明 |
|---|---|---|---|
listFlags(messageId, query?) | 获取 | /messages/:id/flags | 列出消息的质量标志 |
createFlag(messageId, body) | 邮政 | /messages/:id/flags | 在信件上创建质量旗 |
client.artifacts
const resolved = await client.artifacts.createDownloadUrls({
artifacts: [
{
message_id: "message-id-from-the-session-messages-response",
s3_key: "artifacts/<media_id>/extracted_text.txt",
},
],
});
| 方法 | HTTP 密码 | 路径 | 说明 |
|---|---|---|---|
createDownloadUrls(body) | 邮政 | /artifacts/download-urls | 用出处解决授权的文物 URL |
resolve(body) | 邮政 | /artifacts/resolve | 折旧;2026年10月15日 UTC中午12点日落 |
client.variables
变量被限定为工作流程.
const { data } = await client.variables.list("workflow-id");
await client.variables.create("workflow-id", {
name: "MY_VAR",
value: "hello",
});
await client.variables.update("workflow-id", "variable-id", { value: "world" });
await client.variables.delete("workflow-id", "variable-id");
| 方法 | HTTP 密码 | 路径 | 说明 |
|---|---|---|---|
list(workflowId, query?) | 获取 | /workflows/:wId/variables | 工作流程的变量列表 |
create(workflowId, body) | 邮政 | /workflows/:wId/variables | 创建变量 |
update(workflowId, variableId, body) | 帕齐 | /workflows/:wId/variables/:vId | 更新变量 |
delete(workflowId, variableId) | 迪莱特 | /workflows/:wId/variables/:vId | 删除变量 |
client.phoneNumbers
const numbers = await client.phoneNumbers.list();
await client.phoneNumbers.buy({ area_code: "415" });
await client.phoneNumbers.update("id", { name: "Main Line" });
await client.phoneNumbers.getUsage("id");
await client.phoneNumbers.freeUp("id");
await client.phoneNumbers.delete("id");
await client.phoneNumbers.removeFromWorkflow("id", { use_case_id: "..." });
await client.phoneNumbers.getTollFreeVerification("id");
await client.phoneNumbers.createTollFreeVerification("id", { ... });
await client.phoneNumbers.deleteTollFreeVerification("verification-sid");
await client.phoneNumbers.createSipTrunk("id");
await client.phoneNumbers.validateTollFreeNumbers({ phone_numbers: [...] });
| 方法 | HTTP 密码 | 路径 | 说明 |
|---|---|---|---|
list(query?) | 获取 | /phone-numbers | 列出所有电话号码 |
buy(body) | 邮政 | /phone-numbers | 购买新电话号码 |
update(id, body) | 点 | /phone-numbers/:id | 更新名称或呼叫者ID |
getUsage(id) | 获取 | /phone-numbers/:id/usage | 获取使用信息 |
getTollFreeVerification(id) | 获取 | /phone-numbers/:id/tollfree-verification | 获得免费核查状态 |
createTollFreeVerification(id, body) | 邮政 | /phone-numbers/:id/tollfree-verification | 开始免费核查 |
deleteTollFreeVerification(verificationSid) | 迪莱特 | /phone-numbers/tollfree-verification/:sid | 删除免费核查 |
createSipTrunk(id) | 邮政 | /phone-numbers/:id/sip-trunk | 为数字创建 SIP 中继器 |
freeUp(id) | 邮政 | /phone-numbers/:id/free-up-number | 从工作流程中释放一个数字 |
delete(id) | 邮政 | /phone-numbers/:id/delete-number | 永久删除数字 |
removeFromWorkflow(id, body) | 邮政 | /phone-numbers/:id/remove-from-workflow | 从特定的工作流程中删除 |
validateTollFreeNumbers(body) | 邮政 | /phone-numbers/validate-toll-free-numbers | 检查冲突 |
client.sipTrunks
const trunks = await client.sipTrunks.list();
const options = await client.sipTrunks.listOptions();
await client.sipTrunks.create({ name: "Main Trunk", ... });
await client.sipTrunks.createBulk({ trunks: [...] });
const trunk = await client.sipTrunks.get("trunk-id");
await client.sipTrunks.update("trunk-id", { name: "Updated" });
await client.sipTrunks.delete("trunk-id");
| 方法 | HTTP 密码 | 路径 | 说明 |
|---|---|---|---|
list() | 获取 | /sip-trunks | 列出全部 SIP 干线 |
listOptions() | 获取 | /sip-trunks/options | 轻型干线选项列表 |
create(body) | 邮政 | /sip-trunks | 创建 SIP 干线 |
createBulk(body) | 邮政 | /sip-trunks/bulk | 创建多个 SIP 干线 |
get(trunkId) | 获取 | /sip-trunks/:id | 拿个SIP干线 |
update(trunkId, body) | 点 | /sip-trunks/:id | 更新 SIP 干线 |
delete(trunkId) | 迪莱特 | /sip-trunks/:id | 删除 SIP 中继器 |
client.integrations
const integrations = await client.integrations.list();
const integration = await client.integrations.get("integration-id");
await client.integrations.createCredential("integration-id", { name: "My Creds", fields: { ... } });
// Integration-specific sub-resources
await client.integrations.googleSheets.spreadsheets();
await client.integrations.googleSheets.worksheets({ spreadsheet_id: "..." });
await client.integrations.googleSheets.columns({ spreadsheet_id: "...", worksheet_id: "..." });
await client.integrations.googleSheets.rows({ spreadsheet_id: "...", worksheet_id: "..." });
await client.integrations.slack.channels();
await client.integrations.slack.users();
await client.integrations.teams.teams();
await client.integrations.teams.channels();
await client.integrations.teams.users();
await client.integrations.twilioSms.phoneNumbers();
await client.integrations.whatsApp.businesses({ credential_id: "..." });
await client.integrations.whatsApp.businessAccounts({ credential_id: "...", business_id: "..." });
await client.integrations.whatsApp.phoneNumbers({ credential_id: "...", business_account_id: "..." });
await client.integrations.whatsApp.messageTemplates({ credential_id: "...", business_account_id: "..." });
| 方法 | HTTP 密码 | 路径 | 说明 |
|---|---|---|---|
list(query?) | 获取 | /integrations | 列出所有整合 |
get(id) | 获取 | /integrations/:id | 实现一体化及其活动 |
createCredential(id, body) | 邮政 | /integrations/:id/create-credential | 创建基于形式整合的证书 |
googleSheets.spreadsheets(query?) | 获取 | /integrations/google-sheets/spreadsheets | 列表电子表格 |
googleSheets.worksheets(query) | 获取 | /integrations/google-sheets/worksheets | 在电子表格中列出工作表 |
googleSheets.columns(query) | 获取 | /integrations/google-sheets/columns | 在工作表中列出列 |
googleSheets.rows(query) | 获取 | /integrations/google-sheets/rows | 在工作表中列出行 |
slack.channels(query?) | 获取 | /integrations/slack/channels | 列出黑频道 |
slack.users(query?) | 获取 | /integrations/slack/users | 列表 Slack 用户 |
teams.teams(query?) | 获取 | /integrations/teams/teams | 微软团队列表 |
teams.channels(query?) | 获取 | /integrations/teams/channels | 列出微软团队频道 |
teams.users(query?) | 获取 | /integrations/teams/users | 列出微软团队用户列表 |
twilioSms.phoneNumbers(query?) | 获取 | /integrations/twilio-sms/phone-numbers | 列表 Twilio 短消息编号 |
whatsApp.businesses(query) | 获取 | /integrations/whatsapp/businesses | 列表 WhatsApp 业务 |
whatsApp.businessAccounts(query) | 获取 | /integrations/whatsapp/business-accounts | 列表 WhatsApp 商业账户 |
whatsApp.phoneNumbers(query) | 获取 | /integrations/whatsapp/phone-numbers | 列出 WhatsApp 电话号码 |
whatsApp.messageTemplates(query) | 获取 | /integrations/whatsapp/message-templates | 列出 WhatsApp 信件模板 |
client.contacts
const { data } = await client.contacts.list({ search: "John" });
const contact = await client.contacts.resolve({ phone_number: "+14155551234" });
const contact = await client.contacts.get("contact-id");
const interactions = await client.contacts.getInteractions("contact-id");
const memories = await client.contacts.getMemories("contact-id");
| 方法 | HTTP 密码 | 路径 | 说明 |
|---|---|---|---|
list(query?) | 获取 | /contacts | 列表联系人( 曲线标签) |
resolve(query) | 获取 | /contacts/resolve | 通过电话号码或电子邮件查找联系人 |
get(contactId) | 获取 | /contacts/:id | 通过身份联系 |
getInteractions(contactId) | 获取 | /contacts/:id/interactions | 获取联系人的呼叫/消息历史 |
getMemories(contactId) | 获取 | /contacts/:id/memories | 获取联系人的AI记忆 |
client.knowledgeBases
const kbs = await client.knowledgeBases.list();
const files = await client.knowledgeBases.listFiles("kb-id");
const urls = await client.knowledgeBases.getUploadUrls("kb-id", {
files: [{ name: "doc.pdf", content_type: "application/pdf" }],
});
await client.knowledgeBases.triggerChunking("kb-id");
await client.knowledgeBases.deleteFile("kb-id", "file-id");
await client.knowledgeBases.delete("kb-id");
| 方法 | HTTP 密码 | 路径 | 说明 |
|---|---|---|---|
list() | 获取 | /knowledge-bases | 列出所有知识基础 |
listFiles(kbId) | 获取 | /knowledge-bases/:id/files | 在知识库中列出文件 |
getUploadUrls(kbId, body) | 邮政 | /knowledge-bases/:id/upload-urls | 获取预签名的 S3 上传 URL |
triggerChunking(kbId) | 邮政 | /knowledge-bases/:id/trigger-chunking | 开始文档处理/切入 |
deleteFile(kbId, fileId) | 迪莱特 | /knowledge-bases/:id/files/:fileId | 从知识库中删除文件 |
delete(kbId) | 迪莱特 | /knowledge-bases/:id | 删除知识库 |
client.workflowFolders
const { data } = await client.workflowFolders.list();
await client.workflowFolders.create({ name: "Production" });
const folder = await client.workflowFolders.get("folder-id");
await client.workflowFolders.update("folder-id", { name: "Updated" });
await client.workflowFolders.delete("folder-id");
| 方法 | HTTP 密码 | 路径 | 说明 |
|---|---|---|---|
list(query?) | 获取 | /workflow-folders | 列表文件夹( 已标注) |
create(body) | 邮政 | /workflow-folders | 创建文件夹 |
get(folderId) | 获取 | /workflow-folders/:id | 获取文件夹 |
update(folderId, body) | 点 | /workflow-folders/:id | 更新文件夹 |
delete(folderId) | 迪莱特 | /workflow-folders/:id | 删除文件夹 |
client.mcp
const { data } = await client.mcp.list();
await client.mcp.create({ name: "My MCP", url: "https://..." });
await client.mcp.refresh("mcp-id");
| 方法 | HTTP 密码 | 路径 | 说明 |
|---|---|---|---|
list(query?) | 获取 | /mcp | 列出 MCP 服务器( 贴上) |
create(body) | 邮政 | /mcp | 注册一个新的 MCP 服务器 |
refresh(mcpId) | 邮政 | /mcp/:id/refresh | MCP 服务器的再发现工具 |
OAuth2( 存档日期auth_type: "oauth2"(中文(简体) )设置 oauth2_credential_id 改为UUID OAuth 2.0 数据 集成证书( 相同 org) 配置为您的提供者的符号 URL 。 不发送 auth_token; API在创建,上市刷新或工作流程运行时会获取一个短寿命的访问符.
client.billing
const details = await client.billing.getDetails({
start: "2024-01-01",
end: "2024-01-31",
});
const totals = await client.billing.getTotals({
start: "2024-01-01",
end: "2024-01-31",
});
| 方法 | HTTP 密码 | 路径 | 说明 |
|---|---|---|---|
getDetails(query) | 获取 | /billing/usage/details | 详细计费细列项目 |
getTotals(query) | 获取 | /billing/usage/totals | 合计计费总额 |
client.apiKey
const info = await client.apiKey.describe();
| 方法 | HTTP 密码 | 路径 | 说明 |
|---|---|---|---|
describe() | 获取 | /api-key/describe | 透视当前 API 键( ID, name, org等) |
原生情景和保留的历史
通过 client.e2eScenarios。 。 。 . client.adversarialTests 财务报告和审定财务报表 client.adversarialSuites 公开保留的历史只读.
const { scenario } = await client.e2eScenarios.create({
targetUseCaseId: "workflow-id",
targetAgentNodePersistentId: "agent-persistent-id",
targetEnvironment: "production",
mode: "agent_isolated",
seeds: [],
name: "Booking probe",
adversarialPrompt: "Ask to book load L-7.",
});
await client.e2eScenarios.run(scenario.id, "selected-version-id");
const { messages } =
await client.adversarialTests.getRunMessages("legacy-run-id");
client.northstars
北星是决定代理人应如何行事的质量标准. 它们用来自动分级交谈.
const { northstar } = await client.northstars.get("northstar-id");
await client.northstars.update("northstar-id", {
enabled: true,
priority: "high",
});
await client.northstars.delete("northstar-id");
// Get full regeneration history
const { history } = await client.northstars.getHistory("northstar-id");
// Rate a northstar (-2 = strongly wrong, +2 = strongly correct)
const { feedback } = await client.northstars.submitFeedback("northstar-id", {
correctness: 2,
feedback: "This criterion is perfect.",
trigger_regeneration: false,
});
await client.northstars.deleteFeedback("northstar-id");
| 方法 | HTTP 密码 | 路径 | 说明 |
|---|---|---|---|
get(northstarId) | 获取 | /northstars/:id | 找个北星 |
update(northstarId, body) | 帕齐 | /northstars/:id | 更新名称、描述、实例、类别、优先级或启用状态 |
delete(northstarId) | 迪莱特 | /northstars/:id | 删除北星 |
getHistory(northstarId) | 获取 | /northstars/:id/history | 获得完整的再生链,最古老的第一 |
submitFeedback(northstarId, body) | 邮政 | /northstars/:id/feedback | 将北星的正确性( - 2 至 +2 ) 定级为可选触发再生 |
deleteFeedback(northstarId) | 迪莱特 | /northstars/:id/feedback | 删除北星的反馈 |
client.customEvals
自定义 evals 对照预期输出或北星标准测试特定的快速节点.
const { test } = await client.customEvals.get("eval-id");
await client.customEvals.update("eval-id", {
name: "Greeting check",
expected_response: "Hello, how can I help you?",
});
await client.customEvals.delete("eval-id");
// Run an eval
const { run_id } = await client.customEvals.run("eval-id", {
version_id: "v-id",
});
// Poll results
const { runs } = await client.customEvals.listRuns("eval-id");
| 方法 | HTTP 密码 | 路径 | 说明 |
|---|---|---|---|
get(evalId) | 获取 | /custom-evals/:id | 获取自定义 val |
update(evalId, body) | 帕齐 | /custom-evals/:id | 更新信件、预期输出、变量或北星ID |
delete(evalId) | 迪莱特 | /custom-evals/:id | 删除自定义 eval |
run(evalId, body) | 邮政 | /custom-evals/:id/run | 同步执行 , 返回 run_id |
listRuns(evalId, query?) | 获取 | /custom-evals/:id/runs | 名单有通行证/不及格和法官推理 |
client.nodeTests
所保存的节点测试运行一个具有固定上游值的节点,并将其输出与预期输出进行比较. 它们出现在工作流程的"测试"标签中,属于一个版本的节点. 伪造一个版本复制它们.
const { test } = await client.nodeTests.create("node-id", {
name: "Load 123 transcript",
config: { overrides: { "upstream-persistent-id.transcript": "..." } },
expected_output: { carrier: "ACME", rate: 1200 },
ignored_fields: ["notes"],
});
const { run_id } = await client.nodeTests.run(test.id);
const { run } = await client.nodeTests.getRun(test.id, run_id); // poll until status !== "running"
| 方法 | HTTP 密码 | 路径 | 说明 |
|---|---|---|---|
list(nodeId) | 获取 | /nodes/:id/node-tests | 列出节点保存的测试 |
create(nodeId, body) | 邮政 | /nodes/:id/node-tests | 创建已保存的测试 |
get(id) | 获取 | /node-tests/:id | 获得保存的测试 |
update(id, body) | 帕齐 | /node-tests/:id | 更新任何名称、覆盖、预期或被忽略的字段 |
delete(id) | 迪莱特 | /node-tests/:id | 删除已保存的测试 |
run(id) | 邮政 | /node-tests/:id/run | 根据节点当前配置运行 |
listRuns(id, query?) | 获取 | /node-tests/:id/runs | 列表运行, 最先更新( Q)limit, (中文(简体) ), cursor(中文(简体) ) |
getRun(id, runId) | 获取 | /node-tests/:id/runs/:id | 获得运行输出、通过/失败和不匹配字段 |
树枝试验: client.branches.*
在树枝的工作空间,每个树枝上进行现场测试: /branches/{branch_id}/... 路线 client.branches.customEvals, (中文(简体) ), .northstars, (中文(简体) ), .nodeTests, (中文(简体) ), .e2eScenarios 财务报告和审定财务报表 .testSuites。它们使用持续的ID,在编辑和承诺时保持不变。 他们返回的每一个物体 id,其目前的修订,在一项承诺之后有所改变,以及 persistent_id,在路径中;节点是它的 persistent_id 内 client.branches.get(branchId)。编辑分支工作树上的土地,并使用其工作承诺。 上面的平面路线是用于版本上的工作空间,拒绝在分行工作空间上用指针来编辑分行路线.
const branchId = "branch-id";
const { data } = await client.branches.customEvals.listForNode(
branchId,
"prompt-persistent-id"
);
await client.branches.customEvals.update(branchId, data[0].persistent_id, {
name: "Renamed",
});
const { run_id } = await client.branches.customEvals.run(
branchId,
data[0].persistent_id
);
const { runs } = await client.branches.customEvals.listRuns(
branchId,
data[0].persistent_id
);
const { data: northstars, suggestions } =
await client.branches.northstars.listForNode(
branchId,
"prompt-persistent-id"
);
// Refresh proposes changes as suggestions; accept or dismiss them by persistent ID.
await client.branches.northstars.acceptSuggestions(branchId, {
suggestion_ids: suggestions.map((suggestion) => suggestion.persistent_id),
});
const { tests } = await client.branches.nodeTests.list(
branchId,
"node-persistent-id"
);
const { scenarios } = await client.branches.e2eScenarios.list(branchId);
await client.branches.e2eScenarios.run(branchId, scenarios[0].persistent_id);
client.issues
当对话失败时, 就会出现问题( 质量旗帜) .
await client.issues.update("issue-id", { status: "approved" });
| 方法 | HTTP 密码 | 路径 | 说明 |
|---|---|---|---|
update(issueId, body) | 帕齐 | /issues/:id | 最新发行状况open 编号 : approved 编号 : rejected 编号 : closed(中文(简体) ) |
client.auditRemarks
审计评论是谈话中附带的个别北星分数. 对审计意见的反馈改善了今后的评级.
const feedback = await client.auditRemarks.getFeedback("audit-remark-id");
// Thumbs up — automatically adds the remark as a northstar positive example
await client.auditRemarks.submitFeedback("audit-remark-id", {
polarity: true,
});
// Thumbs down with attribution
await client.auditRemarks.submitFeedback("audit-remark-id", {
polarity: false,
issue_attribution: "northstar",
comment: "The northstar criteria was wrong here.",
});
await client.auditRemarks.deleteFeedback("audit-remark-id");
| 方法 | HTTP 密码 | 路径 | 说明 |
|---|---|---|---|
getFeedback(auditRemarkId) | 获取 | /audit-remarks/:id/feedback | 得到你的反馈 对于这个评论,或 null |
submitFeedback(auditRemarkId, body) | 邮政 | /audit-remarks/:id/feedback | 提交上下拇指; 拇指上加注释为北星例 |
deleteFeedback(auditRemarkId) | 迪莱特 | /audit-remarks/:id/feedback | 删除您的反馈 |
客户访问令牌( E)client.tokens(中文(简体) )
使用您的 API 密钥在您的后端创建一个令牌, 然后传递给客户端应用程序以读取特定的会话或运行 。 Tokens使用JWE加密;视其为不透明并使用返回的过期时间.
// Your backend
const access = await client.tokens.create({
grants: [
{ resource: "session", resource_id: sessionId, actions: ["read"] },
{ resource: "run", resource_id: runId, actions: ["read"] },
],
ttl_seconds: 3600,
});
// Your client app
const reader = new HappyRobotClient({ apiKey: access.token });
const history = await reader.sessions.getMessages(sessionId);
POST /tokens 接受1至10项补助。 每笔赠款都必须得到API密钥的允许. 支助资源为: session 财务报告和审定财务报表 run;唯一支持的行动是 read. 寿命默认为3600秒,最少为60秒,最长为86400秒. 答复中仅包含 token 财务报告和审定财务报表 expires_at。 。 。 .
课程赠款允许其细节、信息和流程。 跑步补助金允许那些读取 属于跑步的会话,加 GET /runs/{id}/sessions. 无支持的保护路线返回403;赠款以外的资源返回404。 客户代币不能薄荷代币. 取消或到期 mintting API 键块后续客户端所请求 .
客户端调试消息读取隐藏系统消息,内部事件,提醒,工具结果,以及工具调用. 它们使用现有的组织费率限额。 流出 token_expiring 30秒前就结束了 token_expired 并关闭在过期。 从您的后端请求新代号并重新连接 。 通过 pagized 消息读取并合并了消息 ID; 流不提供光标重放 .
服务器配置:客户端符使用已存在的 ENCRYPTION_KEY (32 UTF-8 字节),由 HKDF-SHA256 生成单独的密钥用于 happyrobot/client-access-token/v1不需要额外的秘密或数据库迁移。 缺失的密钥会禁用以 503 计时; 无效的密钥失败启动 。 旋转 ENCRYPTION_KEY 取消现有的客户端符并影响存储的证书加密.
聊天( C)client.chat + 键 HappyRobotChatClient(中文(简体) )
构建自定义聊天 UI 由您的工作流程驱动 。 使用两级认证模型:
- 您的服务器 使用 API 密钥创建范围化客户端令牌( 保密)
- 您的浏览器 用途
HappyRobotChatClient所有聊天操作都使用此符号
服务器侧: 创建客户端符号
// --- YOUR SERVER (e.g. Next.js API route, Express handler) ---
import { HappyRobotClient } from "@happyrobot-ai/sdk";
const client = new HappyRobotClient({ apiKey: process.env.HAPPYROBOT_API_KEY });
app.post("/api/chat-token", async (req, res) => {
const { token, expires_at } = await client.chat.createToken({
workflow_id: "your-workflow-id",
// Optional. Token lifetime in seconds. Default 3600 (1 hour), min 60, max 86400.
// ttl_seconds: 1800,
});
res.json({ token, expires_at });
});
浏览器边 : HappyRobotChatClient
// --- YOUR BROWSER CODE (React, Vue, vanilla JS, etc.) ---
import { HappyRobotChatClient } from "@happyrobot-ai/sdk";
// 1. Get a client token from your server
const { token } = await fetch("/api/chat-token", { method: "POST" }).then((r) =>
r.json()
);
// 2. Initialize the browser-side client
const chat = new HappyRobotChatClient({ token });
// 3. Create a session
const { session_id } = await chat.createSession();
// 4. Connect bidirectional WebSocket
const connection = chat.connect(session_id, {
onResponseStart: () => {
// Show typing indicator
},
onResponseChunk: (content) => {
// Append streamed text to the UI
},
onResponseEnd: (content) => {
// Full response complete — hide typing indicator
},
onSessionClosed: (event) => {
// Session ended: event.status, event.reason, event.duration
},
// Auto-refresh: ~30s before the token expires the SDK calls this and
// forwards the result over the WebSocket. The connection stays open.
getToken: async () => {
const { token } = await fetch("/api/chat-token", { method: "POST" }).then(
(r) => r.json()
);
return token;
},
onTokenExpired: () => {
// Backstop: only fires if no valid refresh arrived in time
// (e.g. getToken not provided, network failure). Reconnect from scratch.
},
});
// 5. Send messages through the WebSocket
const ack = await connection.sendMessage({ content: "Hello!" });
console.log(ack.message.id); // server-assigned message ID
// 6. Send messages with file attachments
const artifact = await chat.uploadFile(fileBlob, "photo.png", "image/png");
await connection.sendMessage({
content: "Here's the photo",
artifacts: [artifact],
});
// 7. Get history (page reload, reconnect)
const { messages } = await chat.getHistory(session_id);
// 8. Clean up
connection.close();
浏览器侧: 文件上传
// Option A: Use the convenience method (handles all 3 steps)
const artifact = await chat.uploadFile(fileBlob, "photo.png", "image/png");
await connection.sendMessage({
content: "Here's the photo",
artifacts: [artifact],
});
// Option B: Manual 3-step flow for more control
const upload = await chat.getPresignedUpload({
filename: "photo.png",
mime_type: "image/png",
});
await fetch(upload.upload_url, {
method: "PUT",
body: fileBlob,
headers: { "Content-Type": "image/png" },
});
await chat.completeUpload({
artifact_id: upload.artifact_id,
s3_uri: upload.s3_uri,
filename: "photo.png",
mime_type: "image/png",
size_bytes: fileBlob.size,
});
await connection.sendMessage({
content: "Here's the photo",
artifacts: [
{
media_id: upload.artifact_id,
mime_type: "image/png",
filename: "photo.png",
size_bytes: fileBlob.size,
},
],
});
HappyRobotClient (服务器侧)
| 方法 | 说明 |
|---|---|
client.chat.createToken({ workflow_id, env?, ttl_seconds? }) | 创建范围化客户端符 . ttl_seconds 默认为3600(1小时). |
HappyRobotChatClient (浏览器侧)
| 方法 | 说明 |
|---|---|
chat.createSession() | 创建新聊天会话 |
chat.connect(sessionId, handlers) | 打开双向 WebSocket — 返回 ChatConnection |
chat.sendMessage(sessionId, { content, artifacts? }) | 通过 HTTP 发送用户消息( 如果 WS 无法使用 ) |
chat.getHistory(sessionId) | 获取消息历史 |
chat.uploadFile(file, filename, mimeType) | 上传文件( 召集方式) |
chat.getPresignedUpload({ filename, mime_type }) | 获取预签名的 S3 上传 URL |
chat.completeUpload({ artifact_id, s3_uri, ... }) | 上载文物的注册 |
ChatConnection
| 方法 | 说明 |
|---|---|
connection.sendMessage({ content, artifacts? }) | 通过 WebSocket 发送消息 。 回返a Promise 解决与服务器相撞的问题 |
connection.close() | 关闭 WebSocket 连接 |
connection.ws | 基础 WebSocket 实例 |
WebSocket 事件
服务器 – 客户端 :
| 活动 | 字段 | 说明 |
|---|---|---|
connected | session_id | 已建立连接 |
response-start | content | AI开始生成回应 |
response-chunk | content | 部分答复案文 |
response-end | content | 完整答复案文 |
session-closed | session_id, (中文(简体) ), status, (中文(简体) ), reason, (中文(简体) ), duration, (中文(简体) ), timestamp | 结束会话 |
token-refresh-required | —— 说 | 输出前发送~30s. SDK 当 getToken 提供 |
token-refresh-ack | expires_at | 服务器接受刷新后的指示符; 连接寿命延长 |
token-refresh-error | error | 刷新令牌无效或匹配范围; 以前的令牌仍然有效 |
token-expired | —— 说 | 备份站: 没有有效的刷新令牌已过期, 连接正在关闭 |
message-ack | id, (中文(简体) ), message | 服务器确认信件已发送 |
message-error | id, (中文(简体) ), error | 服务器发送消息失败 |
heartbeat | —— 说 | 保持存活(每15个) |
客户端 – 服务器 :
| 活动 | 字段 | 说明 |
|---|---|---|
message | content, (中文(简体) ), artifacts?, (中文(简体) ), id? | 发送用户信息 . id 以相干/反射方式反射 |
token-refresh | token | 为扩展连接提供新标志 。 由 SDK 自动发送 getToken 设定 |
托肯刷新
托肯斯寿命有限(默认为1小时,可通过 ttl_seconds 打开 createToken) (中文(简体) ). 为了在不迫使客户端重新连接的情况下保持长寿连接,SDK支持波段更新:
- ~30s 在活动符号到期前,服务器发送
token-refresh-required。 。 。 . - SDK打电话给你
getToken处理器从您的后端取出新的符号 . - SDK发送
{ type: "token-refresh", token }在WebSocket的上空. - 服务器验证新符号( 镜片必须匹配 :
workflow_id, (中文(简体) ),org, (中文(简体) ),env)和答复token-refresh-ack。 。 。 .onTokenRefreshed(expiresAt)向客户开火. - 如果没有有效的刷新通过exp到达, 服务器发送
token-expired并关闭连接——onTokenExpired发射作为后卫.
如果你不提供 getToken,刷新被跳过,连接将关闭于 exp (遗产行为). 当同一同物在多个并发连接中共享时,每个连接会独立地刷新——在第一次刷新后它们会分到每个接通的符号.
语音( N)client.voice + 键 HappyRobotVoiceClient(中文(简体) )
用您工作流程所驱动的 AI 代理来构建浏览器侧语音调用 。 使用与聊天相同的双层认证模型 :
- 您的服务器 使用 API 密钥创建范围 LiveKit 令牌( 保密)
- 您的浏览器 用途
HappyRobotVoiceClient与该符号通过 WebRTC 连接
服务器侧: 创建语音符号
// --- YOUR SERVER (e.g. Next.js API route, Express handler) ---
import { HappyRobotClient } from "@happyrobot-ai/sdk";
const client = new HappyRobotClient({ apiKey: process.env.HAPPYROBOT_API_KEY });
app.post("/api/voice-token", async (req, res) => {
const result = await client.voice.createToken({
workflow_id: "your-workflow-id",
data: { customer_name: "John" }, // optional — passed to the agent
// Optional. LiveKit token lifetime in seconds.
// Default 21600 (6 hours), min 60, max 86400 (24 hours).
// LiveKit does not refresh tokens on an active call.
// ttl_seconds: 3600,
});
res.json(result); // { url, token, room_name, run_id }
});
app.post("/api/live-session/:sessionId/listen-token", async (req, res) => {
const result = await client.voice.createToken({
session_id: req.params.sessionId,
});
res.json(result); // Hidden, subscribe-only observer token
});
浏览器边 : HappyRobotVoiceClient
// --- YOUR BROWSER CODE (React, Vue, vanilla JS, etc.) ---
import { HappyRobotVoiceClient } from "@happyrobot-ai/sdk/voice";
// 1. Get a voice token from your server
const { url, token } = await fetch("/api/voice-token", { method: "POST" }).then(
(r) => r.json()
);
// 2. Create the voice client and connect
const voice = new HappyRobotVoiceClient({ url, token });
const connection = await voice.connect({
onConnected: () => {
// Call started — microphone is automatically enabled
},
onAgentConnected: (participant) => {
// AI agent joined the room
console.log("Agent:", participant.identity);
},
onDisconnected: (reason) => {
// Call ended
},
onReconnecting: () => {
// Connection temporarily lost
},
onReconnected: () => {
// Successfully reconnected
},
onError: (error) => {
console.error("Voice error:", error);
},
});
// 3. Mute / unmute
await connection.mute();
console.log(connection.isMuted()); // true
await connection.unmute();
// 4. End the call
await connection.disconnect();
在不发表音频或影响AI的情况下听现有电话
代理,创建一个符号 session_id 和使用情况 listen() 在浏览器中 :
const { url, token } = await fetch(
`/api/live-session/${sessionId}/listen-token`,
{ method: "POST" }
).then((r) => r.json());
const voice = new HappyRobotVoiceClient({ url, token });
const listener = await voice.listen();
// If the browser later blocks playback, call this from a click handler:
await listener.startAudio();
// Stop listening without affecting the call:
await listener.disconnect();
设定 should_takeover: true 创建会话符号以保留
已有的收购行为,这就将AI代理从呼叫中移除.
HappyRobotClient (服务器侧)
列出当前工作空间组中可用的声音 。 使用一个 所有口音的语言前缀,或特定位置结果的语言:
const voices = await client.voice.list({ language: "en-GB" });
for (const voice of voices) {
console.log(voice.id, voice.name, voice.locales);
}
voice.id 是工作流程中使用的值 agent.voices 配置 .
| 方法 | 说明 |
|---|---|
client.voice.list({ language? }) | 列出当前工作空间可用的声音 . language 接受前缀如 en 或诸如 en-GB。 。 。 . |
client.voice.createToken({ workflow_id, data?, env?, ttl_seconds? }) | 为新语音调用创建 LiveKit 令牌 . |
client.voice.createToken({ session_id, should_takeover?, ttl_seconds? }) | 观察现场直播 或何时接手 should_takeover 这是真的. |
HappyRobotVoiceClient (浏览器侧)
| 方法 | 说明 |
|---|---|
new HappyRobotVoiceClient({ url, token }) | 用 LiveKit 证书创建客户端 |
voice.connect(handlers?) | 连接和启用麦克风——返回 VoiceConnection |
voice.listen(handlers?) | 无麦克风访问或发布连接——返回 VoiceListenerConnection |
VoiceConnection
| 方法 | 说明 |
|---|---|
connection.disconnect() | 结束电话和与房间的断线 |
connection.mute() | 关掉本地的麦克风 |
connection.unmute() | 解开当地的麦克风 |
connection.isMuted() | 检查哑声状态 |
connection.room | 隐藏 LiveKit Room 例如先进使用案例 |
VoiceListenerConnection
| 方法 | 说明 |
|---|---|
listener.disconnect() | 停止听而不影响电话 |
listener.startAudio() | 从浏览器用户手势中恢复音频播放 |
listener.room | 隐藏 LiveKit Room 例如先进使用案例 |
会议室活动
| 处理器 | 说明 |
|---|---|
onConnected | 连接到 LiveKit 房间 |
onDisconnected | 与房间断接 |
onAgentConnected | AI代理参与者加入了房间 |
onTrackSubscribed | 远程音频音轨订阅( 自动播放) |
onTrackUnsubscribed | 远程音频音轨未订阅 |
onReconnecting | 连接暂时丢失——试图重接 |
onReconnected | 成功重新连接 |
onError | 发生了错误 |
倾斜
列出被粘接返回的方法a PaginatedResponse<T>数字 :
interface PaginatedResponse<T> {
data: T[];
pagination: {
page: number;
page_size: number;
total_pages: number;
total_records: number;
has_next_page: boolean;
has_previous_page: boolean;
};
}
用于支助的资源 listAll(),使用同位素生成器自动将所有页面删除:
for await (const workflow of client.workflows.listAll({ folder_id: "..." })) {
console.log(workflow.name);
}
处理错误
import {
ApiError,
AuthenticationError,
NotFoundError,
} from "@happyrobot-ai/sdk";
try {
const wf = await client.workflows.get("nonexistent");
} catch (err) {
if (err instanceof NotFoundError) {
console.log("Workflow not found");
} else if (err instanceof AuthenticationError) {
console.log("Invalid API key");
} else if (err instanceof ApiError) {
console.log(err.status, err.message);
}
}
共用测试套房
使用 client.testSuites 用于工作流程范围自定义/情景集. create 接受共享 useCaseId, (中文(简体) ), name, (中文(简体) ), origin, (中文(简体) ), generationConfig, (中文(简体) ), coverageScope, (中文(简体) ), folderId,以及 members 字段。 成员变动保留了定义和历史.
const { suite } = await client.testSuites.create({
useCaseId: "workflow-id",
name: "Booking regression",
members: [{ kind: "custom", id: "test-id" }],
});
await client.testSuites.membership(suite.id, {
members: [{ kind: "e2e", id: "scenario-id" }],
});
const { suite_run_id } = await client.testSuites.run(suite.id, "version-id");
const { run, results } = await client.testSuites.results(suite_run_id);
await client.testSuites.delete(suite.id);
AI 世代运行一次从 generationConfig 混凝土版本通过 generate(suiteId, versionId)。成功后,手工编辑定义和成员。 套接字覆盖制指导生成,不凌驾于现有的测试分级.