|
15 | 15 | use Symfony\AI\Platform\Model;
|
16 | 16 | use Symfony\AI\Platform\ModelClientInterface;
|
17 | 17 | use Symfony\AI\Platform\Result\RawHttpResult;
|
| 18 | +use Symfony\Component\HttpClient\Response\MockResponse; |
| 19 | +use Symfony\Contracts\Cache\CacheInterface; |
18 | 20 | use Symfony\Contracts\HttpClient\HttpClientInterface;
|
| 21 | +use Symfony\Contracts\HttpClient\ResponseInterface; |
19 | 22 |
|
20 | 23 | /**
|
21 | 24 | * @author Christopher Hertel <[email protected]>
|
|
25 | 28 | public function __construct(
|
26 | 29 | private HttpClientInterface $httpClient,
|
27 | 30 | private string $hostUrl,
|
| 31 | + private ?CacheInterface $cache = null, |
28 | 32 | ) {
|
29 | 33 | }
|
30 | 34 |
|
@@ -68,10 +72,40 @@ private function doCompletionRequest(array|string $payload, array $options = [])
|
68 | 72 | unset($options['response_format']);
|
69 | 73 | }
|
70 | 74 |
|
71 |
| - return new RawHttpResult($this->httpClient->request('POST', \sprintf('%s/api/chat', $this->hostUrl), [ |
72 |
| - 'headers' => ['Content-Type' => 'application/json'], |
73 |
| - 'json' => array_merge($options, $payload), |
74 |
| - ])); |
| 75 | + $requestCallback = fn ($options, $payload): ResponseInterface => $this->httpClient->request('POST', \sprintf('%s/api/chat', $this->hostUrl), [ |
| 76 | + 'headers' => [ |
| 77 | + 'Content-Type' => 'application/json', |
| 78 | + ], |
| 79 | + 'json' => [ |
| 80 | + ...$options, |
| 81 | + ...$payload, |
| 82 | + ], |
| 83 | + ]); |
| 84 | + |
| 85 | + if ($this->cache instanceof CacheInterface && (\array_key_exists('prompt_cache_key', $options) && $options['prompt_cache_key'])) { |
| 86 | + $cacheKey = \sprintf('%s_%s', $options['prompt_cache_key'], md5(\is_array($payload) ? json_encode($payload) : ['context' => $payload])); |
| 87 | + |
| 88 | + unset($options['prompt_cache_key']); |
| 89 | + |
| 90 | + $cachedResponse = $this->cache->get($cacheKey, static function () use ($requestCallback, $options, $payload): array { |
| 91 | + $response = $requestCallback($options, $payload); |
| 92 | + |
| 93 | + return [ |
| 94 | + 'content' => $response->getContent(), |
| 95 | + 'headers' => $response->getHeaders(), |
| 96 | + 'http_code' => $response->getStatusCode(), |
| 97 | + ]; |
| 98 | + }); |
| 99 | + |
| 100 | + $mockedResponse = new MockResponse($cachedResponse['content'], [ |
| 101 | + 'http_code' => $cachedResponse['http_code'], |
| 102 | + 'response_headers' => $cachedResponse['headers'], |
| 103 | + ]); |
| 104 | + |
| 105 | + return new RawHttpResult(MockResponse::fromRequest('POST', \sprintf('%s/api/chat', $this->hostUrl), $options, $mockedResponse)); |
| 106 | + } |
| 107 | + |
| 108 | + return new RawHttpResult($requestCallback($options, $payload)); |
75 | 109 | }
|
76 | 110 |
|
77 | 111 | /**
|
|
0 commit comments