Site icon R-bloggers

LLM-driven optimisation modelling in R

[This article was first published on R'tichoke, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

When defining an optimisation problem, LLMs can be used as a translation layer. The solver is the calculator that does the actual work and makes no mistakes. The translator, however, could mistranslate occasionally. Still, as long as the problem is specified well and translated correctly, the results are deterministic and reproducible.

This post focuses on building the whole chain in R:

  1. Describe a credit risk problem statement in plain English
  2. Let an LLM (via ellmer) translate the problem into ompr
  3. Solve it with ompr.roi + GLPK
  4. Wrap it all in a reusable nl_to_opt() helper that re-prompts the LLM when the solver complains
  5. Check the answer with LLM-generated controls
Note

The post uses OpenRouter as the LLM provider. To run the code in this post, create an OpenRouter key and set it as the OPENROUTER_API_KEY environment variable (for example in your .Renviron).

< section id="required-packages" class="level2">

Required Packages

# install.packages(c("ellmer", "ompr", "ompr.roi", "ROI", "ROI.plugin.glpk", "dplyr"))
library(ellmer)
library(ompr)
library(ompr.roi)
library(ROI.plugin.glpk)
library(dplyr)
< section id="the-business-problem" class="level2">

The Business Problem

Suppose we want to decide how much credit exposure to allocate to each risk grade. The sample dataset has seven risk grades and the problem can be specified in English as:

“We have a budget of $20 million to lend. Allocate exposure across the seven risk grades to maximise expected profit. Expected loss must stay under 6% of total exposure. No grade may hold more than 30% of total exposure. Do not lend more to a grade than its observed demand.”

First, let’s turn the loan-level data into a small segment table; the LLM only receives a description of its columns.

# Sample dataset
credit <- read.csv("https://bit.ly/42ypcnJ")

seg <- credit |>
  group_by(grade) |>
  summarise(
    n      = n(),
    pd     = mean(bad_flag),          # observed default rate
    rate   = mean(int_rate) / 100,    # average interest rate as a decimal
    demand = sum(loan_amnt),          # total $ requested in the sample
    .groups = "drop"
  ) |>
  mutate(
    lgd = 0.6,                        # assumed loss given default
    profit_per_dollar = (1 - pd) * rate - pd * lgd,
    loss_per_dollar   = pd * lgd
  )

print(seg)
# A tibble: 7 × 8
  grade     n     pd   rate   demand   lgd profit_per_dollar loss_per_dollar
  <chr> <int>  <dbl>  <dbl>    <int> <dbl>             <dbl>           <dbl>
1 A      1882 0.0361 0.0708 27887875   0.6           0.0465           0.0217
2 B      3057 0.0782 0.107  43993175   0.6           0.0516           0.0469
3 C      2805 0.133  0.142  42971225   0.6           0.0431           0.0798
4 D      1435 0.179  0.182  22352850   0.6           0.0416           0.107 
5 E       590 0.244  0.220  10115800   0.6           0.0196           0.146 
6 F       182 0.357  0.259   3374775   0.6          -0.0481           0.214 
7 G        49 0.327  0.280    907975   0.6          -0.00752          0.196 
< section id="llm-call-to-generate-the-model-specification" class="level2">

LLM call to generate the model specification

A good prompt does three things – it describes the data, pins down the output format, and states the rules of the road (variable names, solver, units). Here, instead of using ellmer’s structured output, we’ll ask for a plain text reply.

prompt <- "
You are an expert in operations research who writes R code using the `ompr` package.

You will be given a business problem and a data frame called `seg` with these columns:
- grade: segment name
- pd: probability of default (0 to 1)
- rate: interest rate as a decimal (0.12 = 12%)
- demand: maximum dollars that can be lent to the segment
- profit_per_dollar: expected profit per $1 lent
- loss_per_dollar: expected loss per $1 lent

Rules:
- Return only R code, no explanations and no library() calls.
- Build the model with `model <- MIPModel() |> ...` and assign it to an object called `model`.
- Do not call solve_model() or print anything. Just build `model`.
- Use one continuous, non-negative variable x[i] per row of `seg` (dollars lent).
- Every constraint must be linear.
- Refer to columns as seg$column_name[i] (bare column names will not be found). Do not hard-code numbers from the data.
- Write sums with sum_over()
- Scalar inputs (such as the budget) are in a list called `params`.
"

# Function to talk to an existing agent
ask_llm <- function(chat, prompt) {
  reply <- as.character(chat$chat(prompt, echo = "none"))
  
  # Models often wrap code in ``` fences, so drop those lines
  lines <- strsplit(reply, "\n")[[1]]
  
  paste(lines[!startsWith(trimws(lines), "```")], collapse = "\n")
}

# Set the system behaviour of the agent for the first time
chat <- chat_openrouter(system_prompt = prompt)

Now that the behaviour has been set, we can define the actual problem prompt!

problem <- "
Allocate the budget across grades to maximise total expected profit.
Total exposure must not exceed the budget.
Total expected loss must stay under 6% of total exposure.
No grade may hold more than 30% of total exposure.
No grade may receive more than its demand.
"

# Send to agent
code <- ask_llm(chat, problem)

# Print the response
cat(code)
model <- MIPModel() |>
  add_variable(x[i], i = 1:nrow(seg), type = "continuous", lb = 0) |>
  set_objective(sum_over(seg$profit_per_dollar[i] * x[i], i = 1:nrow(seg)), sense = "max") |>
  add_constraint(sum_over(x[i], i = 1:nrow(seg)) <= params$budget) |>
  add_constraint(sum_over(seg$loss_per_dollar[i] * x[i], i = 1:nrow(seg)) <= 0.06 * sum_over(x[i], i = 1:nrow(seg))) |>
  add_constraint(x[i] <= 0.30 * sum_over(x[j], j = 1:nrow(seg)), i = 1:nrow(seg)) |>
  add_constraint(x[i] <= seg$demand[i], i = 1:nrow(seg))

Let’s understand what’s in the output first:

< section id="solving-the-model" class="level2">

Solving the model

# Create the exact variables needed for the call to the solver
params <- list(budget = 20e6) ## Specify budget

env <- new.env() ## Create a new environment where the call will be evaluated
env$seg    <- seg  ## Create a variable called seg with the segment level table from earlier
env$params <- params  ## Create a variable called params

# Evaluate the LLM output inside the new environment which creates the "model" object
eval(parse(text = code), envir = env)

# Solve the model object
result <- solve_model(env$model, with_ROI(solver = "glpk"))

# Check if a solution was found
result$status
[1] "success"
# Print the optimal solution
get_solution(result, x[i]) |>
  mutate(grade = seg$grade[i]) |>
  select(grade, exposure = value)
  grade exposure
1     A    6e+06
2     B    6e+06
3     C    6e+06
4     D    2e+06
5     E    0e+00
6     F    0e+00
7     G    0e+00

With ompr.roi, a status of "success" means GLPK found an optimal solution; anything else (infeasible, unbounded) comes back as "error". Note that the LLM-generated code was run in a separate environment containing seg and params. This isn’t a security sandbox.

< section id="a-reusable-helper-nl_to_opt" class="level2">

A Reusable Helper: nl_to_opt()

Now the fun part. We can wrap everything into one clean function. The idea is: ask, run, and if something breaks, show the LLM its own error message and ask again.

nl_to_opt <- function(problem,
                      data,
                      params = list(),
                      system_prompt,
                      max_tries = 3,
                      solver = "glpk",
                      model = NULL) {

  # Set the system behaviour as usual
  chat <- chat_openrouter(system_prompt = system_prompt, 
                          model = model)

  # Get the problem definition
  prompt <- problem
  history <- list()

  for (attempt in seq_len(max_tries)) {
    code <- ask_llm(chat, prompt)

    # Run the generated code in a clean environment that sees the data and ompr
    env <- new.env(parent = globalenv())
    env$seg <- data
    env$params <- params

    # Build and solve the model. Any error is captured as a message.
    outcome <- tryCatch({
      eval(parse(text = code), envir = env)
      if (is.null(env$model)) stop("Assign your model to an object called `model`.")

      res <- solve_model(env$model, with_ROI(solver = solver))
      # ompr.roi reports "success" for an optimal solve, "error" otherwise
      if (res$status != "success") stop("The model is infeasible or unbounded.")

      list(ok = TRUE, result = res, model = env$model)
    }, error = function(e) list(ok = FALSE, msg = conditionMessage(e)))

    history[[attempt]] <- list(code = code, 
                               ok = outcome$ok,
                               msg = if (!outcome$ok) outcome$msg)

    if (outcome$ok) {
      return(list(
        model    = outcome$model,
        result   = outcome$result,
        code     = code,
        attempts = attempt,
        history  = history
      ))
    }

    # Feed the error back and try again
    prompt <- sprintf(
      "Your code failed.\n\nError: %s\n\nPlease return corrected code for the same problem.",
      outcome$msg
    )
  }

  stop("No working model after ", max_tries, " attempts. Last error: ",
       history[[max_tries]]$msg)
}

Using it takes one call:

out <- nl_to_opt(
  problem       = problem,
  data          = seg,
  params        = list(budget = 20e6),
  system_prompt = prompt
)

out$attempts        # how many tries it took
[1] 1
cat(out$code)       # the model the LLM wrote
model <- MIPModel() |>
  add_variable(x[i], i = 1:nrow(seg), type = "continuous", lb = 0) |>
  set_objective(sum_over(seg$profit_per_dollar[i] * x[i], i = 1:nrow(seg)), sense = "max") |>
  add_constraint(sum_over(x[i], i = 1:nrow(seg)) <= params$budget) |>
  add_constraint(sum_over(seg$loss_per_dollar[i] * x[i], i = 1:nrow(seg)) <= 0.06 * sum_over(x[i], i = 1:nrow(seg))) |>
  add_constraint(x[i] <= 0.30 * sum_over(x[j], j = 1:nrow(seg)), i = 1:nrow(seg)) |>
  add_constraint(x[i] <= seg$demand[i], i = 1:nrow(seg))
get_solution(out$result, x[i])
  variable i value
1        x 1 6e+06
2        x 2 6e+06
3        x 3 6e+06
4        x 4 2e+06
5        x 5 0e+00
6        x 6 0e+00
7        x 7 0e+00
< section id="how-to-build-controls" class="level2">

How to Build Controls

Since we are using an LLM to translate our business problem into a model that the solver can solve, it’s important to build the right set of controls to ensure the outcome is accurate.

Instead of coding each check by hand, we can ask an LLM to translate plain-English controls into R. We use a fresh chat that never sees the optimisation code, like a second reviewer who only gets the rulebook and the final numbers.

controls <- c(
  "Total amount lent must not exceed the budget",
  "Total expected loss must be at most 6% of the total amount lent",
  "No grade may hold more than 30% of the total amount lent",
  "No grade may receive more than its demand",
  "No grade may receive a negative amount"
)

checker_prompt <- "
Write base R code that tests a lending allocation against a list of controls.
- x is a numeric vector of dollars lent, in the same row order as the data frame seg.
- seg has columns grade, demand and loss_per_dollar. The budget is params$budget.
- Return only code that creates a data frame `checks` with one row per control, in order.
- Column `rule` is the control text. Column `passed` is logical (TRUE or FALSE).
- Allow a tolerance of 1e-6 on every limit.
"

checker    <- chat_openrouter(system_prompt = checker_prompt)
check_code <- ask_llm(checker, paste(controls, collapse = "\n"))

cat(check_code)
total_lent <- sum(x)
total_expected_loss <- sum(x * seg$loss_per_dollar)
grade_lending <- tapply(x, seg$grade, sum)
grade_demand <- tapply(seg$demand, seg$grade, sum)

checks <- data.frame(
  rule = c(
    "Total amount lent must not exceed the budget",
    "Total expected loss must be at most 6% of the total amount lent",
    "No grade may hold more than 30% of the total amount lent",
    "No grade may receive more than its demand",
    "No grade may receive a negative amount"
  ),
  passed = c(
    total_lent <= params$budget + 1e-6,
    total_expected_loss <= 0.06 * total_lent + 1e-6,
    max(grade_lending) <= 0.30 * total_lent + 1e-6,
    all(grade_lending <= seg$demand[match(names(grade_lending), names(grade_demand))] + 1e-6),
    all(x >= -1e-6)
  )
)

A small helper runs the generated checks on any allocation. We test the solver’s answer, and also an allocation we know is bad ($25 million in grade G alone), because the checker can make mistakes too.

run_controls <- function(x) {
  env <- list2env(list(x = x, seg = seg, params = params), parent = globalenv())
  eval(parse(text = check_code), env)

  # Guard against dropped or badly formed checks
  stopifnot(nrow(env$checks) == length(controls),
            is.logical(env$checks$passed), !anyNA(env$checks$passed))
  env$checks
}

# The solver's answer: every control should pass
run_controls(get_solution(out$result, x[i])$value)
                                                             rule passed
1                    Total amount lent must not exceed the budget   TRUE
2 Total expected loss must be at most 6% of the total amount lent   TRUE
3        No grade may hold more than 30% of the total amount lent   TRUE
4                       No grade may receive more than its demand   TRUE
5                          No grade may receive a negative amount   TRUE
# The bad allocation: the first four controls should fail
run_controls(ifelse(seg$grade == "G", 25e6, 0))
                                                             rule passed
1                    Total amount lent must not exceed the budget  FALSE
2 Total expected loss must be at most 6% of the total amount lent  FALSE
3        No grade may hold more than 30% of the total amount lent  FALSE
4                       No grade may receive more than its demand  FALSE
5                          No grade may receive a negative amount   TRUE

However, passing these controls shows that the answer follows the rules specified, not that it is the best answer. A model with an extra constraint, or one that lends nothing, could still pass. Hence, some manual review and scenario testing is required.

< section id="further-reading" class="level2">

Further Reading

To leave a comment for the author, please follow the link and comment on their blog: R'tichoke.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
Exit mobile version