buildApiMessages method

List<Map<String, dynamic>> buildApiMessages(
  1. List<ChatMessage> messages
)

Build API messages array from ChatMessage list

Note: System prompt should be added by the calling module if needed, not here to avoid duplication.

Implementation

List<Map<String, dynamic>> buildApiMessages(List<ChatMessage> messages) {
  final apiMessages = <Map<String, dynamic>>[];

  // Convert messages to OpenAI format
  for (final message in messages) {
    if (message.messageType is ToolResultMessage) {
      // Expand tool results into separate `tool` role messages.
      //
      // OpenAI expects the tool message content to be the tool OUTPUT,
      // not the original function arguments, so we prefer the
      // ChatMessage.content here and only fall back to arguments if the
      // content is empty.
      final toolResults = (message.messageType as ToolResultMessage).results;
      for (final result in toolResults) {
        apiMessages.add({
          'role': 'tool',
          'tool_call_id': result.id,
          'content': message.content.isNotEmpty
              ? message.content
              : (result.function.arguments.isNotEmpty
                  ? result.function.arguments
                  : 'Tool result'),
        });
      }
    } else {
      apiMessages.add(convertMessage(message));
    }
  }

  return apiMessages;
}