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