Skip to contents

Extract named list from LLM response with optional item instructions and validations

Usage

answer_as_named_list(
  prompt,
  item_names,
  item_instructions = NULL,
  item_validations = NULL
)

Arguments

prompt

A single string or a tidyprompt() object

item_names

A character vector specifying the expected item names

item_instructions

An optional named list of additional instructions for each item

item_validations

An optional named list of validation functions for each item. Like validation functions for a prompt_wrap(), these functions should return llm_feedback() if the validation fails. If the validation is successful, the function should return TRUE

Value

A tidyprompt() with an added prompt_wrap() that ensures the LLM response is a named list with the specified item names, optional instructions, and validations.

Examples

if (FALSE) { # \dontrun{
  persona <- "Create a persona for me, please." |>
    answer_as_named_list(
      item_names = c("name", "age", "occupation"),
      item_instructions = list(
        name = "The name of the persona",
        age = "The age of the persona",
        occupation = "The occupation of the persona"
      )
    ) |> send_prompt(llm_provider_ollama())
  # --- Sending request to LLM provider (llama3.1:8b): ---
  #   Create a persona for me, please.
  #
  #   Respond with a named list like so:
  #     -- name: <<value>> (The name of the persona)
  #     -- age: <<value>> (The age of the persona)
  #     -- occupation: <<value>> (The occupation of the persona)
  #   Each name must correspond to: name, age, occupation
  # --- Receiving response from LLM provider: ---
  #   Here is your persona:
  #
  #   -- name: Astrid Welles
  #   -- age: 32
  #   -- occupation: Museum Curator
  persona$name
  # [1] "Astrid Welles"
  persona$age
  # [1] "32"
  persona$occupation
  # [1] "Museum Curator"
} # }