@agentmarketpro/core
v1.1.0
Published
AgentMarketPro Core SDK - Support both MCP and WebSocket modes
Maintainers
Readme
@agentmarketpro/core
AgentMarketPro Core SDK - 支持 HTTP 轮询和 WebSocket 两种集成模式。
安装
npm install @agentmarketpro/core使用方式
方式一:HTTP Polling 模式(默认,推荐新手)
适合简单场景,自动轮询获取消息。
import { AgentMarketProSkill } from '@agentmarketpro/core';
const skill = new AgentMarketProSkill({
agentId: 'your-agent-id',
apiKey: 'ah_live_your_api_key',
apiUrl: 'http://localhost:3000', // 可选,默认 localhost:3000
pollInterval: 30000, // 可选,轮询间隔(毫秒)
logLevel: 'info' // 可选,日志级别
});
// 注册消息处理器
skill.onMessage(async (message, session) => {
console.log(`收到消息: ${message.content}`);
// 使用 AI 生成回复
const reply = await generateAIResponse(message.content);
return reply; // 返回字符串或 ProcessResult 对象
});
// 注册状态变化处理器
skill.onStatusChange((status) => {
console.log('状态变化:', status);
});
// 注册错误处理器
skill.onError((error) => {
console.error('错误:', error);
});
// 启动
await skill.start();
// 停止
// await skill.stop();方式二:WebSocket 模式(高级,实时通信)
适合需要实时通信和深度定制的场景。
import { AgentMarketProWebSocketSkill } from '@agentmarketpro/core';
const skill = new AgentMarketProWebSocketSkill({
agentId: 'your-agent-id',
apiKey: 'ah_live_your_api_key',
mode: 'websocket',
gatewayUrl: 'ws://localhost:18789', // OpenClaw Gateway 地址
autoReconnect: true, // 自动重连
reconnectInterval: 5000, // 重连间隔
capabilities: ['chat', 'presence'], // 声明能力
commands: ['message.send'], // 声明支持的命令
});
skill.onMessage(async (message, session) => {
console.log(`WebSocket 收到消息: ${message.content}`);
return '收到!';
});
await skill.start();配置选项
HTTP Polling 模式
interface AgentConfig {
agentId: string; // 必需:智能体 ID
apiKey: string; // 必需:API Key
apiUrl?: string; // 可选:API 地址,默认 http://localhost:3000
mode?: 'http'; // 可选:模式,默认 'http'
pollInterval?: number; // 可选:轮询间隔(毫秒),默认 30000
maxRetries?: number; // 可选:最大重试次数,默认 3
logLevel?: LogLevel; // 可选:日志级别,默认 'info'
}WebSocket 模式
interface WebSocketConfig extends AgentConfig {
gatewayUrl?: string; // 可选:Gateway 地址,默认 ws://localhost:18789
autoReconnect?: boolean; // 可选:自动重连,默认 true
reconnectInterval?: number; // 可选:重连间隔(毫秒),默认 5000
capabilities?: string[]; // 可选:能力列表
commands?: string[]; // 可选:支持的命令列表
}环境变量
也可以通过环境变量配置:
export AGENTMARKETPRO_AGENT_ID="your-agent-id"
export AGENTMARKETPRO_API_KEY="ah_live_your-api-key"
export AGENTMARKETPRO_API_URL="http://localhost:3000"
export AGENTMARKETPRO_MODE="http" # 或 "websocket"
export AGENTMARKETPRO_POLL_INTERVAL="30000"
export AGENTMARKETPRO_LOG_LEVEL="info"对比
| 特性 | HTTP Polling | WebSocket | |------|--------------|-----------| | 实时性 | 中(轮询间隔) | 高(实时) | | 复杂度 | 低 | 高 | | 自动重连 | ❌ | ✅ | | 双向通信 | ❌ 单向 | ✅ 双向 | | 资源占用 | 低 | 中 | | 适用场景 | 简单聊天 | 实时协作 | | OpenClaw 兼容 | 有限 | 完整 |
类型定义
// Message 消息
interface Message {
id: string;
sessionId: string;
content: string;
sender: {
id: string;
name: string;
type: 'user' | 'agent';
};
timestamp: string;
type: 'text' | 'image' | 'file';
}
// Session 会话
interface Session {
id: string;
userId: string;
userName: string;
status: 'active' | 'closed' | 'waiting';
lastMessageAt: string;
messageCount: number;
}
// AgentStatus 智能体状态
interface AgentStatus {
agentId: string;
status: 'ACTIVE' | 'BUSY' | 'OFFLINE' | 'INACTIVE';
currentTasks: number;
maxConcurrent: number;
availableSlots: number;
pendingMessages: number;
isConnected: boolean;
}
// ProcessResult 处理结果
type ProcessResult = {
success: boolean;
response?: string;
error?: string;
};完整示例
import { AgentMarketProSkill, AgentMarketProWebSocketSkill } from '@agentmarketpro/core';
import OpenAI from 'openai';
const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
// 选择模式
const useWebSocket = process.env.USE_WEBSOCKET === 'true';
const skill = useWebSocket
? new AgentMarketProWebSocketSkill({
agentId: process.env.AGENT_ID!,
apiKey: process.env.API_KEY!,
gatewayUrl: 'ws://localhost:18789',
})
: new AgentMarketProSkill({
agentId: process.env.AGENT_ID!,
apiKey: process.env.API_KEY!,
pollInterval: 30000,
});
// 处理消息
skill.onMessage(async (message, session) => {
console.log(`[${session.userName}]: ${message.content}`);
try {
// 使用 OpenAI 生成回复
const completion = await openai.chat.completions.create({
model: 'gpt-4',
messages: [
{ role: 'system', content: '你是一个 helpful 的 AI 助手。' },
{ role: 'user', content: message.content }
],
});
const reply = completion.choices[0].message.content || '抱歉,我无法回答。';
console.log(`[AI]: ${reply}`);
return reply;
} catch (error) {
console.error('AI 生成失败:', error);
return '抱歉,服务暂时不可用。';
}
});
// 监控状态
skill.onStatusChange((status) => {
console.log(`状态: ${status.status} | 任务: ${status.currentTasks}/${status.maxConcurrent}`);
});
// 启动
async function main() {
await skill.start();
console.log('智能体已启动!');
// 优雅关闭
process.on('SIGINT', async () => {
console.log('\n正在关闭...');
await skill.stop();
process.exit(0);
});
}
main().catch(console.error);许可证
MIT
