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::{ProxyToolDef, ProxyToolExecutor};
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").and_then(|q| q.as_str()).unwrap_or("");
27
28            let max_results = input
29                .get("max_results")
30                .and_then(|m| m.as_u64())
31                .unwrap_or(5) as u32;
32
33            if query.is_empty() {
34                return Ok(serde_json::json!({
35                    "success": false,
36                    "error": "query is required"
37                })
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) => Ok(serde_json::json!({
47                    "success": true,
48                    "query": query,
49                    "total": images.len(),
50                    "images": images
51                })
52                .to_string()),
53                Err(e) => Ok(serde_json::json!({
54                    "success": false,
55                    "error": e.to_string()
56                })
57                .to_string()),
58            }
59        } else {
60            Err(anyhow::anyhow!("Unknown proxy tool: {}", tool_name))
61        }
62    }
63
64    /// 工具定义 - LLM 看到的描述
65    fn tool_definitions() -> Vec<ProxyToolDef> {
66        vec![
67            ProxyToolDef::new(
68                "image_search",
69                "搜索网络图片资源。返回真实图片URL列表(Unsplash/Pexels/Pixabay)。适用于:找壁纸、素材、插图、风景照片等。",
70                serde_json::json!({
71                    "type": "object",
72                    "properties": {
73                        "query": {
74                            "type": "string",
75                            "description": "搜索关键词,建议使用英文获得更多结果"
76                        },
77                        "max_results": {
78                            "type": "integer",
79                            "description": "每个平台返回的最大结果数,默认5,最大10",
80                            "default": 5
81                        }
82                    },
83                    "required": ["query"]
84                })
85            )
86            .with_priority(true)
87            .with_timeout(30000)
88        ]
89    }
90}
91
92/// 创建执行器
93pub fn create_image_search_executor() -> Arc<dyn ProxyToolExecutor> {
94    Arc::new(ImageSearchExecutor)
95}
96
97/// 获取工具定义(直接从 trait 获取)
98pub fn get_image_search_tool_defs() -> Vec<ProxyToolDef> {
99    ImageSearchExecutor::tool_definitions()
100}
101
102// ============================================================================
103// 别名函数(兼容 main.rs 调用)
104// ============================================================================
105
106/// 创建默认执行器(别名)
107pub fn create_default_executor() -> Arc<dyn ProxyToolExecutor> {
108    create_image_search_executor()
109}
110
111/// 获取默认代理工具定义(别名)
112pub fn get_default_proxy_tools() -> Vec<ProxyToolDef> {
113    get_image_search_tool_defs()
114}