Ver Fonte

【格式】优化代码格式和模块结构

- 调整代码缩进和格式,提高可读性
- 优化模块导入顺序和结构
- 移除未使用的代码注释
- 统一错误处理风格
PJ568 há 1 ano atrás
pai
commit
015009e901

+ 1 - 1
Cargo.lock

@@ -2449,7 +2449,7 @@ checksum = "1e9df38ee2d2c3c5948ea468a8406ff0db0b29ae1ffde1bcf20ef305bcc95c51"
 
 [[package]]
 name = "yaa"
-version = "2.13.4"
+version = "2.13.5"
 dependencies = [
  "actix-cors",
  "actix-web",

+ 1 - 1
Cargo.toml

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

+ 9 - 6
src/agent/api.rs

@@ -46,12 +46,11 @@ impl OpenAIClient {
 
 impl Default for OpenAIClient {
     fn default() -> Self {
-        let api_key = std::env::var("OPENAI_API_KEY")
-            .unwrap_or_else(|_| "".to_string());
+        let api_key = std::env::var("OPENAI_API_KEY").unwrap_or_else(|_| "".to_string());
         let base_url = std::env::var("OPENAI_API_BASE")
             .ok()
             .unwrap_or_else(|| "https://api.deepseek.com".to_string());
-        
+
         Self::new(api_key, Some(base_url))
     }
 }
@@ -76,7 +75,8 @@ impl OpenAIApi for &OpenAIClient {
         model: &str,
         temperature: f32,
     ) -> Result<String, ApiError> {
-        let response = self.client
+        let response = self
+            .client
             .post(format!("{}/v1/chat/completions", self.base_url))
             .header("Authorization", format!("Bearer {}", self.api_key))
             .header("Content-Type", "application/json")
@@ -89,7 +89,8 @@ impl OpenAIApi for &OpenAIClient {
             .await
             .map_err(|e| ApiError::RequestFailed(e.to_string()))?;
 
-        let response_text = response.text()
+        let response_text = response
+            .text()
             .await
             .map_err(|e| ApiError::ParseFailed(e.to_string()))?;
 
@@ -99,6 +100,8 @@ impl OpenAIApi for &OpenAIClient {
         json["choices"][0]["message"]["content"]
             .as_str()
             .map(|s| s.to_string())
-            .ok_or_else(|| ApiError::InvalidFormat("Missing required fields".to_string(), response_text))
+            .ok_or_else(|| {
+                ApiError::InvalidFormat("Missing required fields".to_string(), response_text)
+            })
     }
 }

+ 1 - 1
src/agent/mod.rs

@@ -278,7 +278,7 @@ fn get_response_messages(session_data: &SessionData) -> Vec<Message> {
         .rposition(|m| matches!(m.role, Role::User))
         .unwrap_or(0);
 
-        // 跳过用户消息和系统提示词
+    // 跳过用户消息和系统提示词
     let start_idx = last_user_idx + 2;
 
     // 确保 start_idx 不超过消息总数

+ 1 - 1
src/agent/prompt.rs

@@ -163,4 +163,4 @@ impl PromptGenerator {
     }
 }
 
-// TODO 测试
+// TODO 测试

+ 1 - 1
src/agent/tool.rs

@@ -1,8 +1,8 @@
 //! 工具调用相关功能
 
 use crate::agent::tools::finish::FinishTool;
-use crate::agent::tools::rethink::RethinkTool;
 use crate::agent::tools::question::QuestionTool;
+use crate::agent::tools::rethink::RethinkTool;
 use crate::core::tool::ToolRegistry;
 use serde_json;
 

+ 1 - 1
src/agent/tools/finish.rs

@@ -20,7 +20,7 @@ impl Tool for FinishTool {
             name: "reason".to_string(),
             description: "任务完成的总结理由".to_string(),
             required: true,
-            r#type: "string".to_string()
+            r#type: "string".to_string(),
         }]
     }
 

+ 2 - 2
src/agent/tools/mod.rs

@@ -1,5 +1,5 @@
 //! 工具实现模块
 
-pub mod rethink;
 pub mod finish;
-pub mod question;
+pub mod question;
+pub mod rethink;

+ 6 - 9
src/agent/tools/question.rs

@@ -21,26 +21,26 @@ impl Tool for QuestionTool {
                 name: "question".to_string(),
                 description: "想要询问用户的问题".to_string(),
                 required: true,
-                r#type: "string".to_string()
+                r#type: "string".to_string(),
             },
             ToolParam {
                 name: "guess_one".to_string(),
                 description: "用户可能的回答".to_string(),
                 required: false,
-                r#type: "string".to_string()
+                r#type: "string".to_string(),
             },
             ToolParam {
                 name: "guess_two".to_string(),
                 description: "用户可能的回答".to_string(),
                 required: false,
-                r#type: "string".to_string()
+                r#type: "string".to_string(),
             },
             ToolParam {
                 name: "guess_three".to_string(),
                 description: "用户可能的回答".to_string(),
                 required: false,
-                r#type: "string".to_string()
-            }
+                r#type: "string".to_string(),
+            },
         ]
     }
 
