Besides simple prompt templates, there are also chat prompt templates.
Prompt templates are used for tasks that involve generating text, such as
answering questions or completing sentences, and chat prompt templates are
specifically designed for tasks that involve engaging in conversations.
As we ve already discussed, the ChatCompletions API consists of a list of
messages, SystemMessage, HumanMessage, or the prompt and a message.
I will import some classes from the Langchain library, from LangchainPrompts,
Import, ChatPromptTemplate and the HumanMessagePromptTemplate, and from
LangchainCore, Messages, Import, SystemMessage.
HumanMessagePromptTemplate is used to
create dynamic prompts from the user s text and the SystemMessage is used to
format the system message.
Note that there is also a class called
ChatSystemMessagePromptTemplate if you want to generate dynamic system messages.
Now, I will create a new ChatPromptTemplate object from a list of messages.
ChatTemplate equals ChatPromptTemplate .fromMessages and the argument will be a list.
The first message is the SystemMessage and the second message is the
HumanMessagePromptTemplate that represents the user s input.
Now, the arguments.
SystemMessage of content equals and the string.
You respond only in the JSON format and the HumanMessagePromptTemplate
.fromTemplate, I m calling the fromTemplate function of top n countries
in area in curly braces by population.
The placeholders n and area will be
replaced with the actual input text.
Next, I will format the
ChatPromptTemplate object by replacing the placeholders with the provided value.
So, messages equals ChatTemplate .formatMessage of n equals 10 as a string
and area equals Europe.
The resulting messages list contains the
formatted SystemMessage and HumanMessage.
Let s print it print messages and I
running the code.
This is the formatted prompt.
It contains a SystemMessage and a HumanMessage.
n in curly braces was replaced with pen
and area in curly braces was replaced with Europe.
From going with the defaults output equals llm .invoke of messages and I m
printing the output printOutput .content.
I m running the code very well.
Notice how it responded in JSON according to the instructions in the SystemPrompt.
You ve learned about prompt templates and chat prompt templates.
They give you a lot of flexibility in the way you build your chat prompts.
Some benefits of using prompt templates include reusability, scalability and accuracy.
For example, if you want a response with the top 5 countries by population in the
world, you can simply change the argument of chatTemplate .formatMessage, 5 and 1.
You don t have to change the entire prompt.
We are done with prompt templates for the
moment, please take your time to fully understand them as they are a key
component of Langchain.