npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@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-yuanqi

Environment 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-token

Quick 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 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

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 boundaries
  • THINKING_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 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 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:

  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 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 (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

Related Resources