Skip to content

Commit 0aa5c0b

Browse files
authored
fix: Parse OpenAI Response embedding to contain all embeddings (#150)
1 parent 1afc25f commit 0aa5c0b

File tree

2 files changed

+62
-1
lines changed

2 files changed

+62
-1
lines changed

src/Bridge/OpenAI/Embeddings/ResponseConverter.php

+6-1
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,11 @@ public function convert(ResponseInterface $response, array $options = []): Vecto
2222
{
2323
$data = $response->toArray();
2424

25-
return new VectorResponse(new Vector($data['data'][0]['embedding']));
25+
return new VectorResponse(
26+
...\array_map(
27+
static fn (array $item): Vector => new Vector($item['embedding']),
28+
$data['data']
29+
),
30+
);
2631
}
2732
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace PhpLlm\LlmChain\Tests\Bridge\OpenAI\Embeddings;
6+
7+
use PhpLlm\LlmChain\Bridge\OpenAI\Embeddings\ResponseConverter;
8+
use PHPUnit\Framework\Attributes\CoversClass;
9+
use PHPUnit\Framework\Attributes\Small;
10+
use PHPUnit\Framework\Attributes\Test;
11+
use PHPUnit\Framework\TestCase;
12+
use Symfony\Contracts\HttpClient\ResponseInterface;
13+
14+
#[CoversClass(ResponseConverter::class)]
15+
#[Small]
16+
class ResponseConverterTest extends TestCase
17+
{
18+
#[Test]
19+
public function itConvertsAResponseToAVectorResponse(): void
20+
{
21+
$response = $this->createStub(ResponseInterface::class);
22+
$response
23+
->method('toArray')
24+
->willReturn(\json_decode($this->getEmbeddingStub(), true));
25+
26+
$vectorResponse = (new ResponseConverter())->convert($response);
27+
$convertedContent = $vectorResponse->getContent();
28+
29+
self::assertIsArray($convertedContent);
30+
self::assertCount(2, $convertedContent);
31+
32+
self::assertSame([0.3, 0.4, 0.4], $convertedContent[0]->getData());
33+
self::assertSame([0.0, 0.0, 0.2], $convertedContent[1]->getData());
34+
}
35+
36+
private function getEmbeddingStub(): string
37+
{
38+
return <<<'JSON'
39+
{
40+
"object": "list",
41+
"data": [
42+
{
43+
"object": "embedding",
44+
"index": 0,
45+
"embedding": [0.3, 0.4, 0.4]
46+
},
47+
{
48+
"object": "embedding",
49+
"index": 1,
50+
"embedding": [0.0, 0.0, 0.2]
51+
}
52+
]
53+
}
54+
JSON;
55+
}
56+
}

0 commit comments

Comments
 (0)