6. Structured output
Defining the Structure: The example starts by defining a struct that represents the desired output structure:
This struct includes validation tags to ensure the generated data meets specific criteria.
Creating an LLM Instance: The example creates an LLM instance with specific configuration:
Generating JSON Schema: The example generates a JSON schema based on the PersonInfo struct:
The
WithExpandedStruct(true)
option ensures that nested structs are fully expanded in the schema.Creating a Prompt with Schema: A prompt is created that includes the generated JSON schema:
This prompt includes directives for generating the person's information and specifies that the output should adhere to the provided schema.
Generating Structured Output: The example generates the structured output using the LLM:
The
WithJSONSchemaValidation()
option ensures that the generated output adheres to the specified JSON schema.Parsing and Validating the Response: The generated response is parsed into the PersonInfo struct:
Then, the parsed data is validated against the struct's validation rules:
Displaying the Result: Finally, the example prints the validated PersonInfo:
In summary, this example demonstrates:
Defining a struct with validation tags for structured output
Generating a JSON schema from a Go struct
Creating a prompt that includes the JSON schema
Using the LLM to generate data that adheres to the schema
Parsing and validating the generated data against the original struct
This example is particularly useful for developers who need to generate structured data using LLMs, ensuring that the output adheres to a specific format and validation rules. It showcases how gollm can be used to create reliable, schema-compliant outputs from language models.
Last updated