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        true
122    }
123
124    fn description(&self) -> String {
125        include_str!("./fetch_tool/description.md").to_string()
126    }
127
128    fn icon(&self) -> IconName {
129        IconName::Globe
130    }
131
132    fn input_schema(&self, format: LanguageModelToolSchemaFormat) -> Result<serde_json::Value> {
133        json_schema_for::<FetchToolInput>(format)
134    }
135
136    fn ui_text(&self, input: &serde_json::Value) -> String {
137        match serde_json::from_value::<FetchToolInput>(input.clone()) {
138            Ok(input) => format!("Fetch {}", MarkdownEscaped(&input.url)),
139            Err(_) => "Fetch URL".to_string(),
140        }
141    }
142
143    fn run(
144        self: Arc<Self>,
145        input: serde_json::Value,
146        _request: Arc<LanguageModelRequest>,
147        _project: Entity<Project>,
148        _action_log: Entity<ActionLog>,
149        _model: Arc<dyn LanguageModel>,
150        _window: Option<AnyWindowHandle>,
151        cx: &mut App,
152    ) -> ToolResult {
153        let input = match serde_json::from_value::<FetchToolInput>(input) {
154            Ok(input) => input,
155            Err(err) => return Task::ready(Err(anyhow!(err))).into(),
156        };
157
158        let text = cx.background_spawn({
159            let http_client = self.http_client.clone();
160            async move { Self::build_message(http_client, &input.url).await }
161        });
162
163        cx.foreground_executor()
164            .spawn(async move {
165                let text = text.await?;
166                if text.trim().is_empty() {
167                    bail!("no textual content found");
168                }
169
170                Ok(text.into())
171            })
172            .into()
173    }
174}