1pub mod assistant;
79pub mod event;
81pub mod failure;
83pub mod message;
85pub mod model;
87pub mod provider;
89pub mod reasoning;
91pub mod researcher;
93pub mod retry;
95pub 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#[derive(Debug)]
139pub enum GenerateError<E> {
140 Provider(E),
142
143 Parse {
147 source: serde_json::Error,
149 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#[derive(Debug, Clone)]
182pub struct LLMRequest {
183 messages: Vec<Message>,
184 parameters: Parameters,
185 tool_definitions: Vec<tool::ToolDefinition>,
186}
187
188impl LLMRequest {
189 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 #[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 #[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 #[must_use]
217 pub fn with_parameters(mut self, parameters: Parameters) -> Self {
218 self.parameters = parameters;
219 self
220 }
221
222 #[must_use]
224 pub fn messages(&self) -> &[Message] {
225 &self.messages
226 }
227
228 pub const fn messages_mut(&mut self) -> &mut Vec<Message> {
230 &mut self.messages
231 }
232
233 #[must_use]
235 pub const fn parameters(&self) -> &Parameters {
236 &self.parameters
237 }
238
239 #[must_use]
241 pub fn tool_definitions(&self) -> &[tool::ToolDefinition] {
242 &self.tool_definitions
243 }
244
245 #[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#[derive(Debug)]
257pub struct LLMRequestWithTools<'tools> {
258 inner: LLMRequest,
259 tools: &'tools mut Tools,
260}
261
262impl LLMRequest {
263 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 #[must_use]
279 pub const fn request(&self) -> &LLMRequest {
280 &self.inner
281 }
282
283 pub const fn request_mut(&mut self) -> &mut LLMRequest {
285 &mut self.inner
286 }
287
288 #[must_use]
290 pub const fn tools(&mut self) -> &mut Tools {
291 self.tools
292 }
293
294 #[must_use]
296 pub fn into_parts(self) -> (LLMRequest, &'tools mut Tools) {
297 (self.inner, self.tools)
298 }
299
300 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#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
322pub enum TokenCounting {
323 #[default]
325 None,
326 Local,
328 Endpoint,
330}
331
332pub trait LanguageModel: Sized + Send + Sync {
340 type Error: core::error::Error + Classify + Send + Sync + 'static;
342
343 fn token_counting(&self) -> TokenCounting {
345 TokenCounting::None
346 }
347
348 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 fn count_text(&self, text: &str) -> Option<u32> {
363 let _ = text;
364 None
365 }
366
367 fn respond(&self, request: LLMRequest)
375 -> impl Stream<Item = Result<Event, Self::Error>> + Send;
376
377 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 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 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 fn summarize(&self, text: &str) -> impl Stream<Item = Result<Event, Self::Error>> + Send {
413 summarize(self, text)
414 }
415
416 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 fn profile(&self) -> impl Future<Output = Result<Profile, Self::Error>> + Send;
438
439 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
594pub 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 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 serde_json::to_string(&response).map_err(|source| GenerateError::Parse {
627 source,
628 response: response.clone(),
629 })?
630 } else {
631 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
654fn truncate_for_error(response: &str) -> String {
656 const LIMIT: usize = 500;
657 response.chars().take(LIMIT).collect()
658}
659
660pub 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 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}