Example
Let's start with code to see how it works.
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate
from langchain_openai import ChatOpenAI
prompt = ChatPromptTemplate.from_template("tell me a short joke about {topic}")
model = ChatOpenAI(model="gpt-4")
output_parser = StrOutputParser()
chain = prompt | model | output_parser
chain.invoke({"topic": "ice cream"})
chain = prompt | model | output_parser
The | is the Unix pipe operator. It links components together so that the output of one becomes the input to the next.
Prompt
prompt is a BasePromptTemplate, which means it takes a dictionary of template variables and produces a PromptValue. A PromptValue is a wrapper around a completed prompt that can be passed to an LLM (which accepts a string as input) or a ChatModel (which accepts a sequence of messages). It works with any type of language model because it defines the logic for producing BaseMessages and for producing strings.
Here's the input to PromptValue:
prompt_value = prompt.invoke({"topic": "ice cream"})
prompt_value # ChatPromptValue(messages=[HumanMessage(content='tell me a short joke about ice cream')])
prompt_value.to_messages() # [HumanMessage(content='tell me a short joke about ice cream')]
prompt_value.to_string() # 'Human: tell me a short joke about ice cream'
Model
We then pass the PromptValue to the model. In this case, our model is a ChatModel, which means it outputs a BaseMessage.
message = model.invoke(prompt_value)
message # AIMessage(content="Why don't ice creams ever get invited to parties?\n\nBecause they always bring a melt down!")
If our model were an LLM, it would output a string.
from langchain_openai.llms import OpenAI
llm = OpenAI(model="gpt-3.5-turbo-instruct")
llm.invoke(prompt_value) # '\n\nRobot: Why did the ice cream truck break down? Because it had a meltdown!'
Output parser
Finally, we pass the output from our model to output_parser, which is a BaseOutputParser that accepts a string or BaseMessage as input. This StrOutputParser simply converts any input to a string.
output_parser.invoke(message) # "Why did the ice cream go to therapy? \n\nBecause it had too many toppings and couldn't find its cone-fidence!"
Summary
The flow of execution is shown below:
Execution flow diagram
We turn the user input into a dictionary, pass it to PromptTemplate to wrap it as a PromptValue, and pass that to ChatModel; the model returns a ChatMessage, which we then pass to StrOutputParser to finally parse it into a string.