Skip to main content

lc_core/
lib.rs

1#![warn(missing_docs)]
2// lc-core/src/lib.rs
3//! Core abstractions for LangChainRust.
4//!
5//! This crate provides the foundational traits and types:
6//! - `Runnable`: Base execution interface
7//! - `BaseLanguageModel`: LLM abstraction
8//! - `BaseChatModel`: Chat model interface
9//! - `BaseTool`, `Tool`: Tool abstraction
10//! - `RunnableConfig`: Execution configuration with callbacks
11//! - Output parsers, structured output, caching, token counting, batch API
12
13pub mod batch;
14pub mod cache;
15pub mod json_parse;
16pub mod judge;
17pub mod language_models;
18pub mod math;
19pub mod output_parsers;
20pub mod router_llm;
21pub mod runnables;
22pub mod ssrf;
23pub mod structured_output;
24pub mod token_counter;
25pub mod tools;
26
27// Re-export key types at crate root for convenience
28pub use json_parse::{parse_llm_json, parse_llm_json_with_retry, LlmJsonParseError};
29
30pub use judge::{structured_call, truncate, StructuredJudgeError};
31
32pub use language_models::{
33    predict_tools, BaseChatModel, BaseLanguageModel, MultimodalError, MultimodalModel,
34    PredictToolsError, StreamChunk, TokenUsage,
35};
36pub use output_parsers::{
37    BaseOutputParser, CommaSeparatedListOutputParser, JsonOutputParser, OutputParserError,
38    OutputParserResult, StrOutputParser, StructuredOutputParser, TypedOutputParser,
39};
40pub use runnables::{
41    into_runnable_any, CancellationToken, LcelError, RetryConfig, RetryOn, Runnable, RunnableAny,
42    RunnableAnyWrapper, RunnableAssign, RunnableBinding, RunnableBranch, RunnableConfig,
43    RunnableConfigurable, RunnableConfigurableFields, RunnableExt, RunnableLambda,
44    RunnableParallel, RunnablePassthrough, RunnablePick, RunnableRetry, RunnableSequence,
45    RunnableWithFallbacks,
46};
47pub use structured_output::{
48    stream_structured_output, with_structured_output, PartialJsonError, PartialJsonParser,
49    StreamingStructuredOutputExt, StructuredOutputError, StructuredOutputExt,
50};
51pub use tools::{
52    BaseTool, FunctionCall, FunctionDefinition, StructuredOutput, Tool, ToolCall, ToolCallBuilder,
53    ToolCallResult, ToolDefinition, ToolError, ToolRegistry,
54};
55
56/// Unified error type for the lc-core crate.
57///
58/// Aggregates all core-specific error types so the `?` operator works
59/// seamlessly across core module boundaries.
60#[derive(Debug, thiserror::Error)]
61#[non_exhaustive]
62pub enum CoreError {
63    /// Tool execution error.
64    #[error("Tool error: {0}")]
65    Tool(#[from] ToolError),
66
67    /// JSON parse error from LLM output.
68    #[error("JSON parse error: {0}")]
69    JsonParse(#[from] LlmJsonParseError),
70
71    /// Batch processing error.
72    #[error("Batch error: {0}")]
73    Batch(#[from] batch::BatchError),
74
75    /// Router error.
76    #[error("Router error: {0}")]
77    Router(#[from] router_llm::RouterError),
78
79    /// Structured output extraction error.
80    #[error("Structured output error: {0}")]
81    StructuredOutput(#[from] StructuredOutputError),
82
83    /// Partial JSON parsing error.
84    #[error("Partial JSON error: {0}")]
85    PartialJson(#[from] PartialJsonError),
86
87    /// Output parser error.
88    #[error("Output parser error: {0}")]
89    OutputParser(#[from] OutputParserError),
90
91    /// Math operation error.
92    #[error("Math error: {0}")]
93    Math(#[from] math::MathError),
94
95    /// Token counting error.
96    #[error("Token counting error: {0}")]
97    TokenCount(#[from] token_counter::TokenCounterError),
98
99    /// Any other error (e.g., from providers that haven't been extracted yet).
100    #[error("{0}")]
101    Other(String),
102}
103
104// Allow external error types to convert into CoreError via string wrapping
105impl From<std::convert::Infallible> for CoreError {
106    fn from(_: std::convert::Infallible) -> Self {
107        unreachable!()
108    }
109}
110
111/// Helper to convert any error into `CoreError::Other`.
112/// Use this instead of `?` when the error type is not a known CoreError variant.
113pub fn other_error<E: std::fmt::Display>(err: E) -> CoreError {
114    CoreError::Other(err.to_string())
115}
116
117// Allow CoreError to convert into LcelError for LCEL pipeline compatibility
118impl From<CoreError> for runnables::LcelError {
119    fn from(err: CoreError) -> Self {
120        match &err {
121            CoreError::Tool(_) => runnables::LcelError::Tool(err.to_string()),
122            CoreError::JsonParse(_) => runnables::LcelError::Other(err.to_string()),
123            CoreError::Batch(_) => runnables::LcelError::Other(err.to_string()),
124            CoreError::Router(_) => runnables::LcelError::Other(err.to_string()),
125            CoreError::StructuredOutput(_) => runnables::LcelError::Other(err.to_string()),
126            CoreError::PartialJson(_) => runnables::LcelError::Other(err.to_string()),
127            CoreError::OutputParser(_) => runnables::LcelError::OutputParser(err.to_string()),
128            CoreError::Math(_) => runnables::LcelError::Other(err.to_string()),
129            CoreError::TokenCount(_) => runnables::LcelError::Other(err.to_string()),
130            CoreError::Other(_) => runnables::LcelError::Other(err.to_string()),
131        }
132    }
133}