use crate::error::Result;
use crate::llm::broker::LlmBroker;
use crate::llm::gateway::CompletionConfig;
use crate::llm::gateways::TokenizerGateway;
use crate::llm::models::{LlmMessage, MessageRole};
use crate::llm::tools::LlmTool;
use futures::stream::{Stream, StreamExt};
use serde::{Deserialize, Serialize};
use std::pin::Pin;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SizedLlmMessage {
#[serde(flatten)]
pub message: LlmMessage,
pub token_length: usize,
}
impl SizedLlmMessage {
pub fn new(message: LlmMessage, token_length: usize) -> Self {
Self {
message,
token_length,
}
}
pub fn role(&self) -> MessageRole {
self.message.role
}
pub fn content(&self) -> Option<&str> {
self.message.content.as_deref()
}
}
pub struct ChatSession {
broker: LlmBroker,
messages: Vec<SizedLlmMessage>,
tools: Option<Vec<Box<dyn LlmTool>>>,
max_context: usize,
tokenizer_gateway: TokenizerGateway,
completion_config: CompletionConfig,
}
impl ChatSession {
pub fn new(broker: LlmBroker) -> Self {
Self::builder(broker).build()
}
pub fn builder(broker: LlmBroker) -> ChatSessionBuilder {
ChatSessionBuilder::new(broker)
}
pub async fn send(&mut self, query: &str) -> Result<String> {
self.insert_message(LlmMessage::user(query));
let messages: Vec<LlmMessage> = self.messages.iter().map(|m| m.message.clone()).collect();
let config = self.completion_config.clone();
let response = self
.broker
.generate(&messages, self.tools.as_deref(), Some(config), None)
.await?;
self.ensure_all_messages_are_sized();
self.insert_message(LlmMessage::assistant(&response));
Ok(response)
}
pub fn send_stream<'a>(
&'a mut self,
query: &str,
) -> Pin<Box<dyn Stream<Item = Result<String>> + 'a>> {
self.insert_message(LlmMessage::user(query));
let messages: Vec<LlmMessage> = self.messages.iter().map(|m| m.message.clone()).collect();
let config = self.completion_config.clone();
Box::pin(async_stream::stream! {
let mut accumulated = Vec::new();
let tools_ref = self.tools.as_deref();
let mut inner_stream = self.broker.generate_stream(&messages, tools_ref, Some(config), None);
while let Some(result) = inner_stream.next().await {
match &result {
Ok(chunk) => {
accumulated.push(chunk.clone());
yield result;
}
Err(_) => {
yield result;
return;
}
}
}
drop(inner_stream);
self.ensure_all_messages_are_sized();
let full_response = accumulated.join("");
self.insert_message(LlmMessage::assistant(&full_response));
})
}
pub fn insert_message(&mut self, message: LlmMessage) {
let sized_message = self.build_sized_message(message);
self.messages.push(sized_message);
let mut total_length: usize = self.messages.iter().map(|m| m.token_length).sum();
while total_length > self.max_context && self.messages.len() > 1 {
let removed = self.messages.remove(1);
total_length -= removed.token_length;
}
}
pub fn messages(&self) -> &[SizedLlmMessage] {
&self.messages
}
pub fn total_tokens(&self) -> usize {
self.messages.iter().map(|m| m.token_length).sum()
}
fn build_sized_message(&self, message: LlmMessage) -> SizedLlmMessage {
let token_length = if let Some(content) = &message.content {
self.tokenizer_gateway.encode(content).len()
} else {
0
};
SizedLlmMessage::new(message, token_length)
}
fn ensure_all_messages_are_sized(&mut self) {
for i in 0..self.messages.len() {
if self.messages[i].token_length == 0 && self.messages[i].message.content.is_some() {
let content = self.messages[i].message.content.clone().unwrap();
let token_length = self.tokenizer_gateway.encode(&content).len();
self.messages[i].token_length = token_length;
}
}
}
}
pub struct ChatSessionBuilder {
broker: LlmBroker,
system_prompt: String,
tools: Option<Vec<Box<dyn LlmTool>>>,
max_context: usize,
tokenizer_gateway: Option<TokenizerGateway>,
completion_config: CompletionConfig,
}
impl ChatSessionBuilder {
fn new(broker: LlmBroker) -> Self {
Self {
broker,
system_prompt: "You are a helpful assistant.".to_string(),
tools: None,
max_context: 32768,
tokenizer_gateway: None,
completion_config: CompletionConfig::default(),
}
}
pub fn system_prompt(mut self, prompt: impl Into<String>) -> Self {
self.system_prompt = prompt.into();
self
}
pub fn tools(mut self, tools: Vec<Box<dyn LlmTool>>) -> Self {
self.tools = Some(tools);
self
}
pub fn max_context(mut self, max_context: usize) -> Self {
self.max_context = max_context;
self
}
pub fn tokenizer_gateway(mut self, gateway: TokenizerGateway) -> Self {
self.tokenizer_gateway = Some(gateway);
self
}
pub fn completion_config(mut self, config: CompletionConfig) -> Self {
self.completion_config = config;
self
}
pub fn temperature(mut self, temperature: f32) -> Self {
self.completion_config.temperature = Some(temperature);
self
}
pub fn build(self) -> ChatSession {
let tokenizer_gateway = self.tokenizer_gateway.unwrap_or_default();
let system_message = LlmMessage::system(&self.system_prompt);
let token_length = tokenizer_gateway.encode(&self.system_prompt).len();
ChatSession {
broker: self.broker,
messages: vec![SizedLlmMessage::new(system_message, token_length)],
tools: self.tools,
max_context: self.max_context,
tokenizer_gateway,
completion_config: self.completion_config,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::llm::gateway::{LlmGateway, StreamChunk};
use crate::llm::models::LlmGatewayResponse;
use crate::llm::tools::{FunctionDescriptor, ToolDescriptor};
use async_trait::async_trait;
use futures::stream::{self, Stream};
use serde_json::{json, Value};
use std::collections::HashMap;
use std::pin::Pin;
use std::sync::{Arc, Mutex};
struct MockGateway {
responses: Vec<String>,
call_count: Mutex<usize>,
}
impl MockGateway {
fn new(responses: Vec<String>) -> Self {
Self {
responses,
call_count: Mutex::new(0),
}
}
}
#[async_trait::async_trait]
impl LlmGateway for MockGateway {
async fn complete(
&self,
_model: &str,
_messages: &[LlmMessage],
_tools: Option<&[Box<dyn LlmTool>]>,
_config: &CompletionConfig,
) -> Result<LlmGatewayResponse> {
let mut count = self.call_count.lock().unwrap();
let idx = *count;
*count += 1;
let content = if idx < self.responses.len() {
self.responses[idx].clone()
} else {
"default response".to_string()
};
Ok(LlmGatewayResponse {
content: Some(content),
object: None,
tool_calls: vec![],
thinking: None,
..Default::default()
})
}
async fn complete_json(
&self,
_model: &str,
_messages: &[LlmMessage],
_schema: Value,
_config: &CompletionConfig,
) -> Result<Value> {
Ok(json!({}))
}
async fn get_available_models(&self) -> Result<Vec<String>> {
Ok(vec!["test-model".to_string()])
}
async fn calculate_embeddings(
&self,
_text: &str,
_model: Option<&str>,
) -> Result<Vec<f32>> {
Ok(vec![0.1, 0.2, 0.3])
}
fn complete_stream<'a>(
&'a self,
_model: &'a str,
_messages: &'a [LlmMessage],
_tools: Option<&'a [Box<dyn LlmTool>]>,
_config: &'a CompletionConfig,
) -> Pin<Box<dyn Stream<Item = Result<StreamChunk>> + Send + 'a>> {
Box::pin(stream::iter(vec![Ok(StreamChunk::Content("test".to_string()))]))
}
}
#[derive(Clone)]
struct MockTool {
name: String,
}
#[async_trait]
impl LlmTool for MockTool {
async fn run(
&self,
_args: &HashMap<String, Value>,
_ctx: &crate::llm::tools::ToolRunCtx,
) -> Result<Value> {
Ok(json!({"result": "success"}))
}
fn descriptor(&self) -> ToolDescriptor {
ToolDescriptor {
r#type: "function".to_string(),
function: FunctionDescriptor {
name: self.name.clone(),
description: "A mock tool".to_string(),
parameters: json!({}),
},
}
}
fn clone_box(&self) -> Box<dyn LlmTool> {
Box::new(self.clone())
}
}
#[tokio::test]
async fn test_new_session_has_system_message() {
let gateway = Arc::new(MockGateway::new(vec![]));
let broker = LlmBroker::new("test-model", gateway, None);
let session = ChatSession::new(broker);
assert_eq!(session.messages.len(), 1);
assert_eq!(session.messages[0].role(), MessageRole::System);
assert_eq!(session.messages[0].content(), Some("You are a helpful assistant."));
}
#[tokio::test]
async fn test_builder_custom_system_prompt() {
let gateway = Arc::new(MockGateway::new(vec![]));
let broker = LlmBroker::new("test-model", gateway, None);
let session = ChatSession::builder(broker).system_prompt("Custom system prompt").build();
assert_eq!(session.messages.len(), 1);
assert_eq!(session.messages[0].content(), Some("Custom system prompt"));
}
#[tokio::test]
async fn test_builder_custom_temperature() {
let gateway = Arc::new(MockGateway::new(vec![]));
let broker = LlmBroker::new("test-model", gateway, None);
let session = ChatSession::builder(broker).temperature(0.5).build();
assert_eq!(session.completion_config.temperature, Some(0.5));
}
#[tokio::test]
async fn test_builder_custom_max_context() {
let gateway = Arc::new(MockGateway::new(vec![]));
let broker = LlmBroker::new("test-model", gateway, None);
let session = ChatSession::builder(broker).max_context(16384).build();
assert_eq!(session.max_context, 16384);
}
#[tokio::test]
async fn test_send_adds_messages_to_history() {
let gateway = Arc::new(MockGateway::new(vec!["Hello, World!".to_string()]));
let broker = LlmBroker::new("test-model", gateway, None);
let mut session = ChatSession::new(broker);
let response = session.send("Hi").await.unwrap();
assert_eq!(response, "Hello, World!");
assert_eq!(session.messages.len(), 3);
assert_eq!(session.messages[1].role(), MessageRole::User);
assert_eq!(session.messages[1].content(), Some("Hi"));
assert_eq!(session.messages[2].role(), MessageRole::Assistant);
assert_eq!(session.messages[2].content(), Some("Hello, World!"));
}
#[tokio::test]
async fn test_send_multiple_turns() {
let gateway = Arc::new(MockGateway::new(vec![
"First response".to_string(),
"Second response".to_string(),
]));
let broker = LlmBroker::new("test-model", gateway, None);
let mut session = ChatSession::new(broker);
session.send("First query").await.unwrap();
session.send("Second query").await.unwrap();
assert_eq!(session.messages.len(), 5);
assert_eq!(session.messages[3].content(), Some("Second query"));
assert_eq!(session.messages[4].content(), Some("Second response"));
}
#[tokio::test]
async fn test_insert_message_calculates_token_length() {
let gateway = Arc::new(MockGateway::new(vec![]));
let broker = LlmBroker::new("test-model", gateway, None);
let mut session = ChatSession::new(broker);
session.insert_message(LlmMessage::user("Hello"));
assert_eq!(session.messages.len(), 2);
assert!(session.messages[1].token_length > 0);
}
#[tokio::test]
async fn test_context_window_trimming() {
let gateway = Arc::new(MockGateway::new(vec![]));
let broker = LlmBroker::new("test-model", gateway, None);
let mut session = ChatSession::builder(broker).max_context(50).build();
for i in 0..10 {
session.insert_message(LlmMessage::user(format!(
"This is a longer message number {} with more content to increase token count",
i
)));
}
assert!(session.messages.len() < 11);
assert_eq!(session.messages[0].role(), MessageRole::System);
assert!(session.total_tokens() <= 50);
}
#[tokio::test]
async fn test_context_window_preserves_system_prompt() {
let gateway = Arc::new(MockGateway::new(vec![]));
let broker = LlmBroker::new("test-model", gateway, None);
let mut session = ChatSession::builder(broker)
.system_prompt("Important system prompt")
.max_context(50)
.build();
for i in 0..20 {
session.insert_message(LlmMessage::user(format!("Message {}", i)));
}
assert_eq!(session.messages[0].role(), MessageRole::System);
assert_eq!(session.messages[0].content(), Some("Important system prompt"));
}
#[tokio::test]
async fn test_total_tokens() {
let gateway = Arc::new(MockGateway::new(vec![]));
let broker = LlmBroker::new("test-model", gateway, None);
let mut session = ChatSession::new(broker);
let initial_tokens = session.total_tokens();
assert!(initial_tokens > 0);
session.insert_message(LlmMessage::user("Hello"));
assert!(session.total_tokens() > initial_tokens);
}
#[tokio::test]
async fn test_messages_accessor() {
let gateway = Arc::new(MockGateway::new(vec![]));
let broker = LlmBroker::new("test-model", gateway, None);
let mut session = ChatSession::new(broker);
session.insert_message(LlmMessage::user("Test"));
let messages = session.messages();
assert_eq!(messages.len(), 2);
assert_eq!(messages[0].role(), MessageRole::System);
assert_eq!(messages[1].role(), MessageRole::User);
}
#[tokio::test]
async fn test_builder_with_tools() {
let gateway = Arc::new(MockGateway::new(vec![]));
let broker = LlmBroker::new("test-model", gateway, None);
let tool: Box<dyn LlmTool> = Box::new(MockTool {
name: "test_tool".to_string(),
});
let session = ChatSession::builder(broker).tools(vec![tool]).build();
assert!(session.tools.is_some());
assert_eq!(session.tools.as_ref().unwrap().len(), 1);
}
#[tokio::test]
async fn test_sized_message_creation() {
let message = LlmMessage::user("Test content");
let sized = SizedLlmMessage::new(message, 5);
assert_eq!(sized.token_length, 5);
assert_eq!(sized.role(), MessageRole::User);
assert_eq!(sized.content(), Some("Test content"));
}
struct StreamingMockGateway {
stream_chunks: Vec<Vec<String>>,
call_count: Mutex<usize>,
}
impl StreamingMockGateway {
fn new(stream_chunks: Vec<Vec<String>>) -> Self {
Self {
stream_chunks,
call_count: Mutex::new(0),
}
}
}
#[async_trait::async_trait]
impl LlmGateway for StreamingMockGateway {
async fn complete(
&self,
_model: &str,
_messages: &[LlmMessage],
_tools: Option<&[Box<dyn LlmTool>]>,
_config: &CompletionConfig,
) -> Result<LlmGatewayResponse> {
Ok(LlmGatewayResponse {
content: Some("default".to_string()),
object: None,
tool_calls: vec![],
thinking: None,
..Default::default()
})
}
async fn complete_json(
&self,
_model: &str,
_messages: &[LlmMessage],
_schema: Value,
_config: &CompletionConfig,
) -> Result<Value> {
Ok(json!({}))
}
async fn get_available_models(&self) -> Result<Vec<String>> {
Ok(vec!["test-model".to_string()])
}
async fn calculate_embeddings(
&self,
_text: &str,
_model: Option<&str>,
) -> Result<Vec<f32>> {
Ok(vec![0.1, 0.2, 0.3])
}
fn complete_stream<'a>(
&'a self,
_model: &'a str,
_messages: &'a [LlmMessage],
_tools: Option<&'a [Box<dyn LlmTool>]>,
_config: &'a CompletionConfig,
) -> Pin<Box<dyn Stream<Item = Result<StreamChunk>> + Send + 'a>> {
let mut count = self.call_count.lock().unwrap();
let idx = *count;
*count += 1;
let chunks = if idx < self.stream_chunks.len() {
self.stream_chunks[idx].clone()
} else {
vec!["default".to_string()]
};
Box::pin(stream::iter(
chunks.into_iter().map(|c| Ok(StreamChunk::Content(c))).collect::<Vec<_>>(),
))
}
}
#[tokio::test]
async fn test_send_stream_yields_content_chunks() {
let gateway = Arc::new(StreamingMockGateway::new(vec![vec![
"Hello".to_string(),
" world".to_string(),
]]));
let broker = LlmBroker::new("test-model", gateway, None);
let mut session = ChatSession::new(broker);
let mut chunks = Vec::new();
let mut stream = session.send_stream("Hi");
while let Some(result) = stream.next().await {
chunks.push(result.unwrap());
}
assert_eq!(chunks, vec!["Hello", " world"]);
}
#[tokio::test]
async fn test_send_stream_grows_message_history() {
let gateway = Arc::new(StreamingMockGateway::new(vec![vec!["Response".to_string()]]));
let broker = LlmBroker::new("test-model", gateway, None);
let mut session = ChatSession::new(broker);
{
let mut stream = session.send_stream("Hi");
while stream.next().await.is_some() {}
}
assert_eq!(session.messages.len(), 3);
}
#[tokio::test]
async fn test_send_stream_records_assembled_response() {
let gateway = Arc::new(StreamingMockGateway::new(vec![vec![
"Hello".to_string(),
" world".to_string(),
]]));
let broker = LlmBroker::new("test-model", gateway, None);
let mut session = ChatSession::new(broker);
{
let mut stream = session.send_stream("Hi");
while stream.next().await.is_some() {}
}
assert_eq!(session.messages[2].content(), Some("Hello world"));
assert_eq!(session.messages[2].role(), MessageRole::Assistant);
}
#[tokio::test]
async fn test_send_stream_records_user_message() {
let gateway = Arc::new(StreamingMockGateway::new(vec![vec!["Response".to_string()]]));
let broker = LlmBroker::new("test-model", gateway, None);
let mut session = ChatSession::new(broker);
{
let mut stream = session.send_stream("My question");
while stream.next().await.is_some() {}
}
assert_eq!(session.messages[1].role(), MessageRole::User);
assert_eq!(session.messages[1].content(), Some("My question"));
}
#[tokio::test]
async fn test_send_stream_respects_context_capacity() {
let gateway = Arc::new(StreamingMockGateway::new(vec![
vec!["This is a longer response to consume tokens in the context window".to_string()],
vec!["Another longer response that also consumes many tokens in context".to_string()],
]));
let broker = LlmBroker::new("test-model", gateway, None);
let mut session = ChatSession::builder(broker).max_context(50).build();
{
let mut stream = session.send_stream("First longer query message with extra words");
while stream.next().await.is_some() {}
}
{
let mut stream = session.send_stream("Second longer query message with extra words");
while stream.next().await.is_some() {}
}
assert_eq!(session.messages[0].role(), MessageRole::System);
assert!(session.total_tokens() <= 50);
}
#[tokio::test]
async fn test_message_with_no_content_has_zero_tokens() {
let gateway = Arc::new(MockGateway::new(vec![]));
let broker = LlmBroker::new("test-model", gateway, None);
let mut session = ChatSession::new(broker);
let message = LlmMessage {
role: MessageRole::Assistant,
content: None,
tool_calls: None,
image_paths: None,
reasoning_content: None,
};
session.insert_message(message);
assert_eq!(session.messages.len(), 2);
assert_eq!(session.messages[1].token_length, 0);
}
}