client = new Client([ 'base_uri' => rtrim((string) $provider->base_url, '/') . '/', 'timeout' => 120, ]); } public function chat(array $messages, array $data = []): array { $apiKey = $data['api_key'] ?? $this->provider->api_key; if (empty($apiKey)) { throw new \InvalidArgumentException('OpenRouter API key is not configured.'); } try { $response = $this->client->post('chat/completions', [ 'headers' => [ 'Authorization' => 'Bearer ' . $apiKey, 'Content-Type' => 'application/json', 'HTTP-Referer' => $data['http_referer'] ?? config('app.url'), 'X-Title' => $data['x_title'] ?? config('app.name'), ], 'json' => [ 'model' => (string) ($data['model'] ?? ''), 'messages' => $messages, 'temperature' => isset($data['temperature']) ? (float) $data['temperature'] : null, 'max_tokens' => isset($data['max_tokens']) ? (int) $data['max_tokens'] : null, ], ]); $body = json_decode($response->getBody()->getContents(), true); if (!isset($body['choices'][0]['message']['content'])) { throw new \RuntimeException('Invalid response structure from OpenRouter.'); } return [ 'content' => $body['choices'][0]['message']['content'], 'tokens_used' => $body['usage']['total_tokens'] ?? null, 'model' => $body['model'] ?? (string) ($data['model'] ?? ''), ]; } catch (GuzzleException $e) { Log::error('OpenRouter API error: ' . $e->getMessage()); throw new \RuntimeException('Failed to generate prompt with OpenRouter: ' . $e->getMessage(), (int) $e->getCode(), $e); } } /** * {@inheritdoc} */ public function generatePrompt(array $data): array { return $this->chat( [['role' => 'user', 'content' => (string) ($data['prompt'] ?? '')]], $data ); } }