02. Comma SeparatedListOutputParser

CommaSeparatedListOutputParser

CommaSeparatedListOutputParser Is useful when you need to return a comma-separated list of items.

With this output parser, the data entered by the user or the requested information can be separated by commas to be provided in the form of a clear and concise list. For example, when listing multiple data points, names, items, or other types of values, this allows you to effectively organize and pass information to users.

This method structures information, increases readability, and is very useful, especially when dealing with data or requiring results in list form.

from dotenv import load_dotenv

load_dotenv()
True
# LangSmith Set up tracking. https://smith.langchain.com
# !pip install langchain-teddynote
from langchain_teddynote import logging

# Enter a project name.
logging.langsmith("CH03-OutputParser")
 Start tracking LangSmith. 
[Project name] 
CH03-OutputParser
from langchain_core.output_parsers import CommaSeparatedListOutputParser
from langchain_core.prompts import PromptTemplate
from langchain_openai import ChatOpenAI

# Initialize the parser to output a comma-separated list
output_parser = CommaSeparatedListOutputParser()

# Get Output Format Instructions
format_instructions = output_parser.get_format_instructions()
# Setting up a prompt template
prompt = PromptTemplate(
    # Template to list five things about a topic
    template="List five {subject}.\n{format_instructions}",
    input_variables=["subject"],  # As input variable 'subject' use
    # Using format directives with partial variables
    partial_variables={"format_instructions": format_instructions},
)

# ChatOpenAI Initialize model
model = ChatOpenAI(temperature=0)

# Create a chain by connecting prompts, models, and output parsers.
chain = prompt | model | output_parser
  • Run the chain and output the results.

  • chain.stream Use to repeat the stream for "Korea Tourism".

  • Outputs the result of the stream during iteration.

Last updated