Run Pipe Agent with Structured Output

This example demonstrates how to run a pipe agent with structured output.


Run Pipe Agent with Structured Output Example

Run Pipe 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); } await createMathTutorPipe(); await runMathTutorPipe('How can I solve 8x + 22 = -23?'); } /** * Create the pipe agent with the name 'math-tutor-agent' * Set the model to 'openai:gpt-4o' * Set the response_format to the JSON schema. * Set the system message to 'You are a helpful math tutor. Guide the user through the solution step by step.' */ async function createMathTutorPipe() { await langbase.pipes.create({ name: 'math-tutor-agent', model: 'openai:gpt-4o', upsert: true, messages: [ { role: 'system', content: 'You are a helpful math tutor. Guide the user through the solution step by step.' }, ], json: true, response_format: { type: 'json_schema', json_schema: { name: 'math_reasoning', schema: jsonSchema, }, }, }); } /** * Run the pipe agent with the name 'math-tutor-agent' * Send the user message to the pipe agent. * Parse the response using Zod and validate the response is correct. * Display the response to the user. **/ async function runMathTutorPipe(question: string) { const {completion} = await langbase.pipes.run({ stream: false, name: 'math-tutor-agent', messages: [ { role: 'user', content: question } ], }); // Parse and validate the response using Zod const solution = MathReasoningSchema.parse(JSON.parse(completion)); console.log('✅ Structured Output Response:', solution); } main();