langchainrust 0.27.0

A LangChain-inspired framework for building LLM applications in Rust. Supports OpenAI, Agents, Tools, Memory, Chains, RAG, BM25, Hybrid Retrieval, LangGraph, HyDE, Reranking, MultiQuery, and native Function Calling.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
#![warn(missing_docs)]
// crates/lc/src/lib.rs
//! LangChain Rust - A LangChain-compatible framework for building LLM applications.
//!
//! This crate is a Rust implementation inspired by LangChain Python.
//!
//! # Example
//! ```
//! use langchainrust::core::RunnableConfig;
//! use langchainrust::core::runnables::Runnable;
//!
//! let config = RunnableConfig::new()
//!     .with_tag("example")
//!     .with_run_name("my_run");
//! ```

#[cfg(test)]
extern crate tempfile;

// === Core Modules ===

/// Core abstractions: Runnable, BaseTool, BaseLanguageModel, etc.
pub mod core;

/// Message types: Human, AI, System, Tool.
pub mod schema;

/// LLM integrations: OpenAI, Ollama, DeepSeek, Qwen, Anthropic, etc.
pub mod language_models;

/// Built-in tools: Calculator, DateTime, Math, URLFetch.
pub mod tools;

/// Agent implementations: FunctionCallingAgent, ReActAgent.
pub mod agents;

/// Memory management: Buffer, Window, Summary, SummaryBuffer.
pub mod memory;

/// Chain compositions: LLMChain, SequentialChain, RetrievalQA.
pub mod chains;

/// Embedding models: OpenAI, DeepSeek, Qwen, Mock.
pub mod embeddings;

/// Vector stores: InMemory, Qdrant, MongoDB.
pub mod vector_stores;

/// Retrieval: BM25, Hybrid, MultiQuery, HyDE, Reranking.
pub mod retrieval;

/// Prompt templates: PromptTemplate, ChatPromptTemplate.
pub mod prompts;

/// Callbacks: StdOutHandler, LangSmith tracing.
pub mod callbacks;

/// LangGraph: StateGraph, CompiledGraph, Checkpointer.
pub mod langgraph;

/// MCP: Model Context Protocol client.
pub mod mcp;
pub use mcp::MCPServer;

/// Sessions: conversation lifecycle management.
pub mod sessions;
pub use sessions::SessionManagerRunnable;

pub mod evaluation;
/// Guardrails: input/output safety validation.
pub mod guardrails;

/// Unified error type aggregating all sub-module errors.
pub mod error;
pub use error::Error;
// 0.27.0 T1 ($5 low): the bare `Error` name sits beside the `error` module and ~30 per-crate
// error types re-exported at root, so also expose the unambiguous alias `LcError`.
pub use error::LcError;

/// A2A: Agent-to-Agent protocol for inter-agent communication.
pub mod a2a;

// T2-3 (0.27.0): feature-matrix export inventory. The facade gates 18 root/module exports
// behind the following features (each is a real re-export in `lib.rs` — dropping a gate or
// renaming a feature without updating this map is a drift signal). Kept as documentation so
// the matrix is auditable in one place instead of scattered ad-hoc:
//
// | feature                   | loads when feature is on                          |
// |---------------------------|---------------------------------------------------|
// | `observability`           | `JsonLinesSink`                                   |
// | `observability-mongodb`   | `MongoSink`                                       |
// | `vectorstore-memory`      | `VectorStoreRetrieverMemory`                      |
// | `browser-cdp`             | `tools::browser::{*}` CDP tool surface            |
// | `mongodb-persistence`     | `MongoPersistentMemory`, `MongoChunkedDocumentStore`/`MongoStoreConfig` |
// | `local-embeddings`        | `LocalEmbeddings`                                 |
// | `redis-storage`           | `RedisDocumentStore`/`RedisStoreConfig`           |
// | `sqlite-storage`          | `SQLiteDocumentStore`/`SQLiteStoreConfig`         |
// | `pgvector-storage`        | `vector_stores::pgvector` module + `PGVectorConfig`/`PGVectorStore` |
// | `qdrant-integration`      | `QdrantConfig`/`QdrantVectorStore`                |
// | `otlp`                    | `callbacks::otlp` submodule                       |
// | `opentelemetry`           | `OtelHandler`, `OtelTracingBackend`               |
// | `checkpoint-postgres`     | `PostgresCheckpointer`                            |
// | `checkpoint-redis`        | `RedisCheckpointer`                               |
// | `checkpoint-sqlite`       | `SqliteCheckpointer`                              |
//
// Note on `local-candle`/`fastembed` (`lc-embeddings` forward features): they add no new
// `#[cfg]` export here — the embedding entry points they enable live inside `lc-embeddings`.
// See the `[package.metadata.docs.rs]` list above for the docs build's explicit feature set
// (excludes `pgvector-storage` — sqlx 0.8.0 fails on docs.rs's newer rustc — and the
// candle/ort pulls that need platform binaries).

