Skip to main content

rig_agent/run/
calls.rs

1//! The open calls of a `CallTools` step and the answers that close them. The
2//! run classifies each call once, and builds every result from the answer.
3
4use serde::{Deserialize, Serialize};
5
6use rig_core::message::{CallId, ToolCall, ToolName};
7use rig_core::tool::ToolResult;
8
9use super::InvalidToolCallAction;
10
11/// One open tool call of a [`CallTools`](super::AgentRunStep::CallTools) step.
12#[derive(Debug, Clone, Serialize, Deserialize)]
13#[non_exhaustive]
14pub enum PendingToolCall {
15    /// A call whose arguments parsed and that nothing suppressed: execute it.
16    Execute(ExecCall),
17    /// A call whose arguments are not a JSON object: answer it without running it.
18    Malformed(MalformedCall),
19}
20
21/// A tool call the driver should execute, answered with [`ExecCall::answer`].
22#[derive(Debug, Clone, Serialize, Deserialize)]
23pub struct ExecCall {
24    pub(super) turn: usize,
25    pub(super) index: usize,
26    pub(super) tool_call: ToolCall,
27}
28
29impl ExecCall {
30    /// The provider's call id.
31    pub fn id(&self) -> &CallId {
32        &self.tool_call.id
33    }
34
35    /// The tool to execute.
36    pub fn name(&self) -> &ToolName {
37        &self.tool_call.function.name
38    }
39
40    /// The call as the model emitted it, with any repaired tool name applied.
41    pub fn tool_call(&self) -> &ToolCall {
42        &self.tool_call
43    }
44
45    /// The parsed arguments, a JSON object.
46    pub fn arguments(&self) -> serde_json::Value {
47        self.tool_call.function.arguments_value()
48    }
49
50    /// Answer this call with the result of executing it (or of a hook
51    /// skipping it, as [`ToolResult::skipped`]).
52    pub fn answer(self, result: ToolResult) -> ToolAnswer {
53        ToolAnswer {
54            turn: self.turn,
55            index: self.index,
56            call: self.tool_call.id,
57            kind: AnswerKind::Executed(result),
58        }
59    }
60}
61
62/// A tool call whose arguments are not a JSON object. It has no parsed
63/// arguments and is never executed; answer it with [`MalformedCall::answer`].
64///
65/// It cannot be answered as executed:
66///
67/// ```compile_fail,E0308
68/// # use rig_agent::run::MalformedCall;
69/// # use rig_core::tool::{ToolOutput, ToolResult};
70/// fn answer(call: MalformedCall) {
71///     let _ = call.answer(ToolResult::success(ToolOutput::text("wrote 5 bytes")));
72/// }
73/// ```
74///
75/// Nor read as a call to execute:
76///
77/// ```compile_fail,E0624
78/// # use rig_agent::run::MalformedCall;
79/// fn arguments(call: &MalformedCall) {
80///     let _ = call.tool_call();
81/// }
82/// ```
83#[derive(Debug, Clone, Serialize, Deserialize)]
84pub struct MalformedCall {
85    pub(super) turn: usize,
86    pub(super) index: usize,
87    pub(super) tool_call: ToolCall,
88}
89
90impl MalformedCall {
91    /// The provider's call id.
92    pub fn id(&self) -> &CallId {
93        &self.tool_call.id
94    }
95
96    /// The tool the model called.
97    pub fn name(&self) -> &ToolName {
98        &self.tool_call.function.name
99    }
100
101    /// The arguments text exactly as the model sent it.
102    pub fn raw_arguments(&self) -> &str {
103        self.tool_call
104            .function
105            .invalid_arguments
106            .as_deref()
107            .unwrap_or_default()
108    }
109
110    pub(crate) fn tool_call(&self) -> &ToolCall {
111        &self.tool_call
112    }
113
114    /// Answer this call with the invalid-call hook's action, or `None` when no
115    /// hook decided. `None` and [`InvalidToolCallAction::Retry`] tell the model
116    /// to call again, `Skip` answers with a skipped result, and `Stop`, `Fail`
117    /// and `Repair` end the run when the answer is applied.
118    pub fn answer(self, action: Option<InvalidToolCallAction>) -> ToolAnswer {
119        ToolAnswer {
120            turn: self.turn,
121            index: self.index,
122            call: self.tool_call.id,
123            kind: AnswerKind::Malformed(action),
124        }
125    }
126}
127
128/// The answer to one pending call, built only by that call and applied with
129/// [`AgentRun::answer`](super::AgentRun::answer).
130///
131/// A driver cannot build one itself:
132///
133/// ```compile_fail,E0451
134/// # use rig_agent::run::ToolAnswer;
135/// # use rig_core::message::CallId;
136/// fn forge(call: CallId, other: ToolAnswer) -> ToolAnswer {
137///     ToolAnswer { index: 0, call, ..other }
138/// }
139/// ```
140///
141/// Nor hand the run result content it built:
142///
143/// ```compile_fail,E0599
144/// # use rig_agent::run::AgentRun;
145/// # use rig_core::message::UserContent;
146/// fn answer(run: &mut AgentRun, results: Vec<UserContent>) {
147///     let _ = run.tool_results(results);
148/// }
149/// ```
150#[derive(Debug)]
151pub struct ToolAnswer {
152    /// The model turn whose batch issued the call; ids alone may repeat
153    /// across turns.
154    pub(crate) turn: usize,
155    pub(crate) index: usize,
156    pub(crate) call: CallId,
157    pub(crate) kind: AnswerKind,
158}
159
160impl ToolAnswer {
161    /// Whether applying this answer ends the run.
162    pub(crate) fn ends_run(&self) -> bool {
163        matches!(
164            self.kind,
165            AnswerKind::Malformed(Some(
166                InvalidToolCallAction::Stop { .. }
167                    | InvalidToolCallAction::Fail
168                    | InvalidToolCallAction::Repair { .. }
169            ))
170        )
171    }
172}
173
174#[derive(Debug)]
175pub(crate) enum AnswerKind {
176    Executed(ToolResult),
177    Malformed(Option<InvalidToolCallAction>),
178}