64 lines
1.9 KiB
PHP
64 lines
1.9 KiB
PHP
<?php
|
|
|
|
namespace Modules\ChatGPT\Console;
|
|
|
|
use Illuminate\Console\Command;
|
|
use Modules\ChatGPT\Models\ChatGptApiSetting;
|
|
use Modules\ChatGPT\Services\OpenAiFileService;
|
|
use Throwable;
|
|
|
|
class DeleteOpenAiFilesCommand extends Command
|
|
{
|
|
protected $signature = 'chatgpt:delete-api-files {--dry-run : List files without deleting them}';
|
|
|
|
protected $description = 'Delete all OpenAI API files visible to the stored active API key.';
|
|
|
|
/**
|
|
* Execute the console command.
|
|
*/
|
|
public function handle(): int
|
|
{
|
|
$setting = ChatGptApiSetting::active();
|
|
|
|
if (! $setting) {
|
|
$this->error('No active ChatGPT/OpenAI API key is stored.');
|
|
return self::FAILURE;
|
|
}
|
|
|
|
$service = new OpenAiFileService((string) $setting->api_key);
|
|
|
|
try {
|
|
if ((bool) $this->option('dry-run')) {
|
|
$files = $service->listFiles();
|
|
|
|
$this->info('Found ' . count($files) . ' OpenAI API file(s).');
|
|
|
|
foreach ($files as $file) {
|
|
$this->line(sprintf(
|
|
'- %s %s',
|
|
(string) ($file['id'] ?? 'unknown'),
|
|
(string) ($file['filename'] ?? 'unnamed')
|
|
));
|
|
}
|
|
|
|
return self::SUCCESS;
|
|
}
|
|
|
|
$result = $service->deleteAllFiles();
|
|
|
|
$this->info("Listed: {$result['listed']}");
|
|
$this->info("Deleted: {$result['deleted']}");
|
|
$this->info("Failed: {$result['failed']}");
|
|
|
|
foreach ($result['failures'] as $failure) {
|
|
$this->error($failure['file_id'] . ': ' . $failure['error']);
|
|
}
|
|
|
|
return $result['failed'] === 0 ? self::SUCCESS : self::FAILURE;
|
|
} catch (Throwable $exception) {
|
|
$this->error($exception->getMessage());
|
|
return self::FAILURE;
|
|
}
|
|
}
|
|
}
|