> ## 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.

# 3. Parsers Basics

> Learn how to set up and use StrOutputParser and CommaSeparatedListOutputParser

In this section, you will learn how to extract plain text and convert comma-separated string outputs from LLMs into Python list objects.

## Objectives

1. Understand why output parsers are required.
2. Initialize and configure `StrOutputParser` to clean LLM response objects.
3. Configure `CommaSeparatedListOutputParser` and feed format instructions to the LLM.

***

## Invoking Parsers: `.invoke()` vs `.parse()`

When using LangChain output parsers step-by-step, you have two primary methods to run them:

1. **`.invoke(response)`**: Passes the entire model response object (like `AIMessage`). LangChain automatically extracts the raw string under the hood and parses it.
2. **`.parse(raw_text)`**: Passes a raw Python `str` (e.g., `response.content`). Use this when you have manually extracted the text or are parsing raw strings from external sources.

> \[!NOTE]
> In production LCEL chains, the pipe operator `|` automatically runs `.invoke()` behind the scenes, making `.invoke()` the standard approach for unified LangChain components.

***

## Code Implementation

Each step of the implementation is preceded by extensive comments explaining the code logic.

### Setup and Initialization

First, we load environment variables and initialize our chat model using core abstractions (Groq provider).

```python theme={null}
from dotenv import load_dotenv
from langchain.chat_models import init_chat_model

# Load environment variables
load_dotenv()

# Initialize the Groq model using core abstractions
model = init_chat_model("llama-3.3-70b-versatile", model_provider="groq")
```

***

### StrOutputParser

The simplest output parser. It extracts the raw string message content from the model's chat response object.

```python theme={null}
from langchain.prompts import ChatPromptTemplate
from langchain.schema.output_parser import StrOutputParser

# Define prompt template
str_prompt = ChatPromptTemplate.from_messages([
    ("system", "You are a helpful assistant."),
    ("human", "Tell me a one-sentence fun fact about the ocean.")
])

# 1. Format the prompt
str_messages = str_prompt.format_messages()

# 2. Invoke the model to get the response object (AIMessage)
str_response = model.invoke(str_messages)

# 3. Use the parser to extract the string content
parser = StrOutputParser()
str_result = parser.invoke(str_response)

print("Parsed String Output:")
print(str_result)
```

***

### CommaSeparatedListOutputParser

Instructs the model to return a list of items separated by commas, then parses that raw string into a standard Python list.

```python theme={null}
from langchain.prompts import ChatPromptTemplate
from langchain.output_parsers import CommaSeparatedListOutputParser

# Instantiate the list parser
list_parser = CommaSeparatedListOutputParser()

# Get format instructions generated by the parser
format_instructions = list_parser.get_format_instructions()

# Define prompt incorporating format instructions
list_prompt = ChatPromptTemplate.from_messages([
    ("system", "List the requested items. {format_instructions}"),
    ("human", "List 5 top programming languages in 2026.")
])

# 1. Format the prompt with inputs and instructions
list_messages = list_prompt.format_messages(format_instructions=format_instructions)

# 2. Invoke the model
list_response = model.invoke(list_messages)

# 3. Parse the raw string response into a Python list
list_result = list_parser.parse(list_response.content)

print("Parsed List Output:")
print(list_result)
```

***

## Practice & Exercises

To reinforce what you've learned in this section, practice with the interactive notebook:

<CardGroup cols={1}>
  <Card title="Practice & Exercises" icon="laptop-code">
    Practice extracting strings and comma-separated lists from LLM outputs.

    [💻 VS Code](vscode://file/Users/sivaprasad/Downloads/GenAI%20With%20Python/public/notebooks/langchain/3_parsers_basics.ipynb) | [🚀 Colab](https://colab.research.google.com/github/prasad230776/genai-course/blob/master/public/notebooks/langchain/3_parsers_basics.ipynb) | <a href="/public/notebooks/langchain/3_parsers_basics.ipynb" download>📥 Download</a>
  </Card>
</CardGroup>
