跳到主要内容

API 参考

本页列出 @openhex-ai/agent-sdk 对话部分的全部公开方法、事件辅助函数与导出。 工作区相关的方法见工作区方法参考,React 组件的属性见 React 组件。

所有方法最后一个参数都接受 { signal?: AbortSignal },下文不再重复。所有 HTTP 路由都在 /api/v2 之下。

包的入口​

入口内容
@openhex-ai/agent-sdk客户端、事件辅助函数、错误类型、全部 TypeScript 类型
@openhex-ai/agent-sdk/reactChatWidget、ChatBox、useOpenhexChat 及卡片组件

OpenhexClient​

const client = new OpenhexClient(config?: OpenhexClientConfig);

配置​

字段类型默认值说明
apiKeystringOPENHEX_API_KEY个人 API Key、工作区 API Key 或会话令牌,见鉴权
baseUrlstringhttps://api.openhex.tech平台 API 地址
agentIdstring—新对话默认路由到的 Agent;training() 的默认 Agent。获取方式见获取 Agent ID;SDK 不读 OPENHEX_AGENT_ID,需显式传入
timeoutMsnumber30000非流式请求超时
mcpTokensRecord<string,string> | () => …—每次发送都带上的会话级 MCP 凭据,见接入外部工具
fetchtypeof fetch全局 fetch自定义 fetch
loginTypestring—附加 X-Login-Type 请求头(仅登录态 JWT 相关)
actAsstring—附加 X-Act-As 请求头,以自己拥有的服务账号身份调用

属性与方法​

成员说明
sendMessage(message, opts?) → Promise<AgentTurn>发送并等待本轮结束
runTurn(message, opts?) → AsyncGenerator<ChatStreamRecord>发送并流式产出本轮记录
conversation(opts?) → Conversation记住对话 id 的句柄
training(agentId?) → TrainingChat训练模式,见训练模式
workspace(slug) → Workspace绑定 slug 的工作区句柄,见工作区方法参考
chatAgentChatClient,协议原语
filesFilesClient,上传与读取文件
paymentsPaymentsClient,查询收款订单
workspacesWorkspaceClient,以 slug 为参数的工作区方法

sendMessage / runTurn 的选项:

选项说明
conversationId延续这段对话;不传则新建或续上最近的对话
targetAgentIds新对话路由到的 Agent,默认 [config.agentId]
parts附件部件,见附件
mcpTokens本轮的 MCP 凭据,优先于客户端配置
idleTimeoutMs连续多久无事件判定超时,默认 180000
signal取消等待

conversation() 的选项:conversationId、targetAgentIds、mcpTokens。

AgentTurn​

字段类型说明
conversationIdstring对话 id
textstring本轮回复文本
toolCalls{ id?, name, input }[]本轮工具调用
recordsChatStreamRecord[]本轮全部记录
resultChatRawEvent?本轮结束事件
sessionIdstring | null会话 id
lastEventIdstring?最后一条记录的游标

Conversation​

成员说明
id对话 id,第一次发送后才有值
send(message, opts?) → Promise<AgentTurn>发送并等待本轮结束
stream(message, opts?) → AsyncGenerator<ChatStreamRecord>发送并流式产出本轮记录
interrupt() → Promise<InterruptResult>打断正在进行的一轮
submitConnectorSetup(setup, values, { notify? }) → Promise<AgentTurn | undefined>保存用户凭据;默认随后自动发一条消息让 Agent 重试

send / stream 的选项除上表外,还可以带 SendRequest 的字段(如 parts、metadata、senderName)。

AgentChatClient(client.chat)​

方法HTTP说明
send(req) → SendResultPOST /conversations/send发送消息,立即返回
stream(conversationId, opts?)GET /conversations/{id}/stream长连接记录流,断线自动重连
resumeTurn(conversationId, { lastEventId, idleTimeoutMs? })同上从游标读到本轮结束
runTurn(req, opts?) / sendMessage(req, opts?)同上用完整 SendRequest 发送的高层方法
conversation(opts?)—创建 Conversation
messages(conversationId) → { entries }GET /conversations/{id}/messages整段对话历史
history(conversationId, { before, turns?, maxEntries?, includeThinking? }) → { entries, hasMore }GET /conversations/{id}/history游标之前的历史分页
interrupt(conversationId) → InterruptResultPOST /conversations/{id}/interrupt打断正在进行的一轮
messageAudio(agentId, conversationId, messageId, opts?) → MessageAudioResultPOST /agents/{agentId}/messages/{messageId}/audio[/stream]朗读回复,见语音回复
submitConnectorCredentials(connectorTypeId, credentials)PUT /profile/credentials/{connectorTypeId}把 BYOK 凭据存到调用者自己的账户

SendRequest​

