Walkthrough

A detailed step-by-step cookbook of the core features provided by R2R.

This guide shows how to use R2R to:

  1. Ingest files into R2R
  2. Search over ingested files
  3. Use your data as input to RAG (Retrieval-Augmented Generation)
  4. Extract entities and relationships from your data to create a graph.
  5. Perform basic user auth
  6. Observe and analyze an R2R deployment

Introduction

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.

Hello R2R

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
1from r2r import R2RClient
2
3client = R2RClient()
4
5with open("test.txt", "w") as file:
6 file.write("John is a person that works at Google.")
7
8client.documents.create(file_path="test.txt")
9
10# Call RAG directly
11rag_response = client.retrieval.rag(
12 query="Who is john",
13 rag_generation_config={"model": "openai/gpt-4o-mini", "temperature": 0.0},
14)
15results = rag_response["results"]
16
17print(f"Search Results:\n{results['search_results']}")
18# {'chunk_search_results': [{'chunk_id': 'b9f40dbd-2c8e-5c0a-8454-027ac45cb0ed', 'document_id': '7c319fbe-ca61-5770-bae2-c3d0eaa8f45c', 'user_id': '2acb499e-8428-543b-bd85-0d9098718220', 'collection_ids': ['122fdf6a-e116-546b-a8f6-e4cb2e2c0a09'], 'score': 0.6847735847465275, 'text': 'John is a person that works at Google.', 'metadata': {'version': 'v0', 'chunk_order': 0, 'document_type': 'txt', 'associated_query': 'Who is john'}}], 'kg_search_results': []}
19
20print(f"Completion:\n{results['completion']}")
21# {'id': 'chatcmpl-AV1Sc9DORfHvq7yrmukxfJPDV5dCB', 'choices': [{'finish_reason': 'stop', 'index': 0, 'logprobs': None, 'message': {'content': 'John is a person that works at Google [1].', 'refusal': None, 'role': 'assistant', 'audio': None, 'function_call': None, 'tool_calls': None}}], 'created': 1731957146, 'model': 'gpt-4o-mini', 'object': 'chat.completion', 'service_tier': None, 'system_fingerprint': 'fp_04751d0b65', 'usage': {'completion_tokens': 11, 'prompt_tokens': 145, 'total_tokens': 156, 'completion_tokens_details': None, 'prompt_tokens_details': None}}

Document Ingestion and Management

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, with corresponding id, created for each ingested file or context, which contains the downstream Chunks and Entities & Relationships.
  • User and Collection objects for comprehensive document permissions.
  • Graph, construction and maintenance.
  • Flexible document deletion and update mechanisms at global document and chunk levels.
Note, all document related commands are gated to documents the user has uploaded or has access to through shared collections, with the exception of superusers.

R2R offers a powerful data ingestion process that handles various file types including html, pdf, png, mp3, and txt.

The ingestion process parses, chunks, embeds, and stores documents efficiently. A durable orchestration workflow coordinates the entire process.

$# r2r set-api-base https://api.cloud.sciphi.ai ### for self-hosted deployment
># r2r set-api-key sk_..... ### for authenticated deployments, e.g. SciPhi Cloud
>r2r documents create-samples

This command initiates the ingestion process, producing output similar to:

