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