matrixcode_tui/
image_search.rs1use 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
16pub struct ImageSearchExecutor;
20
21#[async_trait]
22impl ProxyToolExecutor for ImageSearchExecutor {
23 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 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
94pub fn create_image_search_executor() -> Arc<dyn ProxyToolExecutor> {
96 Arc::new(ImageSearchExecutor)
97}
98
99pub fn get_image_search_tool_defs() -> Vec<ProxyToolDef> {
101 ImageSearchExecutor::tool_definitions()
102}
103
104pub fn create_default_executor() -> Arc<dyn ProxyToolExecutor> {
110 create_image_search_executor()
111}
112
113pub fn get_default_proxy_tools() -> Vec<ProxyToolDef> {
115 get_image_search_tool_defs()
116}