Creating a Document Assistant with LangChain and Qdrant

FreeAPIGemini · Updated 2026-11-24 · 19 min read

Laptop with code and physical documents on a desk
Setting up the local environment with code and reference materials.

Retrieval-Augmented Generation bridges the gap between static documents and dynamic conversation. By combining a vector database with a language model, you can create an application that answers questions based on specific PDFs rather than relying solely on pre-trained knowledge. This approach ensures that responses are grounded in the provided text, reducing hallucinations and increasing relevance for technical or domain-specific content. The system retrieves relevant snippets from your documents and injects them into the prompt, allowing the model to generate precise, context-aware answers.

Setting up this system involves several moving parts: document parsing, text chunking, vector embedding, and a search mechanism to retrieve relevant snippets. The combination of LangChain for orchestration and Qdrant for storage offers a robust foundation. While the initial setup requires configuring Docker containers and managing dependencies, the result is a scalable architecture that can handle multiple documents and concurrent queries. You will learn how to parse PDFs, generate embeddings, and store them in a vector database for fast retrieval.

Building this application from scratch teaches valuable backend skills, from handling file uploads to managing asynchronous workers. It also highlights the trade-offs between different models and endpoints. While commercial options exist, using an open-weight model like the one available via the free API provides a cost-effective way to experiment with RAG pipelines without immediate financial commitment. The process is iterative, and debugging often reveals nuances in how documents are split and indexed. Note that while this guide uses generic terms, the site is not affiliated with Google, and the models discussed are independent open-weight solutions.

faq[0]": {

Frequently asked questions

What is RAG?

RAG stands for Retrieval-Augmented Generation. It is a technique that enhances language models by providing them with external context from a knowledge base, such as a vector database. This allows the model to generate answers based on specific documents rather than just its pre-trained knowledge, reducing hallucinations and improving accuracy for domain-specific content.

How does LangChain differ from a vector database?

LangChain is an orchestration framework that connects various components like document loaders, splitters, and embedding models. A vector database like Qdrant stores the numerical embeddings of text chunks and enables fast similarity searches. LangChain manages the workflow, while the vector database handles the storage and retrieval of vector data.

Which is better: OpenAI or free-ai for RAG?

OpenAI models offer high quality and reliability but come with costs. The free-ai model is an open-weight 35B parameter model that is compatible with the OpenAI API format. It is free, has fewer refusal rates, and is suitable for cost-effective RAG applications. The choice depends on your budget and quality requirements.

What is the role of embeddings?

Embeddings are numerical representations of text that capture semantic meaning. They allow the system to find similar text by comparing vectors in a high-dimensional space. In RAG, embeddings are used to convert both documents and queries into vectors, enabling the retrieval of relevant context based on semantic similarity.

How do I handle large PDFs?

Large PDFs should be split into smaller chunks using a text splitter. This ensures that each chunk fits within the model's context window. You can use overlap between chunks to preserve context. Additionally, you can use hierarchical retrieval to first identify relevant sections and then retrieve detailed chunks from those sections.

What is Qdrant?

Qdrant is a vector database written in Rust that supports high-performance similarity searches. It is designed to handle large-scale vector data and provides features like filtering, payload storage, and efficient indexing. It is commonly used in RAG applications to store and retrieve document embeddings.

How do I reduce hallucinations?

To reduce hallucinations, ensure that the retrieved context is relevant and sufficient. Use re-ranking to select the most relevant chunks. Encourage the model to cite its sources and state when it does not know the answer. You can also use a secondary model to verify the response against the context.

Can I use this for real-time chat?

Yes, you can build a real-time chat interface using WebSockets or Server-Sent Events (SSE). The backend processes each query, retrieves relevant context, and generates a response. You can stream the response to the frontend for a seamless user experience. The free API supports streaming, which is ideal for chat applications.

