-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathOllama.php
More file actions
216 lines (189 loc) · 5.06 KB
/
Ollama.php
File metadata and controls
216 lines (189 loc) · 5.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
<?php
namespace Utopia\Agents\Adapters;
use Utopia\Agents\Adapter;
use Utopia\Agents\Message;
use Utopia\Fetch\Client;
class Ollama extends Adapter
{
/**
* EmbeddingGemma - Gemma embedding model for Ollama
*/
public const MODEL_EMBEDDING_GEMMA = 'embeddinggemma';
/**
* @var string
*/
protected string $model;
private string $endpoint = 'http://ollama:11434/api/embed';
public const MODELS = [self::MODEL_EMBEDDING_GEMMA];
/**
* Embedding dimensions of specific embedding model
*/
protected const DIMENSIONS = [
self::MODEL_EMBEDDING_GEMMA => 768,
];
/**
* Create a new Ollama adapter (no API key required for local call)
*
* @param string $model
* @param int $timeout
*/
public function __construct(
string $model = self::MODEL_EMBEDDING_GEMMA,
int $timeout = 90
) {
if (! in_array($model, self::MODELS, true)) {
throw new \InvalidArgumentException("Invalid model: {$model}. Supported models: ".implode(', ', self::MODELS));
}
$this->model = $model;
$this->setTimeout($timeout);
}
/**
* Embedding generation (Ollama only supports embeddings, not chat)
*
* @param string $text
* @return array{
* embedding: array<int, float>,
* tokensProcessed: int|null,
* totalDuration: int|null ,
* modelLoadingDuration: int|null
* }
*
* @throws \Exception
*/
public function embed(string $text): array
{
$client = new Client();
$client->setTimeout($this->timeout);
$client->addHeader('Content-Type', 'application/json');
$payload = [
'model' => $this->model,
'input' => $text,
];
$response = $client->fetch(
$this->getEndpoint(),
Client::METHOD_POST,
$payload
);
$body = $response->getBody();
$json = is_string($body) ? json_decode($body, true) : null;
if (! is_array($json)) {
throw new \Exception('Invalid response format received from the API');
}
if (isset($json['error'])) {
throw new \Exception($json['error'], $response->getStatusCode());
}
// totalDuration is entire duration including the modelLoadingDuration
return [
'embedding' => $json['embeddings'][0] ?? [],
'tokensProcessed' => $json['prompt_eval_count'] ?? null,
'totalDuration' => $json['total_duration'] ?? null,
'modelLoadingDuration' => $json['load_duration'] ?? null,
];
}
/**
* Get available models for embeddings (for now, only embeddinggemma)
*
* @return array<string>
*/
public function getModels(): array
{
return self::MODELS;
}
/**
* Get currently selected embedding model
*
* @return string
*/
public function getModel(): string
{
return $this->model;
}
/**
* get embedding dimenion of the current model
*/
public function getEmbeddingDimension(): int
{
return self::DIMENSIONS[$this->model];
}
/**
* Set model to use for embedding
*
* @param string $model
* @return self
*/
public function setModel(string $model): self
{
if (! in_array($model, self::MODELS, true)) {
throw new \InvalidArgumentException("Invalid model: {$model}. Supported models: ".implode(', ', self::MODELS));
}
$this->model = $model;
return $this;
}
/**
* Not applicable for embedding-only adapters.
*
* @param array<\Utopia\Agents\Message> $messages
* @param callable|null $listener
*
* @throws \Exception
*/
public function send(array $messages, ?callable $listener = null): Message
{
throw new \Exception('OllamaAdapter does not support chat or messages. Use embed() instead.');
}
/**
* Embeddings do not support schema.
*
* @return bool
*/
public function isSchemaSupported(): bool
{
return false;
}
/**
* Get the adapter name
*
* @return string
*/
public function getName(): string
{
return 'ollama';
}
/**
* Error formatter (minimal)
*
* @param mixed $json
* @return string
*/
protected function formatErrorMessage($json): string
{
if (! is_array($json)) {
return '(unknown_error) Unknown error';
}
return $json['error'] ?? ($json['message'] ?? 'Unknown error');
}
/**
* Get the API endpoint
*
* @return string
*/
public function getEndpoint(): string
{
return $this->endpoint;
}
/**
* Set the API endpoint
*
* @param string $endpoint
* @return self
*/
public function setEndpoint(string $endpoint): self
{
$this->endpoint = $endpoint;
return $this;
}
public function getSupportForEmbeddings(): bool
{
return true;
}
}