@cloudbase/agent-adapter-yuanqi
v0.0.24
Published
Tencent Yuanqi adapter for AG-Kit agents
Downloads
295
Readme
@cloudbase/agent-adapter-yuanqi
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.
Features
- ✅ 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
Installation
npm install @cloudbase/agent-adapter-yuanqiEnvironment Variables
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.
# Yuanqi Configuration (required)
YUANQI_APP_ID=your-yuanqi-assistant-id # Yuanqi assistant ID
YUANQI_APP_KEY=your-yuanqi-app-key # Yuanqi application key
# CloudBase Configuration (required for chat history persistence)
CLOUDBASE_ENV_ID=your-cloudbase-env-id # CloudBase environment ID
# Alternative env names: CBR_ENV_ID or SCF_NAMESPACE are also supported
# Tencent Cloud Credentials (required for chat history persistence)
# Option 1: Use SecretId + SecretKey (permanent credentials)
TENCENTCLOUD_SECRETID=your-secret-id
TENCENTCLOUD_SECRETKEY=your-secret-key
# Option 2: Use Session Token (temporary credentials, e.g., in cloud functions)
TENCENTCLOUD_SESSIONTOKEN=your-session-tokenQuick Start
Basic Agent Setup
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
},
},
});With Full Custom Configuration
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",
},
},
},
},
});Running the Agent
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
YuanqiAgent
Agent class that extends AbstractAgent from @ag-ui/client and connects to Tencent Yuanqi services.
Constructor:
constructor(config: AgentConfig & { yuanqiConfig: YuanqiConfig })Overridable Methods:
The following protected methods can be overridden in subclasses to customize chat history behavior:
// Get chat history from database and combine with current message
protected async getChatHistory(
subscriber: Subscriber<BaseEvent>,
input: RunAgentInput,
latestUserMessage: Message
): Promise<ChatMessage[]>
// Save user and assistant messages to chat history
protected async saveChatHistory(
subscriber: Subscriber<BaseEvent>,
input: RunAgentInput,
userRecordId: string,
assistantRecordId: string,
userContent: string,
assistantContent: string
): Promise<void>YuanqiConfig
Configuration options for the Yuanqi adapter.
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<YuanqiChatRequest>; // Additional request body options
headers?: Record<string, string>; // Additional request headers
};
}YuanqiChatRequest
Request body options for Yuanqi chat API.
interface YuanqiChatRequest {
assistantId: string; // Yuanqi assistant ID
userId: string; // User identifier
messages: ChatMessage[]; // Chat messages
stream?: boolean; // Enable streaming (default: true)
customVariables?: Record<string, string>; // Custom variables for the assistant
version?: number; // Assistant version
chatType?: "published" | "preview"; // Chat mode
}YuanqiAgentError
Custom error class for Yuanqi-specific errors.
class YuanqiAgentError extends Error {
code?: string;
constructor(message: string, code?: string);
}Error codes include:
MISSING_YUANQI_APP_ID- Yuanqi assistant ID not providedMISSING_YUANQI_APP_KEY- Yuanqi app key not providedMISSING_CLOUDBASE_ENV_ID- CloudBase environment ID not providedMISSING_SECRET_ID- Tencent Cloud SecretId not providedMISSING_SECRET_KEY- Tencent Cloud SecretKey not providedMESSAGE_FORMAT_ERROR- No user message found in the request
processYuanqiStream
Utility function to process Yuanqi streaming responses and emit AG-UI events.
async function* processYuanqiStream(
stream: AsyncIterable<OpenAI.Chat.Completions.ChatCompletionChunk>,
context: StreamContext
): AsyncGenerator<BaseEvent>
interface StreamContext {
threadId: string;
runId: string;
messageId: string;
}ChatHistoryEntity
Entity class for chat history records stored in CloudBase.
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;
}ChatHistoryData
Interface for raw chat history data from CloudBase database.
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;
}Chat History Utilities
The package exports utility functions for chat history management:
// Create a new chat history record
function createChatHistory(params: {
tcbClient: tcb.CloudBase;
chatHistoryEntity: ChatHistoryEntity;
}): Promise<string | undefined>
// Update chat history by record ID
function updateChatHistoryByRecordId(params: {
tcbClient: tcb.CloudBase;
recordId: string;
chatHistoryEntity: ChatHistoryEntity;
}): Promise<string | undefined>
// 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 }[]>Message Conversion Utility
// Convert AG-UI messages to OpenAI chat completion format
function convertMessagesToOpenAI(
messages: Message[],
systemPrompt?: string
): ChatMessage[]Supported Events
The adapter emits the following AG-UI events:
Run Lifecycle:
RUN_STARTED/RUN_FINISHED/RUN_ERROR- Run lifecycle events
Text Response:
TEXT_MESSAGE_START/TEXT_MESSAGE_CONTENT/TEXT_MESSAGE_END- Streaming text response
Thinking/Reasoning (for reasoning models):
THINKING_START/THINKING_END- Thinking block boundariesTHINKING_TEXT_MESSAGE_START/THINKING_TEXT_MESSAGE_CONTENT/THINKING_TEXT_MESSAGE_END- Thinking content
Tool Calls:
TOOL_CALL_START/TOOL_CALL_ARGS/TOOL_CALL_END- Tool call events
Raw 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
RAWevent withtype: "warn"is emitted to notify you - Historical context is automatically loaded from the database (up to
historyCountmessages, default: 10) - History messages are fetched as complete user-assistant pairs to ensure valid conversation context
This design ensures consistent conversation context management through the database rather than relying on client-side message arrays.
Chat History Persistence
Requirements
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:
CLOUDBASE_ENV_ID(orCBR_ENV_ID/SCF_NAMESPACE) environment variable is set- Valid Tencent Cloud credentials are configured via:
TENCENTCLOUD_SECRETID+TENCENTCLOUD_SECRETKEY, orTENCENTCLOUD_SESSIONTOKEN(for temporary credentials in cloud functions)
- The CloudBase environment has database access enabled
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.
Dependencies
@ag-ui/client: AG-UI client protocol (providesAbstractAgentbase class)@cloudbase/node-sdk: Tencent CloudBase Node.js SDK for database operations@cloudbase/manager-node: Tencent CloudBase Manager for collection managementopenai: OpenAI SDK for API compatibilityrxjs: Reactive extensions for JavaScript