// Re-export the commonly used types
pub use agents::{
    parse_review_verdict, parse_supervisor_decision, review_envelope, supervisor_envelope,
    task_adapter, AdaptiveRAG, AdaptiveRAGError, AdaptiveRAGResult, AgentAction, AgentBuilder,
    AgentError, AgentEventRunnable, AgentExecutor, AgentFinish, AgentOutput, AgentRunnable,
    AgentStep, AgentStreamEvent, AgentTask, AllowAll, ApprovalDecision, ApprovalGate,
    ApprovalHandler, BaseAgent, BudgetConfig, BudgetExceeded, CRAGError, CRAGResult, Citation,
    CorrectiveRAGAgent, DeepResearchAgent, FanOutFanIn, FileResumeStore, FunctionCallingAgent,
    HandoffManager, LlmMemoryExtractor, MemoryResumeStore, Orchestrator, OrchestratorRunnable,
    PendingApproval, PlanExecuteAgent, PlanExecuteError, PromptInjectionHook, RagDecision,
    ReActAgent, ResearchError, ResearchReport, ResumeStore, ReviewOrchestrator, ReviewVerdict,
    RunContext, SequentialPipeline, StreamingFunctionCallingAgent, Supervisor, SupervisorNext,
    TaskAdapter, TokenBudgetHook, ToolInput, ToolPolicy, ToolRisk, SUPERVISOR_FINISH,
};
pub use core::batch::{
    BatchClient, BatchError, BatchId, BatchProvider, BatchRequest, BatchResult, BatchStatus,
};
pub use core::cost::{
    CostError, CostRecord, CostReport, CostTracker, ModelPrice, ModelSpend, PricingTable,
};
pub use core::language_models::wrap_chat_model;
pub use core::language_models::{
    predict_tools, LLMResult, MultimodalError, MultimodalModel, PredictToolsError, StreamChunk,
    TokenUsage,
};
pub use core::model_registry::{ModelCapabilities, ModelInfo, ModelRegistry};
pub use core::observability::{AgentMetrics, MetricsSink, ObsError, ObsEvent};
// J1 (0.25.0): the `observability` feature now surfaces the *concrete* sinks, not just the
// `MetricsSink` interface — a facade user can construct/export to `JsonLinesSink` (default
// `jsonl`) and `MongoSink` (`observability-mongodb`) directly.
#[cfg(feature = "observability")]
pub use lc_observability::JsonLinesSink;
#[cfg(feature = "observability-mongodb")]
pub use lc_observability::MongoSink;
// B13 (0.22.4): `BudgetExceeded` is renamed at the umbrella boundary because
// the agent executor already exports its own `agents::BudgetExceeded` enum.
pub use core::router_llm::BudgetExceeded as RouterBudgetExceeded;
pub use core::router_llm::{
    BudgetKind, ModelRateLimit, RateLimitReason, RouterBudget, RouterError, RouterLLM,
    RoutingStrategy,
};
pub use core::token_counter::{ModelPricing, TiktokenCounter, TokenCounter, TokenTrackingLLM};
pub use core::tools::to_tool_definition;
pub use core::tools::StructuredOutput;
pub use core::{
    // LCEL types
    into_runnable_any,
    BaseChatModel,
    BaseLanguageModel,
    BaseTool,
    FunctionCall,
    FunctionDefinition,
    LcelError,
    Runnable,
    RunnableAny,
    RunnableAnyWrapper,
    RunnableBinding,
    RunnableBranch,
    RunnableConfig,
    RunnableConfigurable,
    RunnableConfigurableFields,
    RunnableExt,
    RunnableLambda,
    RunnableParallel,
    RunnablePassthrough,
    RunnablePick,
    RunnableSequence,
    Tool,
    ToolCall,
    ToolCallBuilder,
    ToolCallResult,
    ToolDefinition,
    ToolError,
    ToolRegistry,
};
pub use evaluation::{
    compare_reports, compare_reports_with, paired_significance, percentile, AnswerRelevancy, Bleu,
    CompareOptions, ContainsKeyword, ContextPrecision, ContextRecall, Dataset, EmbeddingSimilarity,
    EvalError, EvalRunner, Evaluator, ExactMatch, Example, Faithfulness, LLMAsJudge, LengthCheck,
    MetricDelta, OverallCost, PairedSignificance, PairwiseEvaluator, PairwiseJudge, Predictor,
    Price, PriceBook, RagEvaluator, RegexMatch, Regression, Report, ReportComparison, Score,
    StringDistance, Verdict,
};
pub use guardrails::{
    ChunkContext, FlushOutput, ForbiddenWordsGuardrail, GuardedAgent, GuardrailError,
    GuardrailRunner, GuardrailsConfig, InputGuardrail, MaxLengthGuardrail, OutputGuardrail,
    PiiKind, PiiRedactionGuardrail, SchemaOutputGuardrail, SensitiveInfoGuardrail,
};
pub use language_models::{
    AnthropicChat, AnthropicConfig, AnthropicError, AnthropicStreamToken,
    AnthropicStructuredOutputMethod, AssistantError, DeepSeekChat, DeepSeekConfig, GeminiChat,
    GeminiConfig, GeminiError, GeminiStructuredOutputMethod, GroqChat, LLMClient, MoonshotChat,
    MoonshotConfig, OllamaChat, OllamaConfig, OpenAIAssistant, OpenAIChat, OpenAICompatibleChat,
    OpenAICompatibleConfig, OpenAIConfig, OpenRouterChat, QwenChat, QwenConfig, ThinkingConfig,
    ThinkingType, XaiChat, ZhipuChat, ZhipuConfig,
};
pub use memory::{
    BaseMemory, ChatMessageHistory, ContextWindow, ConversationBufferMemory,
    ConversationBufferWindowMemory, ConversationSummaryBufferMemory, ConversationSummaryMemory,
    DecayWeights, LexicalScorer, LongTermMemory, MemoryData, MemoryError, MemoryExtractor,
    MemoryHit, MemoryItem, MemoryQuery, MemoryStore, MemoryTier, PersistenceConfig,
    PersistentMemory, PromotionPolicy, RunnableWithMessageHistory, SemanticScorer, SharedMemory,
    ShortTermMemory, StoredMemory, Strategy, TwoTierMemory,
};

