LangChain Integration for AI Pipelines: LCEL, RAG, Agents

We design and deploy artificial intelligence systems: from prototype to production-ready solutions. Our team combines expertise in machine learning, data engineering and MLOps to make AI work not in the lab, but in real business.
Showing 1 of 1All 1564 services
LangChain Integration for AI Pipelines: LCEL, RAG, Agents
Medium
from 1 week to 3 months
Frequently Asked Questions

AI Development Areas

AI Solution Development Stages

Latest works

  • image_website-b2b-advance_0.webp
    B2B ADVANCE company website development
    1351
  • image_web-applications_feedme_466_0.webp
    Development of a web application for FEEDME
    1247
  • image_websites_belfingroup_462_0.webp
    Website development for BELFINGROUP
    950
  • image_ecommerce_furnoro_435_0.webp
    Development of an online store for the company FURNORO
    1186
  • image_logo-advance_0.webp
    B2B Advance company logo design
    642
  • image_crm_enviok_479_0.webp
    Development of a web application for Enviok
    922

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

  1. Audit of current LLM integrations and pipeline architecture.
  2. Design of a unified chain schema (LCEL).
  3. Setup and configuration of a vector database (Qdrant, Chroma, pgvector).
  4. Integration with providers (OpenAI, Claude, local models).
  5. Setup of dialogue memory (Redis, Postgres).
  6. Deployment of LangSmith for tracing and debugging.
  7. Documentation for new chains and developer instructions.
  8. 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.

LLM Development: Fine-Tuning, RAG, Agents, and Production Deployment

Using GPT‑4 or Claude 3.5 Sonnet through a public API is not a solution — it's just a tool. When the requirement is to "make it like ChatGPT, but on our data," there is a real engineering challenge behind it: from prompt engineering to training a 70B model on your own infrastructure. End-to-end LLM solution development is a complex stack, and we have been doing it for over 5 years. During this time, we have completed over 20 projects in generative AI: from RAG systems for legal departments to custom support agents. Where exactly your task falls depends on data, latency requirements, budget, and how critical confidentiality is.

A typical situation: the client has already tried ChatGPT, but results are unstable — sometimes accurate, sometimes hallucinating. Or they need integration into a corporate portal while complying with security policies. Let's break down each layer of the stack in detail — from RAG to production deployment.

Why Do RAG Systems Break and How to Fix It?

RAG (Retrieval-Augmented Generation) looks simple: find relevant documents, put them in context, get an answer. In practice, it fails in several places.

Chunking without overlap. Classic mistake: chunk_size=512, overlap=0. If the answer lies across two chunks, retrieval won't find either with sufficient confidence. Solution: overlap 15–25% of chunk_size, or better yet, sentence-aware splitting with spaCy or NLTK instead of naive character splitting.

Poor embedder. text-embedding-ada-002 is good for general use, but on legal or medical texts, specialized models like E5-large-v2, BGE-M3, or fine-tuned sentence-transformers on domain data outperform it. Recall@5 differences can be 15–25%.

No re-ranking. Vector search optimizes for speed, not relevance. A cross-encoder re-ranker (ms-marco-MiniLM-L-6-v2, bge-reranker-large) after initial retrieval improves top-3 accuracy with acceptable latency (+50–150ms). This is often more impactful than improving the embedding model.

Hybrid search. Dense vectors alone work poorly on exact queries: names, SKUs, codes. BM25 (sparse) finds exact matches but misses semantics. Hybrid via RRF (Reciprocal Rank Fusion) is the optimal compromise. Qdrant, Weaviate, and pgvector 0.7+ support hybrid search natively.

Typical production architecture for a corporate knowledge base
  1. Documents → preprocessing (PyMuPDF, Unstructured)
  2. Chunking → embedding (BGE-M3)
  3. Qdrant (hybrid dense+sparse)
  4. Cross-encoder re-ranking
  5. Context → LLM (vLLM or OpenAI API)
  6. Answer with sources (RAGAS for quality evaluation)

When to Fine-Tune Instead of Prompt Engineering?

Prompt engineering solves ~70% of LLM adaptation tasks for a domain. The remaining 30% require fine-tuning. Three indicators: the model ignores a specific output format even with detailed prompting; the task requires deep knowledge of specialized vocabulary (medicine, law); you need to significantly reduce token costs by replacing a large model with a smaller specialized one.

