Skip to main content

ChatSession

Struct ChatSession 

Source
pub struct ChatSession { /* private fields */ }
Expand description

对话会话

管理多轮对话的消息历史

Implementations§

Source§

impl ChatSession

Source

pub fn new(client: LLMClient) -> ChatSession

创建新会话(自动生成 ID)

Source

pub fn new_with_stores( client: LLMClient, user_id: Uuid, tenant_id: Uuid, agent_id: Uuid, message_store: Arc<dyn MessageStore>, session_store: Arc<dyn SessionStore>, ) -> ChatSession

创建新会话并指定存储实现

Source

pub fn with_id(session_id: Uuid, client: LLMClient) -> ChatSession

使用指定 UUID 创建会话

Source

pub fn with_id_str(session_id: &str, client: LLMClient) -> ChatSession

使用指定字符串 ID 创建会话

Source

pub fn with_id_and_stores( session_id: Uuid, client: LLMClient, user_id: Uuid, tenant_id: Uuid, agent_id: Uuid, message_store: Arc<dyn MessageStore>, session_store: Arc<dyn SessionStore>, context_window_size: Option<usize>, ) -> ChatSession

使用指定 ID 和存储实现创建会话

Source

pub async fn with_id_and_stores_and_persist( session_id: Uuid, client: LLMClient, user_id: Uuid, tenant_id: Uuid, agent_id: Uuid, message_store: Arc<dyn MessageStore>, session_store: Arc<dyn SessionStore>, context_window_size: Option<usize>, ) -> Result<ChatSession, PersistenceError>

使用指定 ID 和存储实现创建会话,并立即持久化到数据库

这个方法会将会话记录保存到数据库,确保会话在创建时就被持久化。 这对于需要将会话 ID 用作外键的场景很重要(例如保存消息时)。

§参数
  • session_id: 会话 ID
  • client: LLM 客户端
  • user_id: 用户 ID
  • agent_id: Agent ID
  • message_store: 消息存储
  • session_store: 会话存储
  • context_window_size: 可选的上下文窗口大小
§返回

返回创建并持久化后的会话

§错误

如果数据库操作失败,返回错误

Source

pub fn session_id(&self) -> Uuid

获取会话 ID

Source

pub fn session_id_str(&self) -> String

获取会话 ID 字符串

Source

pub fn created_at(&self) -> Instant

获取会话创建时间

Source

pub async fn load( session_id: Uuid, client: LLMClient, user_id: Uuid, tenant_id: Uuid, agent_id: Uuid, message_store: Arc<dyn MessageStore>, session_store: Arc<dyn SessionStore>, context_window_size: Option<usize>, ) -> Result<ChatSession, PersistenceError>

从数据库加载会话

创建一个新的 ChatSession 实例,加载指定 ID 的会话和消息。

§参数
  • session_id: 会话 ID
  • client: LLM 客户端
  • user_id: 用户 ID
  • agent_id: Agent ID
  • message_store: 消息存储
  • session_store: 会话存储
  • context_window_size: 可选的上下文窗口大小(轮数),如果指定则只加载最近的 N 轮对话
§注意

当指定 context_window_size 时,只会加载最近的 N 轮对话到内存中。 这对于长期对话很有用,可以避免加载大量历史消息。

Source

pub fn elapsed(&self) -> Duration

获取会话存活时长

Source

pub fn set_metadata(&mut self, key: impl Into<String>, value: impl Into<String>)

设置元数据

Source

pub fn get_metadata(&self, key: &str) -> Option<&String>

获取元数据

Source

pub fn metadata(&self) -> &HashMap<String, String>

获取所有元数据

Source

pub fn with_system(self, prompt: impl Into<String>) -> ChatSession

设置系统提示

Source

pub fn with_context_window_size(self, size: Option<usize>) -> ChatSession

设置上下文窗口大小(滑动窗口)

§参数
  • size: 保留的最大对话轮数(None 表示不限制)
§注意
  • 单位是轮数(rounds),不是 token 数量
  • 每轮对话 ≈ 1 个用户消息 + 1 个助手响应
  • 系统消息始终保留,不计入轮数限制
§示例
let session = ChatSession::new(client)
    .with_context_window_size(Some(10)); // 只保留最近 10 轮对话
Source

pub fn with_tools( self, tools: Vec<Tool>, executor: Arc<dyn ToolExecutor>, ) -> ChatSession

设置工具

Source

pub fn with_tool_executor(self, executor: Arc<dyn ToolExecutor>) -> ChatSession

仅设置工具执行器(工具列表自动发现)

Source

pub async fn send( &mut self, content: impl Into<String>, ) -> Result<String, LLMError>

发送消息

Source

pub async fn send_with_content( &mut self, content: MessageContent, ) -> Result<String, LLMError>

发送结构化消息(支持多模态)

Source

pub fn messages(&self) -> &[ChatMessage]

获取消息历史

Source

pub fn messages_mut(&mut self) -> &mut Vec<ChatMessage>

获取消息历史(可变引用)

Source

pub fn clear(&mut self)

清空消息历史

Source

pub fn len(&self) -> usize

获取消息数量

Source

pub fn is_empty(&self) -> bool

是否为空

Source

pub fn set_context_window_size(&mut self, size: Option<usize>)

设置上下文窗口大小(滑动窗口)

§参数
  • size: 保留的最大对话轮数(None 表示不限制)
§注意
  • 单位是轮数(rounds),不是 token 数量
  • 每轮对话 ≈ 1 个用户消息 + 1 个助手响应(可能包含工具调用)
  • 系统消息始终保留,不计入轮数限制
§示例
session.set_context_window_size(Some(10)); // 只保留最近 10 轮对话
session.set_context_window_size(None);     // 不限制对话轮数
Source

pub fn context_window_size(&self) -> Option<usize>

获取上下文窗口大小(轮数)

Source

pub fn last_response_metadata(&self) -> Option<&LLMResponseMetadata>

获取最后一次 LLM 响应的元数据

Source

pub fn apply_sliding_window_static( messages: &[ChatMessage], window_size: Option<usize>, ) -> Vec<ChatMessage>

静态方法:应用滑动窗口到消息列表

这个方法可以在不拥有 ChatSession 实例的情况下使用, 例如在从数据库加载消息时。

§参数
  • messages: 要过滤的消息列表
  • window_size: 保留的最大对话轮数(None 表示不限制)
Source

pub async fn save(&self) -> Result<(), PersistenceError>

保存会话和消息到数据库

Source

pub async fn delete(&self) -> Result<(), PersistenceError>

从数据库删除会话和消息

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Message for T
where T: Any + Send + 'static,

Source§

fn from_boxed(m: BoxedMessage) -> Result<Self, BoxedDowncastErr>

Convert a BoxedMessage to this concrete type
Source§

fn box_message(self, pid: &ActorId) -> Result<BoxedMessage, BoxedDowncastErr>

Convert this message to a BoxedMessage
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> State for T
where T: Any + Send + 'static,