#[cfg(feature = "vectorstore-memory")]
pub use memory::VectorStoreRetrieverMemory;
pub use schema::{ImageContent, Message, MessageType};
pub use tools::{
    Calculator, CalculatorInput, CodeSandbox, ComputerMode, ComputerUseInput, ComputerUseOutput,
    ComputerUseTool, DateTimeInput, DateTimeTool, DuckDuckGoSearchTool, FileTool, HTTPTool,
    HostedSearchTool, Language, LocalSandbox, MathInput, PythonREPLInput, PythonREPLTool,
    RunResult, SandboxError, SandboxTool, SearchInput, SimpleMathTool, URLFetchInput, URLFetchTool,
    WikipediaInput, WikipediaTool,
};

// B6 (0.22.4): CDP browser tool is opt-in (pulls tokio-tungstenite, plain
// `ws://` only); hosted search itself is re-exported unconditionally above.
#[cfg(feature = "browser-cdp")]
pub use tools::browser::{
    BrowserInput, BrowserOutput, CdpBrowser, CdpBrowserTool, NavigationInfo, PageLink, PageMetadata,
};

pub use chains::{
    BaseChain, ChainError, ChainResult, ChainRunnable, ChainStream, ConversationChain,
    ConversationChainBuilder, ConversationRetrievalChain, LLMChain, LLMChainBuilder,
    LLMRouterChain, MapReduceDocumentsChain, MapRerankDocumentsChain, RefineDocumentsChain,
    RetrievalQA, RouteDestination, RouterChain, SequentialChain, StreamToken, StuffDocumentsChain,
};
#[cfg(feature = "mongodb-persistence")]
pub use memory::MongoPersistentMemory;

