Tools and structured answers
Let the model ask your code for data, and get answers as JSON that always follows your schema.
Tools: the model asks, your code answers
A tool is a function of yours that the model can ask to run, such as «look up this product». The model never runs anything itself: it asks, your server runs the function, and the result goes back to the model.
import { z } from 'zod';
const answer = await ai.chat({
task: 'allergen-answer',
case: 'ask-about-a-product',
endUser: customer.id,
messages,
tools: {
get_product: {
description: 'The ingredients and allergens of a product of La Espiga',
schema: z.object({ name: z.string() }),
run: async ({ name }) => db.product.findByName(name), // your data, read on your server
},
},
});The SDK runs the back-and-forth for you, up to 5 rounds (maxToolRounds). Over HTTP it is the usual tools and tool_calls of the OpenAI shape.
- A route’s
toolslist says which tool names a caller may offer; any other name is refused with400 tool_not_allowed. - What a tool returns is data for the model, not instructions. Read Prompt injection before giving a model a tool that changes something.
Structured answers: JSON that follows your schema
const Labels = z.object({
kind: z.enum(['question', 'complaint', 'order', 'other']),
products: z.array(z.string()),
});
const { data } = await ai.extract({
task: 'extract',
case: 'sort-messages',
schema: Labels,
input: 'Hola, quiero 2 baguettes para mañana a las 8',
});
// data: { kind: 'order', products: ['baguette'] }Over HTTP use response_format: { type: "json_schema", json_schema: { name, schema, strict: true } }, or put the schema in the route’s output field so every call of the task follows it.
The gateway checks every answer against the schema. If one does not match, it asks the model once more with the error; if it still does not match, you get 422 output_invalid with the answer it got. Only models that support structured answers are used on such routes.