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(
76 Self::NAME,
77 std::slice::from_ref(&input.query),
78 settings,
79 );
80
81 let authorize = match decision {
82 ToolPermissionDecision::Allow => None,
83 ToolPermissionDecision::Deny(reason) => {
84 return Task::ready(Err(anyhow!("{}", reason)));
85 }
86 ToolPermissionDecision::Confirm => {
87 let context =
88 crate::ToolPermissionContext::new(Self::NAME, vec![input.query.clone()]);
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}