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 fn name() -> &'static str {
50 "web_search"
51 }
52
53 fn kind() -> acp::ToolKind {
54 acp::ToolKind::Fetch
55 }
56
57 fn initial_title(
58 &self,
59 _input: Result<Self::Input, serde_json::Value>,
60 _cx: &mut App,
61 ) -> SharedString {
62 "Searching the Web".into()
63 }
64
65 /// We currently only support Zed Cloud as a provider.
66 fn supports_provider(provider: &LanguageModelProviderId) -> bool {
67 provider == &ZED_CLOUD_PROVIDER_ID
68 }
69
70 fn run(
71 self: Arc<Self>,
72 input: Self::Input,
73 event_stream: ToolCallEventStream,
74 cx: &mut App,
75 ) -> Task<Result<Self::Output>> {
76 let settings = AgentSettings::get_global(cx);
77 let decision = decide_permission_from_settings(Self::name(), &input.query, settings);
78
79 let authorize = match decision {
80 ToolPermissionDecision::Allow => None,
81 ToolPermissionDecision::Deny(reason) => {
82 return Task::ready(Err(anyhow!("{}", reason)));
83 }
84 ToolPermissionDecision::Confirm => {
85 let context = crate::ToolPermissionContext {
86 tool_name: "web_search".to_string(),
87 input_value: input.query.clone(),
88 };
89 Some(event_stream.authorize(
90 format!("Search the web for {}", MarkdownInlineCode(&input.query)),
91 context,
92 cx,
93 ))
94 }
95 };
96
97 let Some(provider) = WebSearchRegistry::read_global(cx).active_provider() else {
98 return Task::ready(Err(anyhow!("Web search is not available.")));
99 };
100
101 let search_task = provider.search(input.query, cx);
102 cx.background_spawn(async move {
103 if let Some(authorize) = authorize {
104 authorize.await?;
105 }
106
107 let response = futures::select! {
108 result = search_task.fuse() => {
109 match result {
110 Ok(response) => response,
111 Err(err) => {
112 event_stream
113 .update_fields(acp::ToolCallUpdateFields::new().title("Web Search Failed"));
114 return Err(err);
115 }
116 }
117 }
118 _ = event_stream.cancelled_by_user().fuse() => {
119 anyhow::bail!("Web search cancelled by user");
120 }
121 };
122
123 emit_update(&response, &event_stream);
124 Ok(WebSearchToolOutput(response))
125 })
126 }
127
128 fn replay(
129 &self,
130 _input: Self::Input,
131 output: Self::Output,
132 event_stream: ToolCallEventStream,
133 _cx: &mut App,
134 ) -> Result<()> {
135 emit_update(&output.0, &event_stream);
136 Ok(())
137 }
138}
139
140fn emit_update(response: &WebSearchResponse, event_stream: &ToolCallEventStream) {
141 let result_text = if response.results.len() == 1 {
142 "1 result".to_string()
143 } else {
144 format!("{} results", response.results.len())
145 };
146 event_stream.update_fields(
147 acp::ToolCallUpdateFields::new()
148 .title(format!("Searched the web: {result_text}"))
149 .content(
150 response
151 .results
152 .iter()
153 .map(|result| {
154 acp::ToolCallContent::Content(acp::Content::new(
155 acp::ContentBlock::ResourceLink(
156 acp::ResourceLink::new(result.title.clone(), result.url.clone())
157 .title(result.title.clone())
158 .description(result.text.clone()),
159 ),
160 ))
161 })
162 .collect::<Vec<_>>(),
163 ),
164 );
165}