> ## Documentation Index
> Fetch the complete documentation index at: https://genai.codewithsiva.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Output Parsers

> Format raw LLM responses into structured data types like lists, dictionaries, or Pydantic objects

## 💻 Practice Notebook

Master the concepts from this page with hands-on practice:
[💻 VS Code](vscode://file/Users/sivaprasad/Downloads/GenAI%20With%20Python/public/notebooks/prompt-engg/prompt-engg-parsers-vscode.ipynb) | [🚀 Colab](https://colab.research.google.com/github/prasad230776/genai-course/blob/master/public/notebooks/prompt-engg/prompt-engg-parsers-colab.ipynb) | <a href="/public/notebooks/prompt-engg/prompt-engg-parsers-vscode.ipynb" download>📥 Download Notebook</a>

Large Language Models output plain text. However, applications often require structured data to feed into APIs, databases, or frontend components. Output Parsers bridge this gap.

## 1. Introduction to Output Parsers

LangChain provides several output parsers to structure model outputs:

| Parser                           | Output Type                 | Example Use Case                                                 |
| -------------------------------- | --------------------------- | ---------------------------------------------------------------- |
| `StrOutputParser`                | `str` (String)              | Extracting clean text response (bypassing `AIMessage` wrappers). |
| `JsonOutputParser`               | `dict` (Dictionary)         | Extracting structured JSON keys and values.                      |
| `PydanticOutputParser`           | `BaseModel` (Python Object) | Parsing and validating outputs against a strict data schema.     |
| `CommaSeparatedListOutputParser` | `list` (List of strings)    | Splitting comma-separated words into a Python list.              |

## 2. Using Output Parsers

### 2.1 StrOutputParser

Converts the output of a chat model (`AIMessage`) into a clean, raw string.

```python theme={null}
from langchain_core.output_parsers import StrOutputParser

parser = StrOutputParser()
response = parser.invoke("Hello World")

print(response)       # "Hello World"
print(type(response))  # <class 'str'>
```

### 2.2 JsonOutputParser

Parses JSON-formatted strings generated by LLMs into a native Python dictionary.

```python theme={null}
from langchain_core.output_parsers import JsonOutputParser

parser = JsonOutputParser()
response = parser.invoke("""
{
   "name": "John Doe",
   "age": 30,
   "occupation": "Software Engineer"
}
""")

print(response)       # {'name': 'John Doe', 'age': 30, 'occupation': 'Software Engineer'}
print(type(response))  # <class 'dict'>
```

### 2.3 PydanticOutputParser

Validates the output against a Pydantic model definition. This ensures type safety and field presence.

```python theme={null}
from pydantic import BaseModel
from langchain_core.output_parsers import PydanticOutputParser

# Define the schema
class Person(BaseModel):
    name: str
    age: int
    occupation: str

parser = PydanticOutputParser(pydantic_object=Person)
response = parser.invoke("""
{
   "name": "John Doe",
   "age": 30,
   "occupation": "Software Engineer"
}
""")

print(response)            # Person(name='John Doe', age=30, occupation='Software Engineer')
print(type(response))      # <class 'Person'>
print(response.name)       # "John Doe"
```

### 2.4 CommaSeparatedListOutputParser

Splits comma-separated lists generated by the model into a Python list of strings.

```python theme={null}
from langchain_core.output_parsers import CommaSeparatedListOutputParser

parser = CommaSeparatedListOutputParser()
response = parser.invoke("Python, Java, JavaScript, Go, Rust")

print(response)       # ['Python', 'Java', 'JavaScript', 'Go', 'Rust']
print(type(response))  # <class 'list'>
```

## 3. Practice Exercises

### Practice 1: Comma Separated List Parsing

Create a prompt template that requests the model to list the top 3 programming languages for web development, and chain it with the `CommaSeparatedListOutputParser` to obtain a Python list.

<Accordion title="Solution">
  ```python theme={null}
  from langchain_core.prompts import PromptTemplate
  from langchain_core.output_parsers import CommaSeparatedListOutputParser
  from langchain.chat_models import init_chat_model

  llm = init_chat_model("groq:llama-3.3-70b-versatile")
  parser = CommaSeparatedListOutputParser()

  prompt = PromptTemplate(
      template="List 3 top programming languages for {use_case} as a comma-separated list.",
      input_variables=["use_case"]
  )

  chain = prompt | llm | parser
  result = chain.invoke({"use_case": "web development"})

  print(result)
  print(type(result)) # <class 'list'>
  ```
</Accordion>
