@cloudbase/agent-adapter-wx
v0.0.24
Published
WeChat adapter for AG-Kit - Forward LLM messages to WeChat platforms
Readme
@cloudbase/agent-adapter-wx
WeChat adapter for AG-Kit - Forward LLM messages to WeChat platforms
Features
✅ Multi-Platform Support: WeChat Mini Program, Official Account (Service/Subscription), Enterprise WeChat Customer Service
✅ Express Handler: Ready-to-use createWxMessageHandler for Express servers
✅ Agent Adapter: WeChatAgent wraps any AG-UI agent with WeChat integration
✅ CloudBase History: WeChatHistoryManager with CloudBase database storage
✅ Automatic Token Management: Built-in caching and refresh mechanism
✅ Type-Safe: Full TypeScript support
✅ Async/Sync Reply: Supports both sync HTTP response and async message sending
Installation
npm install @cloudbase/agent-adapter-wx
# or
pnpm add @cloudbase/agent-adapter-wxQuick Start
Express Server Handler
import express from "express";
import { createWxMessageHandler, WeChatAgent } from "@cloudbase/agent-adapter-wx";
const app = express();
app.use(express.json());
// Create handler with agent factory
const wxHandler = createWxMessageHandler(
async ({ request, options }) => {
const agent = new WeChatAgent({
agent: yourBaseAgent,
wechatConfig: {
platform: WeChatPlatform.SERVICE,
appId: process.env.WECHAT_APP_ID!,
appSecret: process.env.WECHAT_APP_SECRET!,
},
});
return { agent };
},
{ logger: console }
);
app.post("/wx/message", wxHandler);Direct Message Sending
import { WeChatSender, WeChatPlatform } from "@cloudbase/agent-adapter-wx";
const sender = new WeChatSender({
platform: WeChatPlatform.MINI_APP,
appId: "your-app-id",
appSecret: "your-app-secret",
});
await sender.send({
toUser: "user-openid",
message: {
content: "Hello from LLM!",
type: "text",
},
});Core Components
createWxMessageHandler
Express route handler for WeChat message webhook. Handles the complete message flow:
- Parse incoming WeChat message
- Validate message type (text/voice)
- Handle retry logic for unverified accounts (11-second rule)
- Process "继续" command for async replies
- Run agent and return response
import { createWxMessageHandler } from "@cloudbase/agent-adapter-wx";
const handler = createWxMessageHandler(createAgent, {
logger: console, // optional logger
});
app.post("/wx/callback", handler);Bot ID Resolution Priority:
SCF_FUNCTIONNAMEenvironment variable- Parsed from request URL via
utils.parseBotId() - Parsed from
HOSTNAMEenvironment variable - Fallback:
"agent-id"
WeChatAgent
Wraps any AG-UI AbstractAgent with WeChat-specific functionality:
import { WeChatAgent, WeChatPlatform, WeChatSendMode } from "@cloudbase/agent-adapter-wx";
const wechatAgent = new WeChatAgent({
agent: yourBaseAgent,
wechatConfig: {
platform: WeChatPlatform.SERVICE,
appId: "your-app-id",
appSecret: "your-app-secret",
sendMode: WeChatSendMode.AITOOLS, // or WeChatSendMode.LOCAL
},
recommendQuestions: ["Question 1", "Question 2"],
});WeChatHistoryManager
CloudBase database storage for chat history (singleton pattern):
import { WeChatHistoryManager } from "@cloudbase/agent-adapter-wx";
// Initialize (requires TCB_ENV or CLOUDBASE_ENV)
const historyManager = WeChatHistoryManager.getInstance({
envId: "your-cloudbase-env", // or set TCB_ENV env var
collectionName: "wx_chat_history", // default
botId: "your-bot-id",
});
// Save to history
await historyManager.saveToHistory({
messageId: "msg-123",
role: "user",
content: "Hello",
threadId: "conversation-id",
createdAt: Date.now(),
metadata: {
sender: "user-openid",
triggerSrc: "WXService",
},
});
// Get previous reply
const previous = await historyManager.getPreviousReply(
"conversation-id",
"msg-123"
);Usage Examples
Enterprise WeChat Customer Service
const sender = new WeChatSender({
platform: WeChatPlatform.CUSTOM_SERVICE,
appId: "your-corp-id",
appSecret: "your-corp-secret",
openKfId: "your-kf-id",
});
await sender.send({
toUser: "user-openid",
message: {
content: "Your AI assistant response",
type: "text",
},
msgId: "original-message-id",
});Batch Sending
const results = await sender.sendBatch([
{ toUser: "user1", message: { content: "Message 1", type: "text" } },
{ toUser: "user2", message: { content: "Message 2", type: "text" } },
]);API Reference
Types
WeChatPlatform
enum WeChatPlatform {
CUSTOM_SERVICE = "WXCustomerService", // 企业微信客服
MINI_APP = "WXMiniApp", // 微信小程序
SERVICE = "WXService", // 微信服务号
SUBSCRIPTION = "WXSubscription", // 微信订阅号
}WeChatSendMode
enum WeChatSendMode {
LOCAL = "local", // Use WeChatSender (local development)
AITOOLS = "aitools", // Use aitools SDK (cloud function)
}HistoryEntry
interface HistoryEntry {
id?: string;
messageId: string;
role: "user" | "assistant" | "system";
content?: string;
threadId: string;
createdAt: number;
botId?: string;
runId?: string;
needAsyncReply?: boolean;
status?: string;
type?: string;
metadata?: {
sender?: string;
triggerSrc?: string;
originMsg?: string;
replyTo?: string;
reply?: string;
image?: string;
recommendQuestions?: string[];
};
}WeChatSender Methods
send(options, originMsg?): Promise<WeChatAPIResponse>sendBatch(messages): Promise<WeChatAPIResponse[]>sendAsync(options, originMsg?): Promise<void>clearCache(): void
WeChatHistoryManager Methods
getInstance(config?): WeChatHistoryManager- Get singleton instancegetPreviousReply(threadId, messageId?): Promise<HistoryEntry | null>saveToHistory(record): Promise<void>updateContent(threadId, messageId, content): Promise<void>
Environment Variables
| Variable | Description |
|----------|-------------|
| TCB_ENV or CLOUDBASE_ENV | CloudBase environment ID (required for history) |
| SCF_FUNCTIONNAME | Cloud function name (used as bot ID) |
| HOSTNAME | Container hostname (fallback for bot ID) |
Platform-Specific Notes
| Platform | Trigger Source | Async Reply |
|----------|---------------|-------------|
| Mini Program | WXMiniApp | Always async |
| Service Account | WXService | Based on verification |
| Subscription | WXSubscription | Based on verification |
| Enterprise CS | WXCustomerService | Always async |
License
ISC
