ChatPromptTemplate constructor

const ChatPromptTemplate({
  1. required Set<String> inputVariables,
  2. PartialValues? partialVariables,
  3. required List<ChatMessagePromptTemplate> promptMessages,
})

A prompt template for chat models.

Whereas LLMs take a string as prompt, Chat models take a list of messages. ChatPromptTemplate uses a list of template messages to generate the final prompt.

Each template message can be:

Example:

final promptTemplate = ChatPromptTemplate.fromPromptMessages([
  ChatMessagePromptTemplate.system("Here's some context: {context}"),
  ChatMessagePromptTemplate.human("Hello {foo}, I'm {bar}. Thanks for the {context}"),
  ChatMessagePromptTemplate.ai("I'm an AI. I'm {foo}. I'm {bar}."),
]);
final prompt = promptTemplate.formatPrompt({
    'foo': 'GPT-4',
    'bar': 'Gemini',
    'context': 'competition',
});
final res = await chatModel.invoke(prompt);

If you prompt template only contains one message, you can use the convenient factory constructor ChatPromptTemplate.fromTemplate.

final promptTemplate = ChatPromptTemplate.fromTemplate("Hello {foo}, I'm {bar}. Thanks for the {context}");

If your prompt template contains multiple messages, you can use the convenient factory constructor ChatPromptTemplate.fromTemplates.

final promptTemplate = ChatPromptTemplate.fromTemplates([
  (ChatMessageType.system, 'You are a helpful assistant that translates {input_language} to {output_language}.'),
  (ChatMessageType.human, '{text}'),
]);

If you need a placeholder for a single message or a list of messages, you can use MessagePlaceholder or MessagesPlaceholder.

final promptTemplate = ChatPromptTemplate.fromTemplates([
  (ChatMessageType.system, "You are a helpful AI assistant."),
  (ChatMessageType.messagesPlaceholder, 'history'),
  (ChatMessageType.messagePlaceholder, 'input'),
]);

In general, prefer using ChatPromptTemplate.fromTemplate and ChatPromptTemplate.fromTemplates to create a ChatPromptTemplate as the resulting code is more readable. Use the main ChatPromptTemplate constructor or ChatPromptTemplate.fromPromptMessages for advanced use cases.

Implementation

const ChatPromptTemplate({
  required super.inputVariables,
  super.partialVariables,
  required this.promptMessages,
});