0
0
LangChainframework~5 mins

StrOutputParser for text in LangChain

Choose your learning style9 modes available
Introduction

The StrOutputParser helps you take text output from a process and turn it into a clean, usable form. It makes handling text results easier and more organized.

When you get raw text output from a language model and want to cleanly extract the useful part.
When you want to convert text output into a specific format for your program to use.
When you need to parse and handle text results consistently in a chain of operations.
Syntax
LangChain
from langchain.output_parsers import StrOutputParser

parser = StrOutputParser()

clean_text = parser.parse(output_text)
The parse() method takes raw text and returns it as a clean string.
StrOutputParser is simple and works well when you just want the text without extra processing.
Examples
This example shows how to create the parser and parse a simple text string.
LangChain
from langchain.output_parsers import StrOutputParser

parser = StrOutputParser()
result = parser.parse('Hello, world!')
print(result)
StrOutputParser returns the text as is, so spaces remain unless you clean them yourself.
LangChain
parser = StrOutputParser()
text = '  Some text with spaces  '
clean = parser.parse(text)
print(f'Parsed text: "{clean}"')
Sample Program

This program shows how to use StrOutputParser to get clean text from raw output. It prints the final answer text.

LangChain
from langchain.output_parsers import StrOutputParser

# Create the parser
parser = StrOutputParser()

# Simulate raw output from a language model
raw_output = 'This is the final answer.'

# Parse the output to get clean text
clean_output = parser.parse(raw_output)

print(clean_output)
OutputSuccess
Important Notes

StrOutputParser does not modify the text; it simply returns it as a string.

If you need to extract structured data, consider other parsers designed for that.

Summary

StrOutputParser helps you handle text output simply and cleanly.

Use it when you want to keep the text as is without extra parsing.

It is easy to use with just one parse() method.