Tencent Yuanqi adapter for AG-Kit agents
Tencent Yuanqi adapter for AG-Kit agents. This package provides integration between AG-Kit and Tencent Yuanqi, enabling you to use Yuanqi AI agents with AG-Kit's agent infrastructure.
- ✅ YuanqiAgent: Agent implementation that connects to Tencent Yuanqi AI agents
- ✅ Streaming Support: Real-time streaming responses via OpenAI-compatible API
- ✅ Thinking/Reasoning Support: Handles reasoning content from Yuanqi models with thinking events
- ✅ Custom Variables: Pass custom parameters to Yuanqi agents
- ✅ Chat History Persistence: Automatic conversation history storage via Tencent CloudBase
``bash`
npm install @cloudbase/agent-adapter-yuanqi
Configure the following environment variables:
Important: If chat history behavior is not overridden, chat history will be stored in Tencent CloudBase as default. Please ensure that the necessary environment variables are set for CloudBase authentication.
`bashYuanqi Configuration (required)
YUANQI_APP_ID=your-yuanqi-assistant-id # Yuanqi assistant ID
YUANQI_APP_KEY=your-yuanqi-app-key # Yuanqi application key
Quick Start
$3
`typescript
import { YuanqiAgent } from "@cloudbase/agent-adapter-yuanqi";const agent = new YuanqiAgent({
yuanqiConfig: {
appId: "your-assistant-id",
appKey: "your-app-key",
envId: "your-cloudbase-env-id", // Or set via CLOUDBASE_ENV_ID env
credential: {
secretId: "your-secret-id", // Or set via TENCENTCLOUD_SECRETID env
secretKey: "your-secret-key", // Or set via TENCENTCLOUD_SECRETKEY env
token: "your-session-token", // Optional, for temporary credentials
},
},
});
`$3
`typescript
import { YuanqiAgent } from "@cloudbase/agent-adapter-yuanqi";const agent = new YuanqiAgent({
yuanqiConfig: {
appId: "your-assistant-id",
appKey: "your-app-key",
envId: "your-cloudbase-env-id",
credential: {
secretId: "your-secret-id",
secretKey: "your-secret-key",
},
request: {
baseUrl: "https://yuanqi.tencent.com/openapi/v1/agent", // Default base URL
body: {
chatType: "published", // or "preview"
customVariables: {
key1: "value1",
},
},
},
},
});
`$3
`typescript
import { randomUUID } from "crypto";const runId = randomUUID();
const threadId = randomUUID();
const observable = agent.run({
runId,
threadId,
messages: [
{
id: randomUUID(),
role: "user",
content: "Hello, how can you help me?",
},
],
forwardedProps: {
userId: "user-123", // Optional: custom user ID
customVariables: {
key1: "value1",
},
},
});
observable.subscribe({
next: (event) => console.log(event),
complete: () => console.log("Done"),
error: (err) => console.error(err),
});
`API Reference
$3
Agent class that extends
AbstractAgent from @ag-ui/client and connects to Tencent Yuanqi services.Constructor:
`typescript
constructor(config: AgentConfig & { yuanqiConfig: YuanqiConfig })
`Overridable Methods:
The following protected methods can be overridden in subclasses to customize chat history behavior:
`typescript
// Get chat history from database and combine with current message
protected async getChatHistory(
subscriber: Subscriber,
latestUserMessage: Message
): Promise// Save user and assistant messages to chat history
protected async saveChatHistory(
subscriber: Subscriber,
input: RunAgentInput,
userRecordId: string,
assistantRecordId: string,
userContent: string,
assistantContent: string
): Promise
`$3
Configuration options for the Yuanqi adapter.
`typescript
interface YuanqiConfig {
appId?: string; // Yuanqi assistant ID (optional if YUANQI_APP_ID env is set)
appKey?: string; // Yuanqi app key (optional if YUANQI_APP_KEY env is set)
envId?: string; // CloudBase environment ID (optional if CLOUDBASE_ENV_ID env is set)
historyCount?: number; // Number of history messages to fetch (default: 10)
credential?: {
secretId?: string; // Tencent Cloud SecretId (optional if TENCENTCLOUD_SECRETID env is set)
secretKey?: string; // Tencent Cloud SecretKey (optional if TENCENTCLOUD_SECRETKEY env is set)
token?: string; // Session token for temporary credentials (optional)
};
request?: {
baseUrl?: string; // Base URL (default: https://yuanqi.tencent.com/openapi/v1/agent)
body?: Partial; // Additional request body options
headers?: Record; // Additional request headers
};
}
`$3
Request body options for Yuanqi chat API.
`typescript
interface YuanqiChatRequest {
assistantId: string; // Yuanqi assistant ID
userId: string; // User identifier
messages: ChatMessage[]; // Chat messages
stream?: boolean; // Enable streaming (default: true)
customVariables?: Record; // Custom variables for the assistant
version?: number; // Assistant version
chatType?: "published" | "preview"; // Chat mode
}
`$3
Custom error class for Yuanqi-specific errors.
`typescript
class YuanqiAgentError extends Error {
code?: string;
constructor(message: string, code?: string);
}
`Error codes include:
-
MISSING_YUANQI_APP_ID - Yuanqi assistant ID not provided
- MISSING_YUANQI_APP_KEY - Yuanqi app key not provided
- MISSING_CLOUDBASE_ENV_ID - CloudBase environment ID not provided
- MISSING_SECRET_ID - Tencent Cloud SecretId not provided
- MISSING_SECRET_KEY - Tencent Cloud SecretKey not provided
- MESSAGE_FORMAT_ERROR - No user message found in the request$3
Utility function to process Yuanqi streaming responses and emit AG-UI events.
`typescript
async function* processYuanqiStream(
stream: AsyncIterable,
context: StreamContext
): AsyncGeneratorinterface StreamContext {
threadId: string;
runId: string;
messageId: string;
}
`$3
Entity class for chat history records stored in CloudBase.
`typescript
class ChatHistoryEntity {
id: number;
botId: string;
recordId: string; // Unique conversation ID
role: string; // "user" or "assistant"
content: string;
recommendQuestions: string[];
sender: string;
conversation: string;
type: string;
status: string; // Message status: pending, done, error, cancel
image: string;
triggerSrc: string;
originMsg: string;
replyTo: string;
reply: string;
traceId: string;
needAsyncReply: boolean;
asyncReply: string;
createTime: string;
updateTime: string;
createdAt: number;
updatedAt: number;
event: string;
}
`$3
Interface for raw chat history data from CloudBase database.
`typescript
interface ChatHistoryData {
bot_id: string;
record_id: string;
role: string;
status: string;
content: string;
sender: string;
conversation: string;
type: string;
trigger_src: string;
origin_msg: string;
reply_to: string;
reply: string;
trace_id: string;
need_async_reply: boolean;
async_reply: string;
createdAt: number;
updatedAt: number;
}
`$3
The package exports utility functions for chat history management:
`typescript
// Create a new chat history record
function createChatHistory(params: {
tcbClient: tcb.CloudBase;
chatHistoryEntity: ChatHistoryEntity;
}): Promise// Update chat history by record ID
function updateChatHistoryByRecordId(params: {
tcbClient: tcb.CloudBase;
recordId: string;
chatHistoryEntity: ChatHistoryEntity;
}): Promise
// Query chat history from database (paginated)
function describeChatHistory(params: {
tcbClient: tcb.CloudBase;
botId: string;
sort: "asc" | "desc";
pageSize?: number;
pageNumber?: number;
conversation?: string;
startCreatedAt?: number;
triggerSrc?: string;
}): Promise<[ChatHistoryEntity[], number]>
// Transform raw database data to ChatHistoryEntity
function transDataToChatEntity(item: ChatHistoryData): ChatHistoryEntity
// Query chat history for LLM context
function queryForLLM(params: {
tcbClient: tcb.CloudBase;
botId: string;
pageSize?: number;
startCreatedAt?: number;
triggerSrc?: string;
}): Promise<{ role: string; content: string }[]>
`$3
`typescript
// Convert AG-UI messages to OpenAI chat completion format
function convertMessagesToOpenAI(
messages: Message[],
systemPrompt?: string
): ChatMessage[]
`$3
The adapter emits the following AG-UI events:
Run Lifecycle:
-
RUN_STARTED / RUN_FINISHED / RUN_ERROR - Run lifecycle eventsText Response:
-
TEXT_MESSAGE_START / TEXT_MESSAGE_CONTENT / TEXT_MESSAGE_END - Streaming text responseThinking/Reasoning (for reasoning models):
-
THINKING_START / THINKING_END - Thinking block boundaries
- THINKING_TEXT_MESSAGE_START / THINKING_TEXT_MESSAGE_CONTENT / THINKING_TEXT_MESSAGE_END - Thinking contentTool Calls:
-
TOOL_CALL_START / TOOL_CALL_ARGS / TOOL_CALL_END - Tool call eventsRaw Events:
-
RAW - Custom raw events (e.g., message trimming warnings, database error notifications)Message History Handling
The adapter manages message history through CloudBase database. When you pass multiple messages to the agent:
- Only the latest user message is used for the current request
- Previous messages are trimmed and a
RAW event with type: "warn" is emitted to notify you
- Historical context is automatically loaded from the database (up to historyCount messages, default: 10)
- History messages are fetched as complete user-assistant pairs to ensure valid conversation contextThis design ensures consistent conversation context management through the database rather than relying on client-side message arrays.
Chat History Persistence
$3
The adapter uses a collection named
ai_bot_chat_history_5hobd2b to store chat history. The collection will be automatically created if it doesn't exist. To enable chat history persistence, ensure:1.
CLOUDBASE_ENV_ID (or CBR_ENV_ID/SCF_NAMESPACE) environment variable is set
2. Valid Tencent Cloud credentials are configured via:
- TENCENTCLOUD_SECRETID + TENCENTCLOUD_SECRETKEY, or
- TENCENTCLOUD_SESSIONTOKEN (for temporary credentials in cloud functions)
3. The CloudBase environment has database access enabledImportant: If chat history behavior is not overridden, chat history will be stored in Tencent CloudBase as default. Please ensure that the necessary environment variables are set for CloudBase authentication.
Dependencies
-
@ag-ui/client: AG-UI client protocol (provides AbstractAgent base class)
- @cloudbase/node-sdk: Tencent CloudBase Node.js SDK for database operations
- @cloudbase/manager-node: Tencent CloudBase Manager for collection management
- openai: OpenAI SDK for API compatibility
- rxjs`: Reactive extensions for JavaScript- Tencent Yuanqi
- Yuanqi API Documentation
- Tencent CloudBase Documentation