Step by step

  1. Setup Environment — Install Python and Docker. Create a virtual environment and install LangChain, Qdrant client, and PyMuPDF. Initialize a git repository for version control.
  2. Configure Qdrant — Create a docker-compose.yml file to run Qdrant locally. Start the service and verify it is running by accessing the API on port 6333. Create a collection in Qdrant for your document chunks.
  3. Ingest Documents — Write a script to load PDFs, extract text, and split into chunks. Generate embeddings using an open-source model and upload them to Qdrant. Verify the vectors are stored correctly by performing a test search.
  4. Build Chat Interface — Create a simple web interface using HTML and JavaScript. Implement a chat box that sends queries to your backend. Display the response and source citations. Test the end-to-end flow with a sample PDF.

Understanding the RAG Architecture

Retrieval-Augmented Generation enhances large language models by providing them with external context. Instead of generating answers solely from internal weights, the system first searches a vector database for relevant document segments. These segments are then injected into the prompt, allowing the model to reference specific text. This method is particularly effective for PDFs, which often contain dense, specialized information that would be too large to fit into a model's context window entirely. The architecture separates the storage of knowledge from the reasoning engine, allowing each to scale independently.

The architecture typically involves three main components: the data ingestion pipeline, the vector store, and the generation engine. The ingestion pipeline handles PDF parsing, text cleaning, and chunking. The vector store indexes these chunks using embeddings, which are numerical representations of semantic meaning. Finally, the generation engine retrieves the most similar chunks based on a user query and constructs a response. This separation of concerns allows each component to be optimized independently, such as using a more accurate embedding model or a faster vector search index.

Why Vector Databases?

Vector databases like Qdrant store high-dimensional embeddings, enabling fast similarity searches. Unlike traditional databases that rely on exact matches, vector stores use approximate nearest neighbor algorithms to find semantically related content. This is crucial for RAG, where the user's query might use different wording than the source text but seeks the same information. Qdrant is chosen for its speed, scalability, and support for filtering, which allows for metadata-based retrieval alongside semantic search. It handles high-dimensional data efficiently, making it suitable for large document collections.

The Role of LangChain

LangChain acts as the glue connecting the various components of a RAG application. It provides abstractions for document loaders, text splitters, embedding models, and vector stores. By standardizing the interface between these parts, LangChain simplifies the development process. It also offers chains and agents that can orchestrate the retrieval and generation steps, allowing developers to focus on the application logic rather than the underlying API calls. This is especially useful when iterating on different models or vector stores, as you can swap components without rewriting the entire pipeline.

Setting Up the Environment

Before writing code, you need a consistent environment to manage dependencies and services. Docker is an excellent choice for this, as it allows you to run Qdrant and other services in isolated containers. This ensures that your local development environment matches production, reducing the 'it works on my machine' problem. You will need Python installed for the application logic, along with packages like langchain, qdrant-client, and pymupdf for document processing. A virtual environment helps isolate these dependencies from your system-wide Python installation.

Creating a docker-compose.yml file is the first step. This file defines the Qdrant service, specifying ports and volume mounts for data persistence. Running this command starts the vector database locally, ready to receive embeddings. You also need to set up a virtual environment for your Python project to avoid conflicts with system-wide packages. Installing the required libraries ensures that you have access to the necessary tools for parsing PDFs, generating embeddings, and interacting with the vector store. This setup creates a reproducible environment for your project.

Installing Dependencies

Use pip install langchain langchain-community qdrant-client pymupdf to install the core libraries. Langchain provides the high-level interfaces, while langchain-community includes specific integrations for Qdrant and document loaders. PyMuPDF is a high-performance library for extracting text and metadata from PDF files. These packages form the backbone of the application, enabling the conversion of raw PDF content into a format suitable for vectorization. Ensure you are using a recent version of Python to avoid compatibility issues with these libraries.

Configuring Docker

Define the Qdrant service in your docker-compose.yml file. Set the port to 6333 for the HTTP API and 6334 for gRPC. Mount a volume to persist the index data so it is not lost when the container restarts. This setup provides a reliable backend for your RAG application, ensuring that the vector index remains consistent across development sessions. You can also add other services like a Redis cache if you plan to extend the application with session management. Docker Compose simplifies the management of these multi-container applications.

