Here are your main options for integrating a local LLM into a Shiny app:
Option 1: Python Flask API Backend
This is the most flexible approach. You'll run a Flask server that loads and serves your LLM, then have your Shiny app communicate with it.
Python Flask API (llm_server.py):
from flask import Flask, request, jsonify
from transformers import AutoModelForCausalLM, AutoTokenizer
import torch
app = Flask(__name__)
# Load model once at startup
model_name = "microsoft/phi-2" # Example small model
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForCausalLM.from_pretrained(
model_name,
torch_dtype=torch.float16,
device_map="auto"
)
@app.route('/generate', methods=['POST'])
def generate():
data = request.json
prompt = data.get('prompt', '')
max_length = data.get('max_length', 100)
temperature = data.get('temperature', 0.7)
inputs = tokenizer(prompt, return_tensors="pt")
with torch.no_grad():
outputs = model.generate(
inputs.input_ids,
max_length=max_length,
temperature=temperature,
do_sample=True,
pad_token_id=tokenizer.eos_token_id
)
response = tokenizer.decode(outputs[0], skip_special_tokens=True)
return jsonify({'response': response})
if __name__ == '__main__':
app.run(host='127.0.0.1', port=5000, debug=False)
R Shiny App (app.R):
library(shiny)
library(httr)
library(jsonlite)
ui <- fluidPage(
titlePanel("Local LLM Chat"),
sidebarLayout(
sidebarPanel(
h3("Chat Settings"),
sliderInput("temperature", "Temperature:",
min = 0.1, max = 2.0, value = 0.7, step = 0.1),
sliderInput("max_length", "Max Length:",
min = 50, max = 500, value = 150, step = 50),
hr(),
h4("Model Info"),
textOutput("model_status")
),
mainPanel(
h3("Chat Interface"),
div(id = "chat_history", style = "height: 400px; overflow-y: scroll; border: 1px solid #ddd; padding: 10px;"),
br(),
fluidRow(
column(10,
textAreaInput("user_input", label = NULL,
placeholder = "Type your message here...",
rows = 3, width = "100%")
),
column(2,
actionButton("send_btn", "Send", class = "btn-primary",
style = "margin-top: 20px; width: 100%;")
)
)
)
)
)
server <- function(input, output, session) {
# Check if Flask server is running
output$model_status <- renderText({
tryCatch({
response <- GET("http://127.0.0.1:5000/")
if (status_code(response) == 404) {
"Model server running"
}
}, error = function(e) {
"Model server not connected"
})
})
# Initialize chat history
chat_history <- reactiveVal(character())
# Send message to LLM
observeEvent(input$send_btn, {
req(input$user_input)
# Add user message to chat
current_chat <- chat_history()
user_msg <- paste0("<div style='text-align: right; margin: 10px;'><strong>You:</strong> ",
input$user_input, "</div>")
# Show loading message
loading_msg <- "<div style='text-align: left; margin: 10px;'><strong>Assistant:</strong> <i>Thinking...</i></div>"
updateUI("#chat_history", html = paste0(current_chat, user_msg, loading_msg, collapse = ""))
# Call Flask API
response <- POST(
"http://127.0.0.1:5000/generate",
body = list(
prompt = input$user_input,
temperature = input$temperature,
max_length = input$max_length
),
encode = "json"
)
if (status_code(response) == 200) {
result <- content(response, "parsed")
assistant_msg <- paste0("<div style='text-align: left; margin: 10px; background-color: #f0f0f0; padding: 10px; border-radius: 5px;'><strong>Assistant:</strong> ",
result$response, "</div>")
# Update chat history
new_history <- paste0(current_chat, user_msg, assistant_msg, collapse = "")
chat_history(new_history)
updateUI("#chat_history", html = new_history)
# Scroll to bottom
runjs("document.getElementById('chat_history').scrollTop = document.getElementById('chat_history').scrollHeight;")
} else {
showNotification("Error communicating with model server", type = "error")
}
# Clear input
updateTextAreaInput(session, "user_input", value = "")
})
# Allow Enter key to send
observeEvent(input$user_input, {
if (grepl("\n$", input$user_input)) {
click("send_btn")
}
})
}
# Add this function to update UI elements
updateUI <- function(selector, html) {
runjs(sprintf("$('%s').html('%s');", selector, gsub("'", "\\'", html, fixed = TRUE)))
}
# Include shinyjs for JavaScript operations
library(shinyjs)
ui <- tagList(
useShinyjs(),
ui
)
shinyApp(ui = ui, server = server)
Option 2: Using reticulate (Direct Python Integration)
This approach runs Python directly within R:
library(shiny)
library(reticulate)
# Initialize Python and load model
py_run_string("
from transformers import AutoModelForCausalLM, AutoTokenizer
import torch
model_name = 'microsoft/phi-2'
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForCausalLM.from_pretrained(
model_name,
torch_dtype=torch.float16,
device_map='auto'
)
def generate_text(prompt, max_length=100, temperature=0.7):
inputs = tokenizer(prompt, return_tensors='pt')
with torch.no_grad():
outputs = model.generate(
inputs.input_ids,
max_length=max_length,
temperature=temperature,
do_sample=True,
pad_token_id=tokenizer.eos_token_id
)
return tokenizer.decode(outputs[0], skip_special_tokens=True)
")
ui <- fluidPage(
titlePanel("Local LLM with Reticulate"),
sidebarLayout(
sidebarPanel(
h3("Settings"),
sliderInput("temperature", "Temperature:", 0.1, 2.0, 0.7),
sliderInput("max_length", "Max Length:", 50, 500, 150)
),
mainPanel(
textAreaInput("prompt", "Enter prompt:", rows = 4),
actionButton("generate", "Generate"),
hr(),
h4("Response:"),
verbatimTextOutput("response")
)
)
)
server <- function(input, output, session) {
observeEvent(input$generate, {
showNotification("Generating...", duration = NULL, id = "gen_notif")
response <- py$generate_text(
input$prompt,
max_length = input$max_length,
temperature = input$temperature
)
output$response <- renderText(response)
removeNotification("gen_notif")
})
}
shinyApp(ui = ui, server = server)
Option 3: Using Ollama (Recommended for ease)
If you're open to using Ollama for local model management:
library(shiny)
library(httr)
library(jsonlite)
ui <- fluidPage(
titlePanel("Ollama Local LLM"),
sidebarLayout(
sidebarPanel(
h3("Model Settings"),
selectInput("model", "Select Model:",
choices = c("llama2", "mistral", "phi"),
selected = "llama2"),
sliderInput("temperature", "Temperature:", 0.1, 2.0, 0.7)
),
mainPanel(
textAreaInput("prompt", "Prompt:", rows = 4),
actionButton("generate", "Generate"),
hr(),
verbatimTextOutput("response")
)
)
)
server <- function(input, output, session) {
observeEvent(input$generate, {
response <- POST(
"http://localhost:11434/api/generate",
body = list(
model = input$model,
prompt = input$prompt,
temperature = input$temperature,
stream = FALSE
),
encode = "json"
)
if (status_code(response) == 200) {
result <- content(response, "parsed")
output$response <- renderText(result$response)
}
})
}
shinyApp(ui = ui, server = server)
Setup Instructions:
For Flask approach:
- Install Python dependencies:
pip install flask transformers torch
- Run Flask server:
python llm_server.py
- Run Shiny app:
shiny::runApp()
For reticulate approach:
- Install reticulate:
install.packages("reticulate")
- Install Python dependencies:
reticulate::py_install(c("transformers", "torch"))
- Run the Shiny app directly
For Ollama approach:
- Install Ollama from ollama.ai
- Pull a model:
ollama pull llama2
- Run the Shiny app
The Flask approach gives you the most flexibility and better performance for production use, while reticulate is simpler for development but may have memory management challenges with large models.