t-agent Developer Documentation

Overview

t-agent is a conversational agent SDK built with TypeScript for creating feature-rich conversational applications. It supports plugin extensions and is a pure SDK without UI components, allowing it to work with any framework.

t-agent features powerful Hook mechanisms, error handling, message state management, and other functionalities, providing an excellent development experience.

For more detailed information, please visit the official documentation.

Core Concepts

ChatAgent

ChatAgent is the core class of the entire conversation system, responsible for handling conversation lifecycle, message creation, persistence, and other core functions, and supports extending functionality through plugins and hooks.

Main Properties:

  • agent.session: Stores session data
  • agent.plugins: Contains methods and hooks from applied plugins

Core Methods:

  • agent.start(): Activates the conversation agent
  • agent.dispose(): Deactivates the conversation agent
  • agent.pushInputBlocks(): Pushes user messages to the ChatAgent
  • agent.createMessage(): Creates a message
  • agent.emitTileEvent(): Sends a tile event
  • agent.removeMessage(): Removes a message
  • agent.flushStreamToShow(): Streams updates to message

Lifecycle Hooks

ChatAgent implements event-driven behavior patterns through a hook system. Hooks execute in the following order:

onAgentStart → onChatStart/onChatResume → onMessageListInit → onInputBlocksPush

Main hooks include:

  • onAgentStart: Triggered when the agent initializes
  • onChatStart: Triggered when a conversation starts
  • onChatResume: Triggered when a conversation continues
  • onMessageListInit: Triggered when the message list initializes
  • onInputBlocksPush: Triggered when input message blocks are received
  • onMessageChange: Triggered when a message updates
  • onMessagePersist: Triggered when a message is persisted
  • onTileEvent: Called when a message block event is triggered
  • onAgentDispose: Triggered when the agent is destroyed
  • onUserAbort: Triggered when the user terminates the conversation
  • onError: Triggered when an error occurs

Enhanced Hooks

  • onMessageFeedback: Triggered when message feedback is received
  • onClearHistory: Triggered when clearing history

Usage example:

// Register message feedback handler
agent.plugins.ui.hook('onMessageFeedback', async context => {
  const { messageId, rate, content } = context.payload;
  try {
    await submitFeedback({ messageId, rate, content });
    context.result = { success: true };
  } catch (error) {
    context.result = { success: false };
  }
});

// Register clear history handler
agent.plugins.ui.hook('onClearHistory', async context => {
  try {
    await clearChatHistory();
    context.result = { success: true };
  } catch (error) {
    context.result = { success: false };
  }
});

ChatSession

ChatSession holds the message list and session-related data, created along with the ChatAgent.

Main Properties:

  • session.messages: Message list
  • session.sessionId: Unique session ID
  • session.isNewChat: Distinguishes between new sessions and continued sessions

Main Methods:

  • session.set/get: Sets/gets session data
  • session.getData: Gets all session data
  • session.getLatestMessage: Gets the latest message

Hooks:

  • session.onChange: Registers callbacks for session data changes

ChatMessage

ChatMessage is an abstract representation of conversation content and state, composed of multiple ChatTiles.

Main Properties:

  • message.id: Unique message identifier
  • message.role: Message role ('user'/'assistant')
  • message.status: Message status (ChatMessageStatus enum)
  • message.tiles: List of tiles contained in the message
  • message.bubble: Quick access to the main bubble tile
  • message.meta: Additional metadata attached to the message
  • message.isShow: Whether it has been displayed on the interface

Main Methods:

  • message.show/update/remove: Controls message display state
  • message.persist: Persists the message
  • message.addTile/removeTile: Manages message blocks
  • message.setTilesLocked: Sets the locked state of all tiles in the message
  • message.set: Sets message properties
  • message.setMetaValue: Sets meta properties by key-value
  • message.deleteMetaValue: Deletes meta properties
  • message.setMeta: Directly sets meta object
  • message.findTileByType: Finds tiles by tile type

ChatTile

ChatTile is a visual element in a message, which can be text, images, videos, or other different types.

Main Properties:

  • tile.id: Unique identifier
  • tile.type: Tile type
  • tile.data: Tile data
  • tile.children: List of child tiles
  • tile.locked: Whether it's locked
  • tile.fallback: Fallback content when tile cannot be displayed
  • tile.message: Reference to the message it belongs to

Main Methods:

  • tile.update: Shortcut to tile.message.update
  • tile.show: Shortcut to tile.message.show
  • tile.setLocked: Sets the locked state
  • tile.addTile: Adds child tiles
  • tile.setData: Sets tile data
  • tile.setFallback: Sets fallback display content
  • tile.findByType: Finds child tiles by tile type

Bubble Message Shortcuts

message.bubble is a shortcut that quickly adds a bubble tile to the current message when accessed:

const message = createMessage({ role: 'assistant' });

message.bubble.setText('Hello, world!');
// Equivalent to
message.addTile('bubble', {}).addTile('text', { text: 'Hello, world!' });

await message.show();

For bubble messages, additional methods are provided:

  • message.bubble.text: Read bubble text
  • message.bubble.setText: Set bubble text
  • message.bubble.isMarkdown: Whether it's markdown format
  • message.bubble.setIsMarkdown: Set whether it's markdown format
  • message.bubble.status: Bubble status
  • message.bubble.setStatus: Set bubble status
  • message.bubble.info: Bubble information
  • message.bubble.setInfo: Set bubble information
  • message.bubble.initWithInputBlocks: Initialize bubble with input blocks

Plugin System

t-agent supports extending functionality through plugins. Plugins are implemented based on the Hook mechanism, and plugins can expose methods and properties for developers to use.

Common plugins include:

  • withUI(): Provides UI-related functionality and message bus
  • withDebug(): Provides debugging functionality
  • withAIStream(): Connects to the mini-program AI agent platform
  • withBuildIn(): Provides built-in functionality

Error Handling

Enhanced error handling mechanism with support for more detailed error information and error classification:

agent.onError(error => {
  console.error('Agent error:', error);
  // Error handling logic
});

Built-in supported error types:

  • network-offline: Network is disconnected
  • timeout: Send timeout
  • invalid-params: Invalid parameters
  • session-create-failed: Connection failed
  • connection-closed: Connection closed

Built-in Plugins

withUI

The withUI plugin provides UI-related functionality and message bus capabilities. It is a required plugin that must be the first plugin applied.

Main features:

  • Message bus system
  • UI state management
  • Event handling
  • Context management

withDebug

The withDebug plugin provides debugging functionality, printing detailed logs in the console to help developers debug.

Features:

  • Hook execution logs
  • Message state change logs
  • Error logs
  • Performance monitoring

withAIStream

The withAIStream plugin connects to the mini-program AI agent platform, providing streaming conversation capabilities.

withBuildIn

The withBuildIn plugin provides built-in functionality, including smart home control, knowledge base search, etc.

Summary

t-agent is a flexible conversation agent SDK that can build rich conversational interaction experiences through its core concepts and hook system. Its plugin system allows for flexible extension of functionality to meet the needs of different scenarios. Developers can use t-agent to quickly build conversational applications with modern UI and powerful functionality, such as chatbots, customer service systems, or AI assistants.

For more detailed information and API documentation, please visit the official documentation.