-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMessage.php
More file actions
101 lines (85 loc) · 2.81 KB
/
Copy pathMessage.php
File metadata and controls
101 lines (85 loc) · 2.81 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
<?php
declare(strict_types=1);
namespace fholbrook\Openrouter\DTO;
use fholbrook\Openrouter\Contracts\StampInterface;
class Message
{
public function __construct(
/**
* The content of the message.
*
* @var string|TextContent[]|ImageContent[]|array|null
*/
public string|array|null $content = null,
/**
* The entity that produced the message.
* Possible values are user, assistant, system, function, tool
*
* @var string|null
*/
public ?string $role = null,
/**
* Calling tools e.g. function
*
* @var ToolCall[]|null
*/
public ?array $toolCalls = null,
/**
* An optional name for the participant. Provides the model information to differentiate between participants of the same role.
* e.g. name: "Moe"
*
* @var string|null
*/
public ?string $name = null,
/**
* @var StampInterface[]
*/
public array $stamps = []
) {
}
public function getStampByFQDN(string $fqdn): ?StampInterface
{
foreach ($this->stamps as $stamp) {
if ($stamp::class === $fqdn) {
return $stamp;
}
}
return null;
}
public function addStamp(?StampInterface $stamp): void
{
if ($stamp instanceof StampInterface) {
$this->stamps[] = $stamp;
}
}
public function toArray(bool $includeStamps = false): array
{
$a = array_filter(
[
'content' => (is_array($this->content) ? array_map(fn($content) => (is_object($content) ? $content->toArray() : $content), $this->content) : $this->content),
'role' => $this->role,
'toolCalls' => $this->toolCalls ? array_map(fn($toolCall) => $toolCall->toArray(), $this->toolCalls) : null,
'name' => $this->name
]
);
if ($includeStamps) {
$a['stamps'] = $this->stamps ? array_map(fn(StampInterface $stamp) => array_merge($stamp->toArray(), ['fqdn' => get_class($stamp)]), $this->stamps) : null;
}
return $a;
}
public static function fromArray(array $data): self
{
return new self(
$data['content'],
$data['role'],
!empty($data['toolCalls']) ? array_map(fn($toolCall) => ToolCall::fromArray($toolCall), $data['toolCalls']) : null,
isset($data['name']) ? $data['name'] : null,
!empty($data['stamps']) ? array_map(fn(array $stamp) => self::stampFromArray($stamp), $data['stamps']) : []
);
}
private static function stampFromArray(array $data): StampInterface
{
$fqdn = $data['fqdn'];
return $fqdn::fromArray($data);
}
}