assistant_tool.rs

 1mod action_log;
 2mod tool_registry;
 3mod tool_schema;
 4mod tool_working_set;
 5
 6use std::fmt;
 7use std::fmt::Debug;
 8use std::fmt::Formatter;
 9use std::sync::Arc;
10
11use anyhow::Result;
12use gpui::{App, Entity, SharedString, Task};
13use icons::IconName;
14use language_model::LanguageModelRequestMessage;
15use language_model::LanguageModelToolSchemaFormat;
16use project::Project;
17
18pub use crate::action_log::*;
19pub use crate::tool_registry::*;
20pub use crate::tool_schema::*;
21pub use crate::tool_working_set::*;
22
23pub fn init(cx: &mut App) {
24    ToolRegistry::default_global(cx);
25}
26
27/// The result of running a tool
28pub struct ToolResult {
29    /// The asynchronous task that will eventually resolve to the tool's output
30    pub output: Task<Result<String>>,
31}
32
33impl From<Task<Result<String>>> for ToolResult {
34    /// Convert from a task to a ToolResult
35    fn from(output: Task<Result<String>>) -> Self {
36        Self { output }
37    }
38}
39
40#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone)]
41pub enum ToolSource {
42    /// A native tool built-in to Zed.
43    Native,
44    /// A tool provided by a context server.
45    ContextServer { id: SharedString },
46}
47
48/// A tool that can be used by a language model.
49pub trait Tool: 'static + Send + Sync {
50    /// Returns the name of the tool.
51    fn name(&self) -> String;
52
53    /// Returns the description of the tool.
54    fn description(&self) -> String;
55
56    /// Returns the icon for the tool.
57    fn icon(&self) -> IconName;
58
59    /// Returns the source of the tool.
60    fn source(&self) -> ToolSource {
61        ToolSource::Native
62    }
63
64    /// Returns true iff the tool needs the users's confirmation
65    /// before having permission to run.
66    fn needs_confirmation(&self, input: &serde_json::Value, cx: &App) -> bool;
67
68    /// Returns the JSON schema that describes the tool's input.
69    fn input_schema(&self, _: LanguageModelToolSchemaFormat) -> Result<serde_json::Value> {
70        Ok(serde_json::Value::Object(serde_json::Map::default()))
71    }
72
73    /// Returns markdown to be displayed in the UI for this tool.
74    fn ui_text(&self, input: &serde_json::Value) -> String;
75
76    /// Runs the tool with the provided input.
77    fn run(
78        self: Arc<Self>,
79        input: serde_json::Value,
80        messages: &[LanguageModelRequestMessage],
81        project: Entity<Project>,
82        action_log: Entity<ActionLog>,
83        cx: &mut App,
84    ) -> ToolResult;
85}
86
87impl Debug for dyn Tool {
88    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
89        f.debug_struct("Tool").field("name", &self.name()).finish()
90    }
91}