(Acest articol a fost publicat pentru prima dată pe R’ticchokeși cu amabilitate a contribuit la R-bloggeri). (Puteți raporta problema legată de conținutul acestei pagini aici)
Doriți să vă distribuiți conținutul pe R-bloggeri? dați clic aici dacă aveți un blog, sau aici dacă nu aveți.
La definirea unei probleme de optimizare, LLM-urile pot fi folosite ca a stratul de traducere. Rezolvatorul este calculatorul care face treaba reală și nu face greșeli. Cu toate acestea, traducătorul ar putea traduce greșit ocazional. Totuși, atâta timp cât problema este bine specificată și tradusă corect, rezultatele sunt deterministe și reproductibile.
Această postare se concentrează pe construirea întregului lanț în R:
- Descrieți o declarație privind problema riscului de credit în limba engleză simplă
- Lăsați un LLM (prin
ellmer) traduce problema înompr - Rezolva-l cu
ompr.roi+ GLPK - Înfășurați totul într-un material reutilizabil
nl_to_opt()ajutor care reclamă LLM atunci când rezolutorul se plânge - Verificați răspunsul cu controalele generate de LLM
Postarea folosește OpenRouter ca furnizor LLM. Pentru a rula codul din această postare, creați o cheie OpenRouter și setați-o ca OPENROUTER_API_KEY variabilă de mediu (de exemplu, în dvs .Renviron).
Pachete necesare
# 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)
Problema afacerii
Să presupunem că vrem să decidem câtă expunere de credit să alocăm fiecărui grad de risc. Setul de date eșantion are șapte grade de risc și problema poate fi specificată în limba engleză ca:
„Avem un buget de 20 de milioane de dolari de împrumutat. Alocați expunerea pe cele șapte grade de risc pentru a maximiza profitul așteptat. Pierderea așteptată trebuie să rămână sub 6% din expunerea totală. Niciun grad nu poate deține mai mult de 30% din expunerea totală. Nu împrumutați mai mult la o notă decât cererea observată.”
Mai întâi, să transformăm datele la nivel de împrumut într-un mic tabel cu segmente; LLM primește doar o descriere a coloanelor sale.
# 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_dollar1 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
Apel LLM pentru a genera specificația modelului
Un prompt bun face trei lucruri – descrie datele, stabilește formatul de ieșire și stabilește regulile de drum (nume de variabile, soluție, unități). Aici, în loc să folosim ieșirea structurată a lui ellmer, vom cere un răspuns text simplu.
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)
Acum că comportamentul a fost setat, putem defini promptul real al problemei!
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))
Să înțelegem mai întâi ce este în rezultat:
- Variabile: suma de un dolar pe grad, niciodata negativ.
- Obiectiv: profitul așteptat pe dolar ori dolari împrumuți, însumat pe note.
- Buget: totalul creditului este cel mult bugetul.
- Limită de pierdere: regula „sub 6% din expunere” este a raportcare pare neliniar. Mutarea numitorului îl face liniar:
sum(loss_i * x_i) <= 0.06 * sum(x_i). Acesta este un pas pe care LLM-urile îl pot bâjbâi cu ușurință. - Concentraţie: fiecare nota este de cel mult 30% din expunerea totală efectiv împrumutatănu 30% din buget.
- Cerere: o limită superioară simplă pe grad.
Rezolvarea modelului
# 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
# 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
Cu ompr.roiun statut de "success" înseamnă că GLPK a găsit o soluție optimă; orice altceva (infezabil, nelimitat) revine ca "error". Rețineți că codul generat de LLM a fost rulat într-un mediu separat care conține seg şi params. Acesta nu este un sandbox de securitate.
Un ajutor reutilizabil: nl_to_opt()
Acum partea distractivă. Putem împacheta totul într-o singură funcție curată. Ideea este: întreabă, fugi și dacă se strică ceva, arăta LLM propriul mesaj de eroare si intreaba din nou.
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.nnError: %snnPlease return corrected code for the same problem.",
outcome$msg
)
}
stop("No working model after ", max_tries, " attempts. Last error: ",
history((max_tries))$msg)
}
Folosirea acestuia necesită un apel:
out <- nl_to_opt( problem = problem, data = seg, params = list(budget = 20e6), system_prompt = prompt ) out$attempts # how many tries it took
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
Cum să construiți controale
Deoarece folosim un LLM pentru a traduce problema noastră de afaceri într-un model pe care rezolvatorul îl poate rezolva, este important să construim setul potrivit de controale pentru a ne asigura că rezultatul este exact.
În loc să codificăm fiecare cec manual, putem cere unui LLM să traducă controalele în limba engleză simplă în R. Folosim un conversație proaspătă care nu vede niciodată codul de optimizare, ca un al doilea examinator care primește doar regulamentul și numerele finale.
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)
)
)
Un mic ajutor execută verificările generate pentru orice alocare. Testăm răspunsul rezolutorului și, de asemenea, o alocare stiu este rău (25 de milioane de dolari numai în clasa G), deoarece verificatorul poate face și greșeli.
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
Cu toate acestea, trecerea acestor controale arată că răspunsul respectă regulile specificatenu că ar fi cel mai bun răspuns. Un model cu o constrângere suplimentară, sau unul care nu împrumută nimic, tot ar putea trece. Prin urmare, este necesară o revizuire manuală și testare a scenariilor.
Lectură suplimentară
