A ChatPromptTemplate helps you create clear and organized messages for chatbots or AI conversations. It makes building conversations easier and more consistent.
ChatPromptTemplate for conversations in LangChain
from langchain.prompts import ChatPromptTemplate, SystemMessagePromptTemplate, HumanMessagePromptTemplate chat_prompt = ChatPromptTemplate.from_messages([ SystemMessagePromptTemplate.from_template("{system_instructions}"), HumanMessagePromptTemplate.from_template("{user_input}") ])
Use from_messages to combine different message templates into one chat prompt.
Templates use curly braces {} to mark where input values go.
chat_prompt = ChatPromptTemplate.from_messages([
SystemMessagePromptTemplate.from_template("You are a helpful assistant."),
HumanMessagePromptTemplate.from_template("Hello! Can you help me?")
])chat_prompt = ChatPromptTemplate.from_messages([
SystemMessagePromptTemplate.from_template("You are a friendly assistant."),
HumanMessagePromptTemplate.from_template("What is the weather in {city}?")
])This example creates a chat prompt template with a system message and a user message that asks about a topic. Then it fills in the topic and prints the conversation messages.
from langchain.prompts import ChatPromptTemplate, SystemMessagePromptTemplate, HumanMessagePromptTemplate # Create a chat prompt template with placeholders chat_prompt = ChatPromptTemplate.from_messages([ SystemMessagePromptTemplate.from_template("You are a helpful assistant."), HumanMessagePromptTemplate.from_template("Tell me about {topic}.") ]) # Fill in the placeholder with actual input filled_prompt = chat_prompt.format_prompt(topic="Python programming") # Print the messages in the conversation for message in filled_prompt.messages: print(f"{message.type}: {message.content}")
Always use format_prompt to fill in your template with real values before sending it to the AI.
You can add more message types like AI messages if needed for complex conversations.
Keep your templates simple and clear to avoid confusion in the conversation flow.
ChatPromptTemplate organizes chat messages into a clear conversation structure.
Use placeholders to insert dynamic user inputs easily.
This helps build reusable and consistent chatbots or AI conversations.