Diagram of RAG architecture components
The flow of data from document parsing to vector storage and generation.

Processing PDF Documents

The first step in the RAG pipeline is ingesting PDF documents. PDFs can be complex, containing images, tables, and irregular layouts. Using a robust parser like PyMuPDF ensures that text is extracted accurately. The parser reads the document page by page, extracting text and metadata such as page numbers. This raw text is then passed to a text splitter, which breaks the content into manageable chunks. The goal is to create chunks that are small enough to fit into the model's context window but large enough to retain semantic meaning. Accurate parsing is critical for the quality of the final answers.

Text extraction is just the beginning. You must also clean the data to remove noise. This involves removing excessive whitespace, newlines, and special characters that do not contribute to meaning. This preprocessing step improves the quality of the embeddings by reducing noise. It is also important to preserve page numbers and other metadata, as they can be used later for citation and context. Clean text ensures that the vector representations are more accurate and relevant, leading to better retrieval results.

Text Extraction and Cleaning

Extract text from each page of the PDF. Clean the text by removing excessive whitespace, newlines, and special characters that do not contribute to meaning. This preprocessing step improves the quality of the embeddings by reducing noise. It is also important to preserve page numbers and other metadata, as they can be used later for citation and context. Clean text ensures that the vector representations are more accurate and relevant. You can use regular expressions to clean up the text before passing it to the splitter.

Chunking Strategies

Split the cleaned text into chunks of a fixed size, such as 500 tokens, with an overlap of 50 tokens. The overlap helps preserve context across chunk boundaries, ensuring that sentences or paragraphs are not cut off awkwardly. This strategy balances the need for granular retrieval with the need for coherent context. Too small chunks may lose meaning, while too large chunks may exceed the model's context limits or dilute the signal. Experiment with different sizes to find the optimal balance for your specific documents. LangChain provides several splitters to help with this process.

Generating and Storing Embeddings

Once the text is chunked, each chunk needs to be converted into a vector. This is done using an embedding model, which maps the text to a high-dimensional space where semantically similar texts are close together. LangChain provides a unified interface for various embedding models, allowing you to swap them out easily. The resulting vectors are then sent to the Qdrant vector store, which indexes them for fast retrieval. This indexing process transforms unstructured text into a format that can be efficiently searched. The quality of the embeddings directly impacts the accuracy of the retrieval.

Choosing the right embedding model is crucial. Open-source models like sentence-transformers are a good starting point. They are free and can be run locally, providing a high degree of control. The choice of model affects the quality of the retrieval; a more sophisticated model may capture nuances better but require more computational resources. For most RAG applications, a mid-sized model provides a good balance between speed and accuracy. You can also use commercial embedding APIs if you need higher precision and are willing to pay for it.

Choosing an Embedding Model

Select an embedding model that balances accuracy and performance. Open-source models like sentence-transformers are a good starting point. They are free and can be run locally, providing a high degree of control. The choice of model affects the quality of the retrieval; a more sophisticated model may capture nuances better but require more computational resources. For most RAG applications, a mid-sized model provides a good balance between speed and accuracy. You can benchmark different models to see which performs best for your specific domain.

Uploading to Qdrant

Use the Qdrant client to create a collection and upload the vectors. Each vector is associated with the original text chunk and its metadata, such as the source file and page number. This metadata is crucial for displaying citations in the final response. Qdrant supports efficient indexing structures like HNSW, which allow for fast approximate nearest neighbor searches. Ensure that the collection is properly configured with the correct vector size and distance metric. You can also add filters to the collection to restrict searches to specific documents or metadata fields.

Visual representation of vector search
The retrieval process in a RAG application.

Implementing the Retrieval Logic

Retrieval is the core of the RAG system. When a user submits a query, the system first converts the query into a vector using the same embedding model used for the documents. It then searches the Qdrant collection for the most similar vectors. The number of results to retrieve is a parameter that needs tuning. Retrieving too few chunks may miss relevant information, while retrieving too many may introduce noise. A common starting point is to retrieve 3-5 chunks per query. This balance ensures that the model has enough context without being overwhelmed.

