R2R is an engine for building user-facing Retrieval-Augmented Generation (RAG) applications. At its core, R2R provides this service through an architecture of providers, services, and an integrated RESTful API. This cookbook provides a detailed walkthrough of how to interact with R2R. Refer here for a deeper dive on the R2R system architecture.
R2R gives developers configurable vector search and RAG right out of the box, as well as direct method calls instead of the client-server architecture seen throughout the docs:
core/examples/hello_r2r.py
Copy
Ask AI
from r2r import R2RClientclient = R2RClient("http://localhost:7272")with open("test.txt", "w") as file: file.write("John is a person that works at Google.")client.ingest_files(file_paths=["test.txt"])# Call RAG directlyrag_response = client.rag( query="Who is john", rag_generation_config={"model": "openai/gpt-4o-mini", "temperature": 0.0},)results = rag_response["results"]print(f"Search Results:\n{results['search_results']}")print(f"Completion:\n{results['completion']}")
R2R efficiently handles diverse document types using Postgres with pgvector, combining relational data management with vector search capabilities. This approach enables seamless ingestion, storage, and retrieval of multimodal data, while supporting flexible document management and user permissions.
Key features include:
Unique document_id generation for each ingested file
User and collection permissions through user_id and collection_ids
Document versioning for tracking changes over time
Granular access to document content through chunk retrieval
Flexible deletion and update mechanisms
Note, all document management commands are gated at the user level, with the exception of superusers.
Ingest Data
R2R offers a powerful data ingestion process that handles various file types including html, pdf, png, mp3, and txt. The full list of supported filetypes is available here. The ingestion process parses, chunks, embeds, and stores documents efficiently with a fully asynchronous pipeline. To demonstrate this functionality:
[ { 'text': 'Aristotle[A] (Greek: Ἀριστοτέλης Aristotélēs, pronounced [aristotélɛːs]; 384–322 BC) was an Ancient Greek philosopher and polymath. His writings cover a broad range of subjects spanning the natural sciences, philosophy, linguistics, economics, politics, psychology, and the arts. As the founder of the Peripatetic school of philosophy in the Lyceum in Athens, he began the wider Aristotelian tradition that followed, which set the groundwork for the development of modern science.', 'title': 'aristotle.txt', 'user_id': '2acb499e-8428-543b-bd85-0d9098718220', 'version': 'v0', 'chunk_order': 0, 'document_id': '9fbe403b-c11c-5aae-8ade-ef22980c3ad1', 'extraction_id': 'aeba6400-1bd0-5ee9-8925-04732d675434', 'fragment_id': 'f48bcdad-4155-52a4-8c9d-8ba06e996ba3', }, ...]
These features allow for granular access to document content.
Delete Documents
R2R supports flexible document deletion through a method that can run arbitrary deletion filters. To delete a document by its ID:
Deletion by document ID, extraction ID, or fragment ID, or other.
Cascading deletion of associated chunks and metadata
Confirmation of successful deletion
This flexible deletion mechanism ensures precise control over document management within the R2R system.
Update Documents
R2R provides robust document update capabilities through two main endpoints: update_documents and update_files. These endpoints allow for seamless updating of existing documents while maintaining version control.
Key features of the update process:
Automatic versioning: When updating a document, R2R automatically increments the version (e.g., from “v0” to “v1”).
Metadata preservation: The update process maintains existing metadata while allowing for updates.
Content replacement: The new document content completely replaces the old content in the order shown below
Ingest the new version of the document
Delete the old version
Executing the command below will update one of the sample documents ingested earlier.
Behind the scenes, this command utilizes the update_files endpoint. The process involves:
Reading the new file content
Incrementing the document version
Ingesting the new version with updated metadata
Deleting the old version of the document
For programmatic updates, you can use the RESTful API endpoint /update_files. This endpoint accepts a R2RUpdateFilesRequest, which includes:
files: List of UploadFile objects containing the new document content
document_ids: UUIDs of the documents to update
metadatas: Optional updated metadata for each document
The update process ensures data integrity and maintains a clear history of document changes through versioning.
For more advanced document management techniques and user authentication details, refer to the user auth cookbook.
Certainly! I’ll rewrite the AI Powered Search section without using dropdowns, presenting it as a continuous, detailed explanation of R2R’s search capabilities. Here’s the revised version:
R2R offers powerful and highly configurable search capabilities, including vector search, hybrid search, and knowledge graph-enhanced search. These features allow for more accurate and contextually relevant information retrieval.
Vector search inside of R2R is highly configurable, allowing you to fine-tune your search parameters for optimal results. Here’s how to perform a basic vector search:
Copy
Ask AI
r2r search --query="What was Uber's profit in 2020?"
Copy
Ask AI
r2r search --query="What was Uber's profit in 2020?"
Copy
Ask AI
client.search("What was Uber's profit in 2020?", { "index_measure": "l2_distance", # default is `cosine_distance` "search_limit": 25,})
{ 'results': {'vector_search_results': [ { 'fragment_id': 'ab6d0830-6101-51ea-921e-364984bfd177', 'extraction_id': '429976dd-4350-5033-b06d-8ffb67d7e8c8', 'document_id': '26e0b128-3043-5674-af22-a6f7b0e54769', 'user_id': '2acb499e-8428-543b-bd85-0d9098718220', 'collection_ids': [], 'score': 0.285747126074015, 'text': 'Net\n loss attributable to Uber Technologies, Inc. was $496 million, a 93% improvement year-over-year, driven by a $1.6 billion pre-tax gain on the sale of ourATG\n Business to Aurora, a $1.6 billion pre-tax net benefit relating to Ubers equity investments, as well as reductions in our fixed cost structure and increasedvariable cost effi\nciencies. Net loss attributable to Uber Technologies, Inc. also included $1.2 billion of stock-based compensation expense.Adjusted', 'metadata': {'title': 'uber_2021.pdf', 'version': 'v0', 'chunk_order': 5, 'associatedQuery': "What was Uber's profit in 2020?"} }, ... ] }}
Key configurable parameters for vector search include:
use_vector_search: Enable or disable vector search.
index_measure: Choose between “cosine_distance”, “l2_distance”, or “max_inner_product”.
search_limit: Set the maximum number of results to return.
include_values: Include search score values in the results.
include_metadatas: Include element metadata in the results.
probes: Number of ivfflat index lists to query (higher increases accuracy but decreases speed).
ef_search: Size of the dynamic candidate list for HNSW index search (higher increases accuracy but decreases speed).
R2R supports hybrid search, which combines traditional keyword-based search with vector search for improved results. Here’s how to perform a hybrid search:
Copy
Ask AI
r2r search --query="What was Uber's profit in 2020?" --use-hybrid-search
Copy
Ask AI
r2r search --query="What was Uber's profit in 2020?" --use-hybrid-search
R2R integrates knowledge graph capabilities to enhance search results with structured relationships. Knowledge graph search can be configured to focus on specific entity types, relationships, or search levels. Here’s how to utilize knowledge graph search:
Knowledge Graphs are not constructed by default, refer to the cookbook here before attempting to run the command below!
Copy
Ask AI
r2r search --query="Who founded Airbnb?" --use-kg-search --kg-search-type=local
Copy
Ask AI
r2r search --query="Who founded Airbnb?" --use-kg-search --kg-search-type=local
Copy
Ask AI
client.search("Who founded Airbnb?", kg_search_settings={ "use_kg_search": True, "kg_search_type": "global", "kg_search_level": 0, # level of community to search "max_community_description_length": 65536, "max_llm_queries_for_global_search": 250, "local_search_limits": { "__Entity__": 20, "__Relationship__": 20, "__Community__": 20 }})
Key configurable parameters for knowledge graph search include:
use_kg_search: Enable knowledge graph search.
kg_search_type: Choose between “global” or “local” search.
kg_search_level: Specify the level of community to search.
entity_types: List of entity types to include in the search.
relationships: List of relationship types to include in the search.
max_community_description_length: Maximum length of community descriptions.
max_llm_queries_for_global_search: Limit on the number of LLM queries for global search.
local_search_limits: Set limits for different types of local searches.
Knowledge graph search provides structured information about entities and their relationships, complementing the text-based search results and offering a more comprehensive understanding of the data.
R2R’s search functionality is highly flexible and can be tailored to specific use cases. By adjusting these parameters, you can optimize the search process for accuracy, speed, or a balance between the two, depending on your application’s needs. The combination of vector search, hybrid search, and knowledge graph capabilities allows for powerful and context-aware information retrieval, enhancing the overall performance of your RAG applications.
R2R is built around a comprehensive Retrieval-Augmented Generation (RAG) engine, allowing you to generate contextually relevant responses based on your ingested documents. The RAG process combines all the search functionality shown above with Large Language Models to produce more accurate and informative answers.
Basic RAG
To generate a response using RAG, use the following command:
Copy
Ask AI
r2r rag --query="What was Uber's profit in 2020?"
Copy
Ask AI
r2r rag --query="What was Uber's profit in 2020?"
Copy
Ask AI
client.rag(query="What was Uber's profit in 2020?")
Copy
Ask AI
await client.rag({ query: "What was Uber's profit in 2020?" });
Copy
Ask AI
curl -X POST http://localhost:7272/v2/rag \ -H "Content-Type: application/json" \ -d '{ "query": "What was Uber'\''s profit in 2020?" }'
Example Output:
Copy
Ask AI
{'results': [ ChatCompletion( id='chatcmpl-9RCB5xUbDuI1f0vPw3RUO7BWQImBN', choices=[ Choice( finish_reason='stop', index=0, logprobs=None, message=ChatCompletionMessage( content="Uber's profit in 2020 was a net loss of $6,768 million [10].", role='assistant', function_call=None, tool_calls=None) ) ], created=1716268695, model='gpt-4o-mini', object='chat.completion', system_fingerprint=None, usage=CompletionUsage(completion_tokens=20, prompt_tokens=1470, total_tokens=1490) )]}
This command performs a search on the ingested documents and uses the retrieved information to generate a response.
RAG w/ Hybrid Search
R2R also supports hybrid search in RAG, combining the power of vector search and keyword-based search. To use hybrid search in RAG, simply add the use_hybrid_search flag to your search settings input:
Copy
Ask AI
r2r rag --query="Who is Jon Snow?" --use-hybrid-search
Copy
Ask AI
r2r rag --query="Who is Jon Snow?" --use-hybrid-search
Copy
Ask AI
results = client.rag("Who is Jon Snow?", {"use_hybrid_search": True})
Copy
Ask AI
await client.rag({ query: "Who is Jon Snow?",});
Copy
Ask AI
curl -X POST http://localhost:7272/v2/rag \ -H "Content-Type: application/json" \ -d '{ "query": "Who is Jon Snow?", "vector_search_settings": { "use_vector_search": true, "search_filters": {}, "search_limit": 10, "use_hybrid_search": true } }'
Example Output:
Copy
Ask AI
{'results': [ ChatCompletion( id='chatcmpl-9cbRra4MNQGEQb3BDiFujvDXIehud', choices=[ Choice( finish_reason='stop', index=0, logprobs=None, message=ChatCompletionMessage( content="Jon Snow is mentioned in the context as one of Samwell (Sam) Tarly's closest companions at the Wall [5], [6].", role='assistant', function_call=None, tool_calls=None) ) ], created=1718987443, model='openai/gpt-4o-2024-05-13', object='chat.completion', system_fingerprint=None, usage=CompletionUsage(completion_tokens=20, prompt_tokens=1192, total_tokens=1221) )]}
This example demonstrates how hybrid search can enhance the RAG process by combining semantic understanding with keyword matching, potentially providing more accurate and comprehensive results.
Streaming RAG
R2R also supports streaming RAG responses, which can be useful for real-time applications. To use streaming RAG:
Copy
Ask AI
r2r rag --query="who was aristotle" --use-hybrid-search --stream
Copy
Ask AI
r2r rag --query="who was aristotle" --use-hybrid-search --stream
Copy
Ask AI
response = client.rag( "who was aristotle", rag_generation_config={"stream": True}, vector_search_settings={"use_hybrid_search": True},)for chunk in response: print(chunk, end='', flush=True)
<search>["{\"id\":\"808c47c5-ebef-504a-a230-aa9ddcfbd87 .... </search><completion>Aristotle was an Ancient Greek philosopher and polymath born in 384 BC in Stagira, Chalcidice [1], [4]. He was a student of Plato and later became the tutor of Alexander the Great [2]. Aristotle founded the Peripatetic school of philosophy in the Lyceum in Athens and made significant contributions across a broad range of subjects, including natural sciences, philosophy, linguistics, economics, politics, psychology, and the arts [4]. His work laid the groundwork for the development of modern science [4]. Aristotle's influence extended well beyond his time, impacting medieval Islamic and Christian scholars, and his contributions to logic, ethics, and biology were particularly notable [8], [9], [10].</completion>```
Streaming allows the response to be generated and sent in real-time, chunk by chunk.
Customizing RAG
R2R offers extensive customization options for its Retrieval-Augmented Generation (RAG) functionality:
Search Settings: Customize vector and knowledge graph search parameters using VectorSearchSettings and KGSearchSettings.
Generation Config: Fine-tune the language model’s behavior with GenerationConfig, including:
Temperature, top_p, top_k for controlling randomness
Max tokens, model selection, and streaming options
Advanced settings like beam search and sampling strategies
Multiple LLM Support: Easily switch between different language models and providers:
OpenAI models (default)
Anthropic’s Claude models
Local models via Ollama
Any provider supported by LiteLLM
Example of customizing the model:
Copy
Ask AI
r2r rag --query="who was aristotle?" --rag-model="anthropic/claude-3-haiku-20240307" --stream --use-hybrid-search
Copy
Ask AI
r2r rag --query="who was aristotle?" --rag-model="anthropic/claude-3-haiku-20240307" --stream --use-hybrid-search
Copy
Ask AI
# requires ANTHROPIC_API_KEY is setresponse = client.rag( "Who was Aristotle?", rag_generation_config={"model":"anthropic/claude-3-haiku-20240307", "stream": True})for chunk in response: print(chunk, nl=False)
# requires ANTHROPIC_API_KEY is setcurl -X POST http://localhost:7272/v2/rag \ -H "Content-Type: application/json" \ -d '{ "query": "Who is Jon Snow?", "rag_generation_config": { "model": "claude-3-haiku-20240307", "temperature": 0.7 } }'
This flexibility allows you to optimize RAG performance for your specific use case and leverage the strengths of various LLM providers.
Behind the scenes, R2R’s RetrievalService handles RAG requests, combining the power of vector search, optional knowledge graph integration, and language model generation. The flexible architecture allows for easy customization and extension of the RAG pipeline to meet diverse requirements.
R2R provides robust user auth and management capabilities. This section briefly covers user authentication features and how they relate to document management.
curl -X POST http://localhost:7272/v2/logout \ -H "Authorization: Bearer YOUR_ACCESS_TOKEN"
Copy
Ask AI
await client.logout()
Copy
Ask AI
{ 'results': {'message': 'Logged out successfully'}}
These authentication features ensure that users can only access and manage their own documents. When performing operations like search, RAG, or document management, the results are automatically filtered based on the authenticated user’s permissions.
Remember to replace YOUR_ACCESS_TOKEN and YOUR_REFRESH_TOKEN with actual tokens obtained during the login process.
R2R provides robust observability and analytics features, allowing superusers to monitor system performance, track usage patterns, and gain insights into the RAG application’s behavior. These advanced features are crucial for maintaining and optimizing your R2R deployment.
Observability and analytics features are restricted to superusers only. By default, R2R is configured to treat unauthenticated users as superusers for quick testing and development. In a production environment, you should disable this setting and properly manage superuser access.
Users Overview
R2R offers high level user observability for superusers
This summary returns information for each user about their number of files ingested, the total size of user ingested files, and the corresponding document ids.
Logging
R2R automatically logs various events and metrics during its operation. You can access these logs using the logs command:
Perform statistical analysis on various metrics (e.g., search latencies)
Track performance trends over time
Identify potential bottlenecks or areas for optimization
Custom Analytics
R2R’s analytics system is flexible and allows for custom analysis. You can specify different filters and analysis types to focus on specific aspects of your application’s performance. For example:
Analyze RAG latencies
Track usage patterns by user or document type
Monitor error rates and types
Assess the effectiveness of different LLM models or configurations
To perform custom analytics, modify the filters and analysis_types parameters in the analytics command to suit your specific needs.
These observability and analytics features provide valuable insights into your R2R application’s performance and usage, enabling data-driven optimization and decision-making.