Quellcode durchsuchen

【新增】优化提示词生成和响应消息处理

- 提示词生成逻辑调整,支持多条消息场景
- 响应消息处理逻辑优化,处理最后一条用户消息之前的消息
- 添加调试日志,增强问题排查能力
PJ568 vor 1 Jahr
Ursprung
Commit
23b9676717
4 geänderte Dateien mit 82 neuen und 49 gelöschten Zeilen
  1. 1 1
      Cargo.lock
  2. 1 1
      Cargo.toml
  3. 38 19
      src/agent/mod.rs
  4. 42 28
      src/main.rs

+ 1 - 1
Cargo.lock

@@ -2433,7 +2433,7 @@ checksum = "1e9df38ee2d2c3c5948ea468a8406ff0db0b29ae1ffde1bcf20ef305bcc95c51"
 
 [[package]]
 name = "yaa"
-version = "2.3.2"
+version = "2.4.0"
 dependencies = [
  "actix-web",
  "anyhow",

+ 1 - 1
Cargo.toml

@@ -1,6 +1,6 @@
 [package]
 name = "yaa"
-version = "2.3.2"
+version = "2.4.0"
 edition = "2024"
 
 [dependencies]

+ 38 - 19
src/agent/mod.rs

@@ -49,23 +49,30 @@ pub async fn process_session(
     loop {
         // 当状态为“已中断”时,很可能是用户授权工具调用,直接跳到工具解析
         if matches!(session_data.status, SessionStatus::InProgress) {
-            // 1. 提示词生成(仅有一条消息且只有当最后一条消息是 user 的时才调用)
-            if let Some(last_msg) = session_data.messages.last() {
-                if matches!(last_msg.role, Role::User) {
-                    if session_data.messages.len() == 1 {
-                        let prompt = PromptGenerator::generate_with_current_time(
-                            &last_msg.content,
-                            &session_data.character,
-                            &get_tools_info(tool_registry)[..],
-                            &session_data
-                                .config
-                                .yaa
-                                .language
-                                .as_deref()
-                                .unwrap_or("zh-CN"),
-                        );
-                        session_data.add_message(Role::System, prompt);
-                    }
+            // 1. 提示词生成
+            if let Some(first_msg) = session_data.messages.first() {
+                let prompt = PromptGenerator::generate_with_current_time(
+                    &first_msg.content,
+                    &session_data.character,
+                    &get_tools_info(tool_registry)[..],
+                    &session_data
+                        .config
+                        .yaa
+                        .language
+                        .as_deref()
+                        .unwrap_or("zh-CN"),
+                );
+                // 将提示词插入到第一个消息之后
+                if session_data.messages.len() > 1 {
+                    session_data.messages.insert(
+                        1,
+                        Message {
+                            role: Role::System,
+                            content: prompt,
+                        },
+                    );
+                } else {
+                    session_data.add_message(Role::System, prompt);
                 }
             }
 
@@ -243,7 +250,7 @@ fn get_tools_info(tool_registry: &ToolRegistry) -> Vec<prompt::ToolInfo> {
         .collect()
 }
 
-/// 获取响应消息(最后一条用户消息之后的所有消息)
+/// 获取响应消息(从第三条消息开始,最后一条用户消息之后的所有消息)
 fn get_response_messages(session_data: &SessionData) -> Vec<Message> {
     let last_user_idx = session_data
         .messages
@@ -251,5 +258,17 @@ fn get_response_messages(session_data: &SessionData) -> Vec<Message> {
         .rposition(|m| matches!(m.role, Role::User))
         .unwrap_or(0);
 
-    session_data.messages[last_user_idx + 1..].to_vec()
+    // 如果最后一条用户消息位置小于等于二,则从第三条消息开始
+    let start_idx = if last_user_idx <= 2 {
+        2
+    } else {
+        last_user_idx + 1
+    };
+
+    // 确保 start_idx 不超过消息总数
+    if start_idx >= session_data.messages.len() {
+        return Vec::new();
+    }
+
+    session_data.messages[start_idx..].to_vec()
 }

+ 42 - 28
src/main.rs

@@ -7,7 +7,7 @@ use agent::tools::rethink::RethinkTool;
 use agent::{api::OpenAIClient, process_session};
 use clap::Parser;
 use cli::commands::{Commands, handle_command};
-use core::{session::{SessionData, Config}, tool::ToolRegistry};
+use core::{session::SessionData, tool::ToolRegistry};
 use tokio;
 
 use anyhow::{Context, Result};
@@ -79,9 +79,10 @@ fn merge_json(target: &mut serde_json::Value, source: &serde_json::Value) {
 
 async fn handle_request(
     app_data: web::Data<SessionData>,
-    request_data: web::Json<serde_json::Value>
+    request_data: web::Json<serde_json::Value>,
 ) -> actix_web::HttpResponse {
-    println!("[DEBUG] 接收到的原始数据:{:?}", request_data);
+    println!("[DEBUG] 接收到的原始数据:{:?}\n", request_data);
+    println!("[DEBUG] 初始SessionData:{:#?}\n", app_data);
 
     let mut tool_registry = ToolRegistry::new();
     tool_registry.register(FinishTool);
@@ -96,6 +97,7 @@ async fn handle_request(
         // 如果请求中没有 config 字段,使用 load_config 加载的配置
         user_data["config"] = serde_json::to_value(&merged_data.config).unwrap();
     }
+    println!("[DEBUG] 处理后的SessionData:{:#?}\n", merged_data);
 
     // 将基础配置转换为 JSON Value
     let mut base_data = match serde_json::to_value(&merged_data) {
@@ -103,12 +105,15 @@ async fn handle_request(
         Err(e) => {
             return actix_web::HttpResponse::InternalServerError()
                 .content_type("application/json")
-                .body(serde_json::json!({
-                    "messages": [{
-                        "role": "system",
-                        "content": format!("Failed to serialize base config: {}", e)
-                    }]
-                }).to_string());
+                .body(
+                    serde_json::json!({
+                        "messages": [{
+                            "role": "system",
+                            "content": format!("Failed to serialize base config: {}", e)
+                        }]
+                    })
+                    .to_string(),
+                );
         }
     };
 
@@ -121,16 +126,19 @@ async fn handle_request(
         Err(e) => {
             return actix_web::HttpResponse::BadRequest()
                 .content_type("application/json")
-                .body(serde_json::json!({
-                    "messages": [{
-                        "role": "system",
-                        "content": format!("Invalid request data: {}", e)
-                    }]
-                }).to_string());
+                .body(
+                    serde_json::json!({
+                        "messages": [{
+                            "role": "system",
+                            "content": format!("Invalid request data: {}", e)
+                        }]
+                    })
+                    .to_string(),
+                );
         }
     };
 
-    println!("[DEBUG] 合并后的数据:{:?}", merged_data);
+    println!("[DEBUG] 合并后的数据:{:?}\n", merged_data);
 
     let client = OpenAIClient::new(
         merged_data.config.llm_api.provider.api_key.to_string(),
@@ -144,23 +152,29 @@ async fn handle_request(
                 .body(json),
             Err(e) => actix_web::HttpResponse::InternalServerError()
                 .content_type("application/json")
-                .body(serde_json::json!({
-                    "messages": [{
-                        "role": "system",
-                        "content": format!("Failed to serialize response: {}", e)
-                    }]
-                }).to_string()),
+                .body(
+                    serde_json::json!({
+                        "messages": [{
+                            "role": "system",
+                            "content": format!("Failed to serialize response: {}", e)
+                        }]
+                    })
+                    .to_string(),
+                ),
         },
         Err(e) => {
             eprintln!("Agent Error: {}", e);
             actix_web::HttpResponse::InternalServerError()
                 .content_type("application/json")
-                .body(serde_json::json!({
-                    "messages": [{
-                        "role": "system",
-                        "content": e.to_string()
-                    }]
-                }).to_string())
+                .body(
+                    serde_json::json!({
+                        "messages": [{
+                            "role": "system",
+                            "content": e.to_string()
+                        }]
+                    })
+                    .to_string(),
+                )
         }
     }
 }