Files
toolbox/app/Services/AiService.php

127 lines
3.1 KiB
PHP

<?php
namespace App\Services;
use App\Clients\AiClient;
class AiService
{
public function __construct(
private readonly AiClient $client,
private readonly ConfigService $configService
) {}
/**
* 检查 AI 服务是否已配置
*/
public function isConfigured(): bool
{
return $this->client->isConfigured();
}
/**
* 获取所有 AI 提供商配置
*/
public function getProviders(): array
{
return $this->client->getProviders();
}
/**
* 获取当前激活的提供商
*/
public function getActiveProvider(): ?array
{
return $this->client->getActiveProvider();
}
/**
* 设置激活的提供商
*/
public function setActiveProvider(string $providerKey): void
{
$this->client->setActiveProvider($providerKey);
}
/**
* 保存 AI 提供商配置
*
* @param array $providers 提供商配置数组
*/
public function saveProviders(array $providers): void
{
// 验证配置格式
foreach ($providers as $key => $provider) {
if (empty($provider['endpoint']) || empty($provider['api_key']) || empty($provider['model'])) {
throw new \InvalidArgumentException("提供商 {$key} 配置不完整");
}
}
$this->configService->set(
'log_analysis.ai_providers',
$providers,
'AI 服务提供商配置'
);
}
/**
* 添加或更新单个提供商
*/
public function saveProvider(string $key, array $config): void
{
$providers = $this->getProviders();
$providers[$key] = array_merge($providers[$key] ?? [], $config);
$this->saveProviders($providers);
}
/**
* 删除提供商
*/
public function deleteProvider(string $key): void
{
$providers = $this->getProviders();
unset($providers[$key]);
$this->saveProviders($providers);
// 如果删除的是当前激活的,清除激活状态
$activeKey = $this->configService->get('log_analysis.active_ai_provider');
if ($activeKey === $key) {
$this->configService->set('log_analysis.active_ai_provider', null);
}
}
/**
* 分析日志
*
* @param string $logsContent 日志内容
* @param string|null $codeContext 代码上下文
* @return array 分析结果
*/
public function analyzeLogs(string $logsContent, ?string $codeContext = null): array
{
return $this->client->analyzeLogs($logsContent, $codeContext);
}
/**
* 自定义提示词分析
*
* @param string $content 要分析的内容
* @param string $prompt 自定义提示词
* @return string AI 响应
*/
public function analyze(string $content, string $prompt): string
{
return $this->client->chat([
['role' => 'user', 'content' => $prompt . "\n\n" . $content],
]);
}
/**
* 测试连接
*/
public function testConnection(): array
{
return $this->client->testConnection();
}
}