Skip to main content

matrixcode_tui/
image_search.rs

1//! Proxy Tool Executor Implementation
2//!
3//! 实现 ProxyToolExecutor trait,包含:
4//! - exec(): 执行逻辑
5//! - tool_definitions(): 工具定义(LLM 看到的)
6
7use anyhow::Result;
8use async_trait::async_trait;
9use serde_json::Value;
10use std::sync::Arc;
11
12use matrixcode_core::tools::toolproxy::{ProxyToolExecutor, ProxyToolDef};
13
14use crate::image_utils;
15
16/// 图片搜索执行器
17///
18/// 同时提供执行逻辑和工具定义
19pub struct ImageSearchExecutor;
20
21#[async_trait]
22impl ProxyToolExecutor for ImageSearchExecutor {
23    /// 执行图片搜索
24    async fn exec(&self, tool_name: &str, input: Value) -> Result<String> {
25        if tool_name == "image_search" {
26            let query = input.get("query")
27                .and_then(|q| q.as_str())
28                .unwrap_or("");
29
30            let max_results = input.get("max_results")
31                .and_then(|m| m.as_u64())
32                .unwrap_or(5) as u32;
33
34            if query.is_empty() {
35                return Ok(serde_json::json!({
36                    "success": false,
37                    "error": "query is required"
38                }).to_string());
39            }
40
41            log::info!("Image search: query={}, max_results={}", query, max_results);
42
43            let results = image_utils::search_all(query, max_results).await;
44
45            match results {
46                Ok(images) => {
47                    Ok(serde_json::json!({
48                        "success": true,
49                        "query": query,
50                        "total": images.len(),
51                        "images": images
52                    }).to_string())
53                }
54                Err(e) => {
55                    Ok(serde_json::json!({
56                        "success": false,
57                        "error": e.to_string()
58                    }).to_string())
59                }
60            }
61        } else {
62            Err(anyhow::anyhow!("Unknown proxy tool: {}", tool_name))
63        }
64    }
65
66    /// 工具定义 - LLM 看到的描述
67    fn tool_definitions() -> Vec<ProxyToolDef> {
68        vec![
69            ProxyToolDef::new(
70                "image_search",
71                "搜索网络图片资源。返回真实图片URL列表(Unsplash/Pexels/Pixabay)。适用于:找壁纸、素材、插图、风景照片等。",
72                serde_json::json!({
73                    "type": "object",
74                    "properties": {
75                        "query": {
76                            "type": "string",
77                            "description": "搜索关键词,建议使用英文获得更多结果"
78                        },
79                        "max_results": {
80                            "type": "integer",
81                            "description": "每个平台返回的最大结果数,默认5,最大10",
82                            "default": 5
83                        }
84                    },
85                    "required": ["query"]
86                })
87            )
88            .with_priority(true)
89            .with_timeout(30000)
90        ]
91    }
92}
93
94/// 创建执行器
95pub fn create_image_search_executor() -> Arc<dyn ProxyToolExecutor> {
96    Arc::new(ImageSearchExecutor)
97}
98
99/// 获取工具定义(直接从 trait 获取)
100pub fn get_image_search_tool_defs() -> Vec<ProxyToolDef> {
101    ImageSearchExecutor::tool_definitions()
102}
103
104// ============================================================================
105// 别名函数(兼容 main.rs 调用)
106// ============================================================================
107
108/// 创建默认执行器(别名)
109pub fn create_default_executor() -> Arc<dyn ProxyToolExecutor> {
110    create_image_search_executor()
111}
112
113/// 获取默认代理工具定义(别名)
114pub fn get_default_proxy_tools() -> Vec<ProxyToolDef> {
115    get_image_search_tool_defs()
116}