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::{ProxyToolDef, ProxyToolExecutor};
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").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 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
92pub fn create_image_search_executor() -> Arc<dyn ProxyToolExecutor> {
94 Arc::new(ImageSearchExecutor)
95}
96
97pub fn get_image_search_tool_defs() -> Vec<ProxyToolDef> {
99 ImageSearchExecutor::tool_definitions()
100}
101
102pub fn create_default_executor() -> Arc<dyn ProxyToolExecutor> {
108 create_image_search_executor()
109}
110
111pub fn get_default_proxy_tools() -> Vec<ProxyToolDef> {
113 get_image_search_tool_defs()
114}