R Integration
Native R package for data science and statistical computing with AI agents.
Overview
The archiar package provides idiomatic R bindings to the Archia engine, enabling data scientists to integrate AI
agents directly into their analytical workflows. Built with extendr, it offers seamless integration with the R
ecosystem.
Key Features:
- Native R6 class interface
- Compatible with tidyverse workflows
- Automatic memory management
- RStudio integration
- Support for R 3.6+
Quick Start
Basic Example
library(archiar)
# Create engine
engine <- Engine$new()
# Start a chat session
chat_id <- engine$new_chat("You are a helpful data science assistant")
# Send a message
engine$send(
chat_id = chat_id,
model = "claude-sonnet-4-5-20250929",
message = "Explain PCA in simple terms"
)
# Wait for response
engine$wait_on(chat_id)
# Get the response
response <- engine$chat_message(chat_id, engine$chat_len(chat_id) - 1)
print(response)
Data Analysis Integration
Working with Data Frames
library(archiar)
library(tidyverse)
# Initialize engine
engine <- Engine$new()
# Create analyst agent
analyst <- engine$new_chat(
"You are a data analyst expert in R and tidyverse.
Help analyze data and suggest visualizations."
)
# Load your data
data(mtcars)
# Get analysis suggestions
engine$send(
analyst,
"gpt-4",
paste0(
"I have the mtcars dataset with these columns: ",
paste(names(mtcars), collapse = ", "),
". What interesting analyses would you recommend?"
)
)
engine$wait_on(analyst)
analysis_plan <- engine$chat_message(analyst, -1) # Get last message
# Get code generation
engine$send(
analyst,
"gpt-4",
"Generate R code to create a correlation heatmap of mtcars"
)
engine$wait_on(analyst)
code <- engine$chat_message(analyst, -1)
# Execute generated code (with caution)
# eval(parse(text = code))
Statistical Analysis Assistant
library(archiar)
# Create statistics expert
engine <- Engine$new()
stats_expert <- engine$new_chat(
"You are a statistics expert. Provide rigorous statistical advice."
)
# Get help with analysis
engine$send(
stats_expert,
"claude-3-5-sonnet",
"I have experimental data with 3 treatment groups and want to test
for differences. Sample sizes are 15, 18, and 14. The data appears
slightly skewed. What test should I use?"
)
engine$wait_on(stats_expert)
advice <- engine$chat_message(stats_expert, -1)
cat(advice)
Advanced Features
Using MCP Servers
library(archiar)
library(DBI)
# Initialize with database MCP
engine <- Engine$new()
# Add database MCP server
engine$add_mcp(
name = "analytics_db",
cmd = "mcp-sqlite",
args = c("analytics.db"),
env = list(
LOG_LEVEL = "info"
)
)
# Create agent with database access
db_analyst <- engine$new_chat(
system_prompt = "You are a SQL expert with access to the analytics database.",
mcps = c("analytics_db")
)
# Query through natural language
engine$send(
db_analyst,
"claude-3-5-sonnet",
"Show me monthly revenue trends for the last year"
)
engine$wait_on(db_analyst)
results <- engine$chat_message(db_analyst, -1)
Parallel Processing
library(archiar)
library(parallel)
engine <- Engine$new()
# Function to process with AI
process_with_ai <- function(data_chunk, engine) {
chat_id <- engine$new_chat("You are a data processor")
engine$send(
chat_id,
"gpt-4",
sprintf("Process this data: %s", jsonlite::toJSON(data_chunk))
)
engine$wait_on(chat_id)
engine$chat_message(chat_id, -1)
}
# Split data for parallel processing
data_chunks <- split(iris, cut(seq_along(iris$Species), 4))
# Process in parallel
results <- mclapply(
data_chunks,
function(chunk) process_with_ai(chunk, engine),
mc.cores = 4
)
RStudio Integration
Addins
The archiar package includes RStudio addins for common tasks:
- Insert Code: Generate code snippets with AI
- Explain Selection: Get explanations for selected code
- Debug Helper: Analyze error messages
- Document Function: Generate roxygen documentation
Using Addins
# Select code in RStudio, then:
# Addins -> archiar -> Explain Selection
# Or bind to keyboard shortcuts in:
# Tools -> Modify Keyboard Shortcuts
Custom Addin Example
#' Generate ggplot2 code
#'
#' @export
generate_plot <- function() {
context <- rstudioapi::getActiveDocumentContext()
engine <- archiar::Engine$new()
chat <- engine$new_chat("You are a ggplot2 expert")
engine$send(
chat,
"claude-3-5-sonnet",
"Generate a beautiful ggplot2 visualization for the mtcars dataset"
)
engine$wait_on(chat)
code <- engine$chat_message(chat, -1)
rstudioapi::insertText(code)
}
Shiny Integration
Build interactive AI-powered applications:
library(shiny)
library(archiar)
ui <- fluidPage(
titlePanel("AI Data Analyst"),
sidebarLayout(
sidebarPanel(
textAreaInput("question", "Ask a question:", rows = 3),
selectInput("model", "Model:",
choices = c("claude-3-5-sonnet", "gpt-4", "gpt-3.5-turbo")),
actionButton("submit", "Ask")
),
mainPanel(
verbatimTextOutput("response")
)
)
)
server <- function(input, output, session) {
engine <- Engine$new()
chat_id <- engine$new_chat("You are a helpful data analyst")
observeEvent(input$submit, {
engine$send(
chat_id,
input$model,
input$question
)
engine$wait_on(chat_id)
output$response <- renderText({
engine$chat_message(chat_id, -1)
})
})
}
shinyApp(ui, server)
Error Handling
library(archiar)
safe_send <- function(engine, chat_id, model, message) {
tryCatch({
engine$send(chat_id, model, message)
engine$wait_on(chat_id)
engine$chat_message(chat_id, -1)
},
error = function(e) {
warning("AI request failed: ", e$message)
return(NA)
})
}
# Use safely
engine <- Engine$new()
chat <- engine$new_chat("Assistant")
response <- safe_send(engine, chat, "gpt-4", "Hello")
Performance Optimization
Caching Responses
library(archiar)
library(memoise)
# Create cached query function
cached_query <- memoise(function(prompt, model = "claude-3-5-haiku") {
engine <- Engine$new()
chat <- engine$new_chat("Assistant")
engine$send(chat, model, prompt)
engine$wait_on(chat)
engine$chat_message(chat, -1)
})
# First call - hits API
result1 <- cached_query("What is machine learning?")
# Second call - returns cached result instantly
result2 <- cached_query("What is machine learning?")
Batch Processing
library(archiar)
library(purrr)
engine <- Engine$new()
# Process multiple queries efficiently
queries <- list(
"Explain correlation",
"What is regression?",
"Define p-value"
)
# Create chats for all queries
chats <- map(queries, ~ {
chat_id <- engine$new_chat("Statistics tutor")
list(chat_id = chat_id, query = .x)
})
# Send all queries
walk(chats, ~ engine$send(.x$chat_id, "gpt-3.5-turbo", .x$query))
# Wait for all
walk(chats, ~ engine$wait_on(.x$chat_id))
# Collect results
results <- map(chats, ~ {
engine$chat_message(.x$chat_id, -1)
})
Configuration
Setting Defaults
# Set in .Rprofile or script
options(
archiar.default_model = "claude-haiku-4-5-20251001",
archiar.timeout = 60,
archiar.max_retries = 3
)
Environment Variables
# Set API keys and configuration
Sys.setenv(
ANTHROPIC_API_KEY = "your-key",
OPENAI_API_KEY = "your-key"
)
Common Patterns
Report Generation
generate_report <- function(data, engine) {
analyst <- engine$new_chat(
"You are a report writer. Create professional statistical reports."
)
summary_stats <- summary(data)
prompt <- sprintf(
"Create an executive summary for this dataset:\n%s\n
Include key findings and recommendations.",
capture.output(print(summary_stats))
)
engine$send(analyst, "gpt-4", prompt)
engine$wait_on(analyst)
engine$chat_message(analyst, -1)
}
Code Review
review_code <- function(code_string, engine) {
reviewer <- engine$new_chat(
"You are an R expert. Review code for best practices and bugs."
)
engine$send(
reviewer,
"claude-3-5-sonnet",
paste("Review this R code:\n```r\n", code_string, "\n```")
)
engine$wait_on(reviewer)
engine$chat_message(reviewer, -1)
}
Troubleshooting
Common Issues
Installation fails:
# Ensure Rust is installed
# Install system dependencies
install.packages("archiar", type = "source")
Memory issues:
# Explicitly clean up
rm(engine)
gc()
Timeout errors:
# Increase timeout
options(archiar.timeout = 120)
Examples
Coming soon.