Development Guide
This article introduces how to integrate Agents with the WeChat platform (WeChat Mini Program, WeChat official accounts, WeCom) to enable the use of AI Agents in the WeChat ecosystem.
Prerequisites
1. Creating an Agent
First, create an Agent in the TCB console:
- Go to the TCB console
- Select "AI"
- Click "Create Agent"
- Select "Existing Service" or "Create a Service"
- After the Agent is created, you will obtain the Agent ID (format:
agent-xxx)
2. Agent Transformation
To support integration with the WeChat platform, the Agent needs to be modified to handle the message format of the WeChat platform.
Quick Start
The @cloudbase/agent-adapter-wx module is responsible for receiving callback data from the WeChat platform, converting it to the AG-UI protocol to send to the Agent, and sending the Agent's response back to the WeChat platform.
Export:
WeChatAgent- Agent adapter, wraps any AG-UI AgentcreateWxMessageHandler- Express routing handler
Architecture
┌─────────────────┐ ┌─────────────────────────┐ ┌─────────────────┐
│ WeChat Server │────▶│ createWxMessageHandler │────▶│ WeChatAgent │
└─────────────────┘ └─────────────────────────┘ └────────┬────────┘
│
▼
┌─────────────────┐
│ Base Agent │
│ (AG-UI) │
└─────────────────┘
Step 1: Installation
pnpm add @cloudbase/agent-adapter-wx
Step 2: Environment Variables
# Required: CloudBase Environment ID
ENV_ID=your-cloudbase-env-id
# Optional
LOG_LEVEL=info
ENABLE_CORS=true
Step 3: Create a basic Agent
Create any Agent that conforms to the AG-UI protocol. The following example uses LangChain, but you can also use other frameworks:
import { LangchainAgent } from "@cloudbase/agent-adapter-langchain";
import { createAgent as createLangchainAgent } from "./agent.js";
import { v4 as uuidv4 } from "uuid";
const createAgent = ({ request }) => {
const lcAgent = createLangchainAgent();
return {
agent: new LangchainAgent({ agent: lcAgent }).use((input, next) => {
return next.run(
typeof input.threadId === "string"
? input
: { ...input, threadId: uuidv4() },
);
}),
};
};
Step 4: Wrapping as WeChatAgent
WeChatAgent wraps any AG-UI Agent and provides the following features:
- Message Sending - Automatically sends Agent responses to WeChat (asynchronous mode)
- History Records - Automatically saves user inputs and AI responses to the CloudBase database
- Retry Handling - Handles WeChat's 11-second retry logic
- "Continue" Command - Allows users to send "Continue" to get the last response
import { WeChatAgent, WeChatHistoryManager } from "@cloudbase/agent-adapter-wx";
function createWxAgent({ request, options }) {
const { agent: baseAgent } = createAgent({ request });
return {
agent: new WeChatAgent({
agentId: options?.agentId || "my-wechat-bot",
agent: baseAgent,
wechatConfig: {
sendMode: "aitools",
context: {
extendedContext: {
envId: process.env.ENV_ID,
accessToken: request.headers.authorization,
},
},
},
historyManager: new WeChatHistoryManager({
envId: process.env.ENV_ID,
}),
}),
};
}
Configuration Items
| Configuration Item | Type | Description |
|---|---|---|
agentId | string | Bot identifier, used for routing and history isolation |
agent | AbstractAgent | Any AG-UI compatible Agent |
sendMode | 'aitools' | Message sending mode (cloud function environment) |
historyManager | WeChatHistoryManager | Chat history storage (CloudBase database) |
Step 5: Register Route
It is necessary to register two routes simultaneously:
import express from "express";
import { createWxMessageHandler } from "@cloudbase/agent-adapter-wx";
const app = express();
app.use(express.json());
app.post("/wx-send-message", createWxMessageHandler(createWxAgent));
app.post(
"/v1/aibot/bots/:agentId/wx-send-message",
createWxMessageHandler(createWxAgent),
);
app.listen(9000);
createWxMessageHandler Feature
- WeChat callback data parsing and validation
- Platform identification (Mini Program / WeChat official accounts / WeCom)
- Synchronous/Asynchronous reply mode handling
- Voice message to text
Supported Platforms
| Platform | Enum Values | Reply Mode |
|---|---|---|
| WeChat Mini Program | WXMiniapp | Always asynchronous |
| WeChat Service Account | WXService | Synchronous (authenticated) / Asynchronous (unauthenticated) |
| WeChat Subscription Account | WXSubscription | Synchronous (authenticated) / Asynchronous (unauthenticated) |
| WeCom Customer Service | WXCustomerService | Always asynchronous |
Complete Example
Project Structure
my-wechat-agent/
├── index.js # Entry file
├── agent.js # Agent logic
├── wechat-agent.js # WeChat adapter
└── package.json # Dependency configuration
agent.js - Basic Agent
import { createAgent as createLangchainAgent } from "langchain";
import { MemorySaver } from "@langchain/langgraph";
import { ChatOpenAI } from "@langchain/openai";
import { clientTools } from "@cloudbase/agent-adapter-langchain";
const checkpointer = new MemorySaver();
export function createLcAgent() {
const model = new ChatOpenAI({
model: process.env.TCB_AI_MODEL || "hunyuan-turbos-latest",
apiKey: process.env.TCB_API_KEY,
configuration: {
baseURL: `https://${process.env.TCB_ENV_ID}.api.tcloudbasegateway.com/v1/ai/hunyuan-exp/v1`,
},
});
return createLangchainAgent({
model,
checkpointer,
middleware: [clientTools()],
});
}
wechat-agent.js - WeChat adapter
import { LangchainAgent } from "@cloudbase/agent-adapter-langchain";
import { WeChatAgent, WeChatHistoryManager } from "@cloudbase/agent-adapter-wx";
import { createLcAgent } from "./agent.js";
import { v4 as uuidv4 } from "uuid";
export function createWxAgent({ request, options }) {
// Create a basic Agent
const lcAgent = createLcAgent();
const baseAgent = new LangchainAgent({ agent: lcAgent }).use(
(input, next) => {
return next.run(
typeof input.threadId === "string"
? input
: { ...input, threadId: uuidv4() },
);
},
);
// Wrap as WeChat Agent
return {
agent: new WeChatAgent({
agentId: options?.agentId || "agent-xxx",
agent: baseAgent,
wechatConfig: {
sendMode: "aitools",
context: {
extendedContext: {
envId: process.env.ENV_ID,
accessToken: request.headers.authorization,
},
},
},
historyManager: new WeChatHistoryManager({
envId: process.env.ENV_ID,
}),
}),
};
}
index.js - Entry file
import express from "express";
import { createWxMessageHandler } from "@cloudbase/agent-adapter-wx";
import { createWxAgent } from "./wechat-agent.js";
const app = express();
app.use(express.json());
// Register WeChat message handling route
app.post("/wx-send-message", createWxMessageHandler(createWxAgent));
app.post(
"/v1/aibot/bots/:agentId/wx-send-message",
createWxMessageHandler(createWxAgent),
);
// Cloud function entry point
export const main = app;
// Local development
if (process.env.NODE_ENV !== "production") {
app.listen(9000, () => {
console.log("Server running on http://localhost:9000");
});
}
package.json
{
"name": "my-wechat-agent",
"version": "1.0.0",
"type": "module",
"main": "index.js",
"dependencies": {
"@cloudbase/agent-adapter-wx": "latest",
"@cloudbase/agent-adapter-langchain": "latest",
"langchain": "latest",
"@langchain/openai": "latest",
"@langchain/langgraph": "latest",
"express": "latest",
"uuid": "latest"
}
}
Configuring the WeChat Platform
After completing the code modifications, configuration needs to be performed on the WeChat platform. Depending on the type of WeChat platform, the configuration methods vary:
📄️ Connect to WeChat Official Accounts
Configuration for connecting WeChat official accounts (service account/subscription account) to Agent
📄️ Connect to WeChat Mini Program Customer Service
Configuration for connecting WeChat Mini Program Customer Service to Agent
📄️ Connect to WeCom Customer Service
Configuration for connecting WeCom Customer Service to Agent
📄️ Connect to WeChat Server
Configuration for connecting WeChat server to Agent
Features
1. Automatic message sending
Agent responses are automatically sent to the WeChat platform without the need to manually call the sending interface.
2. Chat History Management
All conversation history is automatically saved to the CloudBase database, supporting:
- User Input Records
- AI Reply Records
- Session Context Preservation
3. Retry Handling
Automatic handling of WeChat's 11-second retry logic:
- First request: returns "Processing"
- Retry request: returns the actual reply or continues waiting
4. "Continue" Command
Users can send "Continue" to obtain the last unfinished reply.