Models: LLMs and Chat Models
Relevant source files
The following files were used as context for generating this wiki page:
- libs/core/langchain_core/language_models/chat_models.py
- libs/core/langchain_core/language_models/init.py
- README.md
- libs/partners/openai/tests/integration_tests/chat_models/test_responses_api.py
- libs/langchain/langchain/chains/constitutional_ai/principles.py
- CLAUDE.md
- SECURITY.md
- libs/langchain/langchain/agents/conversational_chat/prompt.py
In LangChain, language models are the core components for building applications. They provide a generic interface for interacting with various Large Language Models (LLMs). The framework distinguishes between two primary types of models: traditional LLMs and modern Chat Models. While both are foundational, they have different interfaces and are suited for different types of interactions.
This document provides a technical overview of these model abstractions, their key methods, and how they are implemented and extended within the LangChain ecosystem. The focus is on the core abstractions provided in langchain-core and how they are realized in partner integrations like langchain-openai.
Sources: libs/core/langchain_core/language_models/init.py:1-29, README.md:29-32
Core Abstractions
LangChain provides a set of base classes that define the standard interface for all language models. This ensures interoperability and allows developers to easily swap out different model providers.
Sources: libs/core/langchain_core/language_models/chat_models.py:270-281, libs/core/langchain_core/language_models/init.py:1-29
Model Hierarchy
The fundamental base class is BaseLanguageModel. Both BaseLLM and BaseChatModel inherit from it, establishing a common foundation for all language model interactions.
This class diagram illustrates the inheritance structure of the core model classes.
Comparison: LLMs vs. Chat Models
The primary distinction lies in their input and output types.
| Feature | LLMs (BaseLLM) | Chat Models (BaseChatModel) |
|---|---|---|
| Primary Interface | String in, String out | List of BaseMessage in, BaseMessage out |
| Underlying Models | Traditionally older models | Traditionally newer, conversation-optimized models |
| Input Compatibility | Can accept BaseMessage lists, which are formatted into a single string. | Natively consumes structured message lists. |
| Key Abstraction | BaseLLM or LLM | BaseChatModel |
| Use Case | Simple text completion tasks. | Conversational applications, agents, and complex interactions requiring role distinction. |
Sources: libs/core/langchain_core/language_models/init.py:7-29
Chat Models (BaseChatModel)
Chat models are the more modern and versatile abstraction in LangChain. They are designed for conversational AI and can differentiate between roles like system, human, and ai.
Sources: libs/core/langchain_core/language_models/chat_models.py:7-17, libs/langchain/langchain/chat_models/init.py:1-12
Core Concepts
- Input: A list of
BaseMessageobjects (e.g.,HumanMessage,AIMessage,SystemMessage). This structured input allows the model to understand the context and history of a conversation. - Output: A
BaseMessageobject, typically anAIMessage, which may contain simple text, tool calls, or other structured data. - Streaming: Natively supports streaming responses, yielding
BaseMessageChunkobjects. This is crucial for real-time applications. - Tool Use: Provides first-class support for binding tools and generating structured output, which is essential for building agents.
Sources: libs/core/langchain_core/language_models/chat_models.py:382-393, 1289-1300
Key Methods
The BaseChatModel class, as a Runnable, exposes a standard set of methods for interaction.
| Method | Description | Output Type |
|---|---|---|
invoke() | Executes a single call to the model with a given input. | BaseMessage |
ainvoke() | Asynchronous version of invoke. | BaseMessage |
stream() | Streams chunks of the response as they are generated. | Iterator[BaseMessageChunk] |
astream() | Asynchronous version of stream. | AsyncIterator[BaseMessageChunk] |
batch() | Executes multiple invoke calls in parallel for a list of inputs. | list[BaseMessage] |
generate() | A lower-level method for batch processing that returns detailed LLMResult objects. | LLMResult |
Sources: libs/core/langchain_core/language_models/chat_models.py:284-340
Execution Flow (invoke)
The invoke method orchestrates the call to the language model, incorporating features like caching, callbacks, and rate limiting.
The following sequence diagram shows the internal flow of an invoke call on a BaseChatModel.
Extending Model Capabilities
BaseChatModel provides powerful methods to create new Runnable instances with added functionality without modifying the original model.
Tool Binding with bind_tools
This method attaches tool definitions to the model, enabling it to generate tool-calling instructions. The model can be configured to force the use of a specific tool.
# Example of binding tools
from langchain_openai import ChatOpenAI
def multiply(x: int, y: int) -> int:
"""return x * y"""
return x * y
llm = ChatOpenAI(model="gpt-4o-mini")
bound_llm = llm.bind_tools([multiply, {"type": "web_search_preview"}])
ai_msg = bound_llm.invoke("whats 5 * 4")
# ai_msg.tool_calls will contain a call to the 'multiply' tool
Sources: libs/core/langchain_core/language_models/chat_models.py:1289-1300, libs/partners/openai/tests/integration_tests/chat_models/test_responses_api.py:121-133
Structured Output with with_structured_output
This method constrains the model to generate output that conforms to a specified Pydantic model or JSON schema. It uses the model's tool-calling capabilities under the hood to enforce the structure.
This flowchart illustrates the logic of the with_structured_output wrapper.
Security and Responsible AI
When building applications with language models that can interact with external tools, security is a critical consideration.
Principle of Least Privilege
Developers should grant models the narrowest possible permissions to perform their tasks. For instance, if an agent only needs to read from a database, it should be given read-only credentials. This minimizes the potential for unintended or malicious actions, such as data corruption or unauthorized access.
Sources: SECURITY.md:7-13
Constitutional AI
LangChain includes a mechanism called Constitutional AI, which is a process for aligning model behavior with a set of principles. It involves a critique-and-revision cycle where one model critiques another's output based on a "constitutional principle" (e.g., to be harmless), and then revises it accordingly. This is a powerful technique for ensuring model responses are safe and ethical.
The framework provides a predefined set of principles, such as:
harmful1: "Identify specific ways in which the assistant's last response is harmful, unethical, racist, sexist, toxic, dangerous, or illegal."uo-ethics-1: "Discuss whether the AI model's response leads to harmful consequences, either directly or indirectly."
Sources: libs/langchain/langchain/chains/constitutional_ai/principles.py:7-14, 169-173
Conclusion
LangChain's model abstractions, centered around BaseLLM and BaseChatModel, provide a flexible and powerful foundation for building LLM-powered applications. BaseChatModel is the modern, preferred interface, offering robust support for conversational context, streaming, and tool use. By understanding these core components and leveraging declarative methods like bind_tools and with_structured_output, developers can create sophisticated, reliable, and secure applications. The framework's emphasis on standard interfaces ensures that applications remain adaptable as the underlying model technology continues to evolve.
Sources: README.md:34-43, libs/core/langchain_core/language_models/init.py:1-29