-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathMoonshot.php
More file actions
223 lines (195 loc) · 6.51 KB
/
Moonshot.php
File metadata and controls
223 lines (195 loc) · 6.51 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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
<?php
namespace Utopia\Agents\Adapters;
use Utopia\Agents\Message;
use Utopia\Agents\Messages\Text;
use Utopia\Fetch\Chunk;
use Utopia\Fetch\Client;
class Moonshot extends OpenAI
{
/**
* Default Moonshot API endpoint
*/
protected const ENDPOINT = 'https://api.moonshot.ai/v1/chat/completions';
/**
* Kimi K2.5 - General-purpose Moonshot model optimized for long-context chat and coding workflows
*/
public const MODEL_KIMI_K2_5 = 'kimi-k2.5';
/**
* Create a new Moonshot adapter
*
* @throws \Exception
*/
public function __construct(
string $apiKey,
string $model = self::MODEL_KIMI_K2_5,
int $maxTokens = 1024,
float $temperature = 1.0,
?string $endpoint = null,
int $timeout = 90000
) {
parent::__construct(
$apiKey,
$model,
$maxTokens,
$temperature,
$endpoint ?? self::ENDPOINT,
$timeout
);
}
/**
* Check if the model supports structured output.
*
* Moonshot currently exposes JSON mode rather than OpenAI-style strict
* json_schema transport, so we keep schema support enabled and adapt the
* request format inside send().
*/
public function isSchemaSupported(): bool
{
return true;
}
/**
* Send a message to the Moonshot API.
*
* @param array<Message> $messages
*
* @throws \Exception
*/
public function send(array $messages, ?callable $listener = null): Message
{
$agent = $this->getAgent();
if ($agent === null) {
throw new \Exception('Agent not set');
}
$client = new Client();
$client
->setTimeout($this->timeout)
->addHeader('authorization', 'Bearer '.$this->apiKey)
->addHeader('content-type', Client::CONTENT_TYPE_APPLICATION_JSON);
$formattedMessages = [];
foreach ($messages as $message) {
if (empty($message->getRole()) || empty($message->getContent())) {
throw new \Exception('Invalid message format');
}
$formattedMessages[] = [
'role' => $message->getRole(),
'content' => $message->getContent(),
];
}
$instructions = [];
foreach ($agent->getInstructions() as $name => $content) {
$text = is_array($content) ? implode("\n", $content) : $content;
$instructions[] = '# '.$name."\n\n".$text;
}
$systemMessage = $agent->getDescription().
(empty($instructions) ? '' : "\n\n".implode("\n\n", $instructions));
$schema = $agent->getSchema();
if ($schema !== null) {
$systemMessage .= "\n\nUSE THE JSON SCHEMA BELOW TO GENERATE A VALID JSON RESPONSE:\n".$schema->toJson();
}
if (! empty($systemMessage)) {
array_unshift($formattedMessages, [
'role' => 'system',
'content' => $systemMessage,
]);
}
$payload = [
'model' => $this->model,
'messages' => $formattedMessages,
'stream' => $schema === null,
'max_completion_tokens' => $this->maxTokens,
];
$temperature = $this->temperature;
if (! $this->usesDefaultTemperatureOnly()) {
$payload['temperature'] = $temperature;
}
if ($schema !== null) {
$payload['response_format'] = [
'type' => 'json_object',
];
}
$content = '';
if ($payload['stream']) {
$response = $client->fetch(
$this->endpoint,
Client::METHOD_POST,
$payload,
[],
function ($chunk) use (&$content, $listener) {
/** @var Chunk $chunk */
$content .= $this->process($chunk, $listener);
}
);
if ($response->getStatusCode() >= 400) {
throw new \Exception(
ucfirst($this->getName()).' API error: '.$content,
$response->getStatusCode()
);
}
} else {
$response = $client->fetch(
$this->endpoint,
Client::METHOD_POST,
$payload,
);
$body = $response->getBody();
if ($response->getStatusCode() >= 400) {
$json = is_string($body) ? json_decode($body, true) : null;
$content = $this->formatErrorMessage($json);
throw new \Exception(
ucfirst($this->getName()).' API error: '.$content,
$response->getStatusCode()
);
}
$json = is_string($body) ? json_decode($body, true) : null;
$choices = is_array($json) && isset($json['choices']) && is_array($json['choices']) ? $json['choices'] : [];
$firstChoice = isset($choices[0]) && is_array($choices[0]) ? $choices[0] : [];
$message = isset($firstChoice['message']) && is_array($firstChoice['message']) ? $firstChoice['message'] : [];
if (isset($message['content']) && is_string($message['content'])) {
$content = $message['content'];
} else {
throw new \Exception('Invalid response format received from the API');
}
}
return new Text($content);
}
/**
* Get available models.
*
* @return array<string>
*/
public function getModels(): array
{
return [
self::MODEL_KIMI_K2_5,
];
}
/**
* Moonshot expects max_completion_tokens for kimi-k2.5.
*/
protected function usesMaxCompletionTokens(): bool
{
return true;
}
/**
* kimi-k2.5 only supports the default temperature.
*/
protected function usesDefaultTemperatureOnly(): bool
{
if ($this->temperature !== 1.0 && ! $this->hasWarnedTemperatureOverride) {
$this->hasWarnedTemperatureOverride = true;
error_log(
"Moonshot adapter warning: model '{$this->model}' only supports temperature=1.0. "
."Ignoring provided value {$this->temperature}. "
.'Set temperature to 1.0 to remove this warning.'
);
}
return true;
}
/**
* Get the adapter name.
*/
public function getName(): string
{
return 'moonshot';
}
}