最佳实践
本指南总结 OpenHuman 的使用最佳实践,帮助您构建可靠的 agent 工作流。
项目结构
openhuman-project/
├── src/
│ ├── agents/ # Agent 定义
│ ├── tools/ # 自定义工具
│ ├── chains/ # 链式调用
│ └── utils/ # 工具函数
├── memory_tree/ # SQLite 记忆库
├── wiki/ # Obsidian Markdown
├── tests/ # 测试
├── .env # 环境变量
└── package.json
环境变量管理
# .env.example(提交到版本控制)
OPENHUMAN_API_KEY=
OPENHUMAN_BASE_URL=https://api.tinyhumans.ai
# .env(不提交)
OPENHUMAN_API_KEY=sk_xxx
在 .gitignore 中添加:
.env
.env.local
memory_tree/
wiki/
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;
输入验证
function validateInput(input) {
if (typeof input !== 'string') {
throw new Error('输入必须是字符串');
}
if (input.length > 10000) {
throw new Error('输入过长');
}
return input.replace(/[<>]/g, '');
}
记忆管理
主动存储重要信息
// 存储重要信息到记忆树
await client.memory.store({
content: '用户偏好深色主题',
source: 'user_preference',
tags: ['preference', 'ui'],
});
利用 recall 检索
// 查询相关记忆
const memories = await client.memory.recall({
query: '用户的 UI 偏好',
scope: 'user_preference',
});
监控和日志
结构化日志
console.log(JSON.stringify({
level: 'info',
message: 'Agent 运行完成',
agentId: agent.id,
duration: 123,
timestamp: new Date().toISOString(),
}));
关键指标
- 请求成功率
- 平均响应时间
- Token 使用量
- API 调用次数