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, bail};
  7use assistant_tool::{ActionLog, Tool, ToolResult};
  8use futures::AsyncReadExt as _;
  9use gpui::{AnyWindowHandle, App, AppContext as _, Entity};
 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    type Input = FetchToolInput;
117
118    fn name(&self) -> String {
119        "fetch".to_string()
120    }
121
122    fn needs_confirmation(&self, _: &Self::Input, _: &App) -> bool {
123        false
124    }
125
126    fn may_perform_edits(&self) -> bool {
127        false
128    }
129
130    fn description(&self) -> String {
131        include_str!("./fetch_tool/description.md").to_string()
132    }
133
134    fn icon(&self) -> IconName {
135        IconName::Globe
136    }
137
138    fn input_schema(&self, format: LanguageModelToolSchemaFormat) -> Result<serde_json::Value> {
139        json_schema_for::<FetchToolInput>(format)
140    }
141
142    fn ui_text(&self, input: &Self::Input) -> String {
143        format!("Fetch {}", MarkdownEscaped(&input.url))
144    }
145
146    fn run(
147        self: Arc<Self>,
148        input: Self::Input,
149        _request: Arc<LanguageModelRequest>,
150        _project: Entity<Project>,
151        _action_log: Entity<ActionLog>,
152        _model: Arc<dyn LanguageModel>,
153        _window: Option<AnyWindowHandle>,
154        cx: &mut App,
155    ) -> ToolResult {
156        let text = cx.background_spawn({
157            let http_client = self.http_client.clone();
158            async move { Self::build_message(http_client, &input.url).await }
159        });
160
161        cx.foreground_executor()
162            .spawn(async move {
163                let text = text.await?;
164                if text.trim().is_empty() {
165                    bail!("no textual content found");
166                }
167
168                Ok(text.into())
169            })
170            .into()
171    }
172}