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

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

This tutorial shows how to make a LangChain TypeScript app return structured data you can actually trust, instead of brittle free-form text. You need this when your downstream code expects stable fields for validation, routing, persistence, or API responses.

What You'll Need

  • Node.js 18+
  • A TypeScript project with tsconfig.json
  • npm or pnpm
  • Packages:
    • langchain
    • @langchain/openai
    • zod
    • dotenv
    • typescript
    • tsx or another TS runner
  • An OpenAI API key in .env:
    • OPENAI_API_KEY=...

Step-by-Step

  1. Start with a schema first. If you define the shape up front, you can validate the model output before it hits your application logic.
import "dotenv/config";
import { z } from "zod";

const CustomerIntentSchema = z.object({
  customerName: z.string(),
  intent: z.enum(["claim_status", "policy_change", "billing_question"]),
  urgency: z.enum(["low", "medium", "high"]),
  summary: z.string(),
});

type CustomerIntent = z.infer<typeof CustomerIntentSchema>;
  1. Create a model and a structured output parser. LangChain’s parser gives you a format instruction string plus runtime validation against the Zod schema.
import { ChatOpenAI } from "@langchain/openai";
import { StructuredOutputParser } from "@langchain/core/output_parsers";

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

const parser = StructuredOutputParser.fromZodSchema(CustomerIntentSchema);
const formatInstructions = parser.getFormatInstructions();
  1. Build a prompt that forces the model to emit parseable JSON. Keep the instructions explicit and put the parser instructions in the template, not in your head.
import { ChatPromptTemplate } from "@langchain/core/prompts";

const prompt = ChatPromptTemplate.fromMessages([
  [
    "system",
    "You extract structured customer intent data for an insurance workflow.",
  ],
  [
    "user",
    `Extract fields from this message and follow the format instructions exactly.

Message:
{message}

{format_instructions}`,
  ],
]);
  1. Run the chain and parse the response into typed data. At this point you want one object back, not a blob of text with markdown fences and extra commentary.
const message =
  "Hi, I'm Priya Patel. I need to update my policy address and I'm worried about an upcoming billing charge.";

const chain = prompt.pipe(llm).pipe(parser);

async function main() {
  const result: CustomerIntent = await chain.invoke({
    message,
    format_instructions: formatInstructions,
  });

  console.log(result);
}

main().catch(console.error);
  1. Add defensive handling for invalid output. In production, treat parsing errors as normal control flow because models will occasionally drift when prompts change or inputs get messy.
async function safeParse(message: string) {
  try {
    const result = await chain.invoke({ message, format_instructions: formatInstructions });
    return { ok: true as const, data: result };
  } catch (error) {
    return {
      ok: false as const,
      error: error instanceof Error ? error.message : String(error),
    };
  }
}

safeParse("I want to check my claim status after last week's accident.")
  .then(console.log)
  .catch(console.error);

Testing It

Run the script with a real customer-like input and confirm you get a plain object with customerName, intent, urgency, and summary. Then test edge cases like multiple intents in one message, missing names, or vague wording to see how often the parser rejects bad output. If you want stronger guarantees, add unit tests around the Zod schema itself and integration tests around the chain invocation. The key signal is simple: your app should fail loudly on malformed structure instead of silently accepting garbage.

Next Steps

  • Add retry logic with a stricter re-prompt when parsing fails.
  • Move from single-object extraction to arrays of objects for multi-entity extraction.
  • Combine this pattern with tool calling when you need both structured extraction and side effects.

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