ChatSession

Struct ChatSession 

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

A chat session that manages conversation history with context window limits.

ChatSession maintains a list of messages and automatically trims old messages when the total token count exceeds the configured maximum context size. The system prompt (first message) is always preserved.

§Examples

use mojentic::llm::{ChatSession, LlmBroker};
use mojentic::llm::gateways::OllamaGateway;
use std::sync::Arc;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let gateway = Arc::new(OllamaGateway::default());
    let broker = LlmBroker::new("qwen3:32b", gateway);
    let mut session = ChatSession::new(broker);

    let response = session.send("What is Rust?").await?;
    println!("Response: {}", response);

    Ok(())
}

Implementations§

Source§

impl ChatSession

Source

pub fn new(broker: LlmBroker) -> Self

Create a new chat session with default settings.

§Arguments
  • broker - The LLM broker to use for generating responses
§Examples
use mojentic::llm::{ChatSession, LlmBroker};
use mojentic::llm::gateways::OllamaGateway;
use std::sync::Arc;

let gateway = Arc::new(OllamaGateway::default());
let broker = LlmBroker::new("qwen3:32b", gateway);
let session = ChatSession::new(broker);
Source

pub fn builder(broker: LlmBroker) -> ChatSessionBuilder

Create a chat session builder for custom configuration.

§Arguments
  • broker - The LLM broker to use for generating responses
§Examples
use mojentic::llm::ChatSession;

let session = ChatSession::builder(broker)
    .system_prompt("You are a helpful coding assistant.")
    .temperature(0.7)
    .max_context(16384)
    .build();
Source

pub async fn send(&mut self, query: &str) -> Result<String>

Send a message to the LLM and get a response.

This method:

  1. Adds the user message to the conversation history
  2. Generates a response using the LLM
  3. Adds the assistant’s response to the history
  4. Automatically trims old messages if context window is exceeded
§Arguments
  • query - The user’s message
§Returns

The LLM’s response as a string

§Examples
let response = session.send("What is 2 + 2?").await?;
println!("Answer: {}", response);
Source

pub fn send_stream<'a>( &'a mut self, query: &str, ) -> Pin<Box<dyn Stream<Item = Result<String>> + 'a>>

Send a message to the LLM and get a streaming response.

This method:

  1. Adds the user message to the conversation history
  2. Streams the response from the LLM, yielding chunks as they arrive
  3. After the stream is fully consumed, adds the assembled response to history
  4. Automatically trims old messages if context window is exceeded
§Arguments
  • query - The user’s message
§Returns

A stream of string chunks from the LLM response

§Examples
use futures::stream::StreamExt;

let mut stream = session.send_stream("Tell me a story");
while let Some(result) = stream.next().await {
    print!("{}", result?);
}
Source

pub fn insert_message(&mut self, message: LlmMessage)

Insert a message into the conversation history.

If the total token count exceeds max_context, the oldest messages are removed until the total is under the limit. The system prompt (index 0) is always preserved.

§Arguments
  • message - The message to add
Source

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

Get the current conversation history

Source

pub fn total_tokens(&self) -> usize

Get the total token count of the current conversation

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.

§

impl<T> Instrument for T

§

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

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

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.

§

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

§

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
§

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, 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.
§

impl<T> WithSubscriber for T

§

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
§

fn with_current_subscriber(self) -> WithDispatch<Self>

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