Structured answers
Most of what your code wants from a model is data, not prose: a label, a few fields pulled out of an email, a list of
tags. Pass a JSON schema as schema, and the answer's parsed value is r.data:
const r: LlmTextAnswer = await $llm.text.completeAsync({
model: "vultr/glm-5.3",
reasoning: "off",
system: "Extract the order from the email.",
prompt: email,
schema: {
type: "object",
properties: {
name: { type: "string" },
city: { type: "string" },
items: {
type: "array",
items: {
type: "object",
properties: { what: { type: "string" }, count: { type: "integer" } },
required: ["what", "count"],
additionalProperties: false,
},
},
},
required: ["name", "city", "items"],
additionalProperties: false,
},
})
// "Hi, this is Dana. Please send 3 blue mugs and 2 red plates to our Austin office."
// r.data: { name: "Dana", city: "Austin", items: [{ what: "blue mugs", count: 3 }, { what: "red plates", count: 2 }] }
r, err := textv1.Contract.Must(app).Complete(ctx, extkit.Internal, textv1.CompleteInput{
Model: "vultr/glm-5.3",
Reasoning: "off",
System: "Extract the order from the email.",
Prompt: email,
Schema: json.RawMessage(`{
"type": "object",
"properties": {
"name": {"type": "string"},
"city": {"type": "string"},
"items": {"type": "array", "items": {"type": "object",
"properties": {"what": {"type": "string"}, "count": {"type": "integer"}},
"required": ["what", "count"], "additionalProperties": false}}
},
"required": ["name", "city", "items"],
"additionalProperties": false
}`),
})
var order struct {
Name, City string
Items []struct {
What string
Count int
}
}
err = json.Unmarshal(r.Data, &order) // {Dana Austin [{blue mugs 3} {red plates 2}]}
How the schema reaches the model
The schema goes to the provider as OpenAI's response_format (Workers AI gets it in its own form). Most current models
follow it exactly. If an answer still isn't JSON, the call throws bad_answer with the start of what the model wrote.
Tips
- An
enumis the most reliable way to get one of a few labels. - Say
reasoning: "off"for extraction and labels: the thinking adds nothing and costs tokens. - Leave room in
maxTokens, or leave it out: an answer cut off part-way isn't valid JSON. - OpenRouter asks models for strict JSON, which wants
additionalProperties: falseon every object.
Questions and comments
Comments are a GitHub Discussions thread; sign in with GitHub to post.