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