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