Repository navigation
en dev star guides ai conversations
A session is identified by the message source, event.unified_msg_origin (UMO). A conversation is identified by cid and stores a model message history. A session can create and switch between conversations.
To wait for a user's next message, see Session Control. This page covers reading and writing conversation history.
Use self.context.conversations to create, read, update, switch, and delete conversations. Conversation.history is a JSON string containing model messages.
_no_save excludes a message or content part from future model context, but does not prevent its raw content from being stored.
Tip
Starting with v4.30.0, the conversation API changes as follows:
-
self.context.conversation_managerremains a compatibility alias forself.context.conversations. - Replace
event.conversation_eventsandget_conversation_events()withappend_message()orappend_plugin_event(). - Replace
update_conversation_title()andupdate_conversation_persona_id()withupdate_conversation(..., title=...)andupdate_conversation(..., persona_id=...). - Replace platform history links using
llm_checkpoint_idwithturn_idandcontext_event_id.
conversations = self.context.conversations
message_id = await conversations.append_message(
"The user prefers concise answers.",
cid=target_cid,
)content accepts text or a list of AstrBot ContentPart objects:
from astrbot.core.agent.message import ImageURLPart, TextPart
await conversations.append_message(
[
TextPart(text="Describe this image."),
ImageURLPart(
image_url=ImageURLPart.ImageURL(url="https://example.com/image.png")
),
],
cid=target_cid,
)Messages are stored with role="user" and included in future context. They do not change a running agent's context. The returned string is the saved message ID; pass message_id to identify a retry of the same submission.
event_id = await conversations.append_plugin_event(
event_type="my_plugin.retrieval_completed",
data={"document_ids": ["document-1"]},
cid=target_cid,
)Plugin events are stored with the conversation but do not enter model context. Use a plugin-prefixed event_type and a JSON-serializable dict for data. The returned string is the saved event ID; pass event_id to identify a retry of the same submission.
For mutable state that does not need an event history, use plugin KV storage. Include cid in the key for per-conversation state.
Both append methods require cid for an existing conversation and raise ValueError if it is invalid or missing from storage. Neither starts an agent turn.
To change the current execution's context, edit the relevant hook's ProviderRequest.contexts or runtime messages. Direct conversation writes, including update_conversation() and add_message_pair(), do not update a running agent's context and can cause ConversationConflictError if its stored history changes concurrently.
# Before AstrBot v4.30.0:
# from astrbot.core.conversation_mgr import Conversation
from astrbot.api.provider import Conversation
uid = event.unified_msg_origin
conv_mgr = self.context.conversations
curr_cid = await conv_mgr.get_curr_conversation_id(uid)
conversation = await conv_mgr.get_conversation(uid, curr_cid) # Conversation::: details Conversation Type Definition
@dataclass
class Conversation:
"""The conversation entity representing a chat session."""
platform_id: str
"""The platform ID in AstrBot"""
user_id: str
"""The user ID associated with the conversation."""
cid: str
"""The conversation ID, in UUID format."""
history: str = ""
"""The conversation history as a string."""
title: str | None = ""
"""The title of the conversation. For now, it's only used in WebChat."""
persona_id: str | None = ""
"""The persona ID associated with the conversation."""
created_at: int = 0
"""The timestamp when the conversation was created."""
updated_at: int = 0
"""The timestamp when the conversation was last updated.""":::
# Before AstrBot v4.30.0:
# from astrbot.core.agent.message import AssistantMessageSegment, UserMessageSegment, TextPart
from astrbot.api.agents import (
AssistantMessageSegment,
UserMessageSegment,
TextPart,
)
conv_mgr = self.context.conversations
provider_id = await self.context.get_current_chat_provider_id(event.unified_msg_origin)
curr_cid = await conv_mgr.get_curr_conversation_id(event.unified_msg_origin)
user_msg = UserMessageSegment(content=[TextPart(text="hi")])
llm_resp = await self.context.llm_generate(
chat_provider_id=provider_id, # Chat model ID
contexts=[
user_msg
], # When prompt is not specified, contexts is used as input; if both prompt and contexts are provided, prompt is appended to the end of the LLM input
)
await conv_mgr.add_message_pair(
cid=curr_cid,
user_message=user_msg,
assistant_message=AssistantMessageSegment(
content=[TextPart(text=llm_resp.completion_text)]
),
)Warning
The example above uses unified_msg_origin as the conversation history storage key. When Isolate Conversation (platform_settings.unique_session) is enabled, the unified_msg_origin of group messages changes (only on platforms that support isolation), so the same group resolves to a different conversation depending on the setting. Use event.get_group_id() when you need to target a group; see Handling Message Events.
- 首页
- 文档入口
- Top Level
- community events
- config
- deploy
- dev
- others
- platform
- 接入 OneBot v11 协议实现
- 接入钉钉 DingTalk
- 接入 Discord
- 接入 Kook
- 接入飞书
- 接入 LINE
- 接入 Matrix
- 接入 Mattermost
- 接入 Misskey 平台
- 接入 QQ 官方机器人平台
- 通过 QQ官方机器人 接入 QQ (Webhook)
- 通过 QQ官方机器人 接入 QQ (Websockets)
- 接入 Satori 协议
- 接入 server-satori (基于 Koishi)
- 接入 Slack
- 接入消息平台
- 接入 Telegram
- 接入 VoceChat
- AstrBot 接入企业微信
- 接入企业微信智能机器人平台
- AstrBot 接入微信公众平台
- 接入个人微信
- providers
- use
- Home
- Docs Entry
- Top Level
- config
- deploy
- Deploy AstrBot on 1Panel
- Deploy AstrBot on BT Panel
- Deploy AstrBot on CasaOS
- Deploy AstrBot from Source Code
- Community-Provided Deployment Methods
- Deploy via Compshare
- Deploy with AstrBot Desktop Client
- Deploy AstrBot with Docker
- Deploy AstrBot with Kubernetes
- Deploy AstrBot with AstrBot Launcher
- Other Deployments
- Script Deployment
- Installation via System Package Manager
- Preface
- dev
- AstrBot Configuration File
- API Scope–Endpoint Reference
- AstrBot HTTP API
- AstrBot Plugin Market JSON Specification
- AstrBot Plugin Market JSON Specification
- Developing a Platform Adapter
- plugin
- AI
- Agents
- Sessions and Conversations
- Models
- Other APIs
- Tools
- Documentation moved
- Text to Image
- Handling Message Events
- Plugin Configuration
- Plugin Internationalization
- Documentation moved
- Shared Bridge API
- Interactive message component
- Standalone plugin page
- Backend Web APIs
- Workbench page
- Sending Messages
- Session Control
- Minimal Example
- Plugin Storage
- AstrBot Plugin Development Guide 🌠
- Publishing Plugins to the Plugin Marketplace
- ospp
- others
- platform
- Connect OneBot v11 Protocol Implementations
- Connect to DingTalk
- Connecting to Discord
- Connect to KOOK
- Connecting to Lark
- Connecting to LINE
- Connecting to Matrix
- Connecting to Mattermost
- Connecting to Misskey Platform
- Connect QQ Official Bot
- Connect QQ via QQ Official Bot (Webhook)
- Connect QQ via QQ Official Bot (Websockets)
- Connect to Satori Protocol
- Connect server-satori (Koishi)
- Connecting to Slack
- Messaging Platforms
- Connecting to Telegram
- Connect to VoceChat
- Connect AstrBot to WeCom
- Connect to WeCom AI Bot Platform
- Connect AstrBot to WeChat Official Account Platform
- Connect Personal WeChat
- providers
- Connect 302.AI
- Agent Runners
- Built-in Agent Runner
- Connect to Coze
- Connect to Alibaba Cloud Bailian Application
- Connect to DeerFlow
- Connect to Dify
- Connect AIHubMix
- coze
- dashscope
- DeepSeek STT Integration
- DeepSeek TTS Integration
- dify
- Model input images
- Large Language Model Providers
- Connect MiraRouter
- NewAPI
- Connect PPIO Cloud
- Connect LM Studio to Use DeepSeek-R1 and Other Models
- Integrating Ollama
- Connect ShengSuanYun
- Connecting to SiliconFlow
- Connecting Model Services
- Connecting to TokenPony
- use
- Agent Execution Mode {#agent-runner}
- Agent Sandbox Environment
- astrbot sandbox
- AstrBot CLI {#cli-commands}
- Docker-based Code Interpreter
- Built-in Commands
- computer
- Context Compression
- Session Configuration Mappings (formerly Custom Rules)
- AstrBot Knowledge Base
- MCP
- AstrBot Plugins {#astrbot-star}
- Proactive Capabilities
- Skills {#anthropic-skills}
- Subagents {#agent-handsoff-and-subagent}
- Unified Webhook Mode
- Web Search
- DeepSeek Search API
- SerpApi
- WebUI