LangChain Integration for AI Pipelines: LCEL, RAG, Agents
LLM pipelines in production are not a single API call but dozens of steps: document loading, chunking, embedding, retrieval, prompting, response parsing, validation, logging. Without a unified framework, the code turns into spaghetti of retry logic, error handlers, and provider-specific SDKs. As the team grows, each developer writes their own wrapper around the LLM call. Supporting five providers requires five different implementations with common bugs. Our engineers see this pain every day. LangChain is the solution we implement in client projects to unify pipelines. Switching to LangChain reduces integration code volume by an average of 67% compared to direct SDKs, and the time to add a new provider drops from several days to hours.
Why LCEL Is the Foundation of Production Pipelines
LCEL (LangChain Expression Language) is a declarative syntax that combines components via the | operator. Any object implementing Runnable can be chained. This gives you streaming, parallel execution, fallbacks, and automatic tracing. All this works regardless of chain length.
from langchain_openai import ChatOpenAI, OpenAIEmbeddings
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser, JsonOutputParser
from langchain_core.runnables import RunnablePassthrough, RunnableParallel
from langchain_community.vectorstores import Chroma
llm = ChatOpenAI(model="gpt-4o", temperature=0)
# Simple chain
prompt = ChatPromptTemplate.from_messages([
("system", "You are an expert in {domain}."),
("human", "{question}"),
])
chain = prompt | llm | StrOutputParser()
result = chain.invoke({"domain": "financial analysis", "question": "What is EBITDA?"})
# Parallel chain
parallel_chain = RunnableParallel({
"summary": prompt | llm | StrOutputParser(),
"keywords": ChatPromptTemplate.from_template("Extract keywords: {question}") | llm | StrOutputParser(),
})
How LangChain Simplifies Integration with LLM Providers
A unified BaseChatModel interface allows changing the provider without altering the logic. Simply replace the llm object:
# OpenAI
from langchain_openai import ChatOpenAI
llm_openai = ChatOpenAI(model="gpt-4o-mini", temperature=0.2)
# Anthropic
from langchain_anthropic import ChatAnthropic
llm_claude = ChatAnthropic(model="claude-3-5-sonnet-20241022")
# Google
from langchain_google_genai import ChatGoogleGenerativeAI
llm_gemini = ChatGoogleGenerativeAI(model="gemini-2.0-flash")
# Local Ollama
from langchain_ollama import ChatOllama
llm_local = ChatOllama(model="llama3.2:3b", temperature=0)
# Hugging Face
from langchain_huggingface import HuggingFaceEndpoint
llm_hf = HuggingFaceEndpoint(repo_id="mistralai/Mistral-7B-Instruct-v0.3")
RAG Pipeline with Vector Database
RAG (Retrieval-Augmented Generation) is an architecture where the LLM receives context from a vector database. Here is an example with Qdrant:
from langchain_community.document_loaders import DirectoryLoader, PyPDFLoader
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain_openai import OpenAIEmbeddings
from langchain_qdrant import QdrantVectorStore
from langchain_core.runnables import RunnablePassthrough
import json
loader = DirectoryLoader("./docs", glob="**/*.pdf", loader_cls=PyPDFLoader)
docs = loader.load()
splitter = RecursiveCharacterTextSplitter(chunk_size=800, chunk_overlap=100)
chunks = splitter.split_documents(docs)
embeddings = OpenAIEmbeddings(model="text-embedding-3-small")
vectorstore = QdrantVectorStore.from_documents(
chunks,
embedding=embeddings,
url="http://localhost:6333",
collection_name="knowledge_base",
)
retriever = vectorstore.as_retriever(search_kwargs={"k": 5})
rag_prompt = ChatPromptTemplate.from_messages([
("system", "Answer the question based on the context.\n\nContext:\n{context}\n\nQuestion: {question}\n\nIf the answer is not in the context, say so explicitly.")
])
def format_docs(docs):
return "\n\n".join(doc.page_content for doc in docs)
rag_chain = (
{"context": retriever | format_docs, "question": RunnablePassthrough()}
| rag_prompt
| llm
| StrOutputParser()
)
answer = rag_chain.invoke("What are the contract termination conditions?")
Managing Dialogue Memory
For long dialogues, use ConversationBufferWindowMemory with history in Redis:
from langchain.memory import ConversationBufferWindowMemory
from langchain_core.chat_history import BaseChatMessageHistory
from langchain_core.runnables.history import RunnableWithMessageHistory
from langchain_community.chat_message_histories import RedisChatMessageHistory
def get_session_history(session_id: str) -> BaseChatMessageHistory:
return RedisChatMessageHistory(session_id, url="redis://localhost:6379")
chat_prompt = ChatPromptTemplate.from_messages([
("system", "You are a technical support assistant."),
("placeholder", "{history}"),
("human", "{input}"),
])
chain_with_history = RunnableWithMessageHistory(
chat_prompt | llm | StrOutputParser(),
get_session_history,
input_messages_key="input",
history_messages_key="history",
)
config = {"configurable": {"session_id": "user_123"}}
chain_with_history.invoke({"input": "My app is not starting"}, config=config)
chain_with_history.invoke({"input": "Error: 'connection refused'"}, config=config)
Practical Case: Unifying 5 LLM Integrations
Situation: A product team maintained 5 separate integrations (OpenAI, Claude, enterprise YandexGPT, local Llama, Gemini) with duplicated retry logic, prompt formatting, and error handling. From our experience, such 'zoos' arise whenever a team grows quickly and the architecture is not unified.
Solution: Refactoring to LangChain LCEL with a unified interface. Architecture:
- Configurable provider via env variable
LLM_PROVIDER - Shared prompt templates in YAML files
- Unified error handling layer via
.with_fallbacks()
from langchain_core.runnables import RunnableWithFallbacks
primary_llm = ChatOpenAI(model="gpt-4o")
fallback_llm = ChatAnthropic(model="claude-3-5-sonnet-20241022")
robust_llm = primary_llm.with_fallbacks([fallback_llm])
Results:
- Integration code volume: -67% (LCEL reduces code by 5x compared to direct SDK when implementing RAG)
- Time to add a new provider: 3 days → 4 hours
- Pipeline uptime (due to fallbacks): 99.1% → 99.8%
- Visibility in LangSmith: incident debugging time dropped from 2h to 20min
When Is LangChain Overkill?
LangChain adds abstraction that is justified for complex pipelines. For a simple one-shot LLM call, direct SDK (OpenAI, Anthropic) is simpler and more predictable.
| Criterion | Direct SDK | LangChain LCEL |
|---|---|---|
| Code for a single LLM call | 3 lines | 5 lines |
| Code for RAG with memory | ~200 lines | ~40 lines |
| Time to switch providers | 1–2 days | 1 hour |
| Tracing | Separate integration | Built-in via LangSmith |
| Learning complexity | Low | Medium |
Comparison of memory types:
| Memory Type | Storage | Best for |
|---|---|---|
| ConversationBufferWindowMemory | In-memory | Short dialogues |
| RedisChatMessageHistory | Redis | Distributed systems |
| PostgresChatMessageHistory | PostgreSQL | Long-term storage |
LangChain is optimal when: multiple components (retriever + LLM + parser), multiple providers, need tracing and memory. Otherwise, stick with direct SDK.
Performance comparison details: LCEL vs direct SDK
For identical operations, LCEL adds less than 5% overhead on p99 latency but provides an order of magnitude better observability. In tests with 1000 requests to a single LLM, the difference in execution time did not exceed 3%.What’s Included in the Work
- Architecture diagram of LCEL chains
- Configured integration with chosen providers (up to 5)
- Vector database with indexes and configuration
- Dialogue memory system (Redis/Postgres)
- LangSmith tracing with dashboards
- Documentation for new chains and developer instructions
- Warranty of all pipelines operating for one month after launch
- Team training on LangChain (2-hour workshop)
How We Implement LangChain
- Audit of current LLM integrations and pipeline architecture.
- Design of a unified chain schema (LCEL).
- Setup and configuration of a vector database (Qdrant, Chroma, pgvector).
- Integration with providers (OpenAI, Claude, local models).
- Setup of dialogue memory (Redis, Postgres).
- Deployment of LangSmith for tracing and debugging.
- Documentation for new chains and developer instructions.
- Warranty of all pipelines operating for one month after launch.
Timelines
- Basic LangChain integration + 1 provider: 2–4 days
- RAG pipeline with vector database: 1–2 weeks
- Dialogue agent with memory: 1–2 weeks
- Refactoring existing code to LCEL: 1–3 weeks
We'll assess your project for free within 2 days. Contact us — we'll tell you how to unify pipelines and reduce maintenance costs. Get a consultation on LangChain implementation — we'll select the architecture for your project.







