Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

Messages.php

85 lines2.0 KB

1<?php
2​
3declare(strict_types=1);
4​
5function text_from_message(array $message): string
6{
7 if (!empty($message['parts']) && is_array($message['parts'])) {
8 $parts = [];
9 foreach ($message['parts'] as $part) {
10 if (!is_array($part)) {
11 continue;
12 }
13 if (($part['type'] ?? '') === 'text' && is_string($part['content'] ?? null) && $part['content'] !== '') {
14 $parts[] = $part['content'];
15 }
16 }
17 if ($parts !== []) {
18 return implode('', $parts);
19 }
20 }
21​
22 if (!array_key_exists('content', $message)) {
23 return '';
24 }
25​
26 $content = $message['content'];
27​
28 if (is_string($content)) {
29 return $content;
30 }
31​
32 if (is_array($content)) {
33 $parts = [];
34 foreach ($content as $item) {
35 if (!is_array($item)) {
36 continue;
37 }
38 if (($item['type'] ?? '') === 'text' && is_string($item['text'] ?? null)) {
39 $parts[] = $item['text'];
40 }
41 }
42 return implode('', $parts);
43 }
44​
45 return trim((string) $content);
47​
48function to_chat_messages(array $messages): array
50 $system = '';
51 $chat = [];
52​
53 foreach ($messages as $message) {
54 if (!is_array($message)) {
55 continue;
56 }
57​
58 $role = is_string($message['role'] ?? null) ? $message['role'] : '';
59 switch ($role) {
60 case 'developer':
61 $role = 'system';
62 break;
63 case 'tool':
64 case 'reasoning':
65 continue 2;
66 }
67​
68 $text = text_from_message($message);
69 if ($text === '') {
70 continue;
71 }
72​
73 switch ($role) {
74 case 'system':
75 $system = $system === '' ? $text : $system . "\n\n" . $text;
76 break;
77 case 'user':
78 case 'assistant':
79 $chat[] = ['role' => $role, 'content' => $text];
80 break;
81 }
82 }
83​
84 return [$system, $chat];