The retrieval process involves calculating the similarity between the query vector and the stored vectors. Qdrant uses distance metrics like cosine similarity to determine relevance. The results include the vector, the payload (metadata), and the score. These scores can be used to filter out low-relevance results if necessary. The retrieved chunks are then prepared for injection into the prompt. It is important to ensure that the retrieval logic is efficient, as it directly impacts the latency of the application.

Similarity Search

Use the Qdrant client's search method to find the top K vectors closest to the query vector. The distance metric, typically cosine similarity, determines how closely related the vectors are. The results include the vector, the payload (metadata), and the score. These scores can be used to filter out low-relevance results if necessary. The retrieved chunks are then prepared for injection into the prompt. You can also use filters to restrict the search to specific collections or metadata fields.

Re-ranking for Accuracy

After retrieval, it is often beneficial to re-rank the results using a cross-encoder model. This model evaluates the relevance of each chunk to the query more accurately than the embedding similarity score. Re-ranking can significantly improve the quality of the retrieved context by promoting the most relevant chunks and demoting less relevant ones. This step adds latency but can lead to more accurate and coherent responses from the language model. It is particularly useful when the initial retrieval returns a mix of highly relevant and slightly relevant chunks.

Integrating the Language Model

With the relevant context retrieved, the next step is to generate a response using a language model. The retrieved chunks are inserted into a prompt template, along with the user's query. The prompt instructs the model to answer based on the provided context. The choice of model affects the quality and speed of the response. While commercial models offer high quality, open-weight models like the free-ai model provide a cost-effective alternative with fewer refusal rates. The model generates a response, which is then returned to the user. This integration is where the magic happens, combining retrieval with generation.

The prompt construction is critical. You need to clearly separate the context from the query. Use a structure like 'Context: [chunks] Question: [query]'. This helps the model understand the relationship between the context and the question. You can also add instructions to limit the response length or specify the tone. The prompt should be designed to minimize hallucinations by encouraging the model to stick to the provided context. If the context does not contain the answer, the model should state that rather than making up an answer.

Prompt Construction

Create a prompt template that includes the user's query and the retrieved context. Use a clear structure, such as 'Context: [chunks] Question: [query]'. This structure helps the model understand the relationship between the context and the question. You can also add instructions to limit the response length or specify the tone. The prompt should be designed to minimize hallucinations by encouraging the model to stick to the provided context. You can use LangChain's ChatPromptTemplate to manage these templates effectively.

Using the Free API

The free API endpoint provides access to a 35B parameter model that is fine-tuned for fewer refusals. This model is compatible with the OpenAI API format, making it easy to integrate with LangChain. By using this endpoint, you can reduce costs while still achieving good results. The model's ability to handle long contexts and its low refusal rate make it suitable for RAG applications where specific instructions might otherwise trigger a refusal. Remember to set the correct User-Agent to avoid 403 errors. You can find more details about the endpoint on the home page.

from langchain_openai import ChatOpenAI

llm = ChatOpenAI(
    model="free-ai",
    base_url="https://api.freeapigemini.com/v1",
    api_key="",
    temperature=0.7
)
Chat interface UI design
The user-facing chat interface for the PDF assistant.

Building the Frontend Interface

A simple frontend allows users to interact with the RAG application. A chat interface is the most intuitive way to present the results. The frontend sends the user's query to the backend, which processes it and returns the response along with the sources. The interface displays the response and links to the original PDF pages. This transparency helps users verify the accuracy of the answer. Building the frontend skeleton is the first step, followed by implementing the chat logic. You can use any framework, but a simple HTML/JS setup is sufficient for a prototype.

The frontend should support streaming responses to show the model's output in real-time. This improves the user experience by providing immediate feedback. The interface should also display citations, allowing users to click through to the relevant PDF pages. This feature enhances trust in the system by providing evidence for the generated answers. Keep the design simple and focused on the core functionality. You can later add features like dark mode or mobile responsiveness.

Chat Interface Design

