web_search_tool.rs

  1use std::sync::Arc;
  2
  3use crate::{
  4    AgentTool, ToolCallEventStream, ToolPermissionDecision, decide_permission_from_settings,
  5};
  6use agent_client_protocol as acp;
  7use agent_settings::AgentSettings;
  8use anyhow::{Result, anyhow};
  9use cloud_llm_client::WebSearchResponse;
 10use futures::FutureExt as _;
 11use gpui::{App, AppContext, Task};
 12use language_model::{
 13    LanguageModelProviderId, LanguageModelToolResultContent, ZED_CLOUD_PROVIDER_ID,
 14};
 15use schemars::JsonSchema;
 16use serde::{Deserialize, Serialize};
 17use settings::Settings;
 18use ui::prelude::*;
 19use util::markdown::MarkdownInlineCode;
 20use web_search::WebSearchRegistry;
 21
 22/// Search the web for information using your query.
 23/// Use this when you need real-time information, facts, or data that might not be in your training.
 24/// Results will include snippets and links from relevant web pages.
 25#[derive(Debug, Serialize, Deserialize, JsonSchema)]
 26pub struct WebSearchToolInput {
 27    /// The search term or question to query on the web.
 28    query: String,
 29}
 30
 31#[derive(Debug, Serialize, Deserialize)]
 32#[serde(transparent)]
 33pub struct WebSearchToolOutput(WebSearchResponse);
 34
 35impl From<WebSearchToolOutput> for LanguageModelToolResultContent {
 36    fn from(value: WebSearchToolOutput) -> Self {
 37        serde_json::to_string(&value.0)
 38            .expect("Failed to serialize WebSearchResponse")
 39            .into()
 40    }
 41}
 42
 43pub struct WebSearchTool;
 44
 45impl AgentTool for WebSearchTool {
 46    type Input = WebSearchToolInput;
 47    type Output = WebSearchToolOutput;
 48
 49    const NAME: &'static str = "web_search";
 50
 51    fn kind() -> acp::ToolKind {
 52        acp::ToolKind::Fetch
 53    }
 54
 55    fn initial_title(
 56        &self,
 57        _input: Result<Self::Input, serde_json::Value>,
 58        _cx: &mut App,
 59    ) -> SharedString {
 60        "Searching the Web".into()
 61    }
 62
 63    /// We currently only support Zed Cloud as a provider.
 64    fn supports_provider(provider: &LanguageModelProviderId) -> bool {
 65        provider == &ZED_CLOUD_PROVIDER_ID
 66    }
 67
 68    fn run(
 69        self: Arc<Self>,
 70        input: Self::Input,
 71        event_stream: ToolCallEventStream,
 72        cx: &mut App,
 73    ) -> Task<Result<Self::Output>> {
 74        let settings = AgentSettings::get_global(cx);
 75        let decision = decide_permission_from_settings(Self::NAME, &input.query, settings);
 76
 77        let authorize = match decision {
 78            ToolPermissionDecision::Allow => None,
 79            ToolPermissionDecision::Deny(reason) => {
 80                return Task::ready(Err(anyhow!("{}", reason)));
 81            }
 82            ToolPermissionDecision::Confirm => {
 83                let context = crate::ToolPermissionContext {
 84                    tool_name: Self::NAME.to_string(),
 85                    input_value: input.query.clone(),
 86                };
 87                Some(event_stream.authorize(
 88                    format!("Search the web for {}", MarkdownInlineCode(&input.query)),
 89                    context,
 90                    cx,
 91                ))
 92            }
 93        };
 94
 95        let Some(provider) = WebSearchRegistry::read_global(cx).active_provider() else {
 96            return Task::ready(Err(anyhow!("Web search is not available.")));
 97        };
 98
 99        let search_task = provider.search(input.query, cx);
100        cx.background_spawn(async move {
101            if let Some(authorize) = authorize {
102                authorize.await?;
103            }
104
105            let response = futures::select! {
106                result = search_task.fuse() => {
107                    match result {
108                        Ok(response) => response,
109                        Err(err) => {
110                            event_stream
111                                .update_fields(acp::ToolCallUpdateFields::new().title("Web Search Failed"));
112                            return Err(err);
113                        }
114                    }
115                }
116                _ = event_stream.cancelled_by_user().fuse() => {
117                    anyhow::bail!("Web search cancelled by user");
118                }
119            };
120
121            emit_update(&response, &event_stream);
122            Ok(WebSearchToolOutput(response))
123        })
124    }
125
126    fn replay(
127        &self,
128        _input: Self::Input,
129        output: Self::Output,
130        event_stream: ToolCallEventStream,
131        _cx: &mut App,
132    ) -> Result<()> {
133        emit_update(&output.0, &event_stream);
134        Ok(())
135    }
136}
137
138fn emit_update(response: &WebSearchResponse, event_stream: &ToolCallEventStream) {
139    let result_text = if response.results.len() == 1 {
140        "1 result".to_string()
141    } else {
142        format!("{} results", response.results.len())
143    };
144    event_stream.update_fields(
145        acp::ToolCallUpdateFields::new()
146            .title(format!("Searched the web: {result_text}"))
147            .content(
148                response
149                    .results
150                    .iter()
151                    .map(|result| {
152                        acp::ToolCallContent::Content(acp::Content::new(
153                            acp::ContentBlock::ResourceLink(
154                                acp::ResourceLink::new(result.title.clone(), result.url.clone())
155                                    .title(result.title.clone())
156                                    .description(result.text.clone()),
157                            ),
158                        ))
159                    })
160                    .collect::<Vec<_>>(),
161            ),
162    );
163}