ChatPromptTemplate.fromTemplates constructor

ChatPromptTemplate.fromTemplates(
  1. List<(ChatMessageType, String)> messages, {
  2. String? customRole,
  3. PartialValues? partialVariables,
  4. bool validateTemplate = true,
})

Creates a ChatPromptTemplate from a list of pairs of chat message prompt template type and template.

Example:

final promptTemplate = ChatPromptTemplate.fromTemplates([
  (ChatMessageType.system, 'You are an assistant that translates {input_language} to {output_language}.'),
  (ChatMessageType.human, '{text}'),
]);
final prompt = promptTemplate.formatPrompt({
    'input_language': 'English',
    'output_language': 'French',
    'text': 'I love programming.',
});
final res = await chatModel.invoke(prompt);
  • messages the list of pairs of type and templates.
  • customRole the role of the message if type is ChatMessageType.custom.
  • partialVariables the partial variables to use for the template.
  • validateTemplate whether to validate the template.

Implementation

factory ChatPromptTemplate.fromTemplates(
  final List<(ChatMessageType, String)> messages, {
  final String? customRole,
  final PartialValues? partialVariables,
  final bool validateTemplate = true,
}) {
  final chatMessagePromptTemplates = messages.map((final message) {
    final (role, template) = message;
    return switch (role) {
      ChatMessageType.human => HumanChatMessagePromptTemplate.fromTemplate(
          template,
          partialVariables: partialVariables,
          validateTemplate: false,
        ),
      ChatMessageType.ai => AIChatMessagePromptTemplate.fromTemplate(
          template,
          partialVariables: partialVariables,
          validateTemplate: false,
        ),
      ChatMessageType.system => SystemChatMessagePromptTemplate.fromTemplate(
          template,
          partialVariables: partialVariables,
          validateTemplate: false,
        ),
      ChatMessageType.custom => CustomChatMessagePromptTemplate.fromTemplate(
          template,
          role: ArgumentError.checkNotNull(customRole, 'customRole'),
          partialVariables: partialVariables,
          validateTemplate: false,
        ),
      ChatMessageType.messagePlaceholder => MessagePlaceholder(
          variableName: template,
        ),
      ChatMessageType.messagesPlaceholder => MessagesPlaceholder(
          variableName: template,
        ),
    };
  }).toList(growable: false);
  return ChatPromptTemplate.fromPromptMessages(
    chatMessagePromptTemplates,
    validateTemplate: validateTemplate,
  );
}