use crate::error::Result;
use crate::llm::chat_session::ChatSession;
use crate::llm::tools::LlmTool;
use crate::llm::LlmBroker;
use tracing::{info, warn};
pub struct IterativeProblemSolver {
chat: ChatSession,
max_iterations: usize,
}
impl IterativeProblemSolver {
pub fn new(broker: LlmBroker) -> Self {
Self::builder(broker).build()
}
pub fn builder(broker: LlmBroker) -> IterativeProblemSolverBuilder {
IterativeProblemSolverBuilder::new(broker)
}
pub async fn solve(&mut self, problem: &str) -> Result<String> {
let mut iterations_remaining = self.max_iterations;
loop {
let result = self.step(problem).await?;
if result.to_lowercase().contains("fail") {
info!(user_request = problem, result = result.as_str(), "Task failed");
break;
}
if result.to_lowercase().contains("done") {
info!(user_request = problem, result = result.as_str(), "Task completed");
break;
}
iterations_remaining -= 1;
if iterations_remaining == 0 {
warn!(
max_iterations = self.max_iterations,
user_request = problem,
result = result.as_str(),
"Max iterations reached"
);
break;
}
}
let summary = self
.chat
.send(
"Summarize the final result, and only the final result, \
without commenting on the process by which you achieved it.",
)
.await?;
Ok(summary)
}
async fn step(&mut self, problem: &str) -> Result<String> {
let prompt = format!(
"Given the user request:\n\
{}\n\
\n\
Use the tools at your disposal to act on their request. \
You may wish to create a step-by-step plan for more complicated requests.\n\
\n\
If you cannot provide an answer, say only \"FAIL\".\n\
If you have the answer, say only \"DONE\".",
problem
);
self.chat.send(&prompt).await
}
}
pub struct IterativeProblemSolverBuilder {
broker: LlmBroker,
tools: Option<Vec<Box<dyn LlmTool>>>,
max_iterations: usize,
system_prompt: Option<String>,
}
impl IterativeProblemSolverBuilder {
fn new(broker: LlmBroker) -> Self {
Self {
broker,
tools: None,
max_iterations: 3,
system_prompt: None,
}
}
pub fn tools(mut self, tools: Vec<Box<dyn LlmTool>>) -> Self {
self.tools = Some(tools);
self
}
pub fn max_iterations(mut self, max_iterations: usize) -> Self {
self.max_iterations = max_iterations;
self
}
pub fn system_prompt(mut self, prompt: impl Into<String>) -> Self {
self.system_prompt = Some(prompt.into());
self
}
pub fn build(self) -> IterativeProblemSolver {
let system_prompt = self.system_prompt.unwrap_or_else(|| {
"You are a problem-solving assistant that can solve complex problems step by step. \
You analyze problems, break them down into smaller parts, and solve them systematically. \
If you cannot solve a problem completely in one step, you make progress and identify what to do next."
.to_string()
});
let mut chat_builder = ChatSession::builder(self.broker).system_prompt(system_prompt);
if let Some(tools) = self.tools {
chat_builder = chat_builder.tools(tools);
}
IterativeProblemSolver {
chat: chat_builder.build(),
max_iterations: self.max_iterations,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::llm::gateway::{CompletionConfig, LlmGateway, StreamChunk};
use crate::llm::models::{LlmGatewayResponse, LlmMessage};
use crate::llm::tools::{FunctionDescriptor, ToolDescriptor};
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: Arc<Mutex<usize>>,
}
impl MockGateway {
fn new(responses: Vec<String>) -> Self {
Self {
responses,
call_count: Arc::new(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,
})
}
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,
}
impl LlmTool for MockTool {
fn run(&self, _args: &HashMap<String, Value>) -> 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_builder_default_settings() {
let gateway = Arc::new(MockGateway::new(vec![]));
let broker = LlmBroker::new("test-model", gateway, None);
let solver = IterativeProblemSolver::new(broker);
assert_eq!(solver.max_iterations, 3);
}
#[tokio::test]
async fn test_builder_custom_max_iterations() {
let gateway = Arc::new(MockGateway::new(vec![]));
let broker = LlmBroker::new("test-model", gateway, None);
let solver = IterativeProblemSolver::builder(broker).max_iterations(5).build();
assert_eq!(solver.max_iterations, 5);
}
#[tokio::test]
async fn test_builder_with_tools() {
let gateway = Arc::new(MockGateway::new(vec![]));
let broker = LlmBroker::new("test-model", gateway, None);
let tools: Vec<Box<dyn LlmTool>> = vec![Box::new(MockTool {
name: "test_tool".to_string(),
})];
let _solver = IterativeProblemSolver::builder(broker).tools(tools).build();
}
#[tokio::test]
async fn test_solve_completes_with_done() {
let gateway = Arc::new(MockGateway::new(vec![
"Working on it...".to_string(),
"DONE".to_string(),
"The answer is 42".to_string(),
]));
let broker = LlmBroker::new("test-model", gateway, None);
let mut solver = IterativeProblemSolver::new(broker);
let result = solver.solve("Test problem").await.unwrap();
assert_eq!(result, "The answer is 42");
}
#[tokio::test]
async fn test_solve_fails_with_fail() {
let gateway = Arc::new(MockGateway::new(vec![
"Trying...".to_string(),
"FAIL".to_string(),
"Could not solve the problem".to_string(),
]));
let broker = LlmBroker::new("test-model", gateway, None);
let mut solver = IterativeProblemSolver::new(broker);
let result = solver.solve("Impossible problem").await.unwrap();
assert_eq!(result, "Could not solve the problem");
}
#[tokio::test]
async fn test_solve_stops_at_max_iterations() {
let gateway = Arc::new(MockGateway::new(vec![
"Step 1".to_string(),
"Step 2".to_string(),
"Step 3".to_string(),
"Final summary".to_string(),
]));
let broker = LlmBroker::new("test-model", gateway, None);
let mut solver = IterativeProblemSolver::builder(broker).max_iterations(3).build();
let result = solver.solve("Long problem").await.unwrap();
assert_eq!(result, "Final summary");
}
#[tokio::test]
async fn test_solve_case_insensitive_done() {
let gateway = Arc::new(MockGateway::new(vec![
"done".to_string(), "The task is complete".to_string(), ]));
let broker = LlmBroker::new("test-model", gateway, None);
let mut solver = IterativeProblemSolver::new(broker);
let result = solver.solve("Test problem").await.unwrap();
assert_eq!(result, "The task is complete");
}
#[tokio::test]
async fn test_solve_case_insensitive_fail() {
let gateway = Arc::new(MockGateway::new(vec![
"fail".to_string(), "Unable to complete task".to_string(), ]));
let broker = LlmBroker::new("test-model", gateway, None);
let mut solver = IterativeProblemSolver::new(broker);
let result = solver.solve("Test problem").await.unwrap();
assert_eq!(result, "Unable to complete task");
}
#[tokio::test]
async fn test_custom_system_prompt() {
let gateway =
Arc::new(MockGateway::new(vec!["DONE".to_string(), "Custom response".to_string()]));
let broker = LlmBroker::new("test-model", gateway, None);
let mut solver = IterativeProblemSolver::builder(broker)
.system_prompt("Custom system prompt for testing")
.build();
let result = solver.solve("Test problem").await.unwrap();
assert_eq!(result, "Custom response");
}
#[tokio::test]
async fn test_step_method() {
let gateway = Arc::new(MockGateway::new(vec!["Step response".to_string()]));
let broker = LlmBroker::new("test-model", gateway, None);
let mut solver = IterativeProblemSolver::new(broker);
let result = solver.step("Test problem").await.unwrap();
assert_eq!(result, "Step response");
}
#[tokio::test]
async fn test_multiple_iterations_before_done() {
let gateway = Arc::new(MockGateway::new(vec![
"Working...".to_string(),
"Still working...".to_string(),
"Almost there...".to_string(),
"DONE".to_string(),
"Completed successfully".to_string(),
]));
let broker = LlmBroker::new("test-model", gateway, None);
let mut solver = IterativeProblemSolver::builder(broker).max_iterations(5).build();
let result = solver.solve("Complex problem").await.unwrap();
assert_eq!(result, "Completed successfully");
}
#[tokio::test]
async fn test_done_substring_detection() {
let gateway = Arc::new(MockGateway::new(vec![
"I'm DONE with this task".to_string(), "Task completed".to_string(),
]));
let broker = LlmBroker::new("test-model", gateway, None);
let mut solver = IterativeProblemSolver::new(broker);
let result = solver.solve("Test problem").await.unwrap();
assert_eq!(result, "Task completed");
}
#[tokio::test]
async fn test_fail_substring_detection() {
let gateway = Arc::new(MockGateway::new(vec![
"This will FAIL".to_string(), "Failed to complete".to_string(),
]));
let broker = LlmBroker::new("test-model", gateway, None);
let mut solver = IterativeProblemSolver::new(broker);
let result = solver.solve("Test problem").await.unwrap();
assert_eq!(result, "Failed to complete");
}
}