Design a clean interface with a text input for queries and a display area for responses. Use a streaming response to show the model's output in real-time, improving the user experience. The interface should also display citations, allowing users to click through to the relevant PDF pages. This feature enhances trust in the system by providing evidence for the generated answers. Keep the design simple and focused on the core functionality. You can use libraries like marked to render markdown in the responses.

Displaying Sources

Include a section in the response that lists the source documents and page numbers. This information is retrieved from the metadata associated with the vector search results. Displaying sources helps users understand the basis of the answer and verify its accuracy. It also adds value to the application by providing direct access to the original content. Ensure that the source links are clickable and lead directly to the correct page in the PDF viewer. This feature is crucial for building user trust in the system.

Deployment and Scaling

Deploying the application involves packaging the code and services into containers. Docker Compose is a convenient way to manage the dependencies, including the application code, Qdrant, and any other services. Deploying to a platform like Vercel or AWS allows you to scale the application as needed. Monitoring the application's performance is crucial, especially as the number of users and documents grows. Tracking metrics like latency, error rates, and token usage helps identify bottlenecks and optimize the system. You can use the monitor API usage guide to track your token consumption.

The deployment process should be automated to ensure consistency. Use CI/CD pipelines to build and deploy your application. This reduces the risk of human error and ensures that the latest code is always running in production. You can also set up health checks to monitor the status of your services. If a service fails, the pipeline can automatically restart it or alert you. This level of automation is essential for maintaining a reliable application.

Containerization

Create a Dockerfile for the Python application, specifying the base image and dependencies. Build the image and push it to a container registry. Use Docker Compose to define the entire stack, including the application and Qdrant. This ensures that the application runs consistently across different environments. Containerization also simplifies the deployment process, allowing you to spin up new instances quickly. You can use tools like docker build and docker push to manage your images.

Monitoring and Logging

Implement logging to track requests, responses, and errors. Use tools like Prometheus and Grafana to monitor performance metrics. Set up alerts for high latency or error rates. Monitoring helps you understand how the application is performing under load and identify areas for improvement. Logging also provides valuable data for debugging and optimizing the RAG pipeline, such as identifying which queries are most common or which documents are most frequently accessed. You can use the monitor API usage guide to track your token consumption.

Cloud server infrastructure with Docker logo
Deploying the application to a cloud environment.

Common Challenges and Solutions

Building a RAG application is not without its challenges. One common issue is the quality of the retrieved context. If the embeddings are not accurate, the model may receive irrelevant information, leading to poor responses. Another challenge is handling large documents that exceed the context window. This requires careful chunking and potentially hierarchical retrieval strategies. Additionally, managing the trade-off between retrieval speed and accuracy is an ongoing process that requires tuning. You can read more about rate limits to avoid hitting quotas during testing.

Another challenge is hallucination, where the model generates plausible but incorrect answers. This can happen if the retrieved context is insufficient or if the model is not properly instructed to stick to the context. To mitigate this, encourage the model to cite its sources in the response. If the model cannot find an answer in the context, it should state that rather than making up an answer. You can also use a secondary model to verify the response against the context. This additional step can significantly reduce the frequency of hallucinations and improve the reliability of the application.

Handling Context Limits

If the retrieved chunks exceed the model's context window, you need to prioritize the most relevant ones. Use re-ranking scores to select the top K chunks that fit within the limit. Alternatively, use a hierarchical approach where you first retrieve a small set of chunks and then re-rank them. This ensures that the most important information is included in the prompt, even if it means discarding less relevant details. You can also use a smaller model for the initial retrieval and a larger model for the final generation.

Dealing with Hallucinations

Even with RAG, models can hallucinate. To mitigate this, encourage the model to cite its sources in the response. If the model cannot find an answer in the context, it should state that rather than making up an answer. You can also use a secondary model to verify the response against the context. This additional step can significantly reduce the frequency of hallucinations and improve the reliability of the application. You can also use the context compaction guide to manage context length effectively.

Try the free API

Test the keyless endpoint with your own code samples right now to see how it handles your specific requests.

Read also