| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859 |
- <?php
-
- namespace App\Ai;
-
- /**
- * The single door to AI. No other code talks to an AI provider directly.
- *
- * It looks up which provider and model a task uses in config/ai.php, builds that
- * provider's driver, and returns the answer in one common shape.
- */
- class AiManager
- {
- /**
- * Ask the model configured for the given task.
- *
- * @throws AiException
- */
- public function ask(string $task, string $system, string $prompt): AiResponse
- {
- $settings = config("ai.tasks.$task");
-
- if (! is_array($settings) || empty($settings['provider']) || empty($settings['model'])) {
- throw new AiException("AI task [$task] is not configured.", AiException::SETUP);
- }
-
- $provider = (string) $settings['provider'];
- $maxTokens = (int) ($settings['max_tokens'] ?? 4000);
- $providerLimit = (int) config("ai.providers.$provider.max_output_tokens", 0);
-
- if ($providerLimit > 0) {
- $maxTokens = min($maxTokens, $providerLimit);
- }
-
- return $this->driver($provider)->complete(new AiRequest(
- task: $task,
- model: (string) $settings['model'],
- system: $system,
- prompt: $prompt,
- maxTokens: $maxTokens,
- ));
- }
-
- /**
- * Build the driver for a provider named in config/ai.php.
- *
- * @throws AiException
- */
- public function driver(string $provider): AiDriver
- {
- $config = config("ai.providers.$provider");
- $class = is_array($config) ? ($config['driver'] ?? null) : null;
-
- if (! is_string($class) || ! is_subclass_of($class, AiDriver::class)) {
- throw new AiException("AI provider [$provider] is not configured.", AiException::SETUP);
- }
-
- return app()->make($class, ['provider' => $provider, 'config' => $config]);
- }
- }
|