Skip to main content

aither_core/llm/
mod.rs

1//! # Language Models and Conversation Management
2//!
3//! This module provides everything you need to work with language models in a provider-agnostic way.
4//! Build chat applications, generate structured output, and integrate tools without being tied to any specific AI service.
5//!
6//! ## Core Components
7//!
8//! - **[`LanguageModel`]** - The main trait for text generation and conversation
9//! - **[`LLMRequest`]** - Encapsulates messages, tools, and parameters for model calls
10//! - **[`Event`]** - Stream events from the model (text, reasoning, tool calls)
11//! - **[`Message`]** - Represents individual messages in a conversation
12//! - **[`Tool`]** - Function calling interface for extending model capabilities
13//!
14//! ## Design Philosophy
15//!
16//! The core crate provides a **low-level API** that emits events without executing tools.
17//! Tool execution is the responsibility of higher-level abstractions like `aither-agent`.
18//!
19//! This design allows:
20//! - Full control over tool execution flow
21//! - Hooks for intercepting and modifying tool calls
22//! - Proper context management between turns
23//! - Clean separation between LLM communication and agent logic
24//!
25//! ## Quick Start
26//!
27//! ### Basic Conversation
28//!
29//! ```rust,ignore
30//! use aither::llm::{LanguageModel, Event, oneshot};
31//! use futures_lite::StreamExt;
32//!
33//! async fn chat_with_model(model: impl LanguageModel) -> Result<String, Box<dyn std::error::Error>> {
34//!     let request = oneshot("You are a helpful assistant", "What's the capital of Japan?");
35//!     let mut stream = model.respond(request);
36//!     let mut full_text = String::new();
37//!
38//!     while let Some(event) = stream.next().await {
39//!         match event? {
40//!             Event::Text(chunk) => full_text.push_str(&chunk),
41//!             Event::Reasoning(thought) => eprintln!("[thinking] {}", thought),
42//!             Event::ToolCall(call) => {
43//!                 // Handle tool call (typically done by agent crate)
44//!                 println!("Tool requested: {}", call.name);
45//!             }
46//!             _ => {}
47//!         }
48//!     }
49//!
50//!     Ok(full_text)
51//! }
52//! ```
53//!
54//! ### With Tools (Agent-Controlled)
55//!
56//! ```rust,ignore
57//! use aither::llm::{LanguageModel, Event, LLMRequest, Message};
58//!
59//! // The core crate does NOT execute tools - it emits ToolCall events.
60//! // Tool execution should be handled by the agent crate.
61//! let request = LLMRequest::new([Message::user("What's the weather?")])
62//!     .with_tool_definitions(vec![weather_tool_definition()]);
63//!
64//! let mut stream = model.respond(request);
65//! while let Some(event) = stream.next().await {
66//!     match event? {
67//!         Event::ToolCall(call) => {
68//!             // Execute tool and continue conversation
69//!             let result = my_tool_executor.execute(&call).await;
70//!             // Add result to messages and send another request...
71//!         }
72//!         _ => {}
73//!     }
74//! }
75//! ```
76
77/// Assistant module for managing assistant-related functionality.
78pub mod assistant;
79/// Event types for streaming responses.
80pub mod event;
81/// Classification of provider failures.
82pub mod failure;
83/// Message types and conversation handling.
84pub mod message;
85/// Model profiles and capabilities.
86pub mod model;
87/// Provider module for managing language model providers and their configurations.
88pub mod provider;
89/// Provider-opaque reasoning state carried across turns.
90pub mod reasoning;
91/// Deep research workflows and agent capabilities.
92pub mod researcher;
93/// How a failed model request is retried.
94pub mod retry;
95/// Tool system for function calling.
96pub mod tool;
97
98use crate::llm::{model::Parameters, tool::Tools};
99use alloc::{
100    boxed::Box,
101    string::{String, ToString},
102    sync::Arc,
103    vec,
104    vec::Vec,
105};
106use core::{any::TypeId, future::Future};
107pub use event::{Event, ToolCall, Usage};
108pub use failure::{Classify, Failure, FailureKind};
109use futures_core::Stream;
110use futures_lite::{StreamExt, pin};
111pub use message::{Attachment, Message, Role};
112pub use provider::LanguageModelProvider;
113pub use reasoning::ReasoningState;
114pub use researcher::{
115    ResearchCitation, ResearchEvent, ResearchFinding, ResearchOptions, ResearchReport,
116    ResearchRequest, ResearchSource, ResearchStage, Researcher, ResearcherProfile,
117};
118pub use retry::RetryPolicy;
119use schemars::{JsonSchema, schema_for};
120use serde::de::DeserializeOwned;
121pub use tool::{
122    AgentIdentity, AgentPath, AnyApprover, Approval, ApprovalError, ApprovalKind, ApprovalRequest,
123    Approver, ApproverFailure, CallIdentity, CancelSignal, Canceller, CommandOutcome,
124    CommandResult, CommandStream, Interruption, InterruptionCause, IntoToolResult, StoredFile,
125    SubagentIdentity, Tool, ToolCallId, ToolContext, ToolResult, render_interruptions,
126};
127
128use crate::llm::model::Profile;
129
130/// Why a structured-output call failed.
131///
132/// [`LanguageModel::respond`] reports provider failures through the model's own
133/// [`LanguageModel::Error`]. Structured output adds a second, separate way to
134/// fail — the model answered, but not with the requested shape — so this keeps
135/// the two distinguishable instead of flattening both into one opaque error.
136/// Callers need that distinction: a rate limit is worth retrying, a schema
137/// mismatch is worth re-prompting, and an auth failure is worth neither.
138#[derive(Debug)]
139pub enum GenerateError<E> {
140    /// The provider itself failed: transport, rate limit, auth, and so on.
141    Provider(E),
142
143    /// The provider answered, but the response did not match the schema.
144    ///
145    /// Carries the text that could not be parsed so callers can log or retry.
146    Parse {
147        /// The underlying deserialization failure.
148        source: serde_json::Error,
149        /// The response text that failed to parse, truncated for logging.
150        response: String,
151    },
152}
153
154impl<E: core::fmt::Display> core::fmt::Display for GenerateError<E> {
155    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
156        match self {
157            Self::Provider(err) => write!(f, "language model request failed: {err}"),
158            Self::Parse { source, response } => {
159                write!(
160                    f,
161                    "structured output did not match the requested schema: {source}; response: {response}"
162                )
163            }
164        }
165    }
166}
167
168impl<E: core::error::Error + 'static> core::error::Error for GenerateError<E> {
169    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
170        match self {
171            Self::Provider(err) => Some(err),
172            Self::Parse { source, .. } => Some(source),
173        }
174    }
175}
176
177/// Builder-style request passed into [`LanguageModel::respond`].
178///
179/// Wraps the full conversation, model parameters, and tool definitions a provider
180/// needs in order to execute a call.
181#[derive(Debug, Clone)]
182pub struct LLMRequest {
183    messages: Vec<Message>,
184    parameters: Parameters,
185    tool_definitions: Vec<tool::ToolDefinition>,
186}
187
188impl LLMRequest {
189    /// Creates a request from the provided messages using default parameters.
190    pub fn new(messages: impl Into<Vec<Message>>) -> Self {
191        Self {
192            messages: messages.into(),
193            parameters: Parameters::default(),
194            tool_definitions: Vec::new(),
195        }
196    }
197
198    /// Adds tool definitions to the request.
199    ///
200    /// These define what tools the model can request. The model will emit
201    /// [`Event::ToolCall`] events when it wants to use a tool.
202    #[must_use]
203    pub fn with_tool_definitions(mut self, definitions: Vec<tool::ToolDefinition>) -> Self {
204        self.tool_definitions = definitions;
205        self
206    }
207
208    /// Adds a single tool definition.
209    #[must_use]
210    pub fn with_tool<T: Tool>(mut self, tool: &T) -> Self {
211        self.tool_definitions.push(tool::ToolDefinition::new(tool));
212        self
213    }
214
215    /// Overrides the sampling parameters used for this call.
216    #[must_use]
217    pub fn with_parameters(mut self, parameters: Parameters) -> Self {
218        self.parameters = parameters;
219        self
220    }
221
222    /// Returns the current conversation messages.
223    #[must_use]
224    pub fn messages(&self) -> &[Message] {
225        &self.messages
226    }
227
228    /// Returns a mutable reference to messages for modification.
229    pub const fn messages_mut(&mut self) -> &mut Vec<Message> {
230        &mut self.messages
231    }
232
233    /// Returns the current parameter snapshot.
234    #[must_use]
235    pub const fn parameters(&self) -> &Parameters {
236        &self.parameters
237    }
238
239    /// Returns the tool definitions.
240    #[must_use]
241    pub fn tool_definitions(&self) -> &[tool::ToolDefinition] {
242        &self.tool_definitions
243    }
244
245    /// Breaks the request into owned components.
246    #[must_use]
247    pub fn into_parts(self) -> (Vec<Message>, Parameters, Vec<tool::ToolDefinition>) {
248        (self.messages, self.parameters, self.tool_definitions)
249    }
250}
251
252/// Legacy request builder that supports mutable tool registry.
253///
254/// This is provided for backwards compatibility with providers that
255/// handle tool execution internally (built-in tools).
256#[derive(Debug)]
257pub struct LLMRequestWithTools<'tools> {
258    inner: LLMRequest,
259    tools: &'tools mut Tools,
260}
261
262impl LLMRequest {
263    /// Attaches a mutable tool registry to the request.
264    ///
265    /// This is for providers that execute tools internally (e.g., built-in tools).
266    /// For agent-controlled tool execution, use `with_tool_definitions` instead.
267    pub fn with_tools(self, tools: &mut Tools) -> LLMRequestWithTools<'_> {
268        let definitions = tools.definitions();
269        LLMRequestWithTools {
270            inner: self.with_tool_definitions(definitions),
271            tools,
272        }
273    }
274}
275
276impl<'tools> LLMRequestWithTools<'tools> {
277    /// Returns the inner request.
278    #[must_use]
279    pub const fn request(&self) -> &LLMRequest {
280        &self.inner
281    }
282
283    /// Returns the inner request for modification, keeping its tool registry.
284    pub const fn request_mut(&mut self) -> &mut LLMRequest {
285        &mut self.inner
286    }
287
288    /// Returns the tool registry.
289    #[must_use]
290    pub const fn tools(&mut self) -> &mut Tools {
291        self.tools
292    }
293
294    /// Breaks into components.
295    #[must_use]
296    pub fn into_parts(self) -> (LLMRequest, &'tools mut Tools) {
297        (self.inner, self.tools)
298    }
299
300    /// Invokes a registered tool by name, running it with `cx` as its
301    /// [`ToolContext`].
302    ///
303    /// # Errors
304    /// Returns an error if tool is not found or the tool call fails.
305    pub async fn call_tool(
306        &mut self,
307        name: &str,
308        args_json: &str,
309        cx: ToolContext,
310    ) -> crate::Result<ToolResult> {
311        self.tools.call(name, args_json, cx).await
312    }
313}
314
315/// How a model can count the tokens a request costs, when it can.
316///
317/// [`LanguageModel::token_counting`] reports which kind of counting a model
318/// offers: `Local` counts in-process against a published vocabulary and is
319/// cheap enough to run on every assembly; `Endpoint` counts exactly over a
320/// network call and is worth its round trip only near a threshold.
321#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
322pub enum TokenCounting {
323    /// No counting: the caller falls back to its estimate.
324    #[default]
325    None,
326    /// In-process counting against an embedded vocabulary.
327    Local,
328    /// Counting through a provider endpoint.
329    Endpoint,
330}
331
332/// Language models for text generation and conversation.
333///
334/// The `respond` method returns a stream of [`Event`]s. Tool calls are emitted
335/// as events and are NOT automatically executed - this allows higher-level
336/// abstractions (like agents) to control tool execution.
337///
338/// See the [module documentation](crate::llm) for examples and usage patterns.
339pub trait LanguageModel: Sized + Send + Sync {
340    /// The error type returned by this language model.
341    type Error: core::error::Error + Classify + Send + Sync + 'static;
342
343    /// How this model counts prompt tokens, if at all. `None` by default.
344    fn token_counting(&self) -> TokenCounting {
345        TokenCounting::None
346    }
347
348    /// The prompt tokens `request` costs — messages, tool definitions, and
349    /// attachments where the counter supports them — or `None` when this
350    /// model cannot count. The default implementation counts nothing.
351    fn count_tokens(
352        &self,
353        request: &LLMRequest,
354    ) -> impl Future<Output = Result<Option<u32>, GenerateError<Self::Error>>> + Send {
355        let _ = request;
356        async { Ok(None) }
357    }
358
359    /// The tokens `text` takes under a local vocabulary, used while
360    /// streaming to measure decode speed. `None` unless
361    /// [`token_counting`](Self::token_counting) is `Local`.
362    fn count_text(&self, text: &str) -> Option<u32> {
363        let _ = text;
364        None
365    }
366
367    /// Generates a streaming response to a conversation.
368    ///
369    /// Returns a stream of [`Event`]s including:
370    /// - `Event::Text` - Visible text chunks
371    /// - `Event::Reasoning` - Internal reasoning (for reasoning models)
372    /// - `Event::ToolCall` - Requests to execute tools (NOT auto-executed)
373    /// - `Event::BuiltInToolResult` - Results from provider's built-in tools
374    fn respond(&self, request: LLMRequest)
375    -> impl Stream<Item = Result<Event, Self::Error>> + Send;
376
377    /// Generates a streaming response with a mutable tool registry.
378    ///
379    /// This is for providers that support built-in tool execution.
380    /// The default implementation ignores the tools and delegates to `respond`.
381    fn respond_with_tools(
382        &self,
383        request: LLMRequestWithTools<'_>,
384    ) -> impl Stream<Item = Result<Event, Self::Error>> + Send {
385        let (inner, _tools) = request.into_parts();
386        self.respond(inner)
387    }
388
389    /// Generates structured output conforming to JSON schema.
390    ///
391    /// # Note for Implementors
392    /// By default, we use a system prompt to instruct the model to generate structured output based on the provided JSON schema.
393    /// However, that is not efficient enough, if supported, provider should override this method to provide native structured generation support.
394    /// Native structured generation can apply decode rules in token-level, ensuring the output is always valid JSON, and reducing parsing errors.
395    fn generate<T: JsonSchema + DeserializeOwned + 'static>(
396        &self,
397        request: LLMRequest,
398    ) -> impl Future<Output = Result<T, GenerateError<Self::Error>>> + Send {
399        async { structured_generate(self, request).await }
400    }
401
402    /// Completes given text prefix.
403    fn complete(&self, prefix: &str) -> impl Stream<Item = Result<Event, Self::Error>> + Send {
404        self.respond(oneshot("Please complete the following text:", prefix))
405    }
406
407    /// Summarizes text.
408    ///
409    /// # Note for Implementors
410    /// By default, we provide a generic summarization prompt. However, some model provider, like Apple Intelligence, may have native summarization support.
411    /// It would load a summarization-specific lora at runtime, providing better quality.
412    fn summarize(&self, text: &str) -> impl Stream<Item = Result<Event, Self::Error>> + Send {
413        summarize(self, text)
414    }
415
416    /// Categorizes text.
417    ///
418    /// # Note for Implementors
419    /// By default, we use a system prompt to instruct the model to categorize text based on the provided JSON schema.
420    /// However, that is not efficient enough, if supported, provider should override this method to provide native categorization support.
421    fn categorize<T: JsonSchema + DeserializeOwned + 'static>(
422        &self,
423        text: &str,
424    ) -> impl Future<Output = Result<T, GenerateError<Self::Error>>> + Send {
425        async { categorize_text(self, text).await }
426    }
427
428    /// Returns model profile and capabilities.
429    ///
430    /// See [`Profile`] for details on model metadata.
431    ///
432    /// # Errors
433    ///
434    /// Returns an error when the profile cannot be determined — for example
435    /// when neither the provider nor the model registry knows the model's
436    /// context window. Implementations must not substitute a guessed value.
437    fn profile(&self) -> impl Future<Output = Result<Profile, Self::Error>> + Send;
438
439    /// How a request to this model that failed with a retryable failure is
440    /// sent again.
441    ///
442    /// A provider that retries establishing its response stream returns the
443    /// policy it retries under; callers reuse it for a stream that breaks
444    /// after it opened, which the provider cannot retry because the events
445    /// before the break already reached them.
446    fn retry_policy(&self) -> RetryPolicy {
447        RetryPolicy::default()
448    }
449}
450
451macro_rules! impl_language_model {
452    ($($name:ident),*) => {
453        $(
454            impl<T: LanguageModel> LanguageModel for $name<T> {
455                type Error = T::Error;
456
457                fn respond(
458                    &self,
459                    request: LLMRequest,
460                ) -> impl Stream<Item = Result<Event, Self::Error>> + Send {
461                    T::respond(self, request)
462                }
463
464                fn respond_with_tools(
465                    &self,
466                    request: LLMRequestWithTools<'_>,
467                ) -> impl Stream<Item = Result<Event, Self::Error>> + Send {
468                    T::respond_with_tools(self, request)
469                }
470
471                fn generate<U: JsonSchema + DeserializeOwned + 'static>(
472                    &self,
473                    request: LLMRequest,
474                ) -> impl Future<Output = Result<U, GenerateError<Self::Error>>> + Send {
475                    T::generate(self, request)
476                }
477
478                fn complete(
479                    &self,
480                    prefix: &str,
481                ) -> impl Stream<Item = Result<Event, Self::Error>> + Send {
482                    T::complete(self, prefix)
483                }
484
485                fn summarize(
486                    &self,
487                    text: &str,
488                ) -> impl Stream<Item = Result<Event, Self::Error>> + Send {
489                    T::summarize(self, text)
490                }
491
492                fn categorize<U: JsonSchema + DeserializeOwned + 'static>(
493                    &self,
494                    text: &str,
495                ) -> impl Future<Output = Result<U, GenerateError<Self::Error>>> + Send {
496                    T::categorize(self, text)
497                }
498
499                fn profile(&self) -> impl Future<Output = Result<Profile, Self::Error>> + Send {
500                    T::profile(self)
501                }
502
503                fn retry_policy(&self) -> RetryPolicy {
504                    T::retry_policy(self)
505                }
506
507                fn token_counting(&self) -> TokenCounting {
508                    T::token_counting(self)
509                }
510
511                fn count_tokens(
512                    &self,
513                    request: &LLMRequest,
514                ) -> impl Future<Output = Result<Option<u32>, GenerateError<Self::Error>>>
515                + Send {
516                    T::count_tokens(self, request)
517                }
518
519                fn count_text(&self, text: &str) -> Option<u32> {
520                    T::count_text(self, text)
521                }
522            }
523        )*
524    };
525}
526
527impl<T: LanguageModel> LanguageModel for &T {
528    type Error = T::Error;
529
530    fn respond(
531        &self,
532        request: LLMRequest,
533    ) -> impl Stream<Item = Result<Event, Self::Error>> + Send {
534        T::respond(self, request)
535    }
536
537    fn respond_with_tools(
538        &self,
539        request: LLMRequestWithTools<'_>,
540    ) -> impl Stream<Item = Result<Event, Self::Error>> + Send {
541        T::respond_with_tools(self, request)
542    }
543
544    fn generate<U: JsonSchema + DeserializeOwned + 'static>(
545        &self,
546        request: LLMRequest,
547    ) -> impl Future<Output = Result<U, GenerateError<Self::Error>>> + Send {
548        T::generate(self, request)
549    }
550
551    fn complete(&self, prefix: &str) -> impl Stream<Item = Result<Event, Self::Error>> + Send {
552        T::complete(self, prefix)
553    }
554
555    fn summarize(&self, text: &str) -> impl Stream<Item = Result<Event, Self::Error>> + Send {
556        T::summarize(self, text)
557    }
558
559    fn categorize<U: JsonSchema + DeserializeOwned + 'static>(
560        &self,
561        text: &str,
562    ) -> impl Future<Output = Result<U, GenerateError<Self::Error>>> + Send {
563        T::categorize(self, text)
564    }
565
566    fn profile(&self) -> impl Future<Output = Result<Profile, Self::Error>> + Send {
567        T::profile(self)
568    }
569
570    fn retry_policy(&self) -> RetryPolicy {
571        T::retry_policy(self)
572    }
573
574    fn token_counting(&self) -> TokenCounting {
575        T::token_counting(self)
576    }
577
578    fn count_tokens(
579        &self,
580        request: &LLMRequest,
581    ) -> impl Future<Output = Result<Option<u32>, GenerateError<Self::Error>>> + Send {
582        T::count_tokens(self, request)
583    }
584
585    fn count_text(&self, text: &str) -> Option<u32> {
586        T::count_text(self, text)
587    }
588}
589
590mod prompts;
591
592impl_language_model!(Arc, Box);
593
594/// Collects text from an event stream.
595///
596/// # Errors
597///
598/// Returns the first stream error encountered while collecting text chunks.
599pub async fn collect_text<S, E>(stream: S) -> Result<String, E>
600where
601    S: Stream<Item = Result<Event, E>>,
602{
603    pin!(stream);
604    let mut result = String::new();
605    while let Some(event) = stream.next().await {
606        if let Event::Text(text) = event? {
607            result.push_str(&text);
608        }
609    }
610    Ok(result)
611}
612
613async fn structured_generate<T: JsonSchema + DeserializeOwned + 'static, M: LanguageModel>(
614    model: &M,
615    mut request: LLMRequest,
616) -> Result<T, GenerateError<M::Error>> {
617    let schema = schema_for!(T);
618
619    // If it is a string, we are not required to set up structured generation and JSON schema.
620    let json = if schema.as_value().is_string() {
621        let stream = model.respond(request);
622        let response = collect_text(stream)
623            .await
624            .map_err(GenerateError::Provider)?;
625        // Let's encode it as JSON string. Serializing a String cannot fail.
626        serde_json::to_string(&response).map_err(|source| GenerateError::Parse {
627            source,
628            response: response.clone(),
629        })?
630    } else {
631        // Serializing a `Schema` is infallible in practice, but keep the error
632        // typed rather than unwrapping.
633        let schema =
634            serde_json::to_string_pretty(&schema).map_err(|source| GenerateError::Parse {
635                source,
636                response: String::new(),
637            })?;
638        let prompt = prompts::generate(&schema);
639        request.messages.push(Message::system(prompt));
640        request.parameters.structured_outputs = true;
641
642        let stream = model.respond(request);
643        collect_text(stream)
644            .await
645            .map_err(GenerateError::Provider)?
646    };
647
648    parse_json_with_recovery(&json).map_err(|source| GenerateError::Parse {
649        source,
650        response: truncate_for_error(&json),
651    })
652}
653
654/// Keeps a failed response short enough to log without dumping a whole context.
655fn truncate_for_error(response: &str) -> String {
656    const LIMIT: usize = 500;
657    response.chars().take(LIMIT).collect()
658}
659
660/// Convenience helper that creates a single system + user [`LLMRequest`].
661pub fn oneshot(system: impl Into<String>, user: impl Into<String>) -> LLMRequest {
662    let messages = vec![Message::system(system.into()), Message::user(user.into())];
663    LLMRequest::new(messages)
664}
665
666fn summarize<M: LanguageModel>(
667    model: &M,
668    text: &str,
669) -> impl Stream<Item = Result<Event, M::Error>> + Send {
670    let messages = oneshot("Summarize text:", text);
671    model.respond(messages)
672}
673
674async fn categorize_text<T: JsonSchema + DeserializeOwned + 'static, M: LanguageModel>(
675    model: &M,
676    text: &str,
677) -> Result<T, GenerateError<M::Error>> {
678    let request = oneshot("Categorize text by provided schema", text);
679    model.generate(request).await
680}
681
682fn parse_json_with_recovery<T: DeserializeOwned + 'static>(
683    json: &str,
684) -> Result<T, serde_json::Error> {
685    use serde::de::Error as _;
686
687    let trimmed = json.trim();
688    let mut last_error: Option<serde_json::Error> = None;
689    let mut last_candidate: Option<String> = None;
690
691    for candidate in build_json_candidates(trimmed) {
692        match serde_json::from_str::<T>(&candidate) {
693            Ok(value) => return Ok(value),
694            Err(err) => {
695                last_error = Some(err);
696                last_candidate = Some(candidate);
697            }
698        }
699    }
700
701    // A model asked for a plain string will often answer with an object or a
702    // bare word instead. Re-encode whatever it did produce as a JSON string.
703    if is_string_type::<T>()
704        && let Some(candidate) = last_candidate
705        && let Ok(value) = serde_json::from_str::<serde_json::Value>(&candidate)
706    {
707        let text = match value {
708            serde_json::Value::String(s) => s,
709            other => other.to_string(),
710        };
711        let encoded = serde_json::to_string(&text)?;
712        if let Ok(value) = serde_json::from_str::<T>(&encoded) {
713            return Ok(value);
714        }
715    }
716
717    Err(last_error.unwrap_or_else(|| {
718        serde_json::Error::custom("structured output was empty or missing a JSON block")
719    }))
720}
721
722fn strip_code_fences(raw: &str) -> Option<String> {
723    let trimmed = raw.trim();
724    let fence_start = trimmed.find("```")?;
725    let after_fence = &trimmed[fence_start + 3..];
726    let mut lines = after_fence.lines();
727    let _maybe_lang = lines.next();
728    let body = lines.collect::<Vec<_>>().join("\n");
729    let content = body.rfind("```").map_or(body.as_str(), |end| &body[..end]);
730
731    let cleaned = content.trim();
732    if cleaned.is_empty() {
733        None
734    } else {
735        Some(cleaned.to_string())
736    }
737}
738
739fn extract_json_block(raw: &str) -> Option<String> {
740    if let (Some(start), Some(end)) = (raw.find('{'), raw.rfind('}'))
741        && end >= start
742    {
743        let candidate = &raw[start..=end];
744        if !candidate.trim().is_empty() {
745            return Some(candidate.trim().to_string());
746        }
747    }
748    if let (Some(start), Some(end)) = (raw.find('['), raw.rfind(']'))
749        && end >= start
750    {
751        let candidate = &raw[start..=end];
752        if !candidate.trim().is_empty() {
753            return Some(candidate.trim().to_string());
754        }
755    }
756    None
757}
758
759fn build_json_candidates(raw: &str) -> Vec<String> {
760    let mut candidates = Vec::new();
761
762    if !raw.is_empty() {
763        candidates.push(raw.to_string());
764    }
765
766    if let Some(fenced) = strip_code_fences(raw) {
767        candidates.push(fenced);
768    }
769
770    if let Some(block) = extract_json_block(raw) {
771        candidates.push(block);
772    }
773
774    if let Some(dequoted) = dequote_json_string(raw) {
775        candidates.push(dequoted);
776    }
777
778    if let Some(stripped) = strip_leading_label(raw, "json") {
779        candidates.push(stripped);
780    }
781
782    let mut deduped = Vec::new();
783    for candidate in candidates {
784        if deduped.iter().all(|seen| seen != &candidate) {
785            deduped.push(candidate);
786        }
787    }
788    deduped
789}
790
791fn dequote_json_string(raw: &str) -> Option<String> {
792    let trimmed = raw.trim();
793    if !(trimmed.starts_with('"') && trimmed.ends_with('"')) {
794        return None;
795    }
796    let inner: String = serde_json::from_str(trimmed).ok()?;
797    if inner.trim().is_empty() {
798        None
799    } else {
800        Some(inner)
801    }
802}
803
804fn strip_leading_label(raw: &str, label: &str) -> Option<String> {
805    let trimmed = raw.trim_start();
806    if !trimmed.to_ascii_lowercase().starts_with(label) {
807        return None;
808    }
809    let stripped = trimmed[label.len()..]
810        .trim_start_matches(|c: char| c.is_whitespace() || c == ':' || c == '-')
811        .trim();
812    if stripped.is_empty() {
813        None
814    } else {
815        Some(stripped.to_string())
816    }
817}
818
819fn is_string_type<T: 'static>() -> bool {
820    TypeId::of::<T>() == TypeId::of::<String>()
821}
822
823#[cfg(test)]
824mod tests {
825    use super::parse_json_with_recovery;
826    use alloc::string::String;
827    use serde::Deserialize;
828
829    #[derive(Debug, Deserialize, PartialEq, Eq)]
830    struct Foo {
831        a: u8,
832    }
833
834    #[test]
835    fn parses_plain_json() {
836        let foo: Foo = parse_json_with_recovery(r#"{"a":1}"#).unwrap();
837        assert_eq!(foo, Foo { a: 1 });
838    }
839
840    #[test]
841    fn parses_code_fence_json() {
842        let foo: Foo = parse_json_with_recovery("```json\n{\"a\":2}\n```").unwrap();
843        assert_eq!(foo, Foo { a: 2 });
844    }
845
846    #[test]
847    fn parses_embedded_block() {
848        let foo: Foo = parse_json_with_recovery("noise {\"a\":3} trailing").unwrap();
849        assert_eq!(foo, Foo { a: 3 });
850    }
851
852    #[test]
853    fn parses_quoted_json_string() {
854        let foo: Foo = parse_json_with_recovery(r#""{\"a\":4}""#).unwrap();
855        assert_eq!(foo, Foo { a: 4 });
856    }
857
858    #[test]
859    fn parses_labeled_json() {
860        let foo: Foo = parse_json_with_recovery("json {\"a\":5}").unwrap();
861        assert_eq!(foo, Foo { a: 5 });
862    }
863
864    #[test]
865    fn coerces_object_to_string() {
866        let value: String =
867            parse_json_with_recovery(r#"{"title":"summary","type":"content"}"#).unwrap();
868        assert!(
869            value.contains("\"title\":\"summary\"") && value.contains("\"type\":\"content\""),
870            "unexpected value: {value}"
871        );
872    }
873}