RAG System Development: Retrieval-Augmented Generation for Business

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
RAG System Development: Retrieval-Augmented Generation for Business
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
    1347
  • 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
    948
  • image_ecommerce_furnoro_435_0.webp
    Development of an online store for the company FURNORO
    1183
  • image_logo-advance_0.webp
    B2B Advance company logo design
    642
  • image_crm_enviok_479_0.webp
    Development of a web application for Enviok
    921

RAG (Retrieval-Augmented Generation): Why Your Business Needs It and How to Implement

Your company has accumulated thousands of contracts, regulations, and instructions, yet employees spend hours searching for answers. Implementing Retrieval-Augmented Generation (RAG) solves this: the LLM queries your corporate knowledge base in real time and delivers answers with source citations. Our RAG architecture integrates semantic search with vector databases for efficient document indexing and retrieval, ensuring high faithfulness. Unlike fine-tuning, RAG requires no retraining — you simply update the documents, and the system immediately picks up changes. We have 5+ years of experience building RAG systems and have delivered dozens of projects for insurance, legal, and IT companies. Our solutions are trusted by industry leaders for their reliability and accuracy.

The time savings from RAG adoption can be up to 80% on information retrieval — for a typical enterprise, this translates to annual savings of over $100,000 in lost productivity. Get in touch for a consultation to evaluate the economic impact for your company.

We develop end-to-end RAG systems — from document indexing to integration with your services. Below is how it works and what's included.

What a RAG System Consists Of

User → Query
         ↓
 Embedding Model
         ↓
 Vector Search (Top-K)
         ↓
 Retrieved Chunks + Query
         ↓
      LLM
         ↓
      Answer

Components:

  • Indexing pipeline: document loading, chunking, embedding, storage in vector DB.
  • Retrieval: convert query to vector, nearest neighbor search.
  • Generation: pass context + query to LLM.

When RAG Is More Effective Than Fine-Tuning

Fine-tuning requires a labeled dataset and model retraining — costly and time-consuming. RAG allows adding new documents without retraining: just place a file in a folder, and the index updates. For tasks where data changes weekly (contracts, documentation, knowledge bases), RAG is significantly cheaper and faster. Additionally, RAG provides traceable sources, critical for legal and medical scenarios.

Tech Stack for RAG Systems

Component Options
Embedding Model OpenAI text-embedding-3-large, Cohere Embed v3, BGE-M3, E5-large, Nomic Embed
Vector DB Pinecone, Weaviate, Qdrant, ChromaDB, pgvector, Milvus
LLM GPT-4o, Claude 3.5 Sonnet, Llama 3.1, Mistral
Orchestrator LangChain, LlamaIndex, custom
Reranker Cohere Rerank, BGE-Reranker, FlashRank

Building the Indexing Pipeline

from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain_openai import OpenAIEmbeddings
from langchain_community.vectorstores import Qdrant
from langchain_community.document_loaders import PyPDFDirectoryLoader

# Load documents
loader = PyPDFDirectoryLoader("./docs/")
documents = loader.load()

# Split into chunks
splitter = RecursiveCharacterTextSplitter(
    chunk_size=512,
    chunk_overlap=64,
    separators=["\n\n", "\n", ".", " "],
)
chunks = splitter.split_documents(documents)

# Embedding and save
embeddings = OpenAIEmbeddings(model="text-embedding-3-large")
vectorstore = Qdrant.from_documents(
    chunks,
    embeddings,
    url="http://localhost:6333",
    collection_name="corporate-docs",
    force_recreate=True,
)

Answering a Query

from langchain_openai import ChatOpenAI
from langchain.chains import RetrievalQA
from langchain.prompts import ChatPromptTemplate

template = """You are an assistant that answers strictly based on the provided context.
If the answer is not in the context, say "Information not found in the knowledge base."
Always cite the source (document name and section) using <cite> tags, for example: <cite>Contract Section 4.2</cite>.

Context:
{context}

Question: {question}

Answer:"""

prompt = ChatPromptTemplate.from_template(template)
llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)

# Retrieval + Generation
retriever = vectorstore.as_retriever(
    search_type="mmr",   # Maximum Marginal Relevance — reduces duplication
    search_kwargs={"k": 5, "fetch_k": 20}
)

qa_chain = RetrievalQA.from_chain_type(
    llm=llm,
    retriever=retriever,
    chain_type_kwargs={"prompt": prompt},
    return_source_documents=True,
)

result = qa_chain.invoke({"query": "What is the warranty period?"})

Practical Case: RAG for an Insurance Company (from Our Practice)

Challenge: an assistant for handling customer inquiries — searching insurance contracts, payout rules, precedent decisions (12,000 documents, ~2M pages).

Key decisions:

  • Embedding: BGE-M3 (multilingual, works well on Russian, free self-hosted). Dimension 1024.
  • Chunking: hybrid strategy — structural boundaries (contract sections) instead of fixed size. Chunk size 200–600 tokens.
  • Reranking: CrossEncoder after vector search. Top-50 candidates → Top-5 after rerank. +18% faithfulness.

Metrics (RAGAS):

Metric Before rerank After rerank
Context Precision 0.68 0.84
Context Recall 0.71 0.79
Faithfulness 0.74 0.91
Answer Relevancy 0.81 0.89

Self-hosted embedding models are significantly cheaper than OpenAI and provide comparable quality on Russian. This lowers the total cost of ownership of the RAG system — no per-API-call charges. Request a project cost estimate — contact us.

What Affects RAG Accuracy?

RAG system accuracy depends on several factors: chunk quality, embedding model choice, retrieval strategy, and presence of a reranker. Even small changes in chunk_size can shift metrics by 10–20%. Small chunks (128–256 tokens) yield high retrieval precision but may lack full context. Medium chunks (512–1024 tokens) strike a balance — optimal for most tasks. Large chunks (1024–2048 tokens) capture more context but degrade retrieval precision. For documents with long, interconnected sections, use Parent Document Retriever: index small chunks for retrieval, return large chunks to the LLM.

What's Included in RAG System Development?

  1. Audit of existing data and requirements.
  2. Technology stack selection and architecture design.
  3. Indexing pipeline development (chunking, embedding, storage).
  4. Retrieval tuning (vector search + reranker).
  5. LLM integration with custom prompt and sources.
  6. Quality metrics collection (RAGAS, manual validation).
  7. Documentation, team training.
  8. Post-launch support.

Timelines and Cost

  • Prototype (basic RAG): 1–2 weeks. Starting at $15,000.
  • Production-ready system with quality evaluation: 4–8 weeks.
  • Extended RAG (hybrid search, reranking, evaluation): 8–14 weeks.

Cost is calculated individually. Get in touch for a 30-minute consultation on RAG implementation.

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.