字段类型说明
messagestring消息文本
conversationIdstring?延续这段对话
targetAgentIdsstring[]?新对话的 Agent:1 个直接路由;多个由协调者分派
newConversationboolean?不带 conversationId 时强制新开对话,而不是续上最近的一段
partsMessagePart[]?附件:{ type: 'image_url', image_url: { url } } / { type: 'file', file: { filename, file_url } } / { type: 'text', text }
mcpTokensRecord<string,string>?会话级 MCP 凭据
metadataobject?附带给 Agent 的元数据(例如卡片的回答)
toolActionboolean?标记为卡片动作,送达 Agent 但不作为普通消息显示
senderName / senderAvatarstring?标注发送者

SendResult​

{ conversationId, userMessage?, userEventId?, results: [{ agentId, msgId, streamId }] }。userEventId 是这条消息在事件流中的游标,从它之后读就是这条消息的回复。

ChatStreamRecord​

字段说明
id游标,作为 lastEventId 续传
seq / timestamp / sessionId序号、时间、会话
senderuser / assistant / agent / system
eventmessage / agent_status / attachment / …
raw运行时事件,常见 type:user、assistant、result、agent_status、attachment、payment_gate、payment_gate_resolution

FilesClient(client.files)​

方法HTTP说明
upload(file, opts?) → UploadedFilePOST /files/upload上传,返回 { url, filename, size, mimeType, provider, nasPath?, agentPath? }
uploadPart(file, opts?) → MessagePart同上上传并返回可发送的部件;opts.as 强制类型
toPart(uploaded, as?) → MessagePart—把上传结果转成部件
readConversationFile(conversationId, path) → { content, encoding, mimeType }GET /conversations/{id}/files/read读取对话工作区里的文件
downloadConversationFile(conversationId, path) → BlobGET /conversations/{id}/files/download下载对话工作区里的文件

file 可以是 Blob / File,或 { data, filename, contentType? }。上传选项:agentId、chatGroupId、filename、contentType。

PaymentsClient(client.payments)​

方法HTTP说明
status(orderId) → { status, amountCny? }GET /payments/{orderId}/status订单状态:pending / paid / expired / canceled

TrainingChat(client.training())​

方法HTTP说明
send(message) → { ok, msgId? }POST /agents/{id}/dev/send发送训练消息
runTurn(message, opts?)发送后读 GET /agents/{id}/messages/stream流式产出这一轮
stream({ lastEventId?, turns?, reconnect? })GET /agents/{id}/messages/stream训练对话记录流
messages({ before? }) → { entries, hasMore? }GET /agents/{id}/messages/history训练对话历史
interrupt()POST /agents/{id}/dev/interrupt打断

事件辅助函数​

都接收一条 ChatStreamRecord:

函数返回说明
extractText(record)string回复文本(历史里的用户消息也能取到)
extractToolCalls(record){ id?, name, input }[]工具调用
isTurnComplete(record)boolean是否本轮结束
isInterrupt(record)boolean是否表示被打断
isAgentRecord(record)boolean是否来自 Agent
extractImages(record)string[]Agent 生成的图片 URL
extractFileAttachment(record)FileAttachment | nullAgent 产出的文件:{ name, workspacePath, mimeType?, size?, … }
extractDelegations(record) / isDelegationTool(name)Delegation[] / boolean委派,见子 Agent 与委派
extractPaymentGate(record) / isPaymentGate(record)PaymentGatePayload | null / boolean收款卡片
extractPaymentResolution(record){ orderId, status } | null付款结果
extractInfoCollect(record) / isInfoCollect(record)InfoCollectPayload | null / boolean信息收集卡片
infoCollectSubmitMetadata(values) / infoCollectSkipMetadata()object回应信息收集卡片时的 metadata
extractConnectorSetup(record) / isConnectorSetup(record)ConnectorSetupRequest[] / boolean连接器配置卡片

语音​

导出说明
MessageAudioCache(capacity = 10)按最近使用淘汰的音频缓存:get / set / clear / size
downloadMessageAudio(http, agentId, conversationId, messageId, opts?)chat.messageAudio 的底层函数

错误​

OpenhexSdkError(基类)、ApiError(status、body)、AuthenticationError、AbortError、NotImplementedError。见错误处理。

React 导出​

导出说明
ChatWidget / ChatBox / useOpenhexChat见 React 组件
InfoCollectCard / DEFAULT_INFO_COLLECT_LABELS信息收集卡片
PaymentGateCard / DEFAULT_PAYMENT_LABELS收款卡片
PLATFORM_TOKENS / tokenStyle(tokens)主题预设与把变量设在任意元素上的辅助函数
useInjectStyles(enabled) / CHAT_CSS注入内置样式表 / 样式表文本
Markdown组件内部使用的 Markdown 渲染

预留入口​

query()、HttpTransport、tool() / createSdkMcpServer()(@openhex-ai/agent-sdk/tools)、hookMatcher() 以及 OpenhexClient.listSessions / getSession / deleteSession 是为本地 Agent 循环预留的接口,当前调用会抛出 NotImplementedError。

下一步​