* @throws WorkspaceNotFoundException * @throws UserNotFoundException * @throws PresetNotFoundException * @throws InsufficientCreditsException * @throws ApiException * @throws DomainException */ public function handle(GenerateDocumentCommand $cmd): Generator { $ws = $cmd->workspace instanceof WorkspaceEntity ? $cmd->workspace : $this->wsRepo->ofId($cmd->workspace); $user = $cmd->user instanceof UserEntity ? $cmd->user : $this->userRepo->ofId($cmd->user); $preset = null; if ($cmd->prompt instanceof Id) { $cmd->prompt = $this->pRepo->ofId($cmd->prompt); } if ($cmd->prompt instanceof PresetEntity) { $preset = $cmd->prompt; $cmd->prompt = $this->parser->fillTemplate( $cmd->prompt->getTemplate()->value, $cmd->params ); } if (!is_null($ws->getTotalCreditCount()->value) && (float) $ws->getTotalCreditCount()->value <= 0) { throw new InsufficientCreditsException(); } $service = $this->factory->create( CompletionServiceInterface::class, $cmd->model ); $params = $cmd->params; $params['prompt'] = $cmd->prompt; $resp = $service->generateCompletion($cmd->model, $params); $content = ''; foreach ($resp as $chunk) { if ($chunk->data instanceof Token) { $content .= (string) $chunk->data; } yield $chunk; } $service = $this->factory->create( TitleServiceInterface::class, $ws->getSubscription() ? $ws->getSubscription()->getPlan()->getConfig()->titler->model : new Model('gpt-3.5-turbo') ); $content = new Content($content); $titleResp = $service->generateTitle( $content, $ws->getSubscription() ? $ws->getSubscription()->getPlan()->getConfig()->titler->model : new Model('gpt-3.5-turbo') ); /** @var Count */ $cost = $resp->getReturn(); $cost = new Count($cost->value + $titleResp->cost->value); $entity = new DocumentEntity( $ws, $user, $cmd->model, $titleResp->title, $preset, RequestParams::fromArray($cmd->params), $cost ); $entity->setContent($content); $this->repo->add($entity); // Deduct credit from workspace $ws->deductCredit($cost); // Dispatch event $event = new CreditUsageEvent($ws, $cost); $this->dispatcher->dispatch($event); return $entity; } }