mirror of
https://github.com/jez500/pricebuddy.git
synced 2026-11-24 19:58:13 +01:00
Bounding the meta-extraction request stopped a wedged provider costing 120s, but it still cost the full 25s budget on every single request. A provider that has failed the last N calls will almost certainly fail the next one, and finding out is the expensive part. AiProviderHealth tracks consecutive failures per provider id in the cache. After failure_threshold consecutive failures (default 3) the provider is treated as unavailable for cooldown_seconds (default 300), which doubles as the counting window so thinly spread failures never accumulate. Any success closes it immediately. AiService feeds it, since that is the only layer that knows whether a provider call succeeded. The Ollama reachability check deliberately does not close the breaker: listing models proves the HTTP front end is up, not that generation works, which is exactly the state this instance is in. Only callers on a deadline consult it. The meta-extraction endpoint skips healing with the new reason `provider_unavailable`; the admin UI heal button and queued healing keep exercising the provider, so they act as the probe that notices recovery rather than waiting out the cooldown. Verified live against the wedged provider: three requests at 24.1s each, then the fourth returned in 0.105s with reason `provider_unavailable`. Note for API clients: `provider_unavailable` is a new value in the `healing.reason` set. It means the instance is degraded rather than the page being unextractable, so the same URL is worth retrying later.
255 lines
8.5 KiB
PHP
255 lines
8.5 KiB
PHP
<?php
|
|
|
|
namespace App\Services;
|
|
|
|
use App\Dto\AiProviderConfigDto;
|
|
use App\Enums\AiProvider;
|
|
use App\Exceptions\AiProviderException;
|
|
use App\Services\Ai\AiProviderHealth;
|
|
use App\Services\Ai\ConfiguredStructuredAgent;
|
|
use App\Services\Ai\SecretRedactor;
|
|
use App\Services\Helpers\IntegrationHelper;
|
|
use Closure;
|
|
use Illuminate\Contracts\JsonSchema\JsonSchema;
|
|
use Illuminate\Support\Facades\Crypt;
|
|
use Illuminate\Support\Facades\Log;
|
|
use Laravel\Ai\Responses\StructuredAgentResponse;
|
|
use Throwable;
|
|
|
|
class AiService
|
|
{
|
|
public function __construct(protected AiProviderHealth $health) {}
|
|
|
|
public static function new(): self
|
|
{
|
|
return resolve(static::class);
|
|
}
|
|
|
|
public function isEnabled(): bool
|
|
{
|
|
return IntegrationHelper::isAiEnabled();
|
|
}
|
|
|
|
/**
|
|
* Run a structured prompt through the given provider, or the active default.
|
|
*
|
|
* @param Closure(JsonSchema): array<string, mixed> $schema
|
|
* @return array<string, mixed>|null
|
|
*/
|
|
public function structured(string $instructions, Closure $schema, string $prompt, ?AiProviderConfigDto $provider = null): ?array
|
|
{
|
|
$provider ??= IntegrationHelper::getActiveAiProvider();
|
|
|
|
if ($provider === null) {
|
|
return null;
|
|
}
|
|
|
|
return $this->runStructuredFor($provider, $instructions, $schema, $prompt);
|
|
}
|
|
|
|
/**
|
|
* Run a tool-using structured agent and return the validated structured
|
|
* output, or null. Used for agentic flows (e.g. config self-healing).
|
|
*
|
|
* @param Closure(JsonSchema): array<string, mixed> $schema
|
|
* @param array<int, \Laravel\Ai\Contracts\Tool> $tools
|
|
* @return array<string, mixed>|null
|
|
*/
|
|
public function runAgent(string $instructions, Closure $schema, string $prompt, array $tools, ?AiProviderConfigDto $provider = null, int $maxSteps = 25, ?int $timeout = null): ?array
|
|
{
|
|
$provider ??= IntegrationHelper::getActiveAiProvider();
|
|
|
|
if ($provider === null) {
|
|
return null;
|
|
}
|
|
|
|
$this->configureProviderCredentials($provider);
|
|
|
|
$agent = new ConfiguredStructuredAgent(
|
|
instructions: $instructions,
|
|
tools: $tools,
|
|
schema: $schema,
|
|
temperature: $provider->temperature,
|
|
maxTokens: $provider->maxTokens,
|
|
maxSteps: $maxSteps,
|
|
);
|
|
|
|
try {
|
|
$response = $agent->prompt(
|
|
$prompt,
|
|
provider: $provider->type->toLab(),
|
|
model: $provider->model,
|
|
// A caller working to a deadline (the synchronous meta-extraction endpoint)
|
|
// passes the time it has left; everything else uses the provider's own
|
|
// timeout, which is the right ceiling for queued, best-effort work.
|
|
timeout: $timeout ?? $provider->timeoutSeconds,
|
|
);
|
|
|
|
$this->health->recordSuccess($provider);
|
|
|
|
return $response instanceof StructuredAgentResponse ? $response->toArray() : null;
|
|
} catch (Throwable $e) {
|
|
$this->health->recordFailure($provider);
|
|
|
|
Log::error('AI agent run failed.', [
|
|
'provider' => $provider->type->driver(),
|
|
'model' => $provider->model,
|
|
'exception' => $e::class,
|
|
'message' => SecretRedactor::redact($e->getMessage(), $this->decrypt($provider->apiKey)),
|
|
]);
|
|
|
|
throw new AiProviderException('AI agent request failed ('.$e::class.').', previous: $e);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* @param Closure(JsonSchema): array<string, mixed> $schema
|
|
* @return array<string, mixed>|null
|
|
*/
|
|
protected function runStructuredFor(AiProviderConfigDto $provider, string $instructions, Closure $schema, string $prompt): ?array
|
|
{
|
|
$this->configureProviderCredentials($provider);
|
|
|
|
$agent = new ConfiguredStructuredAgent(
|
|
instructions: $instructions,
|
|
schema: $schema,
|
|
temperature: $provider->temperature,
|
|
maxTokens: $provider->maxTokens,
|
|
);
|
|
|
|
try {
|
|
$response = $agent->prompt(
|
|
$prompt,
|
|
provider: $provider->type->toLab(),
|
|
model: $provider->model,
|
|
timeout: $provider->timeoutSeconds,
|
|
);
|
|
|
|
$this->health->recordSuccess($provider);
|
|
|
|
return $response instanceof StructuredAgentResponse ? $response->toArray() : null;
|
|
} catch (Throwable $e) {
|
|
$this->health->recordFailure($provider);
|
|
|
|
Log::error('AI structured prompt failed.', [
|
|
'provider' => $provider->type->driver(),
|
|
'model' => $provider->model,
|
|
'exception' => $e::class,
|
|
'message' => SecretRedactor::redact($e->getMessage(), $this->decrypt($provider->apiKey)),
|
|
]);
|
|
|
|
throw new AiProviderException('AI provider request failed ('.$e::class.').', previous: $e);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* @return true|string true on success, an error message on failure
|
|
*/
|
|
public function testConnection(): true|string
|
|
{
|
|
if (! $this->isEnabled()) {
|
|
return 'AI is not enabled.';
|
|
}
|
|
|
|
$provider = IntegrationHelper::getActiveAiProvider();
|
|
|
|
if ($provider === null) {
|
|
return 'No AI provider is configured.';
|
|
}
|
|
|
|
return $this->testProviderConfig($provider);
|
|
}
|
|
|
|
/**
|
|
* @return true|string true on success, an error message on failure
|
|
*/
|
|
public function testProviderConfig(AiProviderConfigDto $provider): true|string
|
|
{
|
|
if ($provider->type === AiProvider::Ollama) {
|
|
return $this->testOllamaConnection($provider);
|
|
}
|
|
|
|
try {
|
|
$result = $this->runStructuredFor(
|
|
$provider,
|
|
'Reply with the number 1.',
|
|
fn (JsonSchema $schema) => ['ok' => $schema->integer()->required()],
|
|
'Return 1.',
|
|
);
|
|
} catch (AiProviderException $e) {
|
|
return $e->getMessage();
|
|
}
|
|
|
|
return $result === null ? 'The AI provider did not return a valid response.' : true;
|
|
}
|
|
|
|
/**
|
|
* @return true|string true on success, an error message on failure
|
|
*/
|
|
protected function testOllamaConnection(AiProviderConfigDto $provider): true|string
|
|
{
|
|
// Deliberately does not close the circuit breaker on success: listing models only
|
|
// proves the HTTP front end is up. An Ollama host can serve /api/tags instantly
|
|
// while /api/chat never returns, which is precisely the state the breaker exists
|
|
// for. Only a completed generation counts as recovery.
|
|
$baseUrl = $provider->baseUrl;
|
|
|
|
if (blank($baseUrl)) {
|
|
return 'No Ollama base URL is configured.';
|
|
}
|
|
|
|
try {
|
|
$models = OllamaService::new()->listModels($baseUrl);
|
|
} catch (Throwable $e) {
|
|
Log::warning('Ollama reachability check failed.', ['exception' => $e::class]);
|
|
|
|
return "Could not reach Ollama at {$baseUrl}.";
|
|
}
|
|
|
|
if (blank($provider->model)) {
|
|
return 'Connected to Ollama, but no model is selected.';
|
|
}
|
|
|
|
if (! in_array($provider->model, $models, true)) {
|
|
return "Connected to Ollama, but model '{$provider->model}' was not found. Available: ".
|
|
(implode(', ', $models) ?: 'none').'.';
|
|
}
|
|
|
|
return true;
|
|
}
|
|
|
|
/**
|
|
* Push the provider's decrypted key + base URL into the SDK runtime config.
|
|
*
|
|
* Note: this mutates global runtime config for the current process and assumes
|
|
* AI calls are sequential (not interleaved within one PHP worker). If this is
|
|
* later driven from concurrent in-process work, switch to a per-call credential
|
|
* mechanism instead of mutating shared config.
|
|
*/
|
|
protected function configureProviderCredentials(AiProviderConfigDto $provider): void
|
|
{
|
|
$driver = $provider->type->driver();
|
|
|
|
config(["ai.providers.{$driver}.key" => $this->decrypt($provider->apiKey)]);
|
|
|
|
if (filled($provider->baseUrl)) {
|
|
config(["ai.providers.{$driver}.url" => $provider->baseUrl]);
|
|
}
|
|
}
|
|
|
|
protected function decrypt(?string $value): ?string
|
|
{
|
|
if (blank($value)) {
|
|
return null;
|
|
}
|
|
|
|
try {
|
|
return Crypt::decryptString($value);
|
|
} catch (Throwable) {
|
|
Log::warning('AI provider API key could not be decrypted; check APP_KEY and the stored credentials.');
|
|
|
|
return null;
|
|
}
|
|
}
|
|
}
|