read_file_tool.rs

  1use std::path::Path;
  2use std::sync::Arc;
  3
  4use anyhow::{anyhow, Result};
  5use assistant_tool::{ActionLog, Tool};
  6use gpui::{App, Entity, Task};
  7use itertools::Itertools;
  8use language_model::LanguageModelRequestMessage;
  9use project::Project;
 10use schemars::JsonSchema;
 11use serde::{Deserialize, Serialize};
 12
 13#[derive(Debug, Serialize, Deserialize, JsonSchema)]
 14pub struct ReadFileToolInput {
 15    /// The relative path of the file to read.
 16    ///
 17    /// This path should never be absolute, and the first component
 18    /// of the path should always be a root directory in a project.
 19    ///
 20    /// <example>
 21    /// If the project has the following root directories:
 22    ///
 23    /// - directory1
 24    /// - directory2
 25    ///
 26    /// If you wanna access `file.txt` in `directory1`, you should use the path `directory1/file.txt`.
 27    /// If you wanna access `file.txt` in `directory2`, you should use the path `directory2/file.txt`.
 28    /// </example>
 29    pub path: Arc<Path>,
 30
 31    /// Optional line number to start reading on (1-based index)
 32    #[serde(default)]
 33    pub start_line: Option<usize>,
 34
 35    /// Optional line number to end reading on (1-based index)
 36    #[serde(default)]
 37    pub end_line: Option<usize>,
 38}
 39
 40pub struct ReadFileTool;
 41
 42impl Tool for ReadFileTool {
 43    fn name(&self) -> String {
 44        "read-file".into()
 45    }
 46
 47    fn description(&self) -> String {
 48        include_str!("./read_file_tool/description.md").into()
 49    }
 50
 51    fn input_schema(&self) -> serde_json::Value {
 52        let schema = schemars::schema_for!(ReadFileToolInput);
 53        serde_json::to_value(&schema).unwrap()
 54    }
 55
 56    fn ui_text(&self, input: &serde_json::Value) -> String {
 57        match serde_json::from_value::<ReadFileToolInput>(input.clone()) {
 58            Ok(input) => format!("Read file `{}`", input.path.display()),
 59            Err(_) => "Read file".to_string(),
 60        }
 61    }
 62
 63    fn run(
 64        self: Arc<Self>,
 65        input: serde_json::Value,
 66        _messages: &[LanguageModelRequestMessage],
 67        project: Entity<Project>,
 68        action_log: Entity<ActionLog>,
 69        cx: &mut App,
 70    ) -> Task<Result<String>> {
 71        let input = match serde_json::from_value::<ReadFileToolInput>(input) {
 72            Ok(input) => input,
 73            Err(err) => return Task::ready(Err(anyhow!(err))),
 74        };
 75
 76        let Some(project_path) = project.read(cx).find_project_path(&input.path, cx) else {
 77            return Task::ready(Err(anyhow!(
 78                "Path {} not found in project",
 79                &input.path.display()
 80            )));
 81        };
 82
 83        cx.spawn(async move |cx| {
 84            let buffer = cx
 85                .update(|cx| {
 86                    project.update(cx, |project, cx| project.open_buffer(project_path, cx))
 87                })?
 88                .await?;
 89
 90            let result = buffer.read_with(cx, |buffer, _cx| {
 91                let text = buffer.text();
 92                if input.start_line.is_some() || input.end_line.is_some() {
 93                    let start = input.start_line.unwrap_or(1);
 94                    let lines = text.split('\n').skip(start - 1);
 95                    if let Some(end) = input.end_line {
 96                        let count = end.saturating_sub(start);
 97                        Itertools::intersperse(lines.take(count), "\n").collect()
 98                    } else {
 99                        Itertools::intersperse(lines, "\n").collect()
100                    }
101                } else {
102                    text
103                }
104            })?;
105
106            action_log.update(cx, |log, cx| {
107                log.buffer_read(buffer, cx);
108            })?;
109
110            anyhow::Ok(result)
111        })
112    }
113}