跳到主要内容

快速开始

五分钟跑通:安装 SDK、拿到 API Key、和你的 Agent 完成第一次对话,再试试流式输出和多轮对话。 本页用个人 API Key 在 Node.js 里运行;要把聊天放进网页,做完这页后看 React 组件。

1. 安装​

mkdir openhex-demo && cd openhex-demo
npm init -y
npm install @openhex-ai/agent-sdk
npm install -D tsx

需要 Node.js 18 或更高版本。

2. 准备 API Key 和 Agent​

  1. 打开 app.openhex.tech,进入 设置 → API Key,创建一个个人 API Key(形如 mysta_…)。它只显示一次,立刻保存。
  2. 在首页点开要调用的 Agent,浏览器地址栏里 /console/ 后面那段 UUID 就是它的 Agent ID(也可以用接口列出,见获取 Agent ID)。

把 Key 放进环境变量:

export OPENHEX_API_KEY=mysta_...
export OPENHEX_AGENT_ID=你的-agent-id

个人 API Key 等同于你的账号权限,只放在本地或后端,不要提交到代码仓库,也不要放进网页。

3. 第一次对话​

新建 chat.ts:

import { OpenhexClient } from '@openhex-ai/agent-sdk';

const client = new OpenhexClient({ agentId: process.env.OPENHEX_AGENT_ID }); // apiKey 从 OPENHEX_API_KEY 读取

const turn = await client.sendMessage('你好,用一句话介绍你自己。');

console.log('回复:', turn.text);
console.log('对话 id:', turn.conversationId);
console.log('用到的工具:', turn.toolCalls.map(t => t.name));

运行:

npx tsx chat.ts

对话的第一条消息会为 Agent 拉起运行环境,可能要十几秒才有回复。SDK 默认最多等 180 秒,不需要额外处理。

4. 流式输出​

把回复逐字打印出来:

import { OpenhexClient, extractText, isTurnComplete } from '@openhex-ai/agent-sdk';

const client = new OpenhexClient({ agentId: process.env.OPENHEX_AGENT_ID });

for await (const record of client.runTurn('写一首关于秋天的四行诗')) {
if (record.sender === 'assistant' || record.sender === 'agent') {
process.stdout.write(extractText(record));
}
if (isTurnComplete(record)) console.log();
}

5. 多轮对话​

conversation() 记住对话 id,后续消息自动带上上下文:

const convo = client.conversation();

await convo.send('记住:我的项目叫 Orbit。');
const reply = await convo.send('我的项目叫什么?');

console.log(reply.text); // → Orbit

6. 处理错误​

import { ApiError } from '@openhex-ai/agent-sdk';

try {
await client.sendMessage('你好');
} catch (err) {
if (err instanceof ApiError) {
console.error(`请求失败 ${err.status}: ${err.message}`); // 401 = Key 不对或已失效
} else {
throw err;
}
}

下一步​