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
enum: NULL
items: NULL
required: TRUE
country:
type: string
description: Country where the city is located
enum: NULL
items: NULL
required: TRUE
population:
type: number
description: Population of the city
enum: NULL
items: NULL
required: TRUE
4.2 Restrict a field to a fixed set of values
Pass enum to field() when the answer must be exactly one of a known set of labels. It is emitted as the JSON Schema enum key, and a backend with constrained decoding – Ollama – makes any other answer impossible rather than merely detectable, so a categorical answer no longer has to be requested in prose and validated afterwards.
review_schema <- schema(
name = "ReviewSchema",
field("summary", "One-sentence summary of the review", "string"),
field(
"sentiment",
"Overall sentiment of the review",
"string",
enum = c("negative", "mixed", "positive")
)
)
review_schemaReviewSchema:
description: NULL
fields:
summary:
type: string
description: One-sentence summary of the review
enum: NULL
items: NULL
required: TRUE
sentiment:
type: string
description: Overall sentiment of the review
enum: negative, mixed, positive
items: NULL
required: TRUE
enum applies to "string", "number" and "integer" fields. Values are given as characters and emitted in the field’s declared type, so an "integer" field’s enum reaches the model as JSON numbers.
4.3 LLM: Generate structured output
4.3.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
enum: NULL
items: NULL
required: TRUE
country:
type: string
description: Country where the city is located
enum: NULL
items: NULL
required: TRUE
population:
type: number
description: Population of the city
enum: NULL
items: NULL
required: TRUE
generate(llm, "Tell me about Tokyo.")[Reasoning] Thinking Process:
1. **Analyze the Request:** The user asked, "Tell me about Tokyo." This is a broad, general knowledge request requiring a comprehensive overview.
2. **Determine the Persona/Role:** I must respond as an "expert intelligence analyst." This means the tone must be highly professional, objective, structured, analytical, and comprehensive, avoiding overly flowery or purely touristic language.
3. **Analyze the Output Format:** The response must adhere strictly to the provided JSON schema.
* `Report Title`: Needs a formal, analytical title.
* `Executive Summary`: A concise, high-level overview of the subject's significance.
* `Key Domains of Analysis`: Structured sections covering different aspects (e.g., Economy, Geopolitics, Culture, Infrastructure).
* `Threat/Opportunity Assessment`: An analytical conclusion section (mandatory for an intelligence report).
4. **Draft Content (Tokyo):**
* *Significance:* Global hub, economic powerhouse, cultural melting pot, complex urban environment.
* *Economy:* Tech, finance, corporate headquarters (Tokyo Stock Exchange), advanced manufacturing.
* *Geopolitics/Stability:* High stability, complex relationship with neighbors (China, Korea, North Korea), disaster risk (earthquakes).
* *Infrastructure:* World-class, advanced public transport (rail), high density, resilience planning.
* *Culture/Society:* Blend of hyper-modernity and deep tradition (temples, festivals). High population density, unique social dynamics.
* *Challenges/Risks:* Natural disasters, demographic decline (aging population), geopolitical tensions.
5. **Structure and Refine (Applying the Analyst Tone):**
* *Title:* Needs to sound official.
* *Summary:* Focus on complexity and global impact.
* *Domains:* Use analytical headings (e.g., "Economic Profile," "Operational Environment," "Socio-Cultural Dynamics").
* *Assessment:* Frame the findings as actionable intelligence (Opportunities and Risks).
6. **Final Review against Schema:** Ensure all fields are populated accurately and the tone is consistent. (Self-Correction: Ensure the language is formal—use terms like "operational environment," "demographic shifts," "critical infrastructure," etc.) (This leads to the final JSON output.)
[Response] {
"name": "Tokyo Metropolitan Area",
"country": "Japan",
"population": 3700000000000000
}
4.3.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)[Reasoning] Here's a thinking process to construct the expert intelligence analyst response about Honolulu:
1. **Analyze the Request:** The user asked, "Tell me about Honolulu." This is a broad, general request.
2. **Determine the Persona/Format:** The response must be from the perspective of an "expert intelligence analyst" and adhere strictly to the provided schema (which implies a structured, objective, and analytical tone).
3. **Deconstruct "Honolulu" for Intelligence Analysis:** An intelligence analyst doesn't just give a travel brochure. They analyze *function*, *geopolitics*, *infrastructure*, *economic drivers*, and *vulnerabilities*.
* *What is it?* A major urban center, capital of the state of Hawaii.
* *What is its function?* Military hub, commercial center, tourism destination, administrative center.
* *What are its key assets/drivers?* Military presence (Pearl Harbor/Joint Base Pearl Harbor-Hickam), tourism infrastructure, commercial ports, historical significance.
* *What are its challenges/vulnerabilities?* Climate change (sea-level rise), natural disasters (earthquakes, tsunamis, hurricanes), over-reliance on tourism/external supply chains, population density/resource strain.
4. **Map Content to the Schema (Structuring the Analysis):**
* **Designation/Overview:** Define the location, scope, and primary function. (Geographic/Political context).
* **Key Operational Domains:** Break down the core functions that matter to an analyst. (Military, Economic, Infrastructure).
* **Strategic Assets & Capabilities:** What makes the location valuable or powerful? (Ports, Bases, Tourism revenue).
* **Threat Assessment & Vulnerabilities:** What are the risks? (Climate, Natural Hazards, Socio-economic stress).
* **Conclusion/Outlook:** A concise summary of the overall stability and future focus areas.
5. **Drafting Content (Iterative Refinement):**
* *Tone Check:* Maintain formality, objectivity, and analytical depth. Avoid flowery language. Use terms like "critical node," "operational footprint," "geopolitical significance," and "resilience."
* *Refining Operational Domains:* Ensure the military aspect is prominent, as this is a major intelligence concern.
* *Refining Vulnerabilities:* Focus on systemic risks (climate, supply chain) rather than just local issues.
6. **Final Review against Schema:** (Self-Correction: Ensure all sections are covered and the tone is consistent.) The resulting structure is comprehensive, analytical, and directly addresses the prompt while maintaining the required expert persona. (This leads to the final provided response.)
[Response] {
"name": "Honolulu, Oahu, Hawaii",
"country": "United States of America",
"population": 3500000000000000.0000000000000000
}
output_schema is similarly supported in create_agent() and generate() for Agent objects.
4.4 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] #008080
[[2]]
[Reasoning] The user wants the hex code for "california poppy orange". I need to select a representative color for this description. A typical California poppy is a vibrant, warm orange.
[Response] {
"color_name": "California Poppy Orange",
"hex_code": "#FF8C00"
}
[[3]]
[Reasoning] Thinking Process:
1. **Identify the request:** The user wants the hex code for "bougainvillea pink".
2. **Analyze the color:** "Bougainvillea pink" is a specific, vibrant, medium-to-deep pink, often leaning towards magenta or fuchsia.
3. **Determine the hex code:** Since "bougainvillea pink" is a descriptive name, there isn't one single universally accepted hex code. I need to select a representative, accurate, and commonly associated shade.
* *Search/Knowledge retrieval:* A typical bougainvillea color is bright, saturated, and slightly purplish-pink.
* *Selection:* A good representative hex code is often around #D9467A or similar vibrant magentas. I will choose a widely recognized, vibrant pink that captures the essence of the flower.
4. **Format the output:** The required format is `#RRGGBB`.
*(Self-Correction/Refinement: I will use a vibrant, slightly magenta-leaning pink that is highly saturated.)*
5. **Final Hex Code:** #D9467A (or a close variant like #E3628A, but #D9467A is strong and representative). I will use a standard, vibrant choice.
[Response] {
"color_name": "bougainvillea pink",
"hex_code": "#D9467A"
}
attr(,"elapsed")
[1] 0.491 4.152 17.901
attr(,"errors")
[1] index message
<0 rows> (or 0-length row.names)
attr(,"validation")
Schema validation: valid 2; invalid 1; unavailable 0; not_validated 0
index path keyword
1 parse
message
lexical error: invalid char in json text.\n #008080\n (right here) ------^\n
4.5 Surviving a failed call
Over a long batch, one timeout or malformed response should not discard every result already paid for, so map(), llmapply() and agentapply() carry on by default: a failed call warns, leaves that element as NA, and the run continues. The result then carries an errors attribute – a data frame of index and message – so the failures can be retried by position rather than found by scanning for NA. Pass on_error = "abort" to propagate the first error and discard the batch instead.
hex <- llmapply(x, llm, output_schema = ColorSchema, on_error = "na")
attr(hex, "errors")4.6 Reading a probability instead of parsing one
Asking a model to emit a confidence score gives you a number the model has no particular reason to calibrate. Asking a binary question and reading the probability of the first token off the token distribution gives you one it does. Pass logprobs and top_logprobs, then use token_probs().
judge <- create_Ollama(
model_name = "gemma4:e4b",
system_prompt = "Answer with exactly one word: Yes or No."
)
questions <- c("Is the sky blue?", "Is fire cold?", "Do fish live in water?")
out <- llmapply(
questions, judge,
extract_responses = FALSE,
think = FALSE, max_tokens = 2L, temperature = 0,
logprobs = TRUE, top_logprobs = 5L
)token_probs(out, c("Yes", "No")) Yes No
[1,] 9.975436e-01 2.453863e-03
[2,] 9.489538e-09 1.000000e+00
[3,] 9.999974e-01 2.674755e-06
logprobs() gives the full per-token trace, and top = TRUE adds the alternatives the model considered at each position:
logprobs(out[[1]], top = TRUE)[["alternatives"]][[1]] token logprob prob
<char> <num> <num>
1: Yes -0.002460524 9.975425e-01
2: No -6.010091782 2.453863e-03
3: Yes -13.714695930 1.106072e-06
4: Un -14.133341789 7.277256e-07
5: Yellow -14.301609993 6.150206e-07
position = 1 is the first generated token, which is the answer only when reasoning is off. With thinking enabled the opening tokens belong to the reasoning channel, so pass think = FALSE.
Candidates are matched on trimmed, case-folded token text and every match is summed, so "Yes" also picks up " Yes" and "yes". A candidate that does not appear among the returned alternatives is NA rather than zero – its probability is below the top-k cutoff, not known to be zero. Raise top_logprobs if candidates you care about come back NA.
Ollama and OpenAI-compatible backends support this; Anthropic does not return log probabilities, so its messages yield NULL.