Learn R Programming

llmflow (version 3.0.2)

response_as_json: Get JSON response from LLM with validation and retry

Description

Get JSON response from LLM with validation and retry

Usage

response_as_json(
  chat_obj,
  prompt,
  schema = NULL,
  schema_strict = FALSE,
  max_iterations = 3
)

Value

List. Parsed JSON response from the LLM.

Arguments

chat_obj

Chat object (LLM client). Must be a properly initialized LLM client instance.

prompt

Character string. The user prompt to send to the LLM requesting JSON output.

schema

List or NULL. Optional JSON schema for response validation (as R list structure). When provided, validates the LLM response against this schema. Default is NULL.

schema_strict

Logical. Whether to use strict schema validation (no additional properties allowed). Only applies when schema is provided. Default is FALSE.

max_iterations

Integer. Maximum number of retry attempts for invalid JSON or schema validation failures. Must be positive. Default is 3.

Examples

Run this code
if (FALSE) {
# Basic usage without schema
result <- response_as_json(
  chat_obj = llm_client,
  prompt = "List three colors"
)

# With schema validation
schema <- list(
  type = "object",
  properties = list(
    equation = list(type = "string"),
    solution = list(type = "number")
  ),
  required = c("equation", "solution")
)
result <- response_as_json(
  chat_obj = llm_client,
  prompt = "How can I solve 8x + 7 = -23?",
  schema = schema,
  schema_strict = TRUE,
  max_iterations = 3
)
}

Run the code above in your browser using DataLab