1use std::collections::HashSet;
2use std::sync::Arc;
3
4use anyhow::{anyhow, Result};
5use async_trait::async_trait;
6use indoc::formatdoc;
7use oi_kit_provider_types::conversation::message::{Message, MessageContent, ToolRequest};
8use oi_kit_provider_types::conversation::Conversation;
9use oi_kit_provider_types::maybe_send::{MaybeSend, MaybeSync};
10use rmcp::model::{
11 Annotations, CallToolResult, ContentBlock, ErrorCode, ErrorData, JsonObject, Role, TextContent,
12 Tool, ToolAnnotations,
13};
14use serde_json::Value;
15
16use crate::machine::MachineSession;
17use crate::operation::{
18 applied, ends_turn, messages_since_kickoff, not_applicable, yielded_with, ConversationEffect,
19 Emitter, Operation, OperationResult,
20};
21
22pub const FINAL_OUTPUT_TOOL_NAME: &str = "final_output";
23pub const FINAL_OUTPUT_SUCCESS_MESSAGE: &str = "Final output successfully collected.";
24pub const FINAL_OUTPUT_CONTINUATION_MESSAGE: &str =
25 "You MUST call the `final_output` tool NOW with the final output for the user.";
26pub const FINAL_OUTPUT_NOT_ALONE_MESSAGE: &str =
27 "final_output was not accepted because it was called together with other tools. \
28 Read the results of those tools, then call final_output on its own.";
29
30const DEFAULT_UNSUPPORTED_MESSAGE: &str =
31 "This session asks for structured final output, but the provider can't receive the \
32 `final_output` tool, so the model can never provide it. Run it with a different provider.";
33
34pub trait FinalOutputSchemaSource<S>: MaybeSend + MaybeSync {
35 fn json_schema(&self, session: &S) -> Option<Value>;
36}
37
38pub struct FinalOutputTool {
39 json_schema: Value,
40 validator: jsonschema::Validator,
41}
42
43impl FinalOutputTool {
44 pub fn try_new(json_schema: Value) -> Result<Self, String> {
45 let schema = json_schema
46 .as_object()
47 .ok_or_else(|| "json_schema must be an object".to_string())?;
48 if schema.is_empty() {
49 return Err("empty json_schema is not allowed".to_string());
50 }
51 let validator =
52 jsonschema::validator_for(&json_schema).map_err(|error| error.to_string())?;
53 Ok(Self {
54 json_schema,
55 validator,
56 })
57 }
58
59 pub fn latest_turn_output(conversation: &Conversation) -> Option<String> {
60 messages_since_kickoff(conversation)
61 .ok()
62 .and_then(Self::successful_output)
63 }
64
65 pub fn successful_output(messages: &[Message]) -> Option<String> {
66 let successful_responses: HashSet<&str> = messages
67 .iter()
68 .flat_map(|message| &message.content)
69 .filter_map(|content| match content {
70 MessageContent::ToolResponse(response)
71 if response.tool_result.as_ref().is_ok_and(|result| {
72 result.is_error != Some(true)
73 && result.content.iter().any(|content| {
74 content
75 .as_text()
76 .is_some_and(|text| text.text == FINAL_OUTPUT_SUCCESS_MESSAGE)
77 })
78 }) =>
79 {
80 Some(response.id.as_str())
81 }
82 _ => None,
83 })
84 .collect();
85
86 messages
87 .iter()
88 .rev()
89 .flat_map(|message| message.content.iter().rev())
90 .find_map(|content| match content {
91 MessageContent::ToolRequest(request)
92 if successful_responses.contains(request.id.as_str()) =>
93 {
94 request.tool_call.as_ref().ok().and_then(|tool_call| {
95 (tool_call.name == FINAL_OUTPUT_TOOL_NAME).then(|| {
96 Value::Object(tool_call.arguments.clone().unwrap_or_default())
97 .to_string()
98 })
99 })
100 }
101 _ => None,
102 })
103 }
104
105 fn pretty_schema(&self) -> String {
106 serde_json::to_string_pretty(&self.json_schema).unwrap()
107 }
108
109 pub fn tool(&self) -> Tool {
110 let instructions = formatdoc! {r#"
111 The final_output tool collects the final output for the user and provides validation for structured JSON final output against a predefined schema.
112
113 This final_output tool MUST be called with the final output for the user.
114
115 Purpose:
116 - Collects the final output for the user
117 - Ensures that final outputs conform to the expected JSON structure
118 - Provides clear validation feedback when outputs don't match the schema
119
120 Usage:
121 - Call the `final_output` tool with your JSON final output passed as the argument.
122 - Call it on its own, in a reply with no other tool calls, after you have read the results of your other tool calls.
123
124 The expected JSON schema format is:
125
126 {}
127
128 When validation fails, you'll receive:
129 - Specific validation errors
130 - The expected format
131 "#, self.pretty_schema()};
132
133 Tool::new(
134 FINAL_OUTPUT_TOOL_NAME.to_string(),
135 instructions,
136 self.json_schema.as_object().unwrap().clone(),
137 )
138 .annotate(
139 ToolAnnotations::with_title("Final Output".to_string())
140 .read_only(false)
141 .destructive(false)
142 .idempotent(true)
143 .open_world(false),
144 )
145 }
146
147 pub fn system_prompt(&self) -> String {
148 formatdoc! {r#"
149 # Final Output Instructions
150
151 You MUST use the `final_output` tool to collect the final output for the user rather than providing the output directly in your response.
152 The final output MUST be a valid JSON object that is provided to the `final_output` tool when called and it must match the following schema:
153
154 {}
155
156 ----
157 "#, self.pretty_schema()}
158 }
159
160 pub fn validate(&self, arguments: Option<JsonObject>) -> Result<String, ErrorData> {
161 let output = Value::from(arguments);
162 let validation_errors: Vec<String> = self
163 .validator
164 .iter_errors(&output)
165 .map(|error| format!("- {}: {}", error.instance_path(), error))
166 .collect();
167
168 if validation_errors.is_empty() {
169 Ok(serde_json::to_string(&output).unwrap())
170 } else {
171 Err(invalid_params(format!(
172 "Validation failed:\n{}\n\nExpected format:\n{}\n\nPlease correct your output to match the expected JSON schema and try again.",
173 validation_errors.join("\n"),
174 self.pretty_schema()
175 )))
176 }
177 }
178}
179
180fn invalid_params(message: String) -> ErrorData {
181 ErrorData::new(ErrorCode::INVALID_PARAMS, message, None)
182}
183
184fn success_result() -> CallToolResult {
185 CallToolResult::success(vec![ContentBlock::Text(
186 TextContent::new(FINAL_OUTPUT_SUCCESS_MESSAGE)
187 .with_annotations(Annotations::default().with_audience(vec![Role::Assistant])),
188 )])
189}
190
191fn tool_span(tool_name: &str, tool_call_id: &str, session_id: &str) -> tracing::Span {
192 tracing::info_span!(
193 target: "goose::state_machine",
194 "execute_tool",
195 "gen_ai.operation.name" = "execute_tool",
196 "gen_ai.tool.name" = %tool_name,
197 "gen_ai.tool.call.id" = %tool_call_id,
198 "gen_ai.conversation.id" = %session_id,
199 "gen_ai.tool.call.arguments" = tracing::field::Empty,
200 "gen_ai.tool.call.result" = tracing::field::Empty,
201 "error.type" = tracing::field::Empty,
202 session.id = %session_id,
203 )
204}
205
206fn pending_final_output_request(messages: &[Message]) -> Option<ToolRequest> {
207 let answered: HashSet<&str> = messages
208 .iter()
209 .flat_map(Message::get_tool_response_ids)
210 .collect();
211 messages
212 .iter()
213 .filter(|message| message.role == Role::Assistant)
214 .flat_map(|message| &message.content)
215 .filter_map(MessageContent::as_tool_request)
216 .find(|request| {
217 !answered.contains(request.id.as_str())
218 && !request.was_executed_externally()
219 && request
220 .tool_call
221 .as_ref()
222 .is_ok_and(|tool_call| tool_call.name == FINAL_OUTPUT_TOOL_NAME)
223 })
224 .cloned()
225}
226
227fn assistant_block_bounds(messages: &[Message], message_index: usize) -> (usize, usize) {
228 let start = (0..message_index)
229 .rev()
230 .take_while(|index| messages[*index].role == Role::Assistant)
231 .last()
232 .unwrap_or(message_index);
233 let end = (message_index + 1..messages.len())
234 .take_while(|index| messages[*index].role == Role::Assistant)
235 .last()
236 .map_or(message_index + 1, |index| index + 1);
237 (start, end)
238}
239
240fn has_sibling_tool_calls(messages: &[Message], request_id: &str) -> bool {
241 let Some(message_index) = messages.iter().position(|message| {
242 message
243 .content
244 .iter()
245 .filter_map(MessageContent::as_tool_request)
246 .any(|request| request.id == request_id)
247 }) else {
248 return false;
249 };
250 let (start, end) = assistant_block_bounds(messages, message_index);
251 messages[start..end]
252 .iter()
253 .flat_map(|message| &message.content)
254 .filter_map(MessageContent::as_tool_request)
255 .any(|request| request.id != request_id && !request.was_executed_externally())
256}
257
258fn stop_with_error<E>(
259 conversation: &Conversation,
260 message: String,
261 emit: &Emitter,
262) -> Result<OperationResult<E>>
263where
264 E: From<ConversationEffect>,
265{
266 let kickoff = messages_since_kickoff(conversation)?
267 .first()
268 .cloned()
269 .ok_or_else(|| anyhow!("conversation has no kickoff message"))?;
270 let message_id = kickoff
271 .id
272 .clone()
273 .ok_or_else(|| anyhow!("kickoff message has no id"))?;
274 let kickoff = kickoff.with_visibility(true, false);
275 let response = Message::assistant()
276 .with_text(message)
277 .with_visibility(true, false);
278 emit.message(kickoff);
279 let response = emit.message(response);
280 yielded_with(
281 [
282 ConversationEffect::SetMessageVisibility {
283 message_id,
284 user_visible: true,
285 agent_visible: false,
286 },
287 ConversationEffect::from(response),
288 ]
289 .map(E::from),
290 )
291}
292
293pub struct FinalOutputOperation<S> {
294 source: Arc<dyn FinalOutputSchemaSource<S>>,
295 supports_builtin_tools: bool,
296 unsupported_message: String,
297}
298
299impl<S> FinalOutputOperation<S> {
300 pub fn new(source: Arc<dyn FinalOutputSchemaSource<S>>, supports_builtin_tools: bool) -> Self {
301 Self {
302 source,
303 supports_builtin_tools,
304 unsupported_message: DEFAULT_UNSUPPORTED_MESSAGE.to_string(),
305 }
306 }
307
308 pub fn with_unsupported_message(mut self, message: impl Into<String>) -> Self {
309 self.unsupported_message = message.into();
310 self
311 }
312
313 fn final_output_tool(&self, session: &S) -> Result<Option<FinalOutputTool>> {
314 self.source
315 .json_schema(session)
316 .map(FinalOutputTool::try_new)
317 .transpose()
318 .map_err(|error| anyhow!(error))
319 }
320}
321
322#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
323#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
324impl<S, E> Operation<S, E> for FinalOutputOperation<S>
325where
326 S: MachineSession + 'static,
327 E: From<ConversationEffect> + MaybeSend + 'static,
328{
329 fn name(&self) -> &'static str {
330 "final_output"
331 }
332
333 async fn inference_tools(&self, session: &S) -> Result<Vec<Tool>> {
334 Ok(self
335 .final_output_tool(session)?
336 .as_ref()
337 .map(FinalOutputTool::tool)
338 .into_iter()
339 .collect())
340 }
341
342 async fn prompt_parts(
343 &self,
344 session: &S,
345 _conversation: &Conversation,
346 ) -> Result<Vec<(String, String)>> {
347 Ok(self
348 .final_output_tool(session)?
349 .map(|tool| ("final_output".to_string(), tool.system_prompt()))
350 .into_iter()
351 .collect())
352 }
353
354 async fn run(
355 &self,
356 session: &S,
357 conversation: &Conversation,
358 emit: &Emitter,
359 ) -> Result<OperationResult<E>> {
360 let Some(final_output) = self.final_output_tool(session)? else {
361 return not_applicable();
362 };
363
364 if !self.supports_builtin_tools {
365 return stop_with_error(conversation, self.unsupported_message.clone(), emit);
366 }
367
368 let messages = messages_since_kickoff(conversation)?;
369 if let Some(request) = pending_final_output_request(messages) {
370 let mut response = Message::user();
371 if has_sibling_tool_calls(messages, &request.id) {
372 response.add_tool_response_with_metadata(
373 request.id,
374 Err(ErrorData::new(
375 ErrorCode::INVALID_REQUEST,
376 FINAL_OUTPUT_NOT_ALONE_MESSAGE,
377 None,
378 )),
379 request.metadata.as_ref(),
380 );
381 let response = emit.message(response);
382 return applied([E::from(response.into())]);
383 }
384
385 let tool_call = request
386 .tool_call
387 .clone()
388 .map_err(|error| anyhow!("final output tool call could not be parsed: {error}"))?;
389 let span = tool_span(&tool_call.name, &request.id, session.id());
390 let (result, accepted) =
391 match span.in_scope(|| final_output.validate(tool_call.arguments)) {
392 Ok(accepted) => (Ok(success_result()), Some(accepted)),
393 Err(error) => {
394 span.record("error.type", "tool_execution_error");
395 (Err(error), None)
396 }
397 };
398 response.add_tool_response_with_metadata(request.id, result, request.metadata.as_ref());
399 let response = emit.message(response);
400 let Some(accepted) = accepted else {
401 return applied([E::from(response.into())]);
402 };
403 let accepted = emit.message(Message::assistant().with_text(accepted));
404 return applied([E::from(response.into()), E::from(accepted.into())]);
405 }
406
407 if FinalOutputTool::successful_output(messages).is_some() {
408 return not_applicable();
409 }
410
411 if ends_turn(messages) {
412 let message = Message::user()
413 .with_text(FINAL_OUTPUT_CONTINUATION_MESSAGE)
414 .agent_only();
415 let message = emit.message(message);
416 return applied([E::from(message.into())]);
417 }
418
419 not_applicable()
420 }
421}