WordPress\AiClient\Providers\OpenAiCompatibleImplementation
AbstractOpenAiCompatibleTextGenerationModel::prepareMessagesParam
Prepares the messages parameter for the API request.
Method of the class: AbstractOpenAiCompatibleTextGenerationModel{}
No Hooks.
Returns
list
Usage
// protected - for code of main (parent) or child class $result = $this->prepareMessagesParam( $messages, ?string $systemInstruction ): array;
- $messages(list
) (required) - The messages to prepare.
- ?string $systemInstruction
- .
Default:null
Changelog
| Since 0.1.0 | Introduced. |
AbstractOpenAiCompatibleTextGenerationModel::prepareMessagesParam() AbstractOpenAiCompatibleTextGenerationModel::prepareMessagesParam code WP 7.0
protected function prepareMessagesParam(array $messages, ?string $systemInstruction = null): array
{
$messagesParam = array_map(function (Message $message): array {
// Special case: Function response.
$messageParts = $message->getParts();
if (count($messageParts) === 1 && $messageParts[0]->getType()->isFunctionResponse()) {
$functionResponse = $messageParts[0]->getFunctionResponse();
if (!$functionResponse) {
// This should be impossible due to class internals, but still needs to be checked.
throw new RuntimeException('The function response typed message part must contain a function response.');
}
return ['role' => 'tool', 'content' => json_encode($functionResponse->getResponse()), 'tool_call_id' => $functionResponse->getId()];
}
$messageData = ['role' => $this->getMessageRoleString($message->getRole()), 'content' => array_values(array_filter(array_map([$this, 'getMessagePartContentData'], $messageParts)))];
// Only include tool_calls if there are any (OpenAI rejects empty arrays).
$toolCalls = array_values(array_filter(array_map([$this, 'getMessagePartToolCallData'], $messageParts)));
if (!empty($toolCalls)) {
$messageData['tool_calls'] = $toolCalls;
}
return $messageData;
}, $messages);
if ($systemInstruction) {
array_unshift($messagesParam, [
/*
* TODO: Replace this with 'developer' in the future.
* See https://platform.openai.com/docs/api-reference/chat/create#chat_create-messages
*/
'role' => 'system',
'content' => [['type' => 'text', 'text' => $systemInstruction]],
]);
}
return $messagesParam;
}