Skip to content

Instantly share code, notes, and snippets.

@thisisnic
Created November 18, 2025 09:58
Show Gist options
  • Select an option

  • Save thisisnic/22ea38e2f0c8ff1c20ea039232dbc21d to your computer and use it in GitHub Desktop.

Select an option

Save thisisnic/22ea38e2f0c8ff1c20ea039232dbc21d to your computer and use it in GitHub Desktop.
Structured output and enums
library(ellmer)
kendrick_wiki_text <- "Kendrick Lamar Duckworth (born June 17, 1987) is an American rapper, singer, songwriter, and record producer. Regarded as one of the greatest rappers of all time, he was awarded the 2018 Pulitzer Prize for Music, becoming the first musician outside of the classical and jazz genres to receive the award. Lamar's music, rooted in West Coast hip-hop, features conscious, introspective lyrics, with political criticism and social commentary concerning African-American culture."
hip_hop_theme <- type_enum(c("conscious_rap", "party_anthems", "storytelling", "braggadocio", "love_relationships"))
artist_type <- type_object(
name = type_string("Artist's full name"),
birth_date = type_string("Birth date in YYYY-MM-DD format"),
genre = type_string("Primary music genre"),
themes = type_array(hip_hop_theme)
)
chat <- chat_openai()
#> Using model = "gpt-4.1".
#> Using model = "gpt-4.1".
chat$chat_structured(kendrick_wiki_text, type = artist_type)
#> $name
#> [1] "Kendrick Lamar Duckworth"
#>
#> $birth_date
#> [1] "1987-06-17"
#>
#> $genre
#> [1] "hip-hop"
#>
#> $themes
#> [1] conscious_rap storytelling
#> 5 Levels: conscious_rap party_anthems storytelling ... love_relationships
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment