library(rtemis.llm)4 Structured Output
rtemis.llm provides convenience functions schema() and field() to define structured output schemas for LLM responses.
4.1 Define a schema
city_schema <- schema(
name = "CitySchema",
field("name", "Official city name in English", "string"),
field("country", "Country where the city is located", "string"),
field("population", "Population of the city", "number")
)
city_schemaCitySchema:
description: NULL
fields:
name:
type: string
description: Official city name in English
required: TRUE
country:
type: string
description: Country where the city is located
required: TRUE
population:
type: number
description: Population of the city
required: TRUE
4.2 LLM: Generate structured output
4.2.1 LLM with output_schema
llm <- create_Ollama(
model_name = "gemma4:e4b",
system_prompt = "You are an expert intelligence analyst. Respond in the format specified by the provided schema.",
temperature = 0.2,
output_schema = city_schema
)
llm<Ollama>
Model: gemma4:e4b
System Prompt: You are an expert intelligence analyst. Respond in the format specified by the provided schema.
Temperature: 0.2
Output Schema:
CitySchema:
description: NULL
fields:
name:
type: string
description: Official city name in English
required: TRUE
country:
type: string
description: Country where the city is located
required: TRUE
population:
type: number
description: Population of the city
required: TRUE
generate(llm, "Tell me about Tokyo.")[Response] {
"name": "Tokyo",
"country": "Japan",
"population": 37470000.0000000000000000e+0
}
4.2.2 generate() with output_schema
llm <- create_Ollama(
model_name = "gemma4:e4b",
system_prompt = "You are an expert intelligence analyst. Respond in the format specified by the provided schema.",
temperature = 0.2
)
llm<Ollama>
Model: gemma4:e4b
System Prompt: You are an expert intelligence analyst. Respond in the format specified by the provided schema.
Temperature: 0.2
generate(llm, "Tell me about Honolulu.", output_schema = city_schema)[Response] {
"name": "Honolulu",
"country": "United States",
"population": 319322.0000000000577353
}
output_schema is similary supported in create_agent() and generate() for Agent objects.
4.3 map() with output_schema
ColorSchema <- schema(
name = "ColorSchema",
field("color_name", "Name of the color", "string"),
field("hex_code", "Hex code of the color in format #RRGGBB", "string")
)
llm <- create_Ollama(
model_name = "gemma4:e4b",
system_prompt = "Return the hex code for the following color in format #RRGGBB",
temperature = 0.2
)
x <- c("ocean teal", "california poppy orange", "bougainvillea pink")hex <- map(x, llm, output_schema = ColorSchema)hex[[1]]
[Response] {
"color_name": "ocean teal",
"hex_code": "#008080"
}
[[2]]
[Response] {
"color_name": "California Poppy Orange",
"hex_code": "#FF9933"
}
[[3]]
[Response] {
"color_name": "bougainvillea pink",
"hex_code": "#E86A8B"
}