Core Concepts
Relevant source files
The following files were used as context for generating this wiki page:
LangChain is a framework designed to assist in the development of applications powered by large language models (LLMs). It provides a set of interoperable components and third-party integrations to simplify the process of building complex AI applications. The core idea is to chain together different sources of computation or knowledge with LLMs to create more powerful and capable systems.
The framework is built around a few central abstractions, most notably the Runnable interface, which provides a standard way to define, compose, and invoke components. This composability is facilitated by the LangChain Expression Language (LCEL), a declarative syntax for building chains and graphs of operations. LangChain is designed to help with five main areas: Models and Prompts, Chains, Retrieval Augmented Generation (RAG), Agents, and Evaluation.
Sources: libs/langchain/README.md, libs/core/README.md, README.md
The Runnable Interface
The Runnable interface is the fundamental abstraction in langchain-core. It represents a unit of work that can be invoked, batched, streamed, and composed. Most components in the LangChain ecosystem, including models, prompts, retrievers, and tools, implement this interface.
Sources: libs/core/README.md:14-18, libs/core/langchain_core/runnables/base.py:100-102
Key Methods
The Runnable class defines a standard set of invocation methods, each with a synchronous and asynchronous variant.
| Method | Description |
|---|---|
invoke() / ainvoke() | Transforms a single input into an output. |
batch() / abatch() | Efficiently transforms multiple inputs into outputs, typically in parallel. |
stream() / astream() | Streams output from a single input as it's produced. |
transform() / atransform() | Transforms a stream of inputs into a stream of outputs. |
astream_log() | Streams output and selected intermediate results from an input for tracing. |
astream_events() | Generates a stream of events providing real-time information about the progress of the Runnable. |
Sources: libs/core/langchain_core/runnables/base.py:104-110, libs/core/langchain_core/runnables/base.py:1603-1644
Runnable Class Diagram
The following diagram illustrates the abstract base class Runnable and its primary methods.
This diagram shows the Runnable abstract base class with its generic Input and Output types and key invocation and composition methods.
Sources: libs/core/langchain_core/runnables/base.py:100-1981
Configuration and Binding
Runnables can be customized at runtime using configuration objects and binding methods.
with_config(config): Binds aRunnableConfigto aRunnable, allowing for runtime settings like tags, metadata, and callbacks.bind(**kwargs): Binds arguments to aRunnable. This is useful for passing arguments that are not part of the main input, such asstopsequences for an LLM.with_retry(): Adds automatic retries on failure.with_fallbacks(): Provides a sequence of alternativeRunnables to execute if the primary one fails.configurable_fields()/configurable_alternatives(): Allows specific attributes or entireRunnables within a chain to be swapped out at invocation time.
Sources: libs/core/langchain_core/runnables/base.py:1003-1250
LangChain Expression Language (LCEL)
LCEL is a declarative language for composing Runnable components into sequences or Directed Acyclic Graphs (DAGs). It uses the | (pipe) operator to chain Runnables together. Any chain built with LCEL automatically supports synchronous, asynchronous, batch, and streaming operations.
Sources: libs/core/README.md:37-41
Composition Primitives
RunnableSequence: Invokes a series ofRunnables sequentially. The output of one step is the input to the next. It is created using the|operator.RunnableParallel(orRunnableMap): InvokesRunnables concurrently, providing the same input to each. It is created using a dictionary literal within a sequence.
Sources: libs/core/langchain_core/runnables/base.py:1984-2005, libs/core/langchain_core/runnables/base.py:2709-2730
LCEL Flow Example
This diagram shows a typical RAG (Retrieval-Augmented Generation) chain constructed with LCEL.
This flowchart illustrates how a dictionary input is processed in parallel to fetch context and pass the question through, before being combined in a prompt and sent to the model.
Sources: libs/core/langchain_core/runnables/base.py:1984-2005, libs/core/langchain_core/runnables/base.py:2709-2730
Core Components
LangChain provides standard interfaces for common components used in LLM applications.
Chains
Chains involve sequences of calls, either to an LLM or another utility. While RunnableSequence is the modern way to build chains, the concept remains central. Common applications include question answering with RAG and creating chatbots.
Sources: libs/langchain/README.md:52-55
Agents
Agents use an LLM to make decisions about which actions to take. The agent executes an action, observes the outcome, and repeats the process until the task is complete. LangChain provides a standard interface for agents and a selection of pre-built agents.
The core logic of an agent can be visualized as a loop:
This diagram shows the agent's reasoning loop, from decision to action, observation, and iteration.
Sources: libs/langchain/README.md:64-67
Agent prompts are structured to guide the LLM. They typically include a prefix, a list of available tools, response format instructions, and the user's input.
# Example of agent prompt structure
PREFIX = """Assistant is a large language model..."""
FORMAT_INSTRUCTIONS = """RESPONSE FORMAT INSTRUCTIONS
----------------------------
...
```json
{{{{
"action": string, \\ The action to take. Must be one of {tool_names}
"action_input": string \\ The input to the action
}}}}
...
"""
SUFFIX = """TOOLS
{{tools}}
{format_instructions}
USER'S INPUT
{{{{input}}}}"""
Sources: [libs/langchain/langchain/agents/conversational_chat/prompt.py:1-49](https://github.com/langchain-ai/langchain/blob/HEAD/libs/langchain/langchain/agents/conversational_chat/prompt.py#L1-L49)
### Prompts
Prompt management and optimization are key features. LangChain provides `PromptTemplate` classes to create and manage prompts from string templates. These templates can be used for various tasks like summarization, entity extraction, and knowledge triple extraction.
For example, the `ENTITY_MEMORY_CONVERSATION_TEMPLATE` is designed to provide an LLM with context about known entities and conversation history to generate a relevant response.
Sources: [libs/langchain/langchain/memory/prompt.py:3-20](https://github.com/langchain-ai/langchain/blob/HEAD/libs/langchain/langchain/memory/prompt.py#L3-L20), [libs/langchain/README.md:48-50](https://github.com/langchain-ai/langchain/blob/HEAD/libs/langchain/README.md#L48-L50)
## Development and Security
The project emphasizes quality, stability, and security through a set of development guidelines.
### Development Principles
| Principle | Description |
| :--- | :--- |
| **Stable Public Interfaces** | Function signatures and names for public methods should be preserved to avoid breaking changes. |
| **Code Quality** | All Python code must include type hints and Google-style docstrings. Functions should be focused and variable names descriptive. |
| **Testing** | New features and bug fixes must be covered by unit tests (`tests/unit_tests/`) or integration tests (`tests/integration_tests/`). |
| **Security** | Avoid dangerous patterns like `eval()` on user input and ensure proper exception handling and resource cleanup. |
| **Documentation** | Public functions require complete Google-style docstrings. |
Sources: [CLAUDE.md](https://github.com/langchain-ai/langchain/blob/HEAD/CLAUDE.md)
### Security Best Practices
When building applications that interact with external resources (filesystems, APIs, databases), developers must follow security best practices.
* **Limit Permissions**: Adhere to the principle of least privilege. Grant only the permissions necessary for the application's function (e.g., read-only credentials).
* **Anticipate Potential Misuse**: Assume that an LLM may use any access or credentials it has in any way the permissions allow.
* **Defense in Depth**: Combine multiple security approaches, such as using read-only permissions and sandboxing (e.g., running in a container), rather than relying on a single layer of defense.
Sources: [SECURITY.md:5-15](https://github.com/langchain-ai/langchain/blob/HEAD/SECURITY.md#L5-L15)
## Conclusion
The core concepts of LangChain revolve around the `Runnable` interface and the LangChain Expression Language (LCEL), which together provide a powerful, composable framework for building LLM applications. By offering standardized components like Chains and Agents, and enforcing strict development and security guidelines, LangChain enables developers to create robust, scalable, and secure AI systems. The modularity of `langchain-core` ensures that these fundamental abstractions are stable and can be extended with a wide range of integrations from the broader LangChain ecosystem.
Sources: [libs/core/README.md:67-73](https://github.com/langchain-ai/langchain/blob/HEAD/libs/core/README.md#L67-L73), [libs/langchain/README.md:20-25](https://github.com/langchain-ai/langchain/blob/HEAD/libs/langchain/README.md#L20-L25)