Creating Custom Components
Relevant source files
The following files were used as context for generating this wiki page:
- libs/core/langchain_core/language_models/llms.py
- libs/core/langchain_core/retrievers.py
- libs/core/langchain_core/tools/base.py
- libs/core/langchain_core/runnables/base.py
- libs/core/langchain_core/language_models/chat_models.py
- libs/text-splitters/langchain_text_splitters/html.py
- CLAUDE.md
- libs/text-splitters/tests/unit_tests/test_text_splitters.py
LangChain is designed for composability and extensibility. A key aspect of this is the ability for developers to create their own custom components to integrate seamlessly into the LangChain ecosystem. This is achieved by inheriting from base classes and implementing a set of required methods. The core abstractions are designed to be modular and simple, allowing any provider to implement the required interface and be used within the framework.
The central concept underpinning most components is the Runnable interface, which provides a standard set of invocation methods (invoke, batch, stream, etc.) and enables composition through the LangChain Expression Language (LCEL). By building custom components that adhere to these base abstractions, you can ensure they are compatible with the broader LangChain framework, including features like tracing, parallelism, and streaming.
Core Development Principles
When creating custom components, it's crucial to adhere to the project's development guidelines to ensure quality, stability, and consistency.
| Guideline | Description |
|---|---|
| Maintain Stable Public Interfaces | Preserve function signatures, argument positions, and names for exported/public methods. Use keyword-only arguments for new parameters. |
| Code Quality | All Python code must include type hints and return types. Use descriptive, self-explanatory variable names. |
| Documentation | Use Google-style docstrings for all public functions, documenting all parameters, return values, and exceptions. |
| Testing | Every new feature must be covered by unit tests using pytest. |
| Security | Avoid dangerous patterns like eval() on user-controlled input and ensure proper exception handling. |
Sources: CLAUDE.md
Custom Chat Models
To create a custom chat model, you must inherit from BaseChatModel and implement the required abstract methods. This allows your custom model to integrate with the standard LangChain interfaces for invocation, streaming, and tool usage.
Sources: libs/core/langchain_core/language_models/chat_models.py
BaseChatModel Class
The BaseChatModel is the abstract base class for all chat model integrations.
This diagram shows the key abstract and optional methods to implement for a custom chat model.
Implementation Requirements
The following table details the methods and properties that must or can be implemented when creating a custom chat model.
| Method/Property | Required/Optional | Description |
|---|---|---|
_generate | Required | The core logic for generating a chat result from a list of messages. |
_llm_type | Required | A property that returns a string to uniquely identify the model type for logging. |
_agenerate | Optional | A native async implementation of _generate. If not provided, _generate will be run in an executor. |
_stream | Optional | An implementation for streaming responses. If not provided, streaming will fall back to invoke. |
_astream | Optional | A native async implementation of _stream. |
Sources: libs/core/langchain_core/language_models/chat_models.py:321-337
A simplified path for creating a custom model is to inherit from SimpleChatModel, which only requires implementing the _call method.
class SimpleChatModel(BaseChatModel):
"""Simplified implementation for a chat model to inherit from."""
def _generate(
self,
messages: list[BaseMessage],
stop: Optional[list[str]] = None,
run_manager: Optional[CallbackManagerForLLMRun] = None,
**kwargs: Any,
) -> ChatResult:
# ... implementation ...
@abstractmethod
def _call(
self,
messages: list[BaseMessage],
stop: Optional[list[str]] = None,
run_manager: Optional[CallbackManagerForLLMRun] = None,
**kwargs: Any,
) -> str:
"""Simpler interface."""
Sources: libs/core/langchain_core/language_models/chat_models.py:1080-1111
Invocation Flow with Caching
The _generate_with_cache method illustrates the standard invocation flow, which includes checking a cache before calling the model.
This flowchart shows the logic for handling a generation request, including the cache lookup.
Custom Tools
Tools are functions that an agent can call. Creating a custom tool is straightforward using the @tool decorator.
Sources: libs/core/langchain_core/tools/base.py
Using the @tool Decorator
The @tool decorator from langchain_core.tools can be applied to any function to turn it into a LangChain tool. The decorator automatically infers the tool's schema from the function's signature and docstring.
from langchain_core.tools import tool
@tool
def search_database(query: str) -> str:
"""Search the database for relevant information.
Args:
query: The search query string.
"""
# Implementation here
results = ...
return results
Sources: CLAUDE.md
The BaseTool class defines the interface for all tools. While you can inherit from it directly, the decorator is the recommended approach for simplicity.
Sources: libs/core/langchain_core/tools/base.py:11-140
Custom Retrievers
A retriever is a component that returns documents given an unstructured query. To create a custom retriever, you need to inherit from BaseRetriever.
Sources: libs/core/langchain_core/retrievers.py
BaseRetriever Class
This class defines the standard interface for all retrievers.
| Method | Required/Optional | Description |
|---|---|---|
_get_relevant_documents | Required | The core logic for retrieving documents. Takes a query string and run_manager as input. |
_aget_relevant_documents | Optional | A native async implementation of _get_relevant_documents. |
This class diagram shows the structure of the BaseRetriever.
Custom Text Splitters
Text splitters are used to break down long pieces of text into smaller, semantically meaningful chunks. You can create a custom text splitter by inheriting from TextSplitter or one of its more specialized subclasses.
Sources: libs/text-splitters/tests/unit_tests/test_text_splitters.py, libs/text-splitters/langchain_text_splitters/html.py
HTMLHeaderTextSplitter Example
A good example of a custom splitter is the HTMLHeaderTextSplitter, which splits an HTML document based on header tags (<h1>, <h2>, etc.). It maintains a hierarchy of headers in the metadata.
class HTMLHeaderTextSplitter:
def __init__(
self,
headers_to_split_on: list[tuple[str, str]],
return_each_element: bool = False,
) -> None:
# ...
self.headers_to_split_on = sorted(
headers_to_split_on, key=lambda x: int(x[0][1:])
)
# ...
def split_text(self, text: str) -> list[Document]:
# ...
Sources: libs/text-splitters/langchain_text_splitters/html.py:31-118
The test file for text splitters shows many examples of how to instantiate and use various splitters, which can serve as a guide for creating your own. For instance, the test for MarkdownHeaderTextSplitter demonstrates how to define headers to split on and verifies the resulting document structure and metadata.
def test_md_header_text_splitter_1() -> None:
"""Test markdown splitter by header: Case 1."""
markdown_document = (
"# Foo\n\n"
" ## Bar\n\n"
"Hi this is Jim\n\n"
"Hi this is Joe\n\n"
" ## Baz\n\n"
" Hi this is Molly"
)
headers_to_split_on = [
("#", "Header 1"),
("##", "Header 2"),
]
markdown_splitter = MarkdownHeaderTextSplitter(
headers_to_split_on=headers_to_split_on,
)
output = markdown_splitter.split_text(markdown_document)
# ... assertions
Sources: libs/text-splitters/tests/unit_tests/test_text_splitters.py:686-713
Conclusion
Creating custom components in LangChain involves extending a set of well-defined base classes. By implementing a few key methods, you can create new ChatModels, Tools, Retrievers, and TextSplitters that are fully compatible with the LangChain ecosystem. This modularity is a core strength of the framework, enabling developers to adapt and extend LangChain for their specific needs while leveraging its powerful composition and execution engine. Adhering to the project's coding standards ensures that these new components are robust, maintainable, and easy for others to use.