1use std::future::Future;
48
49use aidaemon_core::{
50 Agent, CancellationToken, CoreError, Hook, HookContext, Message, ModelRequest, ModelResponse,
51 Provider, ProviderError, Resolution, ResponseFormat, Role, RunOutcome, RunState, RunStatus,
52 Usage,
53};
54use async_trait::async_trait;
55use schemars::JsonSchema;
56use serde::de::DeserializeOwned;
57use serde_json::Value;
58
59#[derive(Debug, Clone)]
61pub struct Typed<T> {
62 pub value: T,
63 pub response: ModelResponse,
65 pub usage: Usage,
67 pub repaired: bool,
69}
70
71#[derive(Debug, Clone)]
73pub struct TypedOutcome<T> {
74 pub value: T,
75 pub outcome: RunOutcome,
77 pub repaired: bool,
78}
79
80#[derive(Debug, thiserror::Error)]
82pub enum StructuredError {
83 #[error(transparent)]
84 Provider(#[from] ProviderError),
85 #[error(transparent)]
86 Core(#[from] CoreError),
87 #[error("the run ended without a final answer: {:?}", .0.status)]
93 NotFinished(Box<RunOutcome>),
94 #[error("the answer is not valid {type_name}: {error}")]
97 Invalid {
98 type_name: &'static str,
99 error: String,
100 text: String,
101 outcome: Option<Box<RunOutcome>>,
102 },
103}
104
105pub fn parse_answer<T: DeserializeOwned>(text: &str) -> Result<T, String> {
109 let trimmed = text.trim();
110 let first = match serde_json::from_str::<T>(trimmed) {
111 Ok(value) => return Ok(value),
112 Err(err) => err.to_string(),
113 };
114 for candidate in [fenced(trimmed), braced(trimmed)].into_iter().flatten() {
115 if let Ok(value) = serde_json::from_str::<T>(candidate) {
116 return Ok(value);
117 }
118 }
119 Err(first)
120}
121
122fn fenced(text: &str) -> Option<&str> {
123 let start = text.find("```")?;
124 let rest = &text[start + 3..];
125 let rest = rest.strip_prefix("json").unwrap_or(rest);
126 let end = rest.find("```")?;
127 Some(rest[..end].trim())
128}
129
130fn braced(text: &str) -> Option<&str> {
131 let (open, close) = match (text.find('{'), text.find('[')) {
132 (Some(o), Some(a)) if a < o => ('[', ']'),
133 (Some(_), _) => ('{', '}'),
134 (None, Some(_)) => ('[', ']'),
135 (None, None) => return None,
136 };
137 let start = text.find(open)?;
138 let end = text.rfind(close)?;
139 (end > start).then(|| &text[start..=end])
140}
141
142fn format_name<T: ?Sized>() -> String {
143 let full = std::any::type_name::<T>();
144 let base = full.split('<').next().unwrap_or(full);
145 let short = base.rsplit("::").next().unwrap_or(base);
146 let name: String = short
147 .chars()
148 .filter(|c| c.is_ascii_alphanumeric() || *c == '_' || *c == '-')
149 .take(64)
150 .collect();
151 if name.is_empty() {
152 "answer".into()
153 } else {
154 name
155 }
156}
157
158fn schema_instruction(schema: &Value) -> String {
161 format!(
162 "When you give your final answer, reply with only a JSON value matching this JSON \
163 Schema, with no prose and no code fence:\n{schema}"
164 )
165}
166
167fn repair_message(error: &str) -> String {
168 format!(
169 "Your answer could not be read: {error}. Reply again with only the JSON value matching \
170 the schema, with no prose and no code fence."
171 )
172}
173
174fn add_instruction(messages: &mut Vec<Message>, instruction: &str) {
175 match messages.first_mut() {
176 Some(first) if first.role == Role::System => {
177 if !first.content.contains(instruction) {
178 if !first.content.is_empty() {
179 first.content.push_str("\n\n");
180 }
181 first.content.push_str(instruction);
182 }
183 }
184 _ => messages.insert(0, Message::system(instruction)),
185 }
186}
187
188pub async fn complete_typed<T>(
191 provider: &dyn Provider,
192 mut request: ModelRequest,
193) -> Result<Typed<T>, StructuredError>
194where
195 T: DeserializeOwned + JsonSchema,
196{
197 let schema = crate::schema::schema_for::<T>();
198 add_instruction(&mut request.messages, &schema_instruction(&schema));
199 request.options.response_format = ResponseFormat::JsonSchema {
200 name: format_name::<T>(),
201 schema,
202 strict: true,
203 };
204
205 let mut usage = Usage::default();
206 let first = provider.complete(&request).await?;
207 usage.add(first.usage);
208 let error = match parse_answer::<T>(&first.text) {
209 Ok(value) => {
210 return Ok(Typed {
211 value,
212 response: first,
213 usage,
214 repaired: false,
215 });
216 }
217 Err(error) => error,
218 };
219
220 request
221 .messages
222 .push(Message::assistant(first.text.clone(), Vec::new()));
223 request.messages.push(Message::user(repair_message(&error)));
224 let second = provider.complete(&request).await?;
225 usage.add(second.usage);
226 match parse_answer::<T>(&second.text) {
227 Ok(value) => Ok(Typed {
228 value,
229 response: second,
230 usage,
231 repaired: true,
232 }),
233 Err(error) => Err(StructuredError::Invalid {
234 type_name: std::any::type_name::<T>(),
235 error,
236 text: second.text,
237 outcome: None,
238 }),
239 }
240}
241
242struct OutputSchema {
245 name: String,
246 schema: Value,
247 instruction: String,
248}
249
250#[async_trait]
251impl Hook for OutputSchema {
252 fn name(&self) -> &'static str {
253 "structured-output"
254 }
255
256 async fn before_model(&self, _ctx: &HookContext<'_>, request: &mut ModelRequest) {
257 add_instruction(&mut request.messages, &self.instruction);
258 request.options.response_format = ResponseFormat::JsonSchema {
259 name: self.name.clone(),
260 schema: self.schema.clone(),
261 strict: true,
262 };
263 }
264}
265
266fn typed_agent<T: JsonSchema>(agent: &Agent) -> Agent {
267 let schema = crate::schema::schema_for::<T>();
268 agent.with_hook(OutputSchema {
269 name: format_name::<T>(),
270 instruction: schema_instruction(&schema),
271 schema,
272 })
273}
274
275pub trait AgentStructuredExt {
277 fn run_typed<T>(
280 &self,
281 session_id: &str,
282 input: impl Into<Message> + Send,
283 ) -> impl Future<Output = Result<TypedOutcome<T>, StructuredError>> + Send
284 where
285 T: DeserializeOwned + JsonSchema + Send;
286
287 fn run_typed_from<T>(
289 &self,
290 state: RunState,
291 cancel: CancellationToken,
292 ) -> impl Future<Output = Result<TypedOutcome<T>, StructuredError>> + Send
293 where
294 T: DeserializeOwned + JsonSchema + Send;
295
296 fn resume_typed<T>(
300 &self,
301 state: RunState,
302 resolution: Resolution,
303 ) -> impl Future<Output = Result<TypedOutcome<T>, StructuredError>> + Send
304 where
305 T: DeserializeOwned + JsonSchema + Send;
306
307 fn finish_typed<T>(
310 &self,
311 outcome: RunOutcome,
312 ) -> impl Future<Output = Result<TypedOutcome<T>, StructuredError>> + Send
313 where
314 T: DeserializeOwned + JsonSchema + Send;
315}
316
317impl AgentStructuredExt for Agent {
318 async fn run_typed<T>(
319 &self,
320 session_id: &str,
321 input: impl Into<Message> + Send,
322 ) -> Result<TypedOutcome<T>, StructuredError>
323 where
324 T: DeserializeOwned + JsonSchema + Send,
325 {
326 let typed = typed_agent::<T>(self);
327 let outcome = typed.run(session_id, input).await?;
328 finish::<T>(&typed, outcome, CancellationToken::new()).await
329 }
330
331 async fn run_typed_from<T>(
332 &self,
333 state: RunState,
334 cancel: CancellationToken,
335 ) -> Result<TypedOutcome<T>, StructuredError>
336 where
337 T: DeserializeOwned + JsonSchema + Send,
338 {
339 let typed = typed_agent::<T>(self);
340 let outcome = typed.run_from(state, cancel.clone()).await?;
341 finish::<T>(&typed, outcome, cancel).await
342 }
343
344 async fn resume_typed<T>(
345 &self,
346 state: RunState,
347 resolution: Resolution,
348 ) -> Result<TypedOutcome<T>, StructuredError>
349 where
350 T: DeserializeOwned + JsonSchema + Send,
351 {
352 let typed = typed_agent::<T>(self);
353 let outcome = typed.resume(state, resolution).await?;
354 finish::<T>(&typed, outcome, CancellationToken::new()).await
355 }
356
357 async fn finish_typed<T>(&self, outcome: RunOutcome) -> Result<TypedOutcome<T>, StructuredError>
358 where
359 T: DeserializeOwned + JsonSchema + Send,
360 {
361 finish::<T>(&typed_agent::<T>(self), outcome, CancellationToken::new()).await
362 }
363}
364
365fn final_answer(outcome: &RunOutcome) -> Option<&str> {
366 match outcome.status {
367 RunStatus::Completed | RunStatus::Finished { .. } => outcome.final_text.as_deref(),
368 _ => None,
369 }
370}
371
372async fn finish<T>(
373 agent: &Agent,
374 outcome: RunOutcome,
375 cancel: CancellationToken,
376) -> Result<TypedOutcome<T>, StructuredError>
377where
378 T: DeserializeOwned + JsonSchema,
379{
380 let Some(text) = final_answer(&outcome) else {
381 return Err(StructuredError::NotFinished(Box::new(outcome)));
382 };
383 let error = match parse_answer::<T>(text) {
384 Ok(value) => {
385 return Ok(TypedOutcome {
386 value,
387 outcome,
388 repaired: false,
389 });
390 }
391 Err(error) => error,
392 };
393
394 let state = outcome.state.with_user_message(repair_message(&error));
395 let outcome = agent.run_from(state, cancel).await?;
396 let Some(text) = final_answer(&outcome) else {
397 return Err(StructuredError::NotFinished(Box::new(outcome)));
398 };
399 match parse_answer::<T>(text) {
400 Ok(value) => Ok(TypedOutcome {
401 value,
402 outcome,
403 repaired: true,
404 }),
405 Err(error) => Err(StructuredError::Invalid {
406 type_name: std::any::type_name::<T>(),
407 error,
408 text: text.to_string(),
409 outcome: Some(Box::new(outcome)),
410 }),
411 }
412}
413
414#[cfg(test)]
415mod tests {
416 use super::*;
417 use serde::Deserialize;
418
419 #[derive(Debug, Deserialize, PartialEq)]
420 struct Point {
421 x: i32,
422 }
423
424 #[test]
425 fn answers_are_read_bare_fenced_or_in_prose() {
426 assert_eq!(parse_answer::<Point>(r#" {"x": 1} "#), Ok(Point { x: 1 }));
427 assert_eq!(
428 parse_answer::<Point>("```json\n{\"x\": 2}\n```"),
429 Ok(Point { x: 2 })
430 );
431 assert_eq!(
432 parse_answer::<Point>("Here you go: {\"x\": 3}. Anything else?"),
433 Ok(Point { x: 3 })
434 );
435 let err = parse_answer::<Point>(r#"{"y": 1}"#).unwrap_err();
436 assert!(err.contains("missing field `x`"), "{err}");
437 }
438
439 #[test]
440 fn format_names_are_short_and_valid() {
441 assert_eq!(format_name::<Point>(), "Point");
442 assert_eq!(format_name::<Vec<Point>>(), "Vec");
443 }
444}