Разбор и проверка структурированного вывода
Заставляйте LLM возвращать надёжные структурированные данные с помощью анализаторов вывода и схем, а также проверяйте результат или повторяйте запрос, если модель создаёт некорректный вывод.
«Разбор и проверка структурированного вывода» — бесплатный урок AI Agents with LangChain & Autonomous Workflows на CoddyKit. Это урок 4 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения AI Agents with LangChain & Autonomous Workflows, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс AI Agents with LangChain & Autonomous Workflows содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
The Problem with Free Text
LLMs return prose by default, but your code needs structured data: JSON, a list, a typed object. Parsing free text with regex is fragile.
This lesson covers getting reliable structured output from models.
Asking for a Format
The first step is simply instructing the model to produce a specific format. But instruction alone is not enough; models drift, add prose, or wrap output in markdown.
prompt = 'Extract name and age as JSON: "Lena is 30"'
# model might reply: 'Sure! {"name":"Lena","age":30}'Output Parsers
LangChain output parsers do two jobs: they generate format instructions to inject into the prompt, and they parse the model's response back into a structured object.
from langchain.output_parsers import CommaSeparatedListOutputParser
parser = CommaSeparatedListOutputParser()
print(parser.get_format_instructions())Schema-Based Parsing
Define the shape you want with a schema (e.g. a Pydantic model). The parser turns it into instructions and validates the result against the fields and types.
from pydantic import BaseModel
class Person(BaseModel):
name: str
age: intInjecting Format Instructions
Add the parser's instructions into your prompt template so the model knows exactly what structure to emit.
template = 'Extract info.\n{format_instructions}\nText: {text}'
prompt = template.format(
format_instructions=parser.get_format_instructions(),
text='Lena is 30')Parsing the Response
After the model replies, the parser converts the text into your typed object, raising an error if it does not match the schema.
result = parser.parse(model_output)
print(result.name, result.age)Handling Malformed Output
Models occasionally produce invalid JSON. A retry/fixing parser detects the failure and asks the model to correct its own output, turning a hard crash into a recoverable step.
from langchain.output_parsers import RetryOutputParser
robust = RetryOutputParser.from_llm(parser=parser, llm=llm)Native JSON / Tool Modes
Many modern models support a JSON mode or function/tool calling that constrains output to valid structured data at the API level. When available, this is far more reliable than prompt instructions alone.
Validation Beyond Types
A value can be the right type but still wrong: a negative age, an empty required field. Add validators so business rules are enforced, not just the data shape.
if result.age < 0 or result.age > 130:
raise ValueError('age out of range')Why It Matters for Agents
Agents chain steps together, feeding one output into the next. If a step emits malformed data, the whole chain breaks. Structured, validated output is what makes multi-step agents dependable.
A Reliable Output Workflow
Putting it together:
- Define a schema for the data you need
- Inject format instructions into the prompt
- Prefer native JSON/tool mode when available
- Parse and validate, with a retry parser as a safety net
Quick Check
Test your understanding of structured output.
Recap
You learned to get reliable structured data from LLMs.
- Output parsers generate instructions and parse responses
- Schemas validate shape and types
- Retry parsers recover from malformed output
- Native JSON/tool modes are most reliable when available
Часто задаваемые вопросы
Урок «Разбор и проверка структурированного вывода» бесплатный?
Да — полный текст урока «Разбор и проверка структурированного вывода» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс AI Agents with LangChain & Autonomous Workflows, подпишись на CoddyKit PRO. Курс AI Agents with LangChain & Autonomous Workflows содержит 4 уроков всего.
Чему я научусь в уроке «Разбор и проверка структурированного вывода»?
Заставляйте LLM возвращать надёжные структурированные данные с помощью анализаторов вывода и схем, а также проверяйте результат или повторяйте запрос, если модель создаёт некорректный вывод. Ты практикуешь AI Agents with LangChain & Autonomous Workflows с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать AI Agents with LangChain & Autonomous Workflows?
Предыдущий опыт не требуется. AI Agents with LangChain & Autonomous Workflows на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 4 из 4.
Сколько времени занимает урок «Разбор и проверка структурированного вывода»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке AI Agents with LangChain & Autonomous Workflows?
Да. Каждый урок AI Agents with LangChain & Autonomous Workflows включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Эффективные методы проектирования промптов
- Интеграция LLM с LangChain
- Управление параметрами и затратами моделей
- Разбор и проверка структурированного вывода