$[{'message': 'Ingestion task queued successfully.', 'task_id': '6e27dfca-606d-422d-b73f-2d9e138661b4', 'document_id': '28a7266e-6cee-5dd2-b7fa-e4fc8f2b49c6'}, {'message': 'Ingestion task queued successfully.', 'task_id': 'd37deef1-af08-4576-bd79-6d2a7fb6ec33', 'document_id': '2c91b66f-e960-5ff5-a482-6dd0a523d6a1'}, {'message': 'Ingestion task queued successfully.', 'task_id': '4c1240f0-0692-4b67-8d2b-1428f71ea9bc', 'document_id': '638f0ed6-e0dc-5f86-9282-1f7f5243d9fa'}, {'message': 'Ingestion task queued successfully.', 'task_id': '369abcea-79a2-480c-9ade-bbc89f5c500e', 'document_id': 'f25fd516-5cac-5c09-b120-0fc841270c7e'}, {'message': 'Ingestion task queued successfully.', 'task_id': '7c99c168-97ee-4253-8a6f-694437f3e5cb', 'document_id': '77f67c65-6406-5076-8176-3844f3ef3688'}, {'message': 'Ingestion task queued successfully.', 'task_id': '9a6f94b0-8fbc-4507-9435-53e0973aaad0', 'document_id': '9fbe403b-c11c-5aae-8ade-ef22980c3ad1'}, {'message': 'Ingestion task queued successfully.', 'task_id': '61d0e2e0-45ec-43db-9837-ff4da5166ee9', 'document_id': '0032a7a7-cb2a-5d08-bfc1-93d3b760deb4'}, {'message': 'Ingestion task queued successfully.', 'task_id': '1479390e-c295-47b0-a570-370b05b86c8b', 'document_id': 'f55616fb-7d48-53d5-89c2-15d7b8e3834c'}, {'message': 'Ingestion task queued successfully.', 'task_id': '92f73a07-2286-4c42-ac02-d3eba0f252e0', 'document_id': '916b0ed7-8440-566f-98cf-ed7c0f5dba9b'}]

Key features of the ingestion process:

  1. Unique document_id generation for each file
  2. Metadata association, including user_id and collection_ids for document management
  3. Efficient parsing, chunking, and embedding of diverse file types

R2R allows retrieval of high-level document information stored in a relational table within the Postgres database. To fetch this information:

$r2r documents list

This command returns document metadata, including:

$[
> {
> 'id': '9fbe403b-c11c-5aae-8ade-ef22980c3ad1',
> 'title': 'aristotle.txt',
> 'user_id': '2acb499e-8428-543b-bd85-0d9098718220',
> 'type': 'txt',
> 'created_at': '2024-09-06T03:32:02.991742Z',
> 'updated_at': '2024-09-06T03:32:02.991744Z',
> 'ingestion_status': 'success',
> 'restructuring_status': 'pending',
> 'version': 'v0',
> 'collection_ids': ['122fdf6a-e116-546b-a8f6-e4cb2e2c0a09'],
> 'metadata': {'title': 'aristotle.txt', 'version': 'v0'}
> }
> ...
>]

This overview provides quick access to document versions, sizes, and associated metadata, facilitating efficient document management.

R2R enables retrieval of specific document chunks and associated metadata. To fetch chunks for a particular document by id:

$r2r documents list-chunks 9fbe403b-c11c-5aae-8ade-ef22980c3ad1

This command returns detailed chunk information:

