Use this file to discover Exa products, pricing, evaluations, comparisons, use cases, agent interfaces, and technical documentation before exploring further.
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
Boto3 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.
Downloads: PyPI, last thirty days. Stars and releases: GitHub. Amber: no release in over a year.
Libraries and code examples
Boto3
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
Strengths
Cited answers.retrieve_and_generate retrieves from the knowledge base and answers with a chosen foundation model.
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)
OpenAI 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
Strengths
Hosted file search.OpenAI stores, chunks, and searches the files, and the model calls the tool when needed.
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)
@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
Gemini 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
Strengths
Indexing handled by the API.The File Search store imports, chunks, and indexes files without a separate vector database.
@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
)
LangChain Classic
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
Strengths
One-call retrieval chain.create_retrieval_chain joins any LangChain retriever with a chain that answers from the documents.
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'])
@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))
Google ADK
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
Strengths
Retrieval as an agent tool.VertexAiRagRetrieval exposes a Vertex AI RAG corpus to an agent as a callable tool.
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)
Foundry 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
Strengths
Files stay in project storage.With the standard agent setup, uploaded files remain in the project's own storage.
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)
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.")
DSPy
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
Strengths
Retriever as a module.dspy.retrievers.Embeddings searches an in-memory corpus with any configured embedder.
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
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.
Limitations
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.
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
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.
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.
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.
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.
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.
For coding agents
Found your RAG library? Help your agent use it.
Connect Exa so your coding agent can find the library’s documentation, check its API, and look up implementations while you build.