LangChain Structured Output in NestJS: Typed with Zod
Описание и применение
В NestJS с LangChain и Zod агент возвращает типизированный объект OrderDraft вместо текста, упрощая обработку заказов.
Задача
Obtaining structured, typed output from a LangChain agent in a NestJS backend instead of raw text.
Результат
The agent now returns a typed OrderDraft object, simplifying backend logic and improving reliability.
Рабочий процесс
- 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.
Доказательства
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.
- Дата записи: 2026-11-02T04:43:44.687Z