more refactoring
This commit is contained in:
parent
13e17770ca
commit
7268d49b4a
12 changed files with 319 additions and 189 deletions
|
|
@ -17,12 +17,14 @@ pub struct Agent {
|
|||
answer: Option<String>,
|
||||
}
|
||||
|
||||
use crate::error::{AppError, AppResult};
|
||||
|
||||
impl Agent {
|
||||
pub fn new(
|
||||
zen_api_key: Option<String>,
|
||||
tavily_api_key: Option<String>,
|
||||
initial_message: String,
|
||||
) -> Result<Self, Box<dyn std::error::Error>> {
|
||||
) -> AppResult<Self> {
|
||||
let intro = format!(
|
||||
"You are an autonomous agent. You have access to tools that can help
|
||||
you achieve your goals. Use them wisely. The user is unable to respond to you
|
||||
|
|
@ -49,7 +51,8 @@ impl Agent {
|
|||
|
||||
let client = reqwest::Client::builder()
|
||||
.timeout(std::time::Duration::from_secs(60))
|
||||
.build()?;
|
||||
.build()
|
||||
.map_err(|e| AppError::Internal(format!("Failed to build HTTP client: {}", e)))?;
|
||||
|
||||
Ok(Self {
|
||||
client,
|
||||
|
|
@ -71,7 +74,7 @@ impl Agent {
|
|||
pub async fn run(
|
||||
&mut self,
|
||||
config: &crate::config::Config,
|
||||
) -> Result<(String, Option<String>), Box<dyn std::error::Error>> {
|
||||
) -> AppResult<(String, Option<String>)> {
|
||||
let mut finished = false;
|
||||
let start_time = Instant::now();
|
||||
let max_duration = Duration::from_secs(config.agent_max_duration_secs);
|
||||
|
|
@ -80,47 +83,29 @@ impl Agent {
|
|||
|
||||
while !finished {
|
||||
if start_time.elapsed() > max_duration {
|
||||
return Err("Agent run timed out".into());
|
||||
return Err(AppError::Internal("Agent run timed out".into()));
|
||||
}
|
||||
|
||||
if turns >= max_turns {
|
||||
return Err("Agent run exceeded max turns".into());
|
||||
return Err(AppError::Internal("Agent run exceeded max turns".into()));
|
||||
}
|
||||
|
||||
turns += 1;
|
||||
let request = ChatRequest {
|
||||
model: "kimi-k2.5".to_string(),
|
||||
messages: self.messages.clone(),
|
||||
tools: self.tools.clone(),
|
||||
};
|
||||
|
||||
let current_role = self
|
||||
.messages
|
||||
.last()
|
||||
.map(|m| m.role.as_str())
|
||||
.unwrap_or("unknown");
|
||||
self.log(&format!(
|
||||
"--- Sending request to Zen API (Role: {}) ---",
|
||||
self.messages.last().unwrap().role
|
||||
"\n[Turn {}] Sending request (Last role: {})",
|
||||
turns, current_role
|
||||
));
|
||||
|
||||
let mut request_builder = self.client.post(&self.url).json(&request);
|
||||
|
||||
if let Some(key) = &self.zen_api_key {
|
||||
request_builder =
|
||||
request_builder.header("Authorization", format!("Bearer {}", key));
|
||||
}
|
||||
|
||||
let response = request_builder.send().await?;
|
||||
|
||||
if !response.status().is_success() {
|
||||
let status = response.status();
|
||||
let error_text = response.text().await?;
|
||||
self.log(&format!("Error: API request failed with status {}", status));
|
||||
self.log(&format!("Error details: {}", error_text));
|
||||
return Err(format!("API request failed: {}", status).into());
|
||||
}
|
||||
|
||||
let chat_response: ChatResponse = response.json().await?;
|
||||
let chat_response = self.call_llm().await?;
|
||||
let assistant_message = chat_response
|
||||
.choices
|
||||
.get(0)
|
||||
.ok_or("Missing assistant response")?
|
||||
.ok_or_else(|| AppError::Internal("Missing assistant response".into()))?
|
||||
.message
|
||||
.clone();
|
||||
|
||||
|
|
@ -128,41 +113,78 @@ impl Agent {
|
|||
|
||||
if let Some(content) = &assistant_message.content {
|
||||
if !content.is_empty() {
|
||||
self.log(&format!("\nAssistant response:\n{}\n", content));
|
||||
self.log(&format!("\nAssistant: {}", content));
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(tool_calls) = assistant_message.tool_calls {
|
||||
for tool_call in tool_calls {
|
||||
let (tool_message, written, tool_answer) =
|
||||
tools::handle_tool_call(&tool_call, &self.tavily_api_key).await?;
|
||||
self.log(&format!("Calling tool: {}", tool_call.function.name));
|
||||
|
||||
let (tool_message, is_final, tool_answer) =
|
||||
tools::handle_tool_call(&tool_call, &self.tavily_api_key)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
AppError::Internal(format!("Tool execution failed: {}", e))
|
||||
})?;
|
||||
|
||||
if let Some(ans) = tool_answer {
|
||||
self.answer = Some(ans);
|
||||
self.log("Task marked as finished by tool.");
|
||||
}
|
||||
|
||||
if let Some(content) = &tool_message.content {
|
||||
self.log(&format!(
|
||||
"Tool result ({}): {}",
|
||||
tool_call.function.name, content
|
||||
));
|
||||
self.log(&format!("Tool result: {}", content));
|
||||
}
|
||||
|
||||
self.messages.push(tool_message);
|
||||
if written {
|
||||
if is_final {
|
||||
finished = true;
|
||||
}
|
||||
}
|
||||
// Continue the loop to send tool results back
|
||||
continue;
|
||||
}
|
||||
|
||||
// No tool calls from assistant, but we only exit if the task was finished
|
||||
if !finished {
|
||||
self.log("--- Assistant didn't finish yet. Waiting for next turn... ---");
|
||||
} else if assistant_message.content.is_some() {
|
||||
// If assistant just talked without tools, we might be stuck or finished.
|
||||
// But typically we expect a 'finish' tool call.
|
||||
self.log("Assistant responded without tool calls.");
|
||||
// For now we continue unless the assistant explicitly uses a tool to finish,
|
||||
// or we could add heuristic here if needed.
|
||||
}
|
||||
}
|
||||
|
||||
self.log("\n--- Execution Finished ---");
|
||||
Ok((self.logs.clone(), self.answer.clone()))
|
||||
}
|
||||
|
||||
async fn call_llm(&self) -> AppResult<ChatResponse> {
|
||||
let request = ChatRequest {
|
||||
model: "kimi-k2.5".to_string(),
|
||||
messages: self.messages.clone(),
|
||||
tools: self.tools.clone(),
|
||||
};
|
||||
|
||||
let mut request_builder = self.client.post(&self.url).json(&request);
|
||||
|
||||
if let Some(key) = &self.zen_api_key {
|
||||
request_builder = request_builder.header("Authorization", format!("Bearer {}", key));
|
||||
}
|
||||
|
||||
let response = request_builder.send().await.map_err(AppError::Network)?;
|
||||
|
||||
if !response.status().is_success() {
|
||||
let status = response.status();
|
||||
let error_text = response
|
||||
.text()
|
||||
.await
|
||||
.unwrap_or_else(|_| "Unknown error".into());
|
||||
return Err(AppError::Internal(format!(
|
||||
"API request failed: {} - {}",
|
||||
status, error_text
|
||||
)));
|
||||
}
|
||||
|
||||
response
|
||||
.json()
|
||||
.await
|
||||
.map_err(|e| AppError::Internal(format!("Failed to parse LLM response: {}", e)))
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue