-
-
Notifications
You must be signed in to change notification settings - Fork 15
/
llm_mistral.py
421 lines (390 loc) · 15.9 KB
/
llm_mistral.py
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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
import click
from httpx_sse import connect_sse, aconnect_sse
import httpx
import json
import llm
from pydantic import Field
from typing import Optional
DEFAULT_ALIASES = {
"mistral/mistral-tiny": "mistral-tiny",
"mistral/open-mistral-nemo": "mistral-nemo",
"mistral/mistral-small": "mistral-small",
"mistral/mistral-medium": "mistral-medium",
"mistral/mistral-large-latest": "mistral-large",
"mistral/codestral-mamba-latest": "codestral-mamba",
"mistral/codestral-latest": "codestral",
"mistral/ministral-3b-latest": "ministral-3b",
"mistral/ministral-8b-latest": "ministral-8b",
"mistral/pixtral-12b-latest": "pixtral-12b",
"mistral/pixtral-large-latest": "pixtral-large",
}
@llm.hookimpl
def register_models(register):
for model in get_model_details():
model_id = model["id"]
vision = model.get("capabilities", {}).get("vision")
our_model_id = "mistral/" + model_id
alias = DEFAULT_ALIASES.get(our_model_id)
aliases = [alias] if alias else []
register(
Mistral(our_model_id, model_id, vision),
AsyncMistral(our_model_id, model_id, vision),
aliases=aliases,
)
@llm.hookimpl
def register_embedding_models(register):
register(MistralEmbed())
def refresh_models():
user_dir = llm.user_dir()
mistral_models = user_dir / "mistral_models.json"
key = llm.get_key("", "mistral", "LLM_MISTRAL_KEY")
if not key:
raise click.ClickException(
"You must set the 'mistral' key or the LLM_MISTRAL_KEY environment variable."
)
response = httpx.get(
"https://api.mistral.ai/v1/models", headers={"Authorization": f"Bearer {key}"}
)
response.raise_for_status()
models = response.json()
mistral_models.write_text(json.dumps(models, indent=2))
return models
def get_model_details():
user_dir = llm.user_dir()
models = {
"data": [
{"id": model_id.replace("mistral/", "")}
for model_id in DEFAULT_ALIASES.keys()
]
}
mistral_models = user_dir / "mistral_models.json"
if mistral_models.exists():
models = json.loads(mistral_models.read_text())
elif llm.get_key("", "mistral", "LLM_MISTRAL_KEY"):
try:
models = refresh_models()
except httpx.HTTPStatusError:
pass
return [model for model in models["data"] if "embed" not in model["id"]]
def get_model_ids():
return [model["id"] for model in get_model_details()]
@llm.hookimpl
def register_commands(cli):
@cli.group()
def mistral():
"Commands relating to the llm-mistral plugin"
@mistral.command()
def refresh():
"Refresh the list of available Mistral models"
before = set(get_model_ids())
refresh_models()
after = set(get_model_ids())
added = after - before
removed = before - after
if added:
click.echo(f"Added models: {', '.join(added)}", err=True)
if removed:
click.echo(f"Removed models: {', '.join(removed)}", err=True)
if added or removed:
click.echo("New list of models:", err=True)
for model_id in get_model_ids():
click.echo(model_id, err=True)
else:
click.echo("No changes", err=True)
class _Shared:
can_stream = True
needs_key = "mistral"
key_env_var = "LLM_MISTRAL_KEY"
class Options(llm.Options):
temperature: Optional[float] = Field(
description=(
"Determines the sampling temperature. Higher values like 0.8 increase randomness, "
"while lower values like 0.2 make the output more focused and deterministic."
),
ge=0,
le=1,
default=0.7,
)
top_p: Optional[float] = Field(
description=(
"Nucleus sampling, where the model considers the tokens with top_p probability mass. "
"For example, 0.1 means considering only the tokens in the top 10% probability mass."
),
ge=0,
le=1,
default=1,
)
max_tokens: Optional[int] = Field(
description="The maximum number of tokens to generate in the completion.",
ge=0,
default=None,
)
safe_mode: Optional[bool] = Field(
description="Whether to inject a safety prompt before all conversations.",
default=False,
)
random_seed: Optional[int] = Field(
description="Sets the seed for random sampling to generate deterministic results.",
default=None,
)
def __init__(self, our_model_id, mistral_model_id, vision):
self.model_id = our_model_id
self.mistral_model_id = mistral_model_id
if vision:
self.attachment_types = {
"image/jpeg",
"image/png",
"image/gif",
"image/webp",
}
def build_messages(self, prompt, conversation):
messages = []
latest_message = None
if prompt.attachments:
latest_message = {
"role": "user",
"content": [{"type": "text", "text": prompt.prompt}]
+ [
{
"type": "image_url",
"image_url": attachment.url
or f"data:{attachment.resolve_type()};base64,{attachment.base64_content()}",
}
for attachment in prompt.attachments
],
}
else:
latest_message = {"role": "user", "content": prompt.prompt}
if not conversation:
if prompt.system:
messages.append({"role": "system", "content": prompt.system})
messages.append(latest_message)
return messages
current_system = None
for prev_response in conversation.responses:
if (
prev_response.prompt.system
and prev_response.prompt.system != current_system
):
messages.append(
{"role": "system", "content": prev_response.prompt.system}
)
current_system = prev_response.prompt.system
if prev_response.attachments:
messages.append(
{
"role": "user",
"content": [
{
"type": "text",
"text": prev_response.prompt.prompt,
}
]
+ [
{
"type": "image_url",
"image_url": attachment.url
or f"data:{attachment.resolve_type()};base64,{attachment.base64_content()}",
}
for attachment in prev_response.attachments
],
}
)
else:
messages.append(
{"role": "user", "content": prev_response.prompt.prompt}
)
messages.append(
{"role": "assistant", "content": prev_response.text_or_raise()}
)
if prompt.system and prompt.system != current_system:
messages.append({"role": "system", "content": prompt.system})
messages.append(latest_message)
return messages
def build_body(self, prompt, messages):
body = {
"model": self.mistral_model_id,
"messages": messages,
}
if prompt.options.temperature:
body["temperature"] = prompt.options.temperature
if prompt.options.top_p:
body["top_p"] = prompt.options.top_p
if prompt.options.max_tokens:
body["max_tokens"] = prompt.options.max_tokens
if prompt.options.safe_mode:
body["safe_mode"] = prompt.options.safe_mode
if prompt.options.random_seed:
body["random_seed"] = prompt.options.random_seed
return body
def set_usage(self, response, usage):
response.set_usage(
input=usage["prompt_tokens"],
output=usage["completion_tokens"],
)
class Mistral(_Shared, llm.Model):
def execute(self, prompt, stream, response, conversation):
key = self.get_key()
messages = self.build_messages(prompt, conversation)
response._prompt_json = {"messages": messages}
body = self.build_body(prompt, messages)
if stream:
body["stream"] = True
with httpx.Client() as client:
with connect_sse(
client,
"POST",
"https://api.mistral.ai/v1/chat/completions",
headers={
"Content-Type": "application/json",
"Accept": "application/json",
"Authorization": f"Bearer {key}",
},
json=body,
timeout=None,
) as event_source:
# In case of unauthorized:
if event_source.response.status_code != 200:
# Try to make this a readable error, it may have a base64 chunk
try:
decoded = json.loads(event_source.response.read())
type = decoded["type"]
words = decoded["message"].split()
except (json.JSONDecodeError, KeyError):
click.echo(
event_source.response.read().decode()[:200], err=True
)
event_source.response.raise_for_status()
# Truncate any words longer than 30 characters
words = [word[:30] for word in words]
message = " ".join(words)
raise click.ClickException(
f"{event_source.response.status_code}: {type} - {message}"
)
usage = None
event_source.response.raise_for_status()
for sse in event_source.iter_sse():
if sse.data != "[DONE]":
try:
event = sse.json()
if "usage" in event:
usage = event["usage"]
yield event["choices"][0]["delta"]["content"]
except KeyError:
pass
if usage:
self.set_usage(response, usage)
else:
with httpx.Client() as client:
api_response = client.post(
"https://api.mistral.ai/v1/chat/completions",
headers={
"Content-Type": "application/json",
"Accept": "application/json",
"Authorization": f"Bearer {key}",
},
json=body,
timeout=None,
)
api_response.raise_for_status()
yield api_response.json()["choices"][0]["message"]["content"]
details = api_response.json()
usage = details.pop("usage", None)
response.response_json = details
if usage:
self.set_usage(response, usage)
class AsyncMistral(_Shared, llm.AsyncModel):
async def execute(self, prompt, stream, response, conversation):
key = self.get_key()
messages = self.build_messages(prompt, conversation)
response._prompt_json = {"messages": messages}
body = self.build_body(prompt, messages)
if stream:
body["stream"] = True
async with httpx.AsyncClient() as client:
async with aconnect_sse(
client,
"POST",
"https://api.mistral.ai/v1/chat/completions",
headers={
"Content-Type": "application/json",
"Accept": "application/json",
"Authorization": f"Bearer {key}",
},
json=body,
timeout=None,
) as event_source:
# In case of unauthorized:
if event_source.response.status_code != 200:
# Try to make this a readable error, it may have a base64 chunk
try:
decoded = json.loads(event_source.response.read())
type = decoded["type"]
words = decoded["message"].split()
except (json.JSONDecodeError, KeyError):
click.echo(
event_source.response.read().decode()[:200], err=True
)
event_source.response.raise_for_status()
# Truncate any words longer than 30 characters
words = [word[:30] for word in words]
message = " ".join(words)
raise click.ClickException(
f"{event_source.response.status_code}: {type} - {message}"
)
event_source.response.raise_for_status()
usage = None
async for sse in event_source.aiter_sse():
if sse.data != "[DONE]":
try:
event = sse.json()
if "usage" in event:
usage = event["usage"]
yield event["choices"][0]["delta"]["content"]
except KeyError:
pass
if usage:
self.set_usage(response, usage)
else:
async with httpx.AsyncClient() as client:
api_response = await client.post(
"https://api.mistral.ai/v1/chat/completions",
headers={
"Content-Type": "application/json",
"Accept": "application/json",
"Authorization": f"Bearer {key}",
},
json=body,
timeout=None,
)
api_response.raise_for_status()
yield api_response.json()["choices"][0]["message"]["content"]
details = api_response.json()
usage = details.pop("usage", None)
response.response_json = details
if usage:
self.set_usage(response, usage)
class MistralEmbed(llm.EmbeddingModel):
model_id = "mistral-embed"
batch_size = 10
needs_key = "mistral"
key_env_var = "LLM_MISTRAL_KEY"
def embed_batch(self, texts):
key = self.get_key()
with httpx.Client() as client:
api_response = client.post(
"https://api.mistral.ai/v1/embeddings",
headers={
"Content-Type": "application/json",
"Accept": "application/json",
"Authorization": f"Bearer {key}",
},
json={
"model": "mistral-embed",
"input": list(texts),
"encoding_format": "float",
},
timeout=None,
)
api_response.raise_for_status()
return [item["embedding"] for item in api_response.json()["data"]]