
This lesson assumes your OpenAI API key is already configured in your environment.
Quick overview
- Goal: Instruct an LLM to return a comma-separated list and parse it into a native Python
list. - Approach: Append parser-provided
format_instructionsto the prompt so the model emits a predictable format, then use the parser to convert the text to Python objects.
1. Imports and basic prompt setup
Import the required classes, create an LLM client, and define a simple prompt template.2. Invoke the model with a simple prompt (raw output)
Call the LLM without any parser instructions to see the default textual output.3. Add a CommaSeparatedListOutputParser and get format instructions
TheCommaSeparatedListOutputParser provides human-readable instructions that you append to your prompt. These instructions encourage the LLM to produce CSV-style output that can be parsed reliably.
4. Inject the format instructions into the prompt
Usepartial_variables in PromptTemplate to include the parser’s format_instructions in the prompt. This keeps your prompt template flexible and reusable.
final_prompt will look like:
Tip: Using
partial_variables lets you add dynamic instructions (like format hints) without changing the main prompt template every time.5. Invoke the model with the parser-aware prompt and parse the output
Now the model is instructed to return CSV-style text. After receiving the text, feed it tooutput_parser.parse() to get a Python list.
Summary
- Append parser
format_instructionsto your prompt to guide the model toward a predictable output format (CSV in this example). - Use
CommaSeparatedListOutputParserto transform the returned string into a native Pythonlist. - This pattern reduces brittle string processing and improves data reliability when integrating LLM responses into applications.
Quick reference table
Next steps
- Try other output parsers (for example, JSON-specific parsers) if you need objects/dictionaries directly from the model.
- Combine parser format instructions with few-shot examples when you need stronger conditioning.
- Validate parsed outputs before using them in production systems to handle cases where the model doesn’t follow instructions exactly.
Links and references
LLMs may sometimes ignore formatting instructions. Always validate parser output and add fallback handling for unexpected formats.