Run Agent with Structured Output

This example demonstrates how to run an agent with structured output.


Run Agent with Structured Output Example

Run Agent with Structured Output Example

import 'dotenv/config'; import {Langbase} from 'langbase'; import {z} from 'zod'; import {zodToJsonSchema} from 'zod-to-json-schema'; const langbase = new Langbase({ apiKey: process.env.LANGBASE_API_KEY!, }); // Define the Strucutred Output JSON schema with Zod const MathReasoningSchema = z.object({ steps: z.array( z.object({ explanation: z.string(), output: z.string(), }), ), final_answer: z.string(), }); const jsonSchema = zodToJsonSchema(MathReasoningSchema, {target: 'openAi'}); async function main() { if (!process.env.LANGBASE_API_KEY) { console.error('❌ Missing LANGBASE_API_KEY in environment variables.'); process.exit(1); } const {output} = await langbase.agent.run({ model: 'openai:gpt-4.1', apiKey: process.env.LLM_API_KEY!, instructions: 'You are a helpful math tutor. Guide the user through the solution step by step.', input: [ { role: 'user', content: 'How can I solve 8x + 22 = -23?', }, ], json: true, response_format: { type: 'json_schema', json_schema: { name: 'math_reasoning', schema: jsonSchema, }, }, }); // Parse and validate the response using Zod const solution = MathReasoningSchema.parse(JSON.parse(output)); console.log('✅ Structured Output Response:', solution); } main();