Skip to content

Commit 53bb269

Browse files
OliverIostCodeWithKyrian
authored andcommitted
Create MistralAIEmbeddingFunction.php
1 parent 61f4baa commit 53bb269

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
6+
namespace Codewithkyrian\ChromaDB\Embeddings;
7+
8+
use GuzzleHttp\Client;
9+
use Psr\Http\Client\ClientExceptionInterface;
10+
11+
class MistralAIEmbeddingFunction implements EmbeddingFunction
12+
{
13+
private Client $client;
14+
15+
public function __construct(
16+
public readonly string $apiKey,
17+
public readonly string $organization = '',
18+
public readonly string $model = 'mistral-embed',
19+
)
20+
{
21+
$headers = [
22+
'Authorization' => "Bearer $this->apiKey",
23+
'Content-Type' => 'application/json',
24+
];
25+
26+
27+
$this->client = new Client([
28+
'base_uri' => 'https://api.mistral.ai/v1/',
29+
'headers' => $headers
30+
]);
31+
}
32+
33+
/**
34+
* @inheritDoc
35+
*/
36+
public function generate(array $texts): array
37+
{
38+
try {
39+
$response = $this->client->post('embeddings', [
40+
'json' => [
41+
'model' => $this->model,
42+
'input' => $texts,
43+
]
44+
]);
45+
46+
$result = json_decode($response->getBody()->getContents(), true);
47+
$embeddings = $result['data'];
48+
usort($embeddings, fn($a, $b) => $a['index'] <=> $b['index']);
49+
50+
return array_map(fn($embedding) => $embedding['embedding'], $embeddings);
51+
} catch (ClientExceptionInterface $e) {
52+
throw new \RuntimeException("Error calling MistralAI API: {$e->getMessage()}", 0, $e);
53+
}
54+
}
55+
}

0 commit comments

Comments
 (0)