Learn how to build webapps powered by RAG using R2R
Web developers can easily integrate R2R into their projects using the R2R JavaScript client.
For more extensive reference and examples of how to use the r2r-js library, we encourage you to look at the R2R Application and its source code.
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:
First, we create the R2R client and specify the base URL where the R2R server is running:
const{ r2rClient }=require("r2r-js");// http://localhost:7272 or the address that you are running the R2R serverconst client =newr2rClient("http://localhost:7272");
This command processes the ingested, splits them into chunks, embeds the chunks, and stores them into your specified Postgres database. Relational data is also stored to allow for downstream document management, which you can read about in the quickstart.
console.log("Performing RAG...");const ragResponse =await client.rag({query:"What does the file talk about?",rag_generation_config:{model:"openai/gpt-4o",temperature:0.0,stream:false,},});console.log("Search Results:"); ragResponse.results.search_results.vector_search_results.forEach((result, index)=>{console.log(`\nResult ${index +1}:`);console.log(`Text: ${result.metadata.text.substring(0,100)}...`);console.log(`Score: ${result.score}`);},);console.log("\nCompletion:");console.log(ragResponse.results.completion.choices[0].message.content);.../* Performing RAG...SearchResults:Result1:Text: praeterire culinam eius, cuius ianua semper aperta erat, cogebatur.Et quoties praeteribat,iuvenis ...Score:0.08281802143835804Result2:Text:In vespera praecipue calida ineunte Iulio iuvenis e cenaculo in quo hospitabatur inS.loco exiit et...Score:0.052743945852283036Completion:The file discusses the experiences and emotions of a young man who is staying in a small room in a tall house.He is burdened by debt and feels anxious and ashamed whenever he passes by the kitchen of his landlady, whosedoor is always open [1].On a particularly warm evening in early July, he leaves his room and walks slowly towardsa bridge, trying to avoid encountering his landlady on the stairs.His room, which is more like a closet than aproper room, is located under the roof of the five-story house,while the landlady lives on the floor below andprovides him with meals and services [2].*/
Next, create a React component to interact with the API. Here’s an example index.tsx file:
importReact,{ useState }from'react';importstylesfrom'@/styles/R2RWebDevTemplate.module.css';constR2RQueryApp:React.FC=()=>{const[query, setQuery]=useState('');const[result, setResult]=useState('');const[isLoading, setIsLoading]=useState(false);constperformQuery=async()=>{setIsLoading(true);setResult('');try{const response =awaitfetch('/api/r2r-query',{ method:'POST', headers:{'Content-Type':'application/json',}, body:JSON.stringify({ query }),});if(!response.ok){thrownewError('Network response was not ok');}const data =await response.json();setResult(data.result);}catch(error){setResult(`Error: ${error instanceofError? error.message :String(error)}`);}finally{setIsLoading(false);}};return(<divclassName={styles.appWrapper}><h1className={styles.title}>R2R Web Dev Template</h1><p>A simple template for making RAG queries with R2R.Make sure that your R2R server is up and running, and that you've ingested files!</p><p>Check out the <ahref="https://r2r-docs.sciphi.ai/"target="_blank"rel="noopener noreferrer">R2R Documentation</a>for more information.</p><input type="text" value={query} onChange={(e)=>setQuery(e.target.value)} placeholder="Enter your query here" className={styles.queryInput}/><button onClick={performQuery} disabled={isLoading} className={styles.submitButton}>SubmitQuery</button>{isLoading ?(<divclassName={styles.spinner}/>):(<divclassName={styles.resultDisplay}>{result}</div>)}</div>);};exportdefaultR2RQueryApp;
This component creates a simple interface with an input field for the query and a button to submit it. When the button is clicked, it sends a request to the API route we created earlier and displays the result.
For a complete working example, you can check out our template repository. This repository contains a simple Next.js app with R2R integration, providing a starting point for your own R2R-powered web applications.
This template provides a foundation for building more complex applications with R2R, demonstrating how to integrate R2R’s powerful RAG capabilities into a web interface.