LangChain Structured Output in NestJS: Typed with Zod
Description and use
In NestJS with LangChain and Zod, the agent returns a typed OrderDraft object instead of raw text, simplifying order processing.
Problem
Obtaining structured, typed output from a LangChain agent in a NestJS backend instead of raw text.
Outcome
The agent now returns a typed OrderDraft object, simplifying backend logic and improving reliability.
Workflow
- Define a Zod schema OrderDraft with sku (string) and quantity (positive integer).
- Import OrderDraft into the OrdersController.
- Call agent.run() with the customer message and pass {output: OrderDraft} to enforce structured output.
- Return the output object from the controller method.
- Add OrdersController to AppModule controllers.
- Test the endpoint with curl to verify JSON response.
- Optionally run tests with LangChain fakeModel() to validate without API key.
Evidence
To get an object instead of text from a LangChain agent in NestJS, pass a Zod schema as output to run().
Same message, same model. Without a schema, the agent answers in text, and your code has to dig the SKU out of a sentence. With one, it answers an object, checked against the schema and typed by it.
- Record date: 2026-11-02T04:43:44.687Z