# Python RAG libraries

Python RAG libraries connect a language model to a set of documents through retrieval-augmented generation (RAG): code finds the passages relevant to a question and passes them to the model as context. These libraries let AI agents and chat assistants answer from a company's own documents rather than only from what the model learned in training.

## Popularity

| Library | Monthly downloads | Stars | Last release | License |
| --- | --- | --- | --- | --- |
| [Boto3](#botothree) | 2.5B | 9.9K | Nov 2026 | Apache-2.0 |
| [OpenAI File Search](#openai) | 384.4M | 32.2K | Nov 2026 | Apache-2.0 |
| [Gemini File Search](#google-genai) | 168.8M | 4.1K | Nov 2026 | Apache-2.0 |
| [LangChain Classic](#langchain-classic) | 17.3M | 149.6K | Jun 2026 | MIT |
| [Google ADK](#google-adk) | 11.0M | 22.3K | Nov 2026 | Apache-2.0 |
| [Foundry File Search](#azure-ai-projects) | 8.0M | 5.6K | Nov 2026 | MIT |
| [DSPy](#dspy) | 5.9M | 39.1K | Nov 2026 | MIT |
| [LlamaIndex Core](#llamaindex-core) | 5.7M | 52.9K | Nov 2026 | MIT |

Downloads: PyPI, last thirty days. Stars and releases: GitHub. Amber: no release in over a year.

[Boto3](#botothree) has the most monthly downloads in this comparison, at 2.5B, a count that covers the whole AWS SDK rather than its knowledge base client alone.

## Capabilities

| Library | File/corpus loading API | In-process corpus index |
| --- | --- | --- |
| [Boto3](#botothree) | Yes | No |
| [OpenAI File Search](#openai) | Yes | No |
| [Gemini File Search](#google-genai) | Yes | No |
| [LangChain Classic](#langchain-classic) | Via plugin | Yes |
| [Google ADK](#google-adk) | No | No |
| [Foundry File Search](#azure-ai-projects) | Via plugin | No |
| [DSPy](#dspy) | Yes | Yes |
| [LlamaIndex Core](#llamaindex-core) | Yes | Yes |

## Libraries

### Boto3

[GitHub](https://github.com/boto/boto3) · [PyPI](https://pypi.org/project/boto3) · [Docs](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/bedrock-agent-runtime.html)

The AWS SDK for Python reaches Amazon Bedrock Knowledge Bases, a managed service that stores documents, splits them into chunks, and embeds them for retrieval. The knowledge base and its data source are set up in AWS first. From Python, the `bedrock-agent-runtime` client's `retrieve` method returns the matching chunks, and `retrieve_and_generate` also passes them to a chosen foundation model, which answers with citations to the source data. Bedrock can also rerank the chunks with a separate reranking model.

- Downloads / mo: 2.5B
- Stars: 9.9K
- Last release: 1.44.6
- License: Apache-2.0
- Capabilities: [From the Boto3 docs](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/bedrock-agent-runtime.html)

**Strengths**

- **Cited answers.** retrieve_and_generate retrieves from the knowledge base and answers with a chosen foundation model.

```sh
pip install boto3
```

**langchain-ai/langchain-aws** (353 stars)

[langchain-ai/langchain-aws](https://github.com/langchain-ai/langchain-aws) 

```python
def _get_relevant_documents(
    self,
    query: str,
    *,
    run_manager: CallbackManagerForRetrieverRun,
) -> List[Document]:
    """Get relevant document from a KnowledgeBase

    Parameters:
        query: The user's query.
        run_manager: The callback handler to use.

    Returns:
        A list of relevant documents.

    """
    retrieve_request: Dict[str, Any] = self._get_retrieve_request(query)
    response = self.client.retrieve(**retrieve_request)
    results = response["retrievalResults"]
    documents: List[Document] = (
        AmazonKnowledgeBasesRetriever._retrieval_results_to_documents(results)
    )

    return self._filter_by_score_confidence(docs=documents)

```

[libs/aws/langchain_aws/retrievers/bedrock.py](https://github.com/langchain-ai/langchain-aws/blob/9f6d284bb91e622aab03cc4fa21f2dcf601931ab/libs/aws/langchain_aws/retrievers/bedrock.py#L205-L228) · [More projects using Boto3 →](https://dashboard.exa.ai/playground/search?q=boto3%20GitHub%20projects)

**Quickstart**

```python
import boto3

client = boto3.client('bedrock-agent-runtime')
response = client.retrieve_and_generate(
    input={'text': 'What is the refund policy?'},
    retrieveAndGenerateConfiguration={
        'type': 'KNOWLEDGE_BASE',
        'knowledgeBaseConfiguration': {
            'knowledgeBaseId': 'YOUR_KNOWLEDGE_BASE_ID',
            'modelArn': 'YOUR_SUPPORTED_MODEL_ARN',
        },
    },
)
print(response['output']['text'])

```

From [retrieve_and_generate.html](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/bedrock-agent-runtime.html)

### OpenAI File Search

[GitHub](https://github.com/openai/openai-python) · [PyPI](https://pypi.org/project/openai) · [Docs](https://platform.openai.com/docs/guides/tools-file-search)

The OpenAI Python library reaches File Search, a hosted tool in the Responses API. Files are uploaded through the Files API and added to a vector store, where OpenAI chunks and indexes them for semantic and keyword search. A Responses API call lists `file_search` with the vector store ID among its tools, and the model decides when to search and cites the files it used. The retrieval code runs on OpenAI's side.

- Downloads / mo: 384.4M
- Stars: 32.2K
- Last release: 3.55.1
- License: Apache-2.0
- Capabilities: [From the OpenAI File Search docs](https://platform.openai.com/docs/guides/tools-file-search)

**Strengths**

- **Hosted file search.** OpenAI stores, chunks, and searches the files, and the model calls the tool when needed.

```sh
pip install openai
```

**openai/openai-cookbook** (77.2K stars)

[openai/openai-cookbook](https://github.com/openai/openai-cookbook) 

```python
@mcp.tool()
async def fetch(id: str) -> Dict[str, Any]:
    """
    Retrieve complete document content by ID for detailed analysis and citation.

    This tool fetches the full document content from OpenAI Vector Store or local storage.
    Use this after finding relevant documents with the search tool to get complete 
    information for analysis and proper citation.

    Args:
        id: File ID from vector store (file-xxx) or local document ID

    Returns:
        Complete document with id, title, full text content, optional URL, and metadata

    Raises:
        ValueError: If the specified ID is not found
    """
    if not id:
        raise ValueError("Document ID is required")

    if not openai_client:
        logger.error("OpenAI client not initialized - API key missing")
        raise ValueError(
            "OpenAI API key is required for vector store file retrieval")

    logger.info(f"Fetching content from vector store for file ID: {id}")

    # Fetch file content from vector store
    content_response = openai_client.vector_stores.files.content(
        vector_store_id=VECTOR_STORE_ID, file_id=id)

    # Get file metadata
    file_info = openai_client.vector_stores.files.retrieve(
        vector_store_id=VECTOR_STORE_ID, file_id=id)

    # Extract content from paginated response
    file_content = ""
    if hasattr(content_response, 'data') and content_response.data:
        # Combine all content chunks from FileContentResponse objects
        content_parts = []
        for content_item in content_response.data:
            if hasattr(content_item, 'text'):
                content_parts.append(content_item.text)
        file_content = "\n".join(content_parts)
    else:
        file_content = "No content available"

    # Use filename as title and create proper URL for citations
    filename = getattr(file_info, 'filename', f"Document {id}")

    result = {
        "id": id,
        "title": filename,
        "text": file_content,
        "url": f"https://platform.openai.com/storage/files/{id}",
        "metadata": None
    }

    # Add metadata if available from file info
    if hasattr(file_info, 'attributes') and file_info.attributes:
        result["metadata"] = file_info.attributes

    logger.info(f"Successfully fetched vector store file: {id}")
    return result

```

[examples/deep_research_api/how_to_build_a_deep_research_mcp_server/main.py](https://github.com/openai/openai-cookbook/blob/dfd760b4de0bd175b51ad05b9b5260c36dfea09c/examples/deep_research_api/how_to_build_a_deep_research_mcp_server/main.py#L109-L173) · [More projects using OpenAI File Search →](https://dashboard.exa.ai/playground/search?q=openai%20GitHub%20projects)

**Quickstart**

```python
from openai import OpenAI

client = OpenAI()

response = client.responses.create(
    model="gpt-6.2-astra",
    input="What is deep research by OpenAI?",
    tools=[{"type": "file_search", "vector_store_ids": ["<vector_store_id>"]}],
)
print(response)


```

From [tools-file-search.md](https://platform.openai.com/docs/guides/tools-file-search)

### Gemini File Search

[GitHub](https://github.com/googleapis/python-genai) · [PyPI](https://pypi.org/project/google-genai) · [Docs](https://ai.google.dev/gemini-api/docs/file-search)

The Google Gen AI SDK reaches Gemini File Search, a tool in the Gemini API. A File Search store is created with `file_search_stores.create`, and `upload_to_file_search_store` imports a file that the API chunks, embeds, and indexes. A model call that lists the store in its `file_search` tool retrieves passages and answers from them, with citations attached to the response. Google bills for indexing embeddings and model tokens, and storage and query-time embeddings are free.

- Downloads / mo: 168.8M
- Stars: 4.1K
- Last release: 3.6.1
- License: Apache-2.0
- Capabilities: [From the Gemini File Search docs](https://ai.google.dev/gemini-api/docs/file-search)

**Strengths**

- **Indexing handled by the API.** The File Search store imports, chunks, and indexes files without a separate vector database.

```sh
pip install google-genai
```

**google/adk-python** (22.3K stars)

[google/adk-python](https://github.com/google/adk-python) 

```python
@override
async def process_llm_request(
    self,
    *,
    tool_context: ToolContext,
    llm_request: LlmRequest,
) -> None:
  # Use Gemini built-in Vertex AI RAG tool for Gemini models.
  model_check_disabled = is_gemini_model_id_check_disabled()
  if is_gemini_model(llm_request.model) or model_check_disabled:
    llm_request.config = (
        types.GenerateContentConfig()
        if not llm_request.config
        else llm_request.config
    )
    llm_request.config.tools = (
        [] if not llm_request.config.tools else llm_request.config.tools
    )
    llm_request.config.tools.append(
        types.Tool(
            retrieval=types.Retrieval(vertex_rag_store=self.vertex_rag_store)
        )
    )
  else:
    # Add the function declaration to the tools
    await super().process_llm_request(
        tool_context=tool_context, llm_request=llm_request
    )

```

[src/google/adk/tools/retrieval/vertex_ai_rag_retrieval.py](https://github.com/google/adk-python/blob/e2a21ac23260d043bf9d217b573af1bef48f0f70/src/google/adk/tools/retrieval/vertex_ai_rag_retrieval.py#L144-L171) · [More projects using Gemini File Search →](https://dashboard.exa.ai/playground/search?q=google-genai%20GitHub%20projects)

**Quickstart**

```python
from google import genai

client = genai.Client()
interaction = client.interactions.create(
    model='YOUR_SUPPORTED_GEMINI_MODEL',
    input='What is the refund policy?',
    tools=[{'type': 'file_search', 'file_search_store_names': ['YOUR_FILE_SEARCH_STORE_NAME']}],
)
print(interaction)

```

From [file-search/](https://ai.google.dev/gemini-api/docs/file-search)

### LangChain Classic

[GitHub](https://github.com/langchain-ai/langchain) · [PyPI](https://pypi.org/project/langchain-classic) · [Docs](https://reference.langchain.com/python/langchain_classic/chains/retrieval/create_retrieval_chain/)

LangChain Classic contains the chain-based APIs from earlier LangChain releases, including retrieval chains. `create_retrieval_chain` joins a retriever, such as a vector store wrapped with `as_retriever`, with a document-combining chain such as `create_stuff_documents_chain`, which places the retrieved documents in the prompt. Calling `invoke` with an input returns the answer along with the documents it used. Current LangChain guides build RAG as an agent with a retrieval tool, and the classic package keeps existing chains running.

- Downloads / mo: 17.3M
- Stars: 149.6K
- Last release: 1.0.8
- License: MIT
- Capabilities: [From the LangChain Classic docs](https://reference.langchain.com/python/langchain_classic/chains/retrieval/create_retrieval_chain/)

**Strengths**

- **One-call retrieval chain.** create_retrieval_chain joins any LangChain retriever with a chain that answers from the documents.

```sh
pip install langchain-classic langchain-openai
```

**AISecurityLab/hackagent** (541 stars)

[AISecurityLab/hackagent](https://github.com/AISecurityLab/hackagent) 

```python
@app.post("/v1/chat/completions", response_model=ChatCompletionResponse)
async def chat_completions(request: ChatCompletionRequest):
    try:
        # Retrieve last message
        last_user_message = request.messages[-1].content
        print(f"[RAG] Received query: {last_user_message}")

        # Execute RAG
        if "rag_chain" not in globals():
            raise HTTPException(
                status_code=500, detail="The RAG system was not correctly initialized."
            )

        response = rag_chain.invoke({"input": last_user_message})
        answer_text = response["answer"]

        # Answer
        return ChatCompletionResponse(
            id=f"chatcmpl-{uuid.uuid4()}",
            created=int(time.time()),
            model="google/gemma-3n-e4b-it",  # we return the RAG LLM name for compatibility, but it's not actually used by the client since we run a custom RAG chain
            choices=[
                ChatCompletionResponseChoice(
                    index=0,
                    message=Message(role="assistant", content=answer_text),
                    finish_reason="stop",
                )
            ],
            usage={"prompt_tokens": 0, "completion_tokens": 0, "total_tokens": 0},
        )

    except Exception as e:
        print(f"SERVER ERRROR: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))

```

[hackagent/examples/langchain/rag/agent_server.py](https://github.com/AISecurityLab/hackagent/blob/c51b05db84bad1fd0eaeff3a14e3a04c9e0190d3/hackagent/examples/langchain/rag/agent_server.py#L121-L154) · [More projects using LangChain Classic →](https://dashboard.exa.ai/playground/search?q=langchain-classic%20GitHub%20projects)

**Quickstart**

```python
from langchain_core.documents import Document
from langchain_core.vectorstores import InMemoryVectorStore
from langchain_core.prompts import ChatPromptTemplate
from langchain_openai import ChatOpenAI, OpenAIEmbeddings
from langchain_classic.chains import create_retrieval_chain
from langchain_classic.chains.combine_documents import create_stuff_documents_chain

store = InMemoryVectorStore(OpenAIEmbeddings())
store.add_documents([Document(page_content='Refunds are available for 30 days.')])
prompt = ChatPromptTemplate.from_messages([('system', 'Answer from this context: {context}'), ('human', '{input}')])
combine = create_stuff_documents_chain(ChatOpenAI(), prompt)
chain = create_retrieval_chain(store.as_retriever(), combine)
print(chain.invoke({'input': 'When can I get a refund?'})['answer'])

```

From [retrieval.py](https://reference.langchain.com/python/langchain_classic/chains/retrieval/create_retrieval_chain/)

### Google ADK

[GitHub](https://github.com/google/adk-python) · [PyPI](https://pypi.org/project/google-adk) · [Docs](https://google.github.io/adk-docs/)

Google ADK, the Agent Development Kit, connects agents to retrieval through tools. The `VertexAiRagRetrieval` tool queries a corpus in Vertex AI RAG Engine, a hosted Google Cloud service that stores and indexes documents. On Gemini models the tool attaches as native retrieval, and on other models ADK calls the corpus and passes the retrieved contexts back to the agent. The corpus is created and filled in Vertex AI before the agent can use it.

- Downloads / mo: 11.0M
- Stars: 22.3K
- Last release: 2.14.1
- License: Apache-2.0
- Capabilities: [From the Google ADK docs](https://google.github.io/adk-docs/)

**Strengths**

- **Retrieval as an agent tool.** VertexAiRagRetrieval exposes a Vertex AI RAG corpus to an agent as a callable tool.

```sh
pip install google-adk
```

**google/adk-recipes** (10.7K stars)

[google/adk-recipes](https://github.com/google/adk-recipes) 

```python
def create_search_tool(
    data_store_path: str,
) -> VertexAiSearchTool | Callable[[str], str]:
    """Create a Agent Platform Search tool or mock for testing.

    Args:
        data_store_path: Full resource path of the datastore.

    Returns:
        VertexAiSearchTool instance or mock function for testing.
    """
    # For integration tests, return a mock function instead of the real tool
    if os.getenv("INTEGRATION_TEST") == "TRUE":

        def mock_search(query: str) -> str:
            """Mock Agent Platform Search for integration tests."""
            return "Mock search result for testing purposes."

        return mock_search

    return VertexAiSearchTool(data_store_id=data_store_path)

```

[core/python/rag-agent-search/app/retrievers.py](https://github.com/google/adk-recipes/blob/ead8d7f74d5b1def48a5a7451aed8106aae8d2e6/core/python/rag-agent-search/app/retrievers.py#L21-L41) · [More projects using Google ADK →](https://dashboard.exa.ai/playground/search?q=google-adk%20GitHub%20projects)

**Quickstart**

```python
import asyncio
import os
from google.adk.agents import Agent
from google.adk.runners import InMemoryRunner
from google.adk.tools.retrieval.vertex_ai_rag_retrieval import VertexAiRagRetrieval

async def main():
    retrieval = VertexAiRagRetrieval(name='retrieve_docs', description='Retrieve document context.', rag_resources=[{'rag_corpus': os.environ['RAG_CORPUS']}])
    agent = Agent(name='assistant', model=os.environ['GEMINI_MODEL'], instruction='Answer from retrieved documents.', tools=[retrieval])
    runner = InMemoryRunner(agent=agent)
    await runner.run_debug('What is the refund policy?')

asyncio.run(main())

```

From [vertex_ai_rag_retrieval.py](https://pypi.org/pypi/google-adk/2.14.1/json)

### Foundry File Search

[GitHub](https://github.com/Azure/azure-sdk-for-python) · [PyPI](https://pypi.org/project/azure-ai-projects) · [Docs](https://learn.microsoft.com/en-us/azure/ai-foundry/agents/how-to/tools/file-search)

The Azure AI Projects library manages agents in Microsoft Foundry, including the file search tool. Files are uploaded to a vector store, and an agent created with `FileSearchTool` retrieves passages from them when answering. With the standard agent setup, the files stay in the project's own Azure storage and Azure AI Search indexes them. Microsoft charges for file search on top of the model's token fees.

- Downloads / mo: 8.0M
- Stars: 5.6K
- Last release: 2.11.0
- License: MIT
- Capabilities: [From the Foundry File Search docs](https://learn.microsoft.com/en-us/azure/ai-foundry/agents/how-to/tools/file-search)

**Strengths**

- **Files stay in project storage.** With the standard agent setup, uploaded files remain in the project's own storage.

```sh
pip install azure-ai-projects azure-identity
```

**MicrosoftLearning/mslearn-ai-agents** (355 stars)

[MicrosoftLearning/mslearn-ai-agents](https://github.com/MicrosoftLearning/mslearn-ai-agents) 

```python
def main():
    parser = argparse.ArgumentParser(
        description="Create and ground the caldova-knowledge-agent."
    )
    parser.add_argument(
        "--force",
        action="store_true",
        help="Create a new version even if the agent already exists.",
    )
    args = parser.parse_args()

    load_dotenv(ENV_PATH)
    project_endpoint = os.getenv("PROJECT_ENDPOINT")
    model_deployment = os.getenv("MODEL_DEPLOYMENT_NAME")

    if not project_endpoint:
        fail("PROJECT_ENDPOINT is not set in Python/.env. Run 'azd up' or set it from the portal.")
    if not model_deployment:
        fail("MODEL_DEPLOYMENT_NAME is not set in Python/.env. Set it to your deployed model name.")

    data_files = sorted(DATA_DIR.glob("*.md"))
    if not data_files:
        fail(f"No knowledge documents found in {DATA_DIR}.")

    print("Connecting to your Foundry project ...")
    with (
        DefaultAzureCredential() as credential,
        AIProjectClient(endpoint=project_endpoint, credential=credential) as project_client,
        project_client.get_openai_client() as openai_client,
    ):
        if agent_exists(project_client) and not args.force:
            print(f"\nAgent '{AGENT_NAME}' already exists - nothing to do.")
            print("Re-run with --force to add a new grounded version.")
            set_env_value("AGENT_NAME", AGENT_NAME)
            print(f"Ensured AGENT_NAME={AGENT_NAME} in {ENV_PATH}")
            return

        print(f"Grounding the agent (this uploads {len(data_files)} knowledge documents):")
        file_ids = [upload_file(openai_client, path) for path in data_files]
        vector_store_id = build_vector_store(openai_client, file_ids)

        file_search = FileSearchTool(vector_store_ids=[vector_store_id])

        print("Creating the agent ...")
        agent = project_client.agents.create_version(
            agent_name=AGENT_NAME,
            definition=PromptAgentDefinition(
                model=model_deployment,
                instructions=INSTRUCTIONS,
                tools=[file_search],
            ),
        )
        print(f"  Created '{agent.name}' (version {agent.version}).")

    set_env_value("AGENT_NAME", AGENT_NAME)
    print(f"\nWrote AGENT_NAME={AGENT_NAME} to {ENV_PATH}")
    print("You're ready to connect from code: run 'python knowledge_agent.py' from the Python folder.")

```

[Labfiles/B-integrate-agents-with-enterprise-knowledge-and-m365/setup/bootstrap_agent.py](https://github.com/MicrosoftLearning/mslearn-ai-agents/blob/df5b56b41480298afc09abf28c79c0d1856f40dd/Labfiles/B-integrate-agents-with-enterprise-knowledge-and-m365/setup/bootstrap_agent.py#L124-L180) · [More projects using Foundry File Search →](https://dashboard.exa.ai/playground/search?q=azure-ai-projects%20GitHub%20projects)

**Quickstart**

```python
import os
from azure.identity import DefaultAzureCredential
from azure.ai.projects import AIProjectClient
from azure.ai.projects.models import FileSearchTool, PromptAgentDefinition

with AIProjectClient(endpoint=os.environ['FOUNDRY_PROJECT_ENDPOINT'], credential=DefaultAzureCredential()) as project:
    agent = project.agents.create_version(
        agent_name='document-assistant',
        definition=PromptAgentDefinition(
            model=os.environ['FOUNDRY_MODEL_NAME'],
            tools=[FileSearchTool(vector_store_ids=[os.environ['VECTOR_STORE_ID']])],
        ),
    )
    print(agent.name)

```

From [sample_agent_file_search.py](https://learn.microsoft.com/en-us/azure/ai-foundry/agents/how-to/tools/file-search)

### DSPy

[GitHub](https://github.com/stanfordnlp/dspy) · [PyPI](https://pypi.org/project/dspy) · [Docs](https://dspy.ai/tutorials/rag/)

DSPy treats RAG as a program built from modules. A retriever such as `dspy.retrievers.Embeddings` searches an in-memory corpus using any configured embedder, and a module such as `dspy.ChainOfThought` answers from the retrieved context through a signature like context and question in, answer out. The pieces live in a `dspy.Module` subclass. Optimizers then tune the prompts of the full program using example questions and a scoring function.

- Downloads / mo: 5.9M
- Stars: 39.1K
- Last release: 3.5.0
- License: MIT
- Capabilities: [From the DSPy docs](https://dspy.ai/tutorials/rag/)

**Strengths**

- **Retriever as a module.** dspy.retrievers.Embeddings searches an in-memory corpus with any configured embedder.

```sh
pip install dspy[numpy]
```

**SylphAI-Inc/AdalFlow** (4.2K stars)

[SylphAI-Inc/AdalFlow](https://github.com/SylphAI-Inc/AdalFlow) 

```python
def forward(self, question):

    passages = self.retrieve(question).passages

    pred = self.generate_answer(context=passages, question=question)
    return dspy.Prediction(context=passages, answer=pred.answer)

```

[benchmarks/hotpot_qa/dspy_vanilla_rag.py](https://github.com/SylphAI-Inc/AdalFlow/blob/12f3fa686bdaf01099db65d4c5b1c685513f7a65/benchmarks/hotpot_qa/dspy_vanilla_rag.py#L55-L60) · [More projects using DSPy →](https://dashboard.exa.ai/playground/search?q=dspy%20GitHub%20projects)

**Quickstart**

```python
import dspy

dspy.configure(lm=dspy.LM('YOUR_CONFIGURED_LM'))
search = dspy.retrievers.Embeddings(
    embedder=dspy.Embedder('openai/text-embedding-3-small', dimensions=512),
    corpus=['Refunds are available for 30 days.'], k=1, brute_force_threshold=30000,
)
answer = dspy.ChainOfThought('context, question -> response')
question = 'When can I get a refund?'
context = search(question).passages
print(answer(context=context, question=question).response)

```

From [index.ipynb](https://github.com/stanfordnlp/dspy/blob/main/docs/docs/tutorials/rag/index.ipynb#decoded-notebook-cells)

### LlamaIndex Core

[GitHub](https://github.com/run-llama/llama_index) · [PyPI](https://pypi.org/project/llama-index-core) · [Docs](https://developers.llamaindex.ai/python/framework/)

LlamaIndex Core loads documents, indexes them, and answers questions from the retrieved passages. `SimpleDirectoryReader` reads a folder of files, and `VectorStoreIndex.from_documents` splits them into chunks and embeds them. `as_query_engine` returns an engine that retrieves the closest chunks and writes an answer, and `response.source_nodes` lists the chunks behind it. Metadata filters narrow retrieval to matching documents, and the embedding model and vector store come from separate integration packages.

- Downloads / mo: 5.7M
- Stars: 52.9K
- Last release: 0.14.26
- License: MIT
- Capabilities: [From the LlamaIndex Core docs](https://developers.llamaindex.ai/python/framework/)

**Strengths**

- **Exposes retrieved source text.** Inspect response.source_nodes or get_formatted_sources after a query.
- **Filters queries by document metadata.** Restrict retrieval to properties stored with each document.

**Watch out for**

- **Old indexes need stored metadata.** Rebuild indexes saved without metadata before applying filters.
- **Fine control needs explicit components.** Construct a QueryEngine directly when the high-level helper is insufficient.

```sh
pip install llama-index
```

**open-webui/pipelines** (2.4K stars)

[open-webui/pipelines](https://github.com/open-webui/pipelines) 

```python
def pipe(
    self, user_message: str, model_id: str, messages: List[dict], body: dict
) -> Union[str, Generator, Iterator]:
    # This is where you can add your custom RAG pipeline.
    # Typically, you would retrieve relevant information from your knowledge base and synthesize it to generate a response.

    print(messages)
    print(user_message)

    query_engine = self.index.as_query_engine(streaming=True)
    response = query_engine.query(user_message)

    return response.response_gen
```

[examples/pipelines/rag/llamaindex_ollama_pipeline.py](https://github.com/open-webui/pipelines/blob/c7121bd904c15954b458eb2184ba77c379936284/examples/pipelines/rag/llamaindex_ollama_pipeline.py#L62-L74) · [More projects using LlamaIndex Core →](https://dashboard.exa.ai/playground/search?q=Python%20applications%20using%20llama-index-core%20to%20index%20documents%2C%20retrieve%20context%2C%20inspect%20sources%20and%20generate%20grounded%20answers&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```python
import os

os.environ["OPENAI_API_KEY"] = "YOUR_OPENAI_API_KEY"

from llama_index.core import VectorStoreIndex, SimpleDirectoryReader

documents = SimpleDirectoryReader("YOUR_DATA_DIRECTORY").load_data()
index = VectorStoreIndex.from_documents(documents)

query_engine = index.as_query_engine()
query_engine.query("YOUR_QUESTION")

```

From [README.md](https://github.com/run-llama/llama_index/blob/main/README.md)

## FAQ

### Which Python library should I use for RAG?

An application already on one provider can use that provider's hosted search: Bedrock Knowledge Bases through [Boto3](#botothree), [OpenAI File Search](#openai), [Gemini File Search](#google-genai), or [Foundry File Search](#azure-ai-projects). [LlamaIndex](#llamaindex-core), [LangChain Classic](#langchain-classic), and [DSPy](#dspy) build the pipeline in the application's own code, with any embedding model and vector store.

### How do I build RAG with LangChain?

In the classic package, `create_retrieval_chain` joins a retriever with a chain that passes the retrieved documents to the model. Current LangChain guides build RAG as an agent that calls a retrieval tool.

### How do I build RAG with LlamaIndex?

`VectorStoreIndex.from_documents` chunks and embeds the documents, `as_query_engine` returns an engine that retrieves and answers, and `response.source_nodes` lists the passages behind each answer.

### What is Gemini File Search?

Gemini File Search is a tool in the Gemini API that imports, chunks, and indexes uploaded files in a File Search store. A model call that names the store retrieves passages from it and uses them as context.

### What is OpenAI File Search?

OpenAI File Search is a hosted tool in the Responses API. It searches files uploaded to a vector store with semantic and keyword search, and the model calls it on its own when a question needs the files.

### How does DSPy handle RAG?

A DSPy RAG program combines a retriever, such as `dspy.retrievers.Embeddings`, with a module such as `dspy.ChainOfThought` that answers from the retrieved context. DSPy optimizers can then tune the prompts of the whole program against examples.

## How this page was built

Data checked Nov 20, 2026.

Reproduce it with the Exa API:

```json
{
  "endpoint": "/search",
  "body": {
    "query": "Best Python RAG libraries LlamaIndex Haystack txtai LightRAG code examples",
    "numResults": 5
  }
}
```

Docs: https://exa.ai/docs/reference/search
