fetch_tool.rs

  1use std::rc::Rc;
  2use std::sync::Arc;
  3use std::{borrow::Cow, cell::RefCell};
  4
  5use crate::schema::json_schema_for;
  6use anyhow::{Context as _, Result, anyhow, bail};
  7use assistant_tool::{ActionLog, Tool, ToolResult};
  8use futures::AsyncReadExt as _;
  9use gpui::{AnyWindowHandle, App, AppContext as _, Entity, Task};
 10use html_to_markdown::{TagHandler, convert_html_to_markdown, markdown};
 11use http_client::{AsyncBody, HttpClientWithUrl};
 12use language_model::{LanguageModel, LanguageModelRequest, LanguageModelToolSchemaFormat};
 13use project::Project;
 14use schemars::JsonSchema;
 15use serde::{Deserialize, Serialize};
 16use ui::IconName;
 17use util::markdown::MarkdownEscaped;
 18
 19#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
 20enum ContentType {
 21    Html,
 22    Plaintext,
 23    Json,
 24}
 25
 26#[derive(Debug, Serialize, Deserialize, JsonSchema)]
 27pub struct FetchToolInput {
 28    /// The URL to fetch.
 29    url: String,
 30}
 31
 32pub struct FetchTool {
 33    http_client: Arc<HttpClientWithUrl>,
 34}
 35
 36impl FetchTool {
 37    pub fn new(http_client: Arc<HttpClientWithUrl>) -> Self {
 38        Self { http_client }
 39    }
 40
 41    async fn build_message(http_client: Arc<HttpClientWithUrl>, url: &str) -> Result<String> {
 42        let url = if !url.starts_with("https://") && !url.starts_with("http://") {
 43            Cow::Owned(format!("https://{url}"))
 44        } else {
 45            Cow::Borrowed(url)
 46        };
 47
 48        let mut response = http_client.get(&url, AsyncBody::default(), true).await?;
 49
 50        let mut body = Vec::new();
 51        response
 52            .body_mut()
 53            .read_to_end(&mut body)
 54            .await
 55            .context("error reading response body")?;
 56
 57        if response.status().is_client_error() {
 58            let text = String::from_utf8_lossy(body.as_slice());
 59            bail!(
 60                "status error {}, response: {text:?}",
 61                response.status().as_u16()
 62            );
 63        }
 64
 65        let Some(content_type) = response.headers().get("content-type") else {
 66            bail!("missing Content-Type header");
 67        };
 68        let content_type = content_type
 69            .to_str()
 70            .context("invalid Content-Type header")?;
 71        let content_type = match content_type {
 72            "text/html" => ContentType::Html,
 73            "text/plain" => ContentType::Plaintext,
 74            "application/json" => ContentType::Json,
 75            _ => ContentType::Html,
 76        };
 77
 78        match content_type {
 79            ContentType::Html => {
 80                let mut handlers: Vec<TagHandler> = vec![
 81                    Rc::new(RefCell::new(markdown::WebpageChromeRemover)),
 82                    Rc::new(RefCell::new(markdown::ParagraphHandler)),
 83                    Rc::new(RefCell::new(markdown::HeadingHandler)),
 84                    Rc::new(RefCell::new(markdown::ListHandler)),
 85                    Rc::new(RefCell::new(markdown::TableHandler::new())),
 86                    Rc::new(RefCell::new(markdown::StyledTextHandler)),
 87                ];
 88                if url.contains("wikipedia.org") {
 89                    use html_to_markdown::structure::wikipedia;
 90
 91                    handlers.push(Rc::new(RefCell::new(wikipedia::WikipediaChromeRemover)));
 92                    handlers.push(Rc::new(RefCell::new(wikipedia::WikipediaInfoboxHandler)));
 93                    handlers.push(Rc::new(
 94                        RefCell::new(wikipedia::WikipediaCodeHandler::new()),
 95                    ));
 96                } else {
 97                    handlers.push(Rc::new(RefCell::new(markdown::CodeHandler)));
 98                }
 99
100                convert_html_to_markdown(&body[..], &mut handlers)
101            }
102            ContentType::Plaintext => Ok(std::str::from_utf8(&body)?.to_owned()),
103            ContentType::Json => {
104                let json: serde_json::Value = serde_json::from_slice(&body)?;
105
106                Ok(format!(
107                    "```json\n{}\n```",
108                    serde_json::to_string_pretty(&json)?
109                ))
110            }
111        }
112    }
113}
114
115impl Tool for FetchTool {
116    fn name(&self) -> String {
117        "fetch".to_string()
118    }
119
120    fn needs_confirmation(&self, _: &serde_json::Value, _: &App) -> bool {
121        false
122    }
123
124    fn may_perform_edits(&self) -> bool {
125        false
126    }
127
128    fn description(&self) -> String {
129        include_str!("./fetch_tool/description.md").to_string()
130    }
131
132    fn icon(&self) -> IconName {
133        IconName::Globe
134    }
135
136    fn input_schema(&self, format: LanguageModelToolSchemaFormat) -> Result<serde_json::Value> {
137        json_schema_for::<FetchToolInput>(format)
138    }
139
140    fn ui_text(&self, input: &serde_json::Value) -> String {
141        match serde_json::from_value::<FetchToolInput>(input.clone()) {
142            Ok(input) => format!("Fetch {}", MarkdownEscaped(&input.url)),
143            Err(_) => "Fetch URL".to_string(),
144        }
145    }
146
147    fn run(
148        self: Arc<Self>,
149        input: serde_json::Value,
150        _request: Arc<LanguageModelRequest>,
151        _project: Entity<Project>,
152        _action_log: Entity<ActionLog>,
153        _model: Arc<dyn LanguageModel>,
154        _window: Option<AnyWindowHandle>,
155        cx: &mut App,
156    ) -> ToolResult {
157        let input = match serde_json::from_value::<FetchToolInput>(input) {
158            Ok(input) => input,
159            Err(err) => return Task::ready(Err(anyhow!(err))).into(),
160        };
161
162        let text = cx.background_spawn({
163            let http_client = self.http_client.clone();
164            async move { Self::build_message(http_client, &input.url).await }
165        });
166
167        cx.foreground_executor()
168            .spawn(async move {
169                let text = text.await?;
170                if text.trim().is_empty() {
171                    bail!("no textual content found");
172                }
173
174                Ok(text.into())
175            })
176            .into()
177    }
178}