Skip to main content

causa_kernel/context/
tools.rs

1//! Tool declaration facts: which tools the model was offered, and from where
2//! in the conversation.
3//!
4//! A [`ToolChange`] block records that the offered set changed at its
5//! position. The tool state at any position is the fold of every earlier
6//! change, so the context alone says which tools the model saw when, and a
7//! renderer can keep the request-level tool list fixed while the set changes.
8//! Execution vocabulary (the `Tool` trait, the bound `ToolSurface`) lives in
9//! `crate::ports::tool`.
10
11use serde::{Deserialize, Serialize};
12
13use crate::context::block::{BlockContent, ContextBlock};
14
15/// The model-facing description of one callable tool; renderers map it onto
16/// the protocol's tool entries (name, description, parameter schema).
17///
18/// Part of the stable serialized set, because a [`ToolChange`] holds it.
19#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
20#[non_exhaustive]
21pub struct ToolDefinition {
22    /// The name the model uses to invoke the tool.
23    pub name: String,
24    /// Short summary of what the tool does, shown to the model.
25    pub description: String,
26    /// Schema of the arguments the tool accepts, embedded verbatim in the
27    /// rendered request.
28    pub parameters: serde_json::Value,
29}
30impl ToolDefinition {
31    /// A definition from its name, description and JSON Schema parameters.
32    pub fn new(
33        name: impl Into<String>,
34        description: impl Into<String>,
35        parameters: serde_json::Value,
36    ) -> Self {
37        Self {
38            name: name.into(),
39            description: description.into(),
40            parameters,
41        }
42    }
43}
44
45/// A change to the tools offered to the model, effective from the position
46/// of its block onward.
47///
48/// Applying a change removes the `removed` names first, then adds each of
49/// `added`, a definition replacing any current one of the same name. The
50/// first change in a context declares the initial set; [`current_tools`]
51/// folds them all.
52#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
53#[non_exhaustive]
54pub struct ToolChange {
55    /// Definitions offered from here on, replacing same-name definitions.
56    #[serde(default, skip_serializing_if = "Vec::is_empty")]
57    pub added: Vec<ToolDefinition>,
58    /// Names of tools withdrawn from here on. A name that is not offered is
59    /// ignored.
60    #[serde(default, skip_serializing_if = "Vec::is_empty")]
61    pub removed: Vec<String>,
62}
63impl ToolChange {
64    /// A change adding `added` after withdrawing `removed`.
65    pub fn new(added: Vec<ToolDefinition>, removed: Vec<String>) -> Self {
66        Self { added, removed }
67    }
68
69    /// The change that turns the set `previous` into the set `current`.
70    ///
71    /// A tool whose definition differs is withdrawn and added again; a tool
72    /// that only moved in the list is unchanged, since order carries no
73    /// meaning to the model. `added` follows the order of `current`,
74    /// `removed` the order of `previous`.
75    pub fn between(previous: &[ToolDefinition], current: &[ToolDefinition]) -> Self {
76        let find = |set: &[ToolDefinition], name: &str| {
77            set.iter()
78                .find(|definition| definition.name == name)
79                .cloned()
80        };
81        let added = current
82            .iter()
83            .filter(|definition| find(previous, &definition.name).as_ref() != Some(*definition))
84            .cloned()
85            .collect();
86        let removed = previous
87            .iter()
88            .filter(|definition| find(current, &definition.name).as_ref() != Some(*definition))
89            .map(|definition| definition.name.clone())
90            .collect();
91        Self { added, removed }
92    }
93
94    /// Whether the change adds and withdraws nothing.
95    pub fn is_empty(&self) -> bool {
96        self.added.is_empty() && self.removed.is_empty()
97    }
98
99    /// Applies this change to a tool state in place.
100    pub fn apply_to(&self, tools: &mut Vec<ToolDefinition>) {
101        tools.retain(|definition| !self.removed.contains(&definition.name));
102        for definition in &self.added {
103            match tools
104                .iter_mut()
105                .find(|current| current.name == definition.name)
106            {
107                Some(current) => *current = definition.clone(),
108                None => tools.push(definition.clone()),
109            }
110        }
111    }
112}
113
114/// The tools offered after every [`ToolChange`] in `blocks`, in the order
115/// they were first added.
116pub fn current_tools(blocks: &[ContextBlock]) -> Vec<ToolDefinition> {
117    let mut tools = Vec::new();
118    for block in blocks {
119        if let BlockContent::ToolChange(change) = block.content() {
120            change.apply_to(&mut tools);
121        }
122    }
123    tools
124}