Skip to main content

AE 19: Improving LLM outputs

Suggested answers

Application exercise
Answers
Modified

November 11, 2026

12_plot-image-1

library(readr)
library(ellmer)
library(ggplot2)

# Step 1: Make a scatter plot of the penguins dataset
data("penguins")

ggplot(data = penguins, aes(x = flipper_len, y = bill_len)) +
  geom_point(color = "steelblue", size = 3, alpha = 0.8) +
  theme_minimal() +
  labs(
    title = "Flipper and bill length",
    subtitle = "Dimensions for Adelie, Chinstrap and Gentoo Penguins at Palmer Station LTER",
    x = "Flipper length (mm)",
    y = "Bill length (mm)"
  )

chat <- chat("anthropic/claude-sonnet-4-6", echo = "output")
chat$chat(
  "Interpret this plot.",
  content_image_plot()
)

13_plot-image-2

library(readr)
library(ellmer)
library(ggplot2)

set.seed(523)

m <- 32
u <- (seq_len(floor(sqrt(m))) - 0.5) / floor(sqrt(m))
grid <- as.matrix(expand.grid(x = u, y = u))

eps <- 1 / (2 * sqrt(m))
jitter <- matrix(runif(length(grid), -eps, eps), ncol = 2)
grid_jitter <- pmin(pmax(grid + jitter, 0), 1)

ggplot() +
  aes(x = grid_jitter[, 1], y = grid_jitter[, 2]) +
  geom_point(color = "steelblue", size = 3, alpha = 0.8) +
  theme_minimal() +
  labs(
    title = "Flipper and bill length",
    subtitle = "Dimensions for Adelie, Chinstrap and Gentoo Penguins at Palmer Station LTER",
    x = "Flipper length (mm)",
    y = "Bill length (mm)"
  )

chat <- chat("anthropic/claude-sonnet-4-6", echo = "output")
chat$chat(
  "Interpret this plot of penguins.",
  content_image_plot()
)

14_evals

library(ellmer)
library(vitals)

vitals::vitals_log_dir_set("./logs")

# Each case plants a subtle data-quality artifact in the prompt, and the
# eval grades whether each model flags the specific artifact unprompted.
cases <- read_rds(here::here("ae/ae-19/data/bluff-mini-cases.rds"))

# The eval grades responses from two models against the same criteria.
models <- c(
  luna = "openai/gpt-6-luna",
  haiku = "anthropic/claude-haiku-4-5"
)

# Run the eval once per model and collect pass rates by case
tasks <- purrr::imap(models, \(model, model_name) {
  tsk <- Task$new(
    dataset = cases,
    solver = generate(),
    scorer = model_graded_qa(
      scorer_chat = chat_anthropic(model = "claude-sonnet-5")
    ),
    name = model_name
  )

  tsk$eval(
    solver_chat = chat(name = model),
    epochs = 2,
    view = FALSE
  )

  tsk
})

results <- purrr::map(tasks, \(tsk) {
  tsk$get_samples() |>
    dplyr::summarise(
      flagged = sum(score == "C"),
      n = dplyr::n(),
      pass_rate = mean(score == "C"),
      .by = id
    )
}) |>
  purrr::list_rbind(names_to = "model")

results

# Explore the transcripts in the log viewer
vitals::vitals_view()

15_quiz-game-1

library(shiny)
library(bslib)
library(ellmer)
library(shinychat)

# UI ---------------------------------------------------------------------------

ui <- page_fillable(
  chat_mod_ui("chat")
)

# Server -----------------------------------------------------------------------

server <- function(input, output, session) {
  client <- chat(
    "anthropic/claude-sonnet-4-6",
    system_prompt = interpolate_file(
      here::here("_solutions/15_quiz-game-1/prompt.md")
    )
  )

  chat <- chat_mod_server("chat", client)

  observe({
    # Start the game when the app launches
    chat$update_user_input(
      value = "Let's play the quiz game!",
      submit = TRUE
    )
  })
}

shinyApp(ui, server)

prompt.md

## Quiz Game Host

-  Greet the user and ask them to choose a theme. Suggest a list of 5 random themes.
-  Ask simple multiple-choice questions (A–D), one at a time. Show the current question number.
-  After each answer: confirm choice, say correct/incorrect, give a brief explanation, then ask the next question.
-  Every 5 questions: declare the user a winner (regardless of score), praise them, then restart by asking for a theme.
-  Validate input: if not A–D, ask for a valid option and repeat the question.
-  Allow skipping: if asked to skip, reveal the answer briefly, then move on.
-  Keep tone upbeat, concise, and emoji-rich. Avoid repeating questions in a session. Gradually increase difficulty.

## Examples

Assistant:
    🎉 Welcome to the Quiz Game Show! Pick a theme to begin:
    - Science
    - History
    - Movies
    - Sports
    Which theme would you like?

User:
    Science

Assistant:
    ✅ Great choice: Science!
    **Question 1:** What is the center of an atom called?

    A) Electron \
    B) Proton \
    C) Neutron \
    D) Nucleus

User:
    D

Assistant:
    Correct! ✅ The nucleus is the dense center containing protons and neutrons.
    **Question 2:** Which planet is known as the Red Planet?

    A) Venus \
    B) Mars \
    C) Jupiter \
    D) Mercury

User:
    E

Assistant:
    Oops! ❗ Please answer with A, B, C, or D.
    **Question 2:** Which planet is known as the Red Planet?

    A) Venus \
    B) Mars \
    C) Jupiter \
    D) Mercury

User:
    skip

Assistant:
    Skipped! ⏭️ The correct answer is B) Mars.
    **Question 3:** …

16_coding-assistant

# Task ------------------------------------------------------------------------
library(ellmer)

# **Step 1:** Run the code below as-is to try the task without any extra
# context. How does the model do? Does it know enough about the {weathR}
# package to complete the task?
#
# **Step 2:** Now, let's add some context. Head over to GitHub repo for {weathR}
# (link in `docs.R.md`). Copy the project description from the `README.md` and
# paste it into the `docs.r.md` file.
#
# **Step 3:** Uncomment the extra lines to include these docs in the prompt and
# try again.

chat <- chat(
  "anthropic/claude-sonnet-4-6",
  echo = "output",
  system_prompt = brio::read_file(here::here(
    "_solutions/16_coding-assistant/docs.R.md"
  ))
)

chat$chat(
  # Task prompt
  paste(
    "Write a simple function that takes latitude and longitude as inputs",
    "and returns the weather forecast for that location using the {weathR}",
    "package. Keep the function concise and simple and don't include error",
    "handling or data re-formatting. Include documentation in roxygen2 format,",
    "including examples for NYC and Atlanta, GA."
  )
)

# Result ----------------------------------------------------------------------

#' Get Weather Forecast for a Location
#'
#' Retrieves the weather forecast for a given latitude and longitude using the
#' National Weather Service API
#'
#' @param lat Numeric latitude value
#' @param lon Numeric longitude value
#' @return A dataframe containing forecast data including time and temperature
#' @export
#'
#' @examples
#' # Get forecast for New York City (Central Park)
#' get_forecast(40.768473, -73.976004)
#'
#' # Get forecast for Atlanta, GA
#' get_forecast(33.749045, -84.388792)
get_forecast <- function(lat, lon) {
  weathR::point_forecast(lat = lat, lon = lon)
}

Acknowledgments