$[
> {
> '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.

R2R supports flexible document deletion through a method that can run arbitrary deletion filters. To delete a document by its ID:

$r2r documents delete 9fbe403b-c11c-5aae-8ade-ef22980c3ad1

This command produces output similar to:

${"results": {"success": True}}

Key features of the deletion process:

  1. Deletion by document ID,
  2. Cascading deletion of associated chunks and metadata
  3. Deletion by filter, e.g. by text match, user id match, or other with documents/by-filter.

This flexible deletion mechanism ensures precise control over document management within the R2R system.

For more advanced document management techniques and user authentication details, refer to the user documentation.

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 parameters inside of R2R can be fine-tuned at runtime for optimal results. Here’s how to perform a basic vector search:

1r2r retrieval search --query="What was Uber's profit in 2020?"
1{ 'results':
2 {'chunk_search_results':
3 [
4 {
5 'fragment_id': 'ab6d0830-6101-51ea-921e-364984bfd177',
6 'extraction_id': '429976dd-4350-5033-b06d-8ffb67d7e8c8',
7 'document_id': '26e0b128-3043-5674-af22-a6f7b0e54769',
8 'user_id': '2acb499e-8428-543b-bd85-0d9098718220',
9 'collection_ids': [],
10 'score': 0.285747126074015,
11 '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',
12 'metadata': {'title': 'uber_2021.pdf', 'version': 'v0', 'chunk_order': 5, 'associatedQuery': "What was Uber's profit in 2020?"}
13 },
14 ...
15 ]
16 }
17}

Key configurable parameters for vector search can be inferred from the retrieval API reference.

R2R supports hybrid search, which combines traditional keyword-based search with vector search for improved results. Here’s how to perform a hybrid search:

1r2r retrieval search --query="What was Uber's profit in 2020?" --use-hybrid-search=True

Retrieval-Augmented Generation (RAG)

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.

To generate a response using RAG, use the following command:

$r2r retrieval rag --query="What was Uber's profit in 2020?"

Example Output:

${'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.

R2R also supports streaming RAG responses, which can be useful for real-time applications. To use streaming RAG:

$r2r retrieval rag --query="who was aristotle" --use-hybrid-search=True --stream

Example Output:

$<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.

R2R offers extensive customization options for its Retrieval-Augmented Generation (RAG) functionality:

  1. Search Settings: Customize vector and knowledge graph search parameters using VectorSearchSettings and KGSearchSettings.

  2. 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
  3. 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:

$r2r retrieval rag --query="who was aristotle?" --rag-model="anthropic/claude-3-haiku-20240307" --stream --use-hybrid-search=True

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.

Graphs in R2R

R2R implements a Git-like model for knowledge graphs, where each collection has a corresponding graph that can diverge and be independently managed. This approach allows for flexible knowledge management while maintaining data consistency.

Graph-Collection Relationship

  • Each collection has an associated graph that acts similar to a Git branch
  • Graphs can diverge from their underlying collections through independent updates
  • The pull operation syncs the graph with its collection, similar to a Git pull
  • This model enables experimental graph modifications without affecting the base collection

Knowledge Graph Workflow

Extract entities and relationships from the previously ingested document:

$# default document id for default user and sample document
>document_id=9fbe403b-c11c-5aae-8ade-ef22980c3ad1
>
>r2r documents extract $document_id
>
># wait for extraction to complete, you can poll `r2r documents list` and track `extraction_status`
>r2r documents list-entities $document_id
>r2r documents list-relationships $document_id

This step processes the document to identify entities and their relationships.

Sync the graph with the collection and view extracted knowledge:

$# default collection id for default user
>collection_id=122fdf6a-e116-546b-a8f6-e4cb2e2c0a09
>
># Sync graph with collection
>r2r graphs pull $collection_id
>
># View extracted knowledge
>r2r graphs list-entities $collection_id
>r2r graphs list-relationships $collection_id

Build and list graph communities:

$# Build graph communities
>r2r graphs build $collection_id --settings '{}'
>
># List communities
>r2r graphs list-communities $collection_id

Reset the graph to a clean state:

$r2r graphs reset $collection_id

Best Practices

  1. Graph Synchronization

    • Always pull before attempting to list or work with entities
    • Keep track of which documents have been added to the graph
  2. Community Management

    • Build communities after significant changes to the graph
    • Use community information to enhance search results
  3. Version Control

    • Treat graphs like Git branches - experiment freely
    • Use reset to start fresh if needed
    • Maintain documentation of graph modifications

This Git-like model provides a flexible framework for knowledge management while maintaining data consistency and enabling experimental modifications.

User Management

R2R provides robust user auth and management capabilities. This section briefly covers user authentication features and how they relate to document management.

To register a new user:

1from r2r import R2RClient
2
3client = R2RClient()
4register_response = client.users.register("[email protected]", "password123")
5print(f"Registration response: {register_response}")

Example output:

${
> 'results': {
> 'email': '[email protected]',
> 'id': '60af344f-7bd2-43c9-98fd-da53fe5e6d05',
> 'is_superuser': False,
> 'is_active': True,
> 'is_verified': False,
> 'verification_code_expiry': None,
> 'name': None,
> 'bio': None,
> 'profile_picture': None,
> 'created_at': '2024-07-16T21:50:57.017675Z', 'updated_at': '2024-07-16T21:50:57.017675Z'
> }
>}

After registration, users need to verify their email:

1verify_response = client.users.verify_email("123456") # Verification code sent to email
2print(f"Email verification response: {verify_response}")

To log in and obtain access tokens:

1login_response = client.users.login("[email protected]", "password123")
2print(f"Login response: {login_response}")
$# Note, verification is False in default settings
>Registration response: {
> 'results': {
> 'access_token': {
> 'token': 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ0ZXN0cXFAZXhhbXBsZS5jb20iLCJleHAiOjE3MjExOTU3NDQuNzQ1MTM0LCJ0b2tlbl90eXBlIjoiYWNjZXNzIn0.-HrQlguPW4EmPupOYyn5793luaDb-YhEpEsIyQ2CbLs',
> 'token_type': 'access'
> },
> 'refresh_token': {
> 'token': 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ0ZXN0cXFAZXhhbXBsZS5jb20iLCJleHAiOjE3MjE3NzE3NDQsInRva2VuX3R5cGUiOiJyZWZyZXNoIn0.auuux_0Gg6_b5gTlUOQVCcdPuZl0eM-NFlC1OHdBqiE',
> 'token_type': 'refresh'
> }
> }
>}

To refresh an expired access token:

1# requires client.users.login(...)
2refresh_response = client.users.refresh_access_token()["results"]
3print(f"Token refresh response: {refresh_response}")
$Token refresh response:
>{
> 'access_token': {
> 'token': 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ0ZXN0cXFAZXhhbXBsZS5jb20iLCJleHAiOjE3MjExOTU5NTYuODEzNDg0LCJ0b2tlbl90eXBlIjoiYWNjZXNzIn0.-CJy_cH7DRH5FKpZZauAFPP4mncnSa1j8NnaM7utGHo',
> 'token_type': 'access'
> },
> 'refresh_token': {
> 'token': 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ0ZXN0cXFAZXhhbXBsZS5jb20iLCJleHAiOjE3MjE3NzE5NTYsInRva2VuX3R5cGUiOiJyZWZyZXNoIn0.uGsgTYaUd3Mn5h24uE4ydCWhOr2vFNA9ziRAAaYgnfk',
> 'token_type': 'refresh'
> }
>}

To log out and invalidate the current access token:

1# requires client.users.login(...)
2logout_response = client.users.logout()
3print(f"Logout response: {logout_response}")
${
> '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.

Observability and Analytics

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.

R2R offers high level user observability for superusers

$r2r users list

This command returns detailed log user information, here’s some example output:

${'results': [{'user_id': '2acb499e-8428-543b-bd85-0d9098718220', 'num_files': 9, 'total_size_in_bytes': 4027056, 'document_ids': ['9fbe403b-c11c-5aae-8ade-ef22980c3ad1', 'e0fc8bbc-95be-5a98-891f-c17a43fa2c3d', 'cafdf784-a1dc-5103-8098-5b0a97db1707', 'b21a46a4-2906-5550-9529-087697da2944', '9fbe403b-c11c-5aae-8ade-ef22980c3ad1', 'f17eac52-a22e-5c75-af8f-0b25b82d43f8', '022fdff4-f87d-5b0c-82e4-95d53bcc4e60', 'c5b31b3a-06d2-553e-ac3e-47c56139b484', 'e0c2de57-171d-5385-8081-b546a2c63ce3']}, ...]}}

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.

R2R automatically logs various events and metrics during its operation. You can access these logs using the logs command:

$r2r system logs

This command returns detailed log entries for various operations, including search and RAG requests. Here’s an example of a log entry:

1{
2 'run_id': UUID('27f124ad-6f70-4641-89ab-f346dc9d1c2f'),
3 'run_type': 'rag',
4 'entries': [
5 {'key': 'search_results', 'value': '["{\\"id\\":\\"7ed3a01c-88dc-5a58-a68b-6e5d9f292df2\\",...}"]'},
6 {'key': 'search_query', 'value': 'Who is aristotle?'},
7 {'key': 'rag_generation_latency', 'value': '3.79'},
8 {'key': 'llm_response', 'value': 'Aristotle (Greek: Ἀριστοτέλης Aristotélēs; 384–322 BC) was...'}
9 ]
10}

These logs provide detailed information about each operation, including search results, queries, latencies, and LLM responses.

These observability and analytics features provide valuable insights into your R2R application’s performance and usage, enabling data-driven optimization and decision-making.

Next Steps

Now that you have a basic understanding of R2R’s core features, you can explore more advanced topics:

Built with