LangChain Tutorial (TypeScript): parsing structured output for intermediate developers

By Cyprian AaronsUpdated 2026-04-21
langchainparsing-structured-output-for-intermediate-developerstypescript

This tutorial shows how to make a LangChain TypeScript chain return structured data you can reliably parse into a typed object. You need this when you want model output that your app can validate, store, or pass into downstream logic without brittle string parsing.

What You'll Need

  • Node.js 18+
  • TypeScript 5+
  • An OpenAI API key
  • These packages:
    • langchain
    • @langchain/openai
    • zod
    • typescript
    • ts-node or a similar runner
  • A .env file with:
    • OPENAI_API_KEY=...

Step-by-Step

  1. Start by defining the shape of the output you want. Use Zod so the schema is both a runtime validator and a source of truth for your TypeScript types.
import { z } from "zod";

const SupportTicketSchema = z.object({
  customerName: z.string(),
  priority: z.enum(["low", "medium", "high"]),
  issueSummary: z.string(),
  requiresEscalation: z.boolean(),
});

type SupportTicket = z.infer<typeof SupportTicketSchema>;
  1. Create a prompt that tells the model to produce structured output. The key is to be explicit about the fields and keep the instruction tight.
import { ChatPromptTemplate } from "@langchain/core/prompts";

const prompt = ChatPromptTemplate.fromMessages([
  [
    "system",
    "You extract support ticket details from user text. Return only valid JSON matching the schema.",
  ],
  ["human", "{input}"],
]);
  1. Use a chat model that supports structured output and bind it to your schema. In LangChain JS, withStructuredOutput handles the parsing for you and returns validated data instead of raw text.
import { ChatOpenAI } from "@langchain/openai";

const model = new ChatOpenAI({
  model: "gpt-4o-mini",
  temperature: 0,
});

const structuredModel = model.withStructuredOutput(SupportTicketSchema);
  1. Build the chain and run it against sample input. This gives you a typed object you can safely use in application code.
import "dotenv/config";

async function main() {
  const chain = prompt.pipe(structuredModel);

  const result: SupportTicket = await chain.invoke({
    input:
      "Hi, I'm Priya Patel. My payment failed three times and I need this escalated because it's blocking an urgent invoice.",
  });

  console.log(result);
}

main().catch(console.error);
  1. If you need stricter control, add an explicit parse step around raw model output. This is useful when you're working with models or providers that don't support native structured output well enough for your use case.
import { JsonOutputParser } from "@langchain/core/output_parsers";

const parser = new JsonOutputParser<SupportTicket>();

async function fallbackExample() {
  const rawChain = prompt.pipe(model).pipe(parser);

  const result = await rawChain.invoke({
    input: "I'm Alex Chen. The shipment never arrived and this is urgent.",
  });

  console.log(result.priority);
}

fallbackExample().catch(console.error);

Testing It

Run the script with ts-node or compile it with tsc and execute the generated JavaScript. You should see an object with customerName, priority, issueSummary, and requiresEscalation, not a free-form paragraph.

Test with inputs that are easy and hard to classify. For example, change the text to something ambiguous like “this is kind of urgent” and confirm the schema still validates while the field values reflect the model’s best interpretation.

If validation fails, inspect whether your prompt is too vague or whether the schema is too strict for real user input. In production, log both the original input and validation errors so you can tune prompts without guessing.

Next Steps

  • Add nested objects and arrays to your Zod schema for more complex extraction tasks.
  • Learn how to combine structured output with tool calling for routing workflows.
  • Add retries and fallback parsers for cases where models return malformed JSON or incomplete fields.

Keep learning

By Cyprian Aarons, AI Consultant at Topiax.

Want the complete 8-step roadmap?

Grab the free AI Agent Starter Kit — architecture templates, compliance checklists, and a 7-email deep-dive course.

Get the Starter Kit

Related Guides