LoRA and QLoRA are the standard for SFT. LoRA adds trainable low-rank matrices to attention layers. A typical configuration for Llama-3 8B: r=64, lora_alpha=128, target_modules=["q_proj","v_proj","k_proj","o_proj"] yields ~0.8% trainable parameters, training on one A100 40GB. QLoRA adds 4-bit quantization (NF4) and allows fine-tuning 70B models on two A100 40GB, though speed drops by half compared to bf16.

DPO instead of RLHF. Direct Preference Optimization requires only (chosen, rejected) pairs, not scalar reward signals. DPOTrainer from the trl library (Hugging Face) implements it in a few dozen lines.

Common mistake. A dataset of 500 examples, 5 epochs, validation loss 0.8 — seems fine. But on test, the model degrades on general instructions. Cause: catastrophic forgetting. Solution: add 10–20% general instruction-following examples (Alpaca, FLAN) to the training set to preserve original capabilities.

How to Choose a Base Model: 8B or 70B?

Model Parameters Strengths Context
Llama-3.1 8B 8B Quality/speed balance 128k
Llama-3.1 70B 70B Complex reasoning 128k
Mistral 7B / Mixtral 8x7B 7B / 47B Efficiency for size 32k
Qwen2.5 72B 72B Code, multilingual 128k
Gemma 2 27B 27B Open license 8k

For most tasks, fine-tuning an 8B model is sufficient. 70B is needed when deep reasoning is required or the 8B baseline does not reach the required quality even after fine-tuning. Inference cost for Llama-3 8B via vLLM on A100 is efficient; the exact cost depends on volume.

What Does PagedAttention Bring to Production?

vLLM is the first choice for serving open-source models. PagedAttention is the key technical innovation: KV-cache is managed like virtual memory in an OS, without fragmentation. This yields 2–4x higher throughput compared to naive HuggingFace Transformers inference. The vLLM documentation confirms that continuous batching and PagedAttention are the standard for high-load LLM services.

Typical numbers on A100 80GB for Llama-3 8B (bf16): 400–600 req/s, P50 latency 200–400ms, P99 latency 600–900ms at concurrency 64. For 70B on two A100 with tensor parallelism: 80–120 req/s, P99 latency 1.5–2.5s. AWQ or GPTQ quantization reduces memory consumption by 2x with quality loss within 1–3%.

Multi-Agent Systems

Agents are LLMs with access to tools: search, code execution, API calls, database interaction. Common patterns:

  • ReAct (Reason + Act): the model reasons → chooses a tool → observes the result → reasons again. LangChain and LlamaIndex implement it out of the box.
  • Multi-agent orchestration: multiple specialized agents with a coordinator on top. Example: coordinator → researcher (search + summarization) → coder (code generation and execution) → critic (verification). Tools: AutoGen (Microsoft), CrewAI, custom implementation on LangGraph.

In production, agent systems are non-deterministic. Essential: guardrails, step limits, logging of each step, human-in-the-loop for critical actions.

How We Work: Stages, Timeline, Deliverables

Stage Duration What You Get
Audit and data collection 1–2 weeks Eval dataset of 100+ examples, task formalization
Baseline (prompt + RAG) 1–2 weeks Working prototype, quality metrics
Fine-tuning (if needed) 2–4 weeks Trained model, LoRA weights, model card
Deployment and monitoring 1–2 weeks vLLM server, Grafana + Prometheus
Documentation and training 1 week API documentation, team training

What Is Included

We deliver:

  • Technical documentation (model card, configs, deployment instructions)
  • Access to infrastructure (code repository, trained weights)
  • 1 month of post-deployment support (consultations, bug fixes)
  • Customer team training (2–3 sessions on system operation)

Timeline: basic RAG prototype — 1–2 weeks. Fine-tuning with customer data — 3–6 weeks (including data preparation). Production system with monitoring and retraining — 2–4 months. Cost is calculated individually based on data volume, model complexity, and infrastructure requirements.

We guarantee the quality of the final model with performance benchmarks and ongoing monitoring. Our engineers have hands‑on experience with dozens of production LLM systems.

Want to evaluate your project? Leave a request — we will prepare a preliminary summary within 1–2 business days. Or get a consultation on choosing the approach: RAG, fine-tuning, or hybrid — we will tell you what works best for you. Contact us to discuss your LLM development needs. Schedule a free consultation today.