// Embeddings
pub use embeddings::{
    cosine_similarity, l2_normalize, BagOfWordsEmbeddings, DeepSeekEmbeddings,
    DeepSeekEmbeddingsConfig, EmbeddingError, Embeddings, MockEmbeddings, OpenAIEmbeddings,
    OpenAIEmbeddingsConfig, QwenEmbeddings, QwenEmbeddingsConfig,
};
// 1.0: without the `local-embeddings` feature, `LocalEmbeddings` is unavailable (the deprecated alias was removed).
#[cfg(feature = "local-embeddings")]
pub use embeddings::LocalEmbeddings;

// Vector Stores
pub use vector_stores::{
    ChromaDBConfig, ChromaDBVectorStore, Document, FileVectorStore, FilterOp, InMemoryVectorStore,
    MetadataFilter, SearchResult, VectorStore, VectorStoreBuilder, VectorStoreError,
    VectorStoreProvider, VectorStoreType,
};

#[cfg(feature = "redis-storage")]
pub use vector_stores::{RedisDocumentStore, RedisStoreConfig};

#[cfg(feature = "sqlite-storage")]
pub use vector_stores::{SQLiteDocumentStore, SQLiteStoreConfig};

// Typed PGVector storage: available once the `pgvector-storage` feature is enabled (the sqlx + pgvector
// dependencies come in via the feature; no user-side setup needed). Both the module path and the type path are exposed.
#[cfg(feature = "pgvector-storage")]
pub use vector_stores::pgvector;
#[cfg(feature = "pgvector-storage")]
pub use vector_stores::{PGVectorConfig, PGVectorStore};

pub use vector_stores::PineconeStore;
pub use vector_stores::{
    ChunkDocument, ChunkedDocumentStore, ChunkedDocumentStoreTrait, InMemoryChunkedDocumentStore,
};

#[cfg(feature = "qdrant-integration")]
pub use vector_stores::{QdrantConfig, QdrantVectorStore};

#[cfg(feature = "mongodb-persistence")]
pub use vector_stores::{MongoChunkedDocumentStore, MongoStoreConfig};

// Retrieval
pub use retrieval::{
    filter_by_score, reciprocal_rank_fusion, RAGPipeline, RAGPipelineBuilder, RAGQueryResult,
    RagRunnable, RetrievalSource, RetrievedDocument,
};
pub use retrieval::{
    AutoMergingConfig, BM25Params, BM25Retriever, ChunkedBM25Retriever, ChunkedSearchResult,
    Tokenizer,
};
pub use retrieval::{
    BM25Reranker, KeywordReranker, Reranker, RerankingConfig, RerankingError, RerankingExecutor,
};
// v0.23/v0.24 retrieval depth: hosted neural rerankers, small-to-big retrieval,
// MMR diversity selection and the token-level late-chunking entry points.
pub use retrieval::{late_chunk, late_index_in, LateChunk, LateChunkConfig};
pub use retrieval::{mmr, SentenceWindowRetriever};
pub use retrieval::{rerank_async, AsyncReranker, CohereRerank, JinaRerank};
pub use retrieval::{
    CSVLoader, DocumentLoader, DocxLoader, HTMLLoader, JSONLoader, LoaderError, MarkdownLoader,
    PDFLoader, ParentDocumentRetriever, RecursiveCharacterSplitter, Retriever, RetrieverError,
    RetrieverRunnable, RetrieverTrait, SelfQueryRetriever, SemanticSplitter, SimilarityRetriever,
    SitemapLoader, TextLoader, TextSplitter, WebScraperLoader,
};
pub use retrieval::{FusionMode, HybridIndexConfig, HybridSearchResult, UnifiedHybridIndex};
pub use retrieval::{
    GlobalLevel as GraphGlobalLevel, GraphCommunity, GraphEntity, GraphRAG, GraphRAGConfig,
    GraphRAGError, GraphRAGResult, GraphRelation, GraphStore, QueryMode as GraphQueryMode,
};
pub use retrieval::{HyDEConfig, HyDEError, HyDERetriever};
pub use retrieval::{MultiQueryConfig, MultiQueryError, MultiQueryRetriever, StaticQueryGenerator};

// Prompts
pub use prompts::{
    ChatPromptTemplate, ExampleSelector, FewShotPromptTemplate, LengthBasedExampleSelector,
    PromptRegistry, PromptTemplate, PromptVersionInfo, RegisteredPrompt, VariableDiff, VersionSpec,
    MIN_HASH_PREFIX,
};

