| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455 |
- <?php
-
- namespace Tests\Support;
-
- use App\Ai\AiDriver;
- use App\Ai\AiException;
- use App\Ai\AiRequest;
- use App\Ai\AiResponse;
-
- /**
- * A test driver that gives back the answers it was told to, in order, and remembers what it was asked.
- */
- final class ScriptedDriver implements AiDriver
- {
- /** @var list<string|AiException> */
- public static array $answers = [];
-
- /** @var list<AiRequest> */
- public static array $requests = [];
-
- /**
- * @param array<string, mixed> $config
- */
- public function __construct(private readonly string $provider, private readonly array $config) {}
-
- /**
- * Point both tasks at this driver and queue up its answers.
- *
- * @param list<string|AiException> $answers
- */
- public static function use(array $answers): void
- {
- self::$answers = $answers;
- self::$requests = [];
-
- config([
- 'ai.providers.scripted' => ['driver' => self::class],
- 'ai.tasks.generate.provider' => 'scripted',
- 'ai.tasks.edit.provider' => 'scripted',
- ]);
- }
-
- public function complete(AiRequest $request): AiResponse
- {
- self::$requests[] = $request;
-
- $answer = array_shift(self::$answers) ?? throw new AiException('No scripted answer left.');
-
- if ($answer instanceof AiException) {
- throw $answer;
- }
-
- return new AiResponse($answer, $this->provider, $request->model, 100, 200);
- }
- }
|