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