Adding RAG (Retrieval-Augmented Generation) to Your Shiny App with Local LLM
To implement RAG with your local LLM in Shiny, where the model can answer questions about a displayed data table, you'll need to:
- Store your data in a retrievable format
- Implement a retrieval mechanism
- Augment prompts with relevant context
- Display the results in your UI
Here's a complete implementation:
Option 1: Pure R Implementation with llama2.r
library(shiny)
library(llama2.r)
library(dplyr)
library(DT) # For interactive tables
library(stringr)
# Sample data - replace with your actual data
create_sample_data <- function() {
data.frame(
id = 1:10,
name = c("Product A", "Product B", "Product C", "Product D", "Product E",
"Product F", "Product G", "Product H", "Product I", "Product J"),
category = c("Electronics", "Clothing", "Electronics", "Home", "Clothing",
"Electronics", "Home", "Clothing", "Electronics", "Home"),
price = c(199.99, 29.99, 149.99, 49.99, 39.99, 249.99, 79.99, 19.99, 129.99, 89.99),
stock = c(45, 120, 33, 87, 92, 15, 64, 145, 28, 56)
)
}
# Initialize the LLM model
init_llama <- function() {
# Set the path to your model files
model_path <- "path/to/your/llama-model" # Update this path
# Initialize the model
llama <- Llama$new(
model_path = model_path,
n_ctx = 1024, # Larger context window for RAG
n_threads = 4
)
return(llama)
}
# Function to retrieve relevant data based on question
retrieve_context <- function(question, data) {
# Simple keyword-based retrieval (you could implement more sophisticated methods)
keywords <- str_split(tolower(question), "\\W+")[[1]]
keywords <- keywords[keywords != ""]
# Convert data to text for similarity comparison
data_text <- apply(data, 1, function(row) {
paste(names(row), row, collapse = " ", sep = ": ")
})
# Simple scoring based on keyword matches
scores <- sapply(data_text, function(text) {
sum(sapply(keywords, function(kw) grepl(kw, tolower(text))))
})
# Get top 3 most relevant rows
top_indices <- order(scores, decreasing = TRUE)[1:3]
relevant_data <- data[top_indices, ]
# Format the context for the LLM
context <- paste("Relevant data:\n", paste(
apply(relevant_data, 1, function(row) {
paste(names(row), row, collapse = ", ", sep = ": ")
}),
collapse = "\n"
))
return(context)
}
ui <- fluidPage(
titlePanel("RAG with Local LLM"),
sidebarLayout(
sidebarPanel(
textInput("question", "Ask a question about the data:", ""),
actionButton("submit", "Submit"),
width = 4
),
mainPanel(
tabsetPanel(
tabPanel("Data Table", DTOutput("data_table")),
tabPanel("LLM Response", verbatimTextOutput("response"))
)
)
)
)
server <- function(input, output) {
# Load data
data <- reactive(create_sample_data())
# Initialize the model
llama <- init_llama()
# Display the data table
output$data_table <- renderDT({
datatable(data())
})
output$response <- renderPrint({
req(input$submit)
question <- input$question
current_data <- data()
# Retrieve relevant context
context <- retrieve_context(question, current_data)
# Create the augmented prompt
prompt <- paste(
"You are a helpful assistant that answers questions about product data.\n",
"Use the following context to answer the question. If you don't know the answer, say you don't know.\n",
context, "\n\n",
"Question: ", question, "\n",
"Answer:"
)
# Generate response from the LLM
response <- llama$prompt(prompt)
# Print the response
cat("LLM Response:\n")
cat(response)
})
}
shinyApp(ui, server)