-
Notifications
You must be signed in to change notification settings - Fork 0
Add Moonshot adapter for kimi-k2.5 #26
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,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; | ||
| } | ||
|
|
||
ChiragAgg5k marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| /** | ||
| * 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'; | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,30 @@ | ||
| <?php | ||
|
|
||
| namespace Utopia\Tests\Agents\Conversation; | ||
|
|
||
| use Utopia\Agents\Adapter; | ||
| use Utopia\Agents\Adapters\Moonshot; | ||
|
|
||
| class ConversationMoonshotTest extends ConversationBase | ||
| { | ||
| protected function createAdapter(): Adapter | ||
| { | ||
| $apiKey = getenv('LLM_KEY_MOONSHOT'); | ||
|
|
||
| if ($apiKey === false || empty($apiKey)) { | ||
| throw new \RuntimeException('LLM_KEY_MOONSHOT environment variable is not set'); | ||
| } | ||
|
|
||
| return new Moonshot( | ||
| $apiKey, | ||
| Moonshot::MODEL_KIMI_K2_5, | ||
| 1024, | ||
| 1.0 | ||
| ); | ||
| } | ||
|
|
||
| protected function getAgentDescription(): string | ||
| { | ||
| return 'Test Moonshot Agent Description'; | ||
| } | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.