// Callbacks
#[cfg(feature = "otlp")]
pub use callbacks::otlp;
#[cfg(feature = "opentelemetry")]
pub use callbacks::OtelHandler;
pub use callbacks::{
    CallbackHandler, CallbackManager, FileCallbackHandler, LangSmithClient, LangSmithConfig,
    LangSmithError, LangSmithHandler, LogFormat, RunTree, RunType, StdOutHandler,
};

// Tracing
#[cfg(feature = "opentelemetry")]
pub use callbacks::OtelTracingBackend;
pub use callbacks::{
    clear_span_stack, ConsoleTracingBackend, InMemoryTracingBackend, SpanGuard, SpanId, SpanKind,
    SpanStatus, SpanTokenUsage, TraceNode, TraceSpan, Tracer, TracingBackend,
};

// Output Parsers
pub use core::output_parsers::{
    BaseOutputParser, CommaSeparatedListOutputParser, JsonOutputParser, OutputParserError,
    OutputParserResult, StrOutputParser, StructuredOutputParser, TypedOutputParser,
};

// Structured Output
pub use core::structured_output::{
    stream_structured_output, with_structured_output, PartialJsonError, PartialJsonParser,
    StreamingStructuredOutputExt, StructuredOutputError, StructuredOutputExt,
};

// A2A
pub use a2a::{
    A2AClient, A2AError, A2AErrorData, A2AMessage, A2ARequest, A2AResponse, A2AServer, A2ATask,
    A2ATaskResult, AgentCard, TaskStatus,
};
// B7 (0.25.0): security/identity surface lifted to the umbrella. ServeConfig is
// not lifted because it is gated behind lc-a2a's `axum` feature (not enabled in
// this crate's prod dependency); reach it as `a2a::ServeConfig`.
pub use a2a::{Authenticator, Principal, StaticBearer};

// LangGraph
pub use langgraph::{
    AgentState, AppendMessagesReducer, AppendReducer, AppendStepsReducer, AsyncFn,
    AsyncFunctionRouter, AsyncNode, CheckpointData, CheckpointInfo, Checkpointer, CompiledGraph,
    ConditionalEdge, EdgeDefinition, EdgeTarget, EdgeType, ExecutionStep, FileCheckpointer,
    FilePersistence, FunctionRouter, GraphBuilder, GraphDefinition, GraphEdge, GraphError,
    GraphExecution, GraphInvocation, GraphNode, GraphPersistence, GraphResult, InterruptibleNode,
    MemoryCheckpointer, MemoryPersistence, MessageEntry, MessageRole, NodeConfig, NodeDefinition,
    NodeResult, NodeType, ParallelBranch, ParallelInvocation, PendingInterrupt, Reducer,
    ReplaceReducer, RouterDefinition, StateGraph, StateSchema, StateUpdate, StepEntry, StreamEvent,
    SubgraphBuilder, SubgraphNode, ThreadSafeMemoryCheckpointer, END, START,
};

// B2 (0.22.4): durable LangGraph checkpointers.
#[cfg(feature = "checkpoint-postgres")]
pub use langgraph::PostgresCheckpointer;
#[cfg(feature = "checkpoint-redis")]
pub use langgraph::RedisCheckpointer;
#[cfg(feature = "checkpoint-sqlite")]
pub use langgraph::SqliteCheckpointer;

// ===========================================================================
// Re-export guard — 0.27.0 T1 ($4 high): the root re-export surface is built by
// hand and leans on rename-aliases to dodge collisions, with no compile-time
// fence guarding it. These tests pin the collision-resolution aliases (so an
// orphan or a merge of two colliding types pulls the build red), and verify the
// hand-picked core provenance of name-prone exports like `Tool`/`BaseTool`
// (the future-additive ambiguity the triage flags). A full trybuild / cargo
// public-api snapshot (`$5 high`) remains a follow-up T2.
// ===========================================================================
#[cfg(test)]
mod reexport_guard {
    use std::any::TypeId;
    use std::sync::Arc;

