本文档说明如何在本地开发环境中调试智能体(Agent)。通过启用调试模式,可以将智能体的 API 请求转发到本地开发服务器,方便进行本地开发和调试。
在创建智能体实例时,传入
import { cloud } from '@xhs/mp-core-api/cloud'
const agent = cloud.AI.createAgent({
agentId: 'your-agent-id',
env: 'development',
version: '0.1.0',
// 启用调试模式
debuggerInfo: {
serverUrl: 'localhost:3000' // 本地开发服务器地址
}
})
确保本地开发服务器正在运行,并且支持以下 API 路径:
启用调试模式后,所有 API 调用会自动转发到本地服务器:
// 发送消息
const response = agent.sendMessage({
msg: 'Hello, AI!',
history: [],
stream: true
})
// 获取会话列表
const conversations = await agent.getConversations()
// 获取历史消息
const messages = await agent.getHistoryMessages({
conversation_id: 'conv-123',
cursor: 0,
count: 20
})
// 查询任务
const taskResult = await agent.queryTasks({
taskId: 'task-123'
})
参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
serverUrl | string | 是 | 本地开发服务器地址,支持格式: - localhost:3000 - 127.0.0.1:3000 - http://localhost:3000 - http://127.0.0.1:3000 |
const agent = cloud.AI.createAgent({
// 智能体 ID(必填)
agentId: 'demo-agent',
// 环境配置(调试模式下可选,默认使用 development)
env: 'development',
// 版本号(调试模式下可选,默认使用 latest)
version: '0.1.0',
// 调试模式配置
debuggerInfo: {
serverUrl: 'localhost:3000'
}
})
调试模式下,API 路径会自动从线上格式转换为本地格式:
线上模式:
https://gateway.xiaohongshu.com/v1/agent/{agentId}/chat
调试模式:
http://localhost:3000/v1/aiagent/agents/{agentId}/send-message
调试模式下会自动跳过 accessToken 的获取和验证,方便本地开发:
系统会自动验证
✅ 允许的格式:
❌ 不允许的格式:
启用调试模式后,控制台会输出调试信息:
🔧 当前处于调试模式 📡 调试服务器地址: localhost:3000 ✅ 调试模式验证通过
import { cloud } from '@xhs/mp-core-api/cloud'
// 创建调试模式的智能体
const agent = cloud.AI.createAgent({
agentId: 'my-test-agent',
debuggerInfo: {
serverUrl: 'localhost:3000'
}
})
// 发送消息
const response = agent.sendMessage({
msg: '测试消息',
history: [],
stream: true
})
response.onMessage((chunk) => {
console.log('收到消息片段:', chunk)
})
response.onSuccess((result) => {
console.log('消息发送成功:', result)
})
response.onError((error) => {
console.error('消息发送失败:', error)
})
const agent = cloud.AI.createAgent({
agentId: 'my-agent',
env: 'development',
version: '0.2.0',
debuggerInfo: {
serverUrl: '127.0.0.1:8080'
}
})
// 根据环境变量决定是否启用调试模式
const isDevelopment = process.env.NODE_ENV === 'development'
const agent = cloud.AI.createAgent({
agentId: 'my-agent',
env: 'development',
version: '0.1.0',
...(isDevelopment && {
debuggerInfo: {
serverUrl: 'localhost:3000'
}
})
})
如果配置错误,会抛出相应的错误:
try {
const agent = cloud.AI.createAgent({
agentId: 'my-agent',
debuggerInfo: {
serverUrl: 'example.com:3000' // 非 localhost 地址
}
})
} catch (error) {
// 错误: `createAgent` failed, `debuggerInfo.serverUrl` must be a localhost address
console.error(error.message)
}
A: 这是安全限制,确保调试模式只能访问本地服务器,防止误配置导致请求发送到外部服务器。
A: 由于安全限制,系统只允许 localhost 地址。真机调试时,建议:
A: 调试模式下会自动跳过 token 的获取和验证,本地服务器应该自行处理认证逻辑。
A: 可以通过