use anyhow::Result;
use rig::completion::Message;
use super::providers::ProviderAgent;
pub struct SummaryReasoner;
impl SummaryReasoner {
pub async fn summarize_and_reason(
agent_without_tools: &ProviderAgent,
original_system_prompt: &str,
original_user_prompt: &str,
chat_history: &[Message],
tool_calls_history: &[String],
) -> Result<String> {
let summary_prompt = Self::build_summary_prompt(
original_system_prompt,
original_user_prompt,
chat_history,
tool_calls_history,
);
let result = agent_without_tools.prompt(&summary_prompt).await?;
Ok(result)
}
fn build_summary_prompt(
original_system_prompt: &str,
original_user_prompt: &str,
chat_history: &[Message],
tool_calls_history: &[String],
) -> String {
let mut prompt = String::new();
prompt.push_str("# 原始任务背景\n");
prompt.push_str(original_system_prompt);
prompt.push_str("\n\n");
prompt.push_str("# 原始用户问题\n");
prompt.push_str(original_user_prompt);
prompt.push_str("\n\n");
if !tool_calls_history.is_empty() {
prompt.push_str("# 已执行的工具调用记录\n");
for (index, tool_call) in tool_calls_history.iter().enumerate() {
prompt.push_str(&format!("{}. {}\n", index + 1, tool_call));
}
prompt.push_str("\n");
}
let conversation_details = Self::extract_detailed_conversation_info(chat_history);
if !conversation_details.is_empty() {
prompt.push_str("# 详细对话历史与工具结果\n");
prompt.push_str(&conversation_details);
prompt.push_str("\n\n");
}
prompt.push_str("# 总结推理任务\n");
prompt.push_str("基于以上信息,虽然多轮推理过程因达到最大迭代次数而被截断,但请你根据已有的上下文信息、工具调用记录和对话历史,");
prompt.push_str("对原始用户问题提供一个完整的、有价值的回答。请综合分析已获得的信息,给出最佳的解决方案或答案。\n\n");
prompt.push_str("注意:\n");
prompt.push_str("1. 请基于已有信息进行推理,不要虚构不存在的内容\n");
prompt.push_str("2. 如果信息不足以完全回答问题,请说明已知的部分并指出需要进一步了解的方面\n");
prompt.push_str("3. 请提供具体可行的建议或解决方案\n");
prompt.push_str("4. 充分利用已经执行的工具调用和其结果来形成答案\n");
prompt
}
fn extract_detailed_conversation_info(chat_history: &[Message]) -> String {
let mut details = String::new();
for (index, message) in chat_history.iter().enumerate() {
if index == 0 { continue;
}
match message {
Message::User { content } => {
details.push_str(&format!("## 用户输入 [轮次{}]\n", index + 1));
details.push_str(&format!("{:#?}\n\n", content));
}
Message::Assistant { content, .. } => {
details.push_str(&format!("## 助手响应 [轮次{}]\n", index + 1));
let mut has_content = false;
for item in content.iter() {
match item {
rig::completion::AssistantContent::Text(text) => {
if !text.text.is_empty() {
details.push_str(&format!("**文本回复:** {}\n\n", text.text));
has_content = true;
}
}
rig::completion::AssistantContent::ToolCall(tool_call) => {
details.push_str(&format!(
"**工具调用:** `{}` \n参数: `{}`\n\n",
tool_call.function.name,
tool_call.function.arguments
));
has_content = true;
}
rig::completion::AssistantContent::Reasoning(reasoning) => {
if !reasoning.reasoning.is_empty() {
let reasoning_text = reasoning.reasoning.join("\n");
details.push_str(&format!("**推理过程:** {}\n\n", reasoning_text));
has_content = true;
}
}
}
}
if !has_content {
details.push_str("无具体内容\n\n");
}
}
}
}
details
}
}