    // B13-style collision: both `agents::BudgetExceeded` and
    // `core::router_llm::BudgetExceeded` are exported at root; the rename
    // `as RouterBudgetExceeded` keeps them distinct. If someone merges the
    // types or drops the alias, this (and the `pub use`) fail together.
    #[test]
    fn budget_exceeded_collision_is_disambiguated() {
        let agents = TypeId::of::<crate::agents::BudgetExceeded>();
        let router = TypeId::of::<crate::core::router_llm::BudgetExceeded>();
        assert_ne!(
            agents, router,
            "agents 与 router_llm 的 BudgetExceeded 撞名,根级必须靠 RouterBudgetExceeded 区分"
        );
        assert_eq!(
            TypeId::of::<crate::RouterBudgetExceeded>(),
            router,
            "RouterBudgetExceeded 别名必须解析到 router_llm 侧"
        );
    }

    // Generic names from the retrieval facade are prefixed to avoid future
    // ambiguity at root (`GlobalLevel`→`GraphGlobalLevel`, `QueryMode`→`GraphQueryMode`).
    #[test]
    fn graph_prefixed_aliases_resolve_to_retrieval_source() {
        assert_eq!(
            TypeId::of::<crate::GraphGlobalLevel>(),
            TypeId::of::<crate::retrieval::GlobalLevel>(),
        );
        assert_eq!(
            TypeId::of::<crate::GraphQueryMode>(),
            TypeId::of::<crate::retrieval::QueryMode>(),
        );
    }

    // The root `Tool` / `BaseTool` must keep resolving to the core (LCEL)
    // abstractions the facade pins its public API to, not a same-named future
    // type from `lc-tools` — a regressing provenance on either is a layout
    // regression that would otherwise go silent.
    #[test]
    fn tool_and_base_tool_resolve_from_core() {
        // Root `Tool`/`BaseTool` are core's (LCEL) **traits**, so `TypeId` can't
        // probe a separate identity. Pin provenance structurally:
        //  - BaseTool is object-safe (`Arc<dyn BaseTool>` is used across core),
        //    so coercing a root `&dyn crate::BaseTool` to the core trait object
        //    only type-checks because they are the very same item.
        //  - Both `Tool` and `BaseTool` are also bound together against the root
        //    and core paths on one generic param.
        // An lc-tools `Tool`/`BaseTool` that shadows the root export (the §4 中T1
        // future-additive ambiguity) makes these references fail to compile.
        let _: fn(&dyn crate::core::BaseTool) = |_: &dyn crate::BaseTool| {};
    }

    // The unambiguous error alias added for $5 low resolves to the unified error.
    #[test]
    fn lc_error_alias_is_the_unified_error() {
        assert_eq!(
            TypeId::of::<crate::LcError>(),
            TypeId::of::<crate::error::Error>(),
        );
    }

    // T2-1: `core/mod.rs` builds `pub mod language_models` as an explicit override of the
    // glob `pub use lc_core::*;` (the glob already re-exports `lc_core::language_models` at
    // that same path). Dropping the explicit module — e.g. assuming the glob covers it —
    // silently reverts to `lc_core::language_models` and hides the facade's wrapper surface.
    // These pin-references compile ONLY while the override is present; a glob-fallback makes
    // `crate::core::language_models::{ChatModelWrapper, wrap_provider_model}` unresolved and
    // pulls the build red.
    #[test]
    #[allow(clippy::type_complexity)] // the verbose fn-pointer signature is intentional: it pins `wrap_provider_model`'s provenance exactly
    fn core_language_models_override_keeps_wrapper_surface() {
        let _: Option<crate::core::language_models::ChatModelWrapper<()>> = None;
        let _: fn(
            Arc<dyn crate::core::BaseChatModel<Error = lc_providers::ProviderError> + Send + Sync>,
        ) -> Arc<
            dyn crate::core::BaseChatModel<Error = crate::error::Error> + Send + Sync,
        > = crate::core::language_models::wrap_provider_model;
    }

    // T2-2: the facade re-exports a large surface at BOTH root and module level to keep the
    // convenience paths reachable. The drift risk is a same-named type re-exported from a
    // different module at one level (a silently divergent double-export). Pin representative
    // concrete items so root↔module provenance is held to a single item.
    #[test]
    fn double_exports_resolve_to_one_item() {
        assert_eq!(
            TypeId::of::<crate::Message>(),
            TypeId::of::<crate::schema::Message>(),
            "root `Message` 必须与 `schema::Message` 是同一项"
        );
        assert_eq!(
            TypeId::of::<crate::RunnableConfig>(),
            TypeId::of::<crate::core::RunnableConfig>(),
            "root `RunnableConfig` 必须与 `core::RunnableConfig` 是同一项"
        );
    }
}