跳到主要内容

最佳实践

本文档介绍 OpenHuman 使用的最佳实践。

开发规范

项目结构

my-openhuman-project/
├── src/
│ ├── agents/ # Agent 定义
│ ├── tools/ # 自定义工具
│ ├── chains/ # 链式调用
│ └── utils/ # 工具函数
├── tests/ # 测试文件
├── docs/ # 文档
├── .env # 环境变量
└── package.json

代码规范

使用 ESLint 和 Prettier:

npm install --save-dev eslint prettier

环境变量管理

# .env.example(提交到版本控制)
OPENHUMAN_API_KEY=
OPENHUMAN_BASE_URL=https://api.openhuman.ai

# .env(不提交)
OPENHUMAN_API_KEY=sk_xxx
OPENHUMAN_BASE_URL=https://api.openhuman.ai

.gitignore 中添加:

.env
.env.local

Agent 设计

清晰的指令

await client.agents.create({
instructions: `
你是一个专业的技术文档助手。

职责:
1. 回答用户关于 OpenHuman 的问题
2. 提供准确、简洁的技术解释
3. 在适当时候给出代码示例

限制:
1. 不提供任何违法建议
2. 不透露敏感信息
3. 不重复已知信息
`,
});

适当的工具选择

await client.agents.create({
// 只使用必要的工具
tools: ['web-search', 'calculator'],
// 避免添加不相关的工具
});

性能优化

批量处理

// 不好:逐个处理
for (const item of items) {
await processItem(item);
}

// 好:批量处理
const batchSize = 10;
for (let i = 0; i < items.length; i += batchSize) {
const batch = items.slice(i, i + batchSize);
await Promise.all(batch.map(processItem));
}

缓存结果

const cache = new Map();

async function getOrCreate(key, factory) {
if (!cache.has(key)) {
cache.set(key, await factory());
}
return cache.get(key);
}

流式响应

// 处理大量数据时使用流式
const stream = await client.agents.runStream(agent.id, {
message: '生成一份长报告',
});

let fullResponse = '';
for await (const chunk of stream) {
process.stdout.write(chunk.delta);
fullResponse += chunk.delta;
}

错误处理

完整的错误处理

try {
const response = await client.agents.run(agent.id, {
message: '用户输入',
});
} catch (error) {
if (error.code === 'rate_limit') {
// 处理速率限制
await sleep(60000);
return retry();
} else if (error.code === 'invalid_api_key') {
// 处理认证错误
console.error('API 密钥无效');
} else {
// 其他错误
console.error('未知错误:', error);
}
}

重试机制

async function withRetry(fn, maxRetries = 3) {
for (let i = 0; i < maxRetries; i++) {
try {
return await fn();
} catch (error) {
if (i === maxRetries - 1) throw error;
await sleep(Math.pow(2, i) * 1000);
}
}
}

安全实践

保护 API 密钥

// 不好:在代码中硬编码
const apiKey = 'sk_xxx';

// 好:使用环境变量
const apiKey = process.env.OPENHUMAN_API_KEY;

// 更好:使用密钥管理服务
const apiKey = await keyManager.getSecret('openhuman-api-key');

输入验证

function validateInput(input) {
if (typeof input !== 'string') {
throw new Error('输入必须是字符串');
}
if (input.length > 10000) {
throw new Error('输入过长');
}
// 清理特殊字符
return input.replace(/[<>]/g, '');
}

限制输出

await client.agents.create({
instructions: `
回答应该简洁明了。
最多使用 500 个字符。
禁止生成超过指定长度。
`,
});

监控和日志

结构化日志

console.log(JSON.stringify({
level: 'info',
message: 'Agent 运行完成',
agentId: agent.id,
duration: 123,
timestamp: new Date().toISOString(),
}));

关键指标

  • 请求成功率
  • 平均响应时间
  • Token 使用量
  • API 调用次数

测试

单元测试

// tests/agent.test.js
describe('Agent', () => {
it('应该正确创建', async () => {
const agent = await client.agents.create({
name: '测试 Agent',
instructions: '测试',
});
expect(agent.id).toBeDefined();
});

it('应该正确响应', async () => {
const response = await client.agents.run(agent.id, {
message: '你好',
});
expect(response.message).toBeDefined();
});
});

下一步