|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace App\SymfonyConBot\ToolBox\SerpApi; |
| 6 | + |
| 7 | +use App\SymfonyConBot\ToolBox\FunctionInterface; |
| 8 | +use Symfony\Contracts\HttpClient\HttpClientInterface; |
| 9 | + |
| 10 | +/** |
| 11 | + * @phpstan-import-type FunctionParameterDefinition from FunctionInterface |
| 12 | + */ |
| 13 | +final readonly class SerpApiFunction implements FunctionInterface |
| 14 | +{ |
| 15 | + public function __construct( |
| 16 | + private HttpClientInterface $httpClient, |
| 17 | + private string $apiKey, |
| 18 | + ) { |
| 19 | + } |
| 20 | + |
| 21 | + public static function getName(): string |
| 22 | + { |
| 23 | + return 'serpapi'; |
| 24 | + } |
| 25 | + |
| 26 | + public static function getDescription(): string |
| 27 | + { |
| 28 | + return 'search for information on the internet'; |
| 29 | + } |
| 30 | + |
| 31 | + /** |
| 32 | + * @return FunctionParameterDefinition |
| 33 | + */ |
| 34 | + public static function getParametersDefinition(): array |
| 35 | + { |
| 36 | + return [ |
| 37 | + 'type' => 'object', |
| 38 | + 'properties' => [ |
| 39 | + 'query' => [ |
| 40 | + 'type' => 'string', |
| 41 | + 'description' => 'The search query to use', |
| 42 | + ], |
| 43 | + ], |
| 44 | + 'required' => ['query'], |
| 45 | + ]; |
| 46 | + } |
| 47 | + |
| 48 | + /** |
| 49 | + * @param array{query: string} $arguments |
| 50 | + */ |
| 51 | + public function execute(array $arguments): string |
| 52 | + { |
| 53 | + $response = $this->httpClient->request('GET', 'https://serpapi.com/search', [ |
| 54 | + 'query' => [ |
| 55 | + 'q' => $arguments['query'], |
| 56 | + 'api_key' => $this->apiKey, |
| 57 | + ], |
| 58 | + ]); |
| 59 | + |
| 60 | + return sprintf('Results for "%s" are "%s".', $arguments['query'], $this->extractBestResponse($response->toArray())); |
| 61 | + } |
| 62 | + |
| 63 | + /** |
| 64 | + * @param array<string, mixed> $results |
| 65 | + */ |
| 66 | + private function extractBestResponse(array $results): string |
| 67 | + { |
| 68 | + return implode(PHP_EOL, array_map(fn ($story) => sprintf('%s: %s', $story['title'], $story['snippet']), $results['organic_results'])); |
| 69 | + } |
| 70 | +} |
0 commit comments