1use std::collections::HashMap;
2
3use serde_json::Value;
4use tools_rs::ToolError;
5
6use crate::{
7 chat::state::Unstructured,
8 error::ChatError,
9 types::{
10 callback::{CallbackStrategy, RetryStrategy},
11 messages::{content::Content, tool::ToolStatus},
12 options::ChatOptions,
13 response::PauseReason,
14 tools::{Action, ToolDeclarations, TypedCollection},
15 },
16};
17
18pub mod completion;
19pub mod embed;
20pub mod state;
21#[cfg(feature = "stream")]
22pub mod stream;
23
24#[derive(Default)]
25pub struct Chat<CP, Output = Unstructured> {
26 pub(crate) model: CP,
27 pub(crate) output_shape: Option<schemars::Schema>,
28 pub(crate) model_options: Option<ChatOptions>,
29 pub(crate) max_steps: Option<u16>,
30 pub(crate) max_retries: Option<u16>,
31 pub(crate) retry_strategy: Option<RetryStrategy>,
32 pub(crate) before_strategy: Option<CallbackStrategy>,
33 pub(crate) after_strategy: Option<CallbackStrategy>,
34 pub(crate) scoped_collections: Vec<Box<dyn TypedCollection>>,
35 pub(crate) routing: HashMap<String, usize>,
36 pub(crate) _output: std::marker::PhantomData<Output>,
37}
38
39#[derive(Debug, Default)]
47pub(crate) struct ToolCallPass {
48 pub executed: bool,
49 pub pause: Option<PauseReason>,
50}
51
52pub(crate) struct AggregatedDeclarations<'a> {
60 collections: &'a [Box<dyn TypedCollection>],
61}
62
63impl<'a> ToolDeclarations for AggregatedDeclarations<'a> {
64 fn json(&self) -> Result<Value, ToolError> {
65 let mut all = Vec::new();
66 for coll in self.collections {
67 if let Value::Array(arr) = coll.declarations()? {
68 all.extend(arr);
69 }
70 }
71 Ok(Value::Array(all))
72 }
73}
74
75pub(crate) fn tool_declarations_from(
80 collections: &[Box<dyn TypedCollection>],
81) -> Option<AggregatedDeclarations<'_>> {
82 if collections.is_empty() {
83 None
84 } else {
85 Some(AggregatedDeclarations { collections })
86 }
87}
88
89impl<P, Output> Chat<P, Output> {
90 fn collection_for(&self, name: &str) -> Option<&dyn TypedCollection> {
92 self.routing
93 .get(name)
94 .and_then(|&idx| self.scoped_collections.get(idx).map(|b| b.as_ref()))
95 }
96
97 pub(crate) async fn tool_call(&self, content: &mut Content) -> Result<ToolCallPass, ChatError> {
102 let mut pass = ToolCallPass::default();
103
104 let mut idx = 0;
105 while idx < content.parts.0.len() {
106 let part = &mut content.parts.0[idx];
107 let tool = match part {
108 crate::types::messages::parts::PartEnum::Tool(t) => t,
109 _ => {
110 idx += 1;
111 continue;
112 }
113 };
114
115 if tool.is_resolved() {
116 idx += 1;
117 continue;
118 }
119
120 let already_approved = matches!(tool.status, ToolStatus::Approved { .. });
121
122 let action = if already_approved {
123 Action::Execute
124 } else {
125 let coll = self.collection_for(&tool.call.name).ok_or_else(|| {
126 ChatError::InvalidResponse(format!(
127 "no scoped collection owns tool `{}`",
128 tool.call.name
129 ))
130 })?;
131 coll.decide(&tool.call)
132 };
133
134 match action {
135 Action::Execute => {
136 let coll = self.collection_for(&tool.call.name).ok_or_else(|| {
137 ChatError::InvalidResponse(format!(
138 "no scoped collection owns tool `{}`",
139 tool.call.name
140 ))
141 })?;
142 tool.mark_running();
143 let call = tool.effective_call().clone();
144 match coll.call(call).await {
145 Ok(response) => tool.complete(response),
146 Err(ToolError::Runtime(msg)) => tool.fail(msg),
147 Err(e) => tool.fail(format!("{e:?}")),
148 }
149 pass.executed = true;
150 }
151 Action::RequireApproval => match &mut pass.pause {
152 None => {
153 pass.pause = Some(PauseReason::AwaitingApproval {
154 tool_ids: vec![tool.id.clone()],
155 });
156 }
157 Some(PauseReason::AwaitingApproval { tool_ids }) => {
158 tool_ids.push(tool.id.clone());
159 }
160 Some(PauseReason::Scheduled { .. }) => {
161 let prev = pass
162 .pause
163 .replace(PauseReason::AwaitingApproval { tool_ids: vec![] });
164 if let Some(PauseReason::Scheduled {
165 tool_ids: sch_ids,
166 earliest,
167 }) = prev
168 {
169 pass.pause = Some(PauseReason::Mixed {
170 approvals: vec![tool.id.clone()],
171 scheduled: sch_ids.into_iter().map(|id| (id, earliest)).collect(),
172 });
173 }
174 }
175 Some(PauseReason::Mixed { approvals, .. }) => {
176 approvals.push(tool.id.clone());
177 }
178 },
179 Action::Defer { at } => match &mut pass.pause {
180 None => {
181 pass.pause = Some(PauseReason::Scheduled {
182 tool_ids: vec![tool.id.clone()],
183 earliest: at,
184 });
185 }
186 Some(PauseReason::Scheduled { tool_ids, earliest }) => {
187 tool_ids.push(tool.id.clone());
188 if at < *earliest {
189 *earliest = at;
190 }
191 }
192 Some(PauseReason::AwaitingApproval { tool_ids }) => {
193 let approvals = std::mem::take(tool_ids);
194 pass.pause = Some(PauseReason::Mixed {
195 approvals,
196 scheduled: vec![(tool.id.clone(), at)],
197 });
198 }
199 Some(PauseReason::Mixed { scheduled, .. }) => {
200 scheduled.push((tool.id.clone(), at));
201 }
202 },
203 Action::Reject { reason } => {
204 tool.reject(Some(reason));
205 pass.executed = true;
206 }
207 }
208
209 idx += 1;
210 }
211
212 Ok(pass)
213 }
214}