1use std::path::Path;
2use std::sync::Arc;
3
4use anyhow::{anyhow, Result};
5use assistant_tool::Tool;
6use gpui::{App, Entity, Task};
7use language_model::LanguageModelRequestMessage;
8use project::Project;
9use schemars::JsonSchema;
10use serde::{Deserialize, Serialize};
11
12#[derive(Debug, Serialize, Deserialize, JsonSchema)]
13pub struct ReadFileToolInput {
14 /// The relative path of the file to read.
15 ///
16 /// This path should never be absolute, and the first component
17 /// of the path should always be a root directory in a project.
18 ///
19 /// <example>
20 /// If the project has the following root directories:
21 ///
22 /// - directory1
23 /// - directory2
24 ///
25 /// If you wanna access `file.txt` in `directory1`, you should use the path `directory1/file.txt`.
26 /// If you wanna access `file.txt` in `directory2`, you should use the path `directory2/file.txt`.
27 /// </example>
28 pub path: Arc<Path>,
29}
30
31pub struct ReadFileTool;
32
33impl Tool for ReadFileTool {
34 fn name(&self) -> String {
35 "read-file".into()
36 }
37
38 fn description(&self) -> String {
39 include_str!("./read_file_tool/description.md").into()
40 }
41
42 fn input_schema(&self) -> serde_json::Value {
43 let schema = schemars::schema_for!(ReadFileToolInput);
44 serde_json::to_value(&schema).unwrap()
45 }
46
47 fn run(
48 self: Arc<Self>,
49 input: serde_json::Value,
50 _messages: &[LanguageModelRequestMessage],
51 project: Entity<Project>,
52 cx: &mut App,
53 ) -> Task<Result<String>> {
54 let input = match serde_json::from_value::<ReadFileToolInput>(input) {
55 Ok(input) => input,
56 Err(err) => return Task::ready(Err(anyhow!(err))),
57 };
58
59 let Some(project_path) = project.read(cx).find_project_path(&input.path, cx) else {
60 return Task::ready(Err(anyhow!("Path not found in project")));
61 };
62 cx.spawn(|cx| async move {
63 let buffer = cx
64 .update(|cx| {
65 project.update(cx, |project, cx| project.open_buffer(project_path, cx))
66 })?
67 .await?;
68
69 buffer.read_with(&cx, |buffer, _cx| {
70 if buffer
71 .file()
72 .map_or(false, |file| file.disk_state().exists())
73 {
74 Ok(buffer.text())
75 } else {
76 Err(anyhow!("File does not exist"))
77 }
78 })?
79 })
80 }
81}