Generative AIby Dhruv Narang

1. Why Structured Output?

Apps send data through an API, save it in a database, or show it on a screen. All of them need data. But an LLM always answers in text.

TextWhat the LLM gives
Here are four popular programming languages widely used today: 1. **Python** – Known for its simplicity…
↓so we convert it
DataWhat your app needs
An API
{"languages": ["Python", "Java"]}
sends JSON
A database
one row per language
saves values
A screen
PythonJava
shows a list

2. What Is an Output Parser?

Definition

An output parser converts the model's reply text into the structure your app needs.

The model replied
Python, JavaScript, Java, C++
Text
→output parser
Your app gets
PythonJavaScriptJavaC++
Data: a list

3. Types of Output Parsers

LangChain gives you ready-made parsers. Some of them also give you format instructions: text you add to your prompt, so the model writes in the right shape. You get it by calling get_format_instructions() on the parser.

ParserGives youFormat instructions
StrOutputParserstrnone
CommaSeparatedListOutputParserlistadded to the prompt
JsonOutputParserdictadded to the prompt
PydanticOutputParseryour own objectadded to the prompt
from langchain_core.output_parsers import StrOutputParser

res1 = model.invoke("What is the capital of India? Answer in one word.")

str_parser = StrOutputParser()
print(str_parser.invoke(res1))from langchain_core.output_parsers import CommaSeparatedListOutputParser
from langchain_core.prompts import ChatPromptTemplate

list_parser = CommaSeparatedListOutputParser()

template2 = ChatPromptTemplate.from_template(
    "Give 4 popular programming languages.\n{format_instructions}"
)
prompt2 = template2.invoke({
    "format_instructions": list_parser.get_format_instructions(),
})
res2 = model.invoke(prompt2)

languages = list_parser.invoke(res2)
print(languages)from langchain_core.output_parsers import JsonOutputParser
from langchain_core.prompts import ChatPromptTemplate

json_parser = JsonOutputParser()

template3 = ChatPromptTemplate.from_template(
    "Give the capital and currency of {country}.\n{format_instructions}"
)
prompt3 = template3.invoke({
    "country": "Japan",
    "format_instructions": json_parser.get_format_instructions(),
})
res3 = model.invoke(prompt3)
print(res3.content)

data = json_parser.invoke(res3)
Format instructions: text added to your prompt
None. StrOutputParser adds nothing to your prompt.Your response should be a list of comma separated values, eg: `foo, bar, baz` or `foo,bar,baz`Return a JSON object.
The model replied
AIMessage(content='New Delhi', response_metadata={…}Python, JavaScript, Java, C++```json
{
  "country": "Japan",
  "capital": "Tokyo",
  "currency": {
    "code": "JPY",
    "name": "Japanese Yen",
    "symbol": "¥"
  }
}
```
You get
'New Delhi'['Python', 'JavaScript', 'Java', 'C++']{'country': 'Japan', 'capital': 'Tokyo', 'currency': {'code': 'JPY', 'name': 'Japanese Yen', 'symbol': '¥'}}
Takes the text out of the AIMessage.Splits the reply on commas into a list.Removes the fences and reads the JSON into a dict.

4. What the Parser Does With the Reply

A parser does not clean the reply by magic. Each parser reads the text in its own way, and a model sometimes writes more than you asked.

The format instructions do not ask for backticks. Many chat models write JSON inside a ```json block by habit. The JSON parser is built for this.
1. Try
Read the whole reply
It is read as JSON. This fails if there is text before the JSON.
2. Find
Look for ```
Take everything after the first ```.
3. Clean
Trim both ends
Spaces, new lines and backticks go.
4. Read
Read the JSON
Text left over is ignored.
The comma parser only splits at commas. Extra sentences or backticks stay in the list.
Code
Output parsers01_output_parsers.py · 55 linesShow code
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
from dotenv import load_dotenv
from langchain.chat_models import init_chat_model
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser, CommaSeparatedListOutputParser, JsonOutputParser

load_dotenv()

model = init_chat_model("mistralai:open-mistral-nemo", temperature=0)

"""Parser = extra format text in the prompt + convert the reply text"""

"""1. StrOutputParser: AIMessage -> text"""
res1 = model.invoke("What is the capital of India? Answer in one word.")
print(res1)

str_parser = StrOutputParser()
print(str_parser.invoke(res1))


"""2. CommaSeparatedListOutputParser: text -> list (split by comma)"""
list_parser = CommaSeparatedListOutputParser()
print(list_parser.get_format_instructions())

template2 = ChatPromptTemplate.from_template(
    "Give 4 popular programming languages.\n{format_instructions}"
)
prompt2 = template2.invoke({
    "format_instructions": list_parser.get_format_instructions(),
})
res2 = model.invoke(prompt2)

languages = list_parser.invoke(res2)
print(languages)
print(type(languages))


"""3. JsonOutputParser: text -> dict (removes ```json, then json.loads)"""
json_parser = JsonOutputParser()
print(json_parser.get_format_instructions())

template3 = ChatPromptTemplate.from_template(
    "Give the capital and currency of {country}.\n{format_instructions}"
)
prompt3 = template3.invoke({
    "country": "Japan",
    "format_instructions": json_parser.get_format_instructions(),
})
res3 = model.invoke(prompt3)
print(res3.content)

data = json_parser.invoke(res3)
print(data)
print(type(data))
print(data["capital"])