@@ -68,10 +68,7 @@ impl Tool for QuestionTool {
         // 添加工具调用消息到会话
         session.add_message(
             crate::core::session::Role::System,
-            format!(
-                "[{}]执行成功。",
-                self.name()
-            ),
+            format!("[{}]执行成功。", self.name()),
         );
 
         Ok(ToolOutput {

+ 2 - 2
src/cli/commands.rs

@@ -1,5 +1,5 @@
-use clap::Subcommand;
 use anyhow::Result;
+use clap::Subcommand;
 
 #[derive(Subcommand, Debug)]
 pub enum Commands {
@@ -26,4 +26,4 @@ pub fn handle_command(cmd: Commands) -> Result<()> {
             Ok(())
         }
     }
-}
+}

+ 20 - 13
src/cli/mod.rs

@@ -1,45 +1,52 @@
 pub mod commands;
 
+use crate::agent::{api::OpenAIClient, process_session};
 use crate::core::session::{FinishReason, Message, SessionData};
 use crate::core::tool::ToolRegistry;
-use crate::agent::{process_session, api::OpenAIClient};
 use anyhow::Result;
 use std::io::{self, Write};
 
-pub async fn run_interactive(tool_registry: &ToolRegistry, client: &OpenAIClient, session_data: &SessionData) -> Result<()> {
+pub async fn run_interactive(
+    tool_registry: &ToolRegistry,
+    client: &OpenAIClient,
+    session_data: &SessionData,
+) -> Result<()> {
     println!("=== YAA 智能体命令行交互模式 ===");
     println!("输入 '/exit' 退出");
-    
+
     let mut session = session_data.clone();
-    
+
     loop {
         print!("> ");
         io::stdout().flush()?;
-        
+
         let mut input = String::new();
         io::stdin().read_line(&mut input)?;
         let input = input.trim();
-        
+
         if input.eq_ignore_ascii_case("/exit") {
             break;
         }
-        
+
         session.messages.push(Message {
             role: crate::core::session::Role::User,
             content: input.to_string(),
         });
-        
+
         let response = process_session(session.clone(), tool_registry, client).await?;
-        
+
         for msg in &response.messages {
             println!("【{:?}】\n{}", msg.role, msg.content);
             session.add_message(msg.role.clone(), msg.content.clone());
         }
-        
-        if matches!(response.finish_reason, FinishReason::Completed | FinishReason::Interrupted) {
+
+        if matches!(
+            response.finish_reason,
+            FinishReason::Completed | FinishReason::Interrupted
+        ) {
             break;
         }
     }
-    
+
     Ok(())
-}
+}

+ 0 - 1
src/core/mod.rs

@@ -2,4 +2,3 @@
 
 pub mod session;
 pub mod tool;
-

+ 7 - 6
src/core/session.rs

@@ -1,5 +1,5 @@
-use serde::{Serialize, Deserialize};
 use chrono::{DateTime, Utc};
+use serde::{Deserialize, Serialize};
 use uuid::Uuid;
 
 #[derive(Debug, Clone, Serialize, Deserialize)]
@@ -39,7 +39,6 @@ pub struct Usage {
     pub total_tokens: u32,
 }
 
-
 #[derive(Debug, Clone, Serialize, Deserialize)]
 #[serde(rename_all = "camelCase")]
 pub struct SessionData {
@@ -66,8 +65,7 @@ pub struct Message {
     pub content: String,
 }
 
-#[derive(Debug, Clone, Serialize, Deserialize)]
-#[derive(PartialEq)]
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
 #[serde(rename_all = "lowercase")]
 pub enum Role {
     User,
@@ -150,7 +148,10 @@ pub struct ToolApprovalConfig {
 }
 
 impl SessionData {
-    pub fn new(character: impl Into<String>, tool_registry: Option<&crate::core::tool::ToolRegistry>) -> Self {
+    pub fn new(
+        character: impl Into<String>,
+        tool_registry: Option<&crate::core::tool::ToolRegistry>,
+    ) -> Self {
         Self {
             id: Uuid::new_v4().to_string(),
             title: None,
@@ -246,4 +247,4 @@ impl Default for Config {
             tool: ToolConfig::default(),
         }
     }
-}
+}