- Turning a numbered list into a comma-separated string
- Parsing that string into a Python list
Table of Contents
- Prerequisites
- Initializing LangChain and OpenAI
- Generating an Unstructured List
- Formatting as CSV with CommaSeparatedListOutputParser
- Parsing the CSV into a Python List
- Next Steps
- References
Prerequisites
- Python 3.7+
- An OpenAI API key
langchaininstalled
Initializing LangChain and OpenAI
Import the core components:Generating an Unstructured List
Define a simple prompt template without format constraints:This human-readable list is great for display but difficult to process in scripts. Next, we’ll add format instructions for a comma-separated response.
Formatting as CSV with CommaSeparatedListOutputParser
-
Instantiate the CSV parser and retrieve its instructions:
Expected instruction:
-
Embed these instructions into a new prompt template:
-
Invoke the LLM with the CSV constraint:
Now the model returns:
Parsing the CSV into a Python List
Convert the raw string into a Python list:things directly in your application.
Next Steps
Explore more advanced parsers for structured outputs:| Parser Type | Use Case | Example |
|---|---|---|
| CommaSeparatedListOutputParser | Simple lists in CSV | foo, bar, baz |
| ListOutputParser | Numbered or bullet lists | 1. foo\n2. bar\n |
| JSONOutputParser | Complex nested data structures | { "name": "Alice", "age": 30 } |
JSONOutputParser to extract richer data types from LLM responses.
References
- LangChain Output Parsers
- PromptTemplate Documentation
- OpenAI LLM Client
- CommaSeparatedListOutputParser Source