chatlas 0.9.2__py3-none-any.whl → 0.11.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of chatlas might be problematic. Click here for more details.
- chatlas/__init__.py +25 -1
- chatlas/_chat.py +95 -14
- chatlas/_content.py +8 -1
- chatlas/_provider.py +43 -1
- chatlas/_provider_anthropic.py +51 -5
- chatlas/_provider_cloudflare.py +173 -0
- chatlas/_provider_databricks.py +18 -0
- chatlas/_provider_deepseek.py +171 -0
- chatlas/_provider_github.py +63 -3
- chatlas/_provider_google.py +26 -2
- chatlas/_provider_huggingface.py +155 -0
- chatlas/_provider_mistral.py +181 -0
- chatlas/_provider_ollama.py +40 -9
- chatlas/_provider_openai.py +38 -7
- chatlas/_provider_openrouter.py +149 -0
- chatlas/_provider_perplexity.py +9 -1
- chatlas/_provider_portkey.py +131 -0
- chatlas/_provider_snowflake.py +6 -0
- chatlas/_tokens.py +5 -5
- chatlas/_tools.py +12 -0
- chatlas/_typing_extensions.py +3 -3
- chatlas/_version.py +16 -3
- chatlas/data/prices.json +329 -18
- chatlas/types/__init__.py +2 -0
- chatlas/types/anthropic/_client.py +1 -1
- chatlas/types/anthropic/_client_bedrock.py +1 -1
- chatlas/types/openai/_client.py +1 -1
- chatlas/types/openai/_client_azure.py +1 -1
- chatlas/types/openai/_submit.py +3 -0
- {chatlas-0.9.2.dist-info → chatlas-0.11.0.dist-info}/METADATA +3 -3
- chatlas-0.11.0.dist-info/RECORD +54 -0
- chatlas-0.9.2.dist-info/RECORD +0 -48
- {chatlas-0.9.2.dist-info → chatlas-0.11.0.dist-info}/WHEEL +0 -0
- {chatlas-0.9.2.dist-info → chatlas-0.11.0.dist-info}/licenses/LICENSE +0 -0
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
from typing import TYPE_CHECKING, Optional, cast
|
|
5
|
+
|
|
6
|
+
from ._chat import Chat
|
|
7
|
+
from ._logging import log_model_default
|
|
8
|
+
from ._provider_openai import OpenAIProvider
|
|
9
|
+
from ._turn import Turn
|
|
10
|
+
from ._utils import MISSING, MISSING_TYPE, is_testing
|
|
11
|
+
|
|
12
|
+
if TYPE_CHECKING:
|
|
13
|
+
from openai.types.chat import ChatCompletion, ChatCompletionMessageParam
|
|
14
|
+
|
|
15
|
+
from .types.openai import ChatClientArgs, SubmitInputArgs
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def ChatDeepSeek(
|
|
19
|
+
*,
|
|
20
|
+
system_prompt: Optional[str] = None,
|
|
21
|
+
model: Optional[str] = None,
|
|
22
|
+
api_key: Optional[str] = None,
|
|
23
|
+
base_url: str = "https://api.deepseek.com",
|
|
24
|
+
seed: Optional[int] | MISSING_TYPE = MISSING,
|
|
25
|
+
kwargs: Optional["ChatClientArgs"] = None,
|
|
26
|
+
) -> Chat["SubmitInputArgs", ChatCompletion]:
|
|
27
|
+
"""
|
|
28
|
+
Chat with a model hosted on DeepSeek.
|
|
29
|
+
|
|
30
|
+
DeepSeek is a platform for AI inference with competitive pricing
|
|
31
|
+
and performance.
|
|
32
|
+
|
|
33
|
+
Prerequisites
|
|
34
|
+
-------------
|
|
35
|
+
|
|
36
|
+
::: {.callout-note}
|
|
37
|
+
## API key
|
|
38
|
+
|
|
39
|
+
Sign up at <https://platform.deepseek.com> to get an API key.
|
|
40
|
+
:::
|
|
41
|
+
|
|
42
|
+
Examples
|
|
43
|
+
--------
|
|
44
|
+
|
|
45
|
+
```python
|
|
46
|
+
import os
|
|
47
|
+
from chatlas import ChatDeepSeek
|
|
48
|
+
|
|
49
|
+
chat = ChatDeepSeek(api_key=os.getenv("DEEPSEEK_API_KEY"))
|
|
50
|
+
chat.chat("What is the capital of France?")
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
Known limitations
|
|
54
|
+
--------------
|
|
55
|
+
|
|
56
|
+
* Structured data extraction is not supported.
|
|
57
|
+
* Images are not supported.
|
|
58
|
+
|
|
59
|
+
Parameters
|
|
60
|
+
----------
|
|
61
|
+
system_prompt
|
|
62
|
+
A system prompt to set the behavior of the assistant.
|
|
63
|
+
model
|
|
64
|
+
The model to use for the chat. The default, None, will pick a reasonable
|
|
65
|
+
default, and warn you about it. We strongly recommend explicitly choosing
|
|
66
|
+
a model for all but the most casual use.
|
|
67
|
+
api_key
|
|
68
|
+
The API key to use for authentication. You generally should not supply
|
|
69
|
+
this directly, but instead set the `DEEPSEEK_API_KEY` environment variable.
|
|
70
|
+
base_url
|
|
71
|
+
The base URL to the endpoint; the default uses DeepSeek's API.
|
|
72
|
+
seed
|
|
73
|
+
Optional integer seed that DeepSeek uses to try and make output more
|
|
74
|
+
reproducible.
|
|
75
|
+
kwargs
|
|
76
|
+
Additional arguments to pass to the `openai.OpenAI()` client constructor.
|
|
77
|
+
|
|
78
|
+
Returns
|
|
79
|
+
-------
|
|
80
|
+
Chat
|
|
81
|
+
A chat object that retains the state of the conversation.
|
|
82
|
+
|
|
83
|
+
Note
|
|
84
|
+
----
|
|
85
|
+
This function is a lightweight wrapper around [](`~chatlas.ChatOpenAI`) with
|
|
86
|
+
the defaults tweaked for DeepSeek.
|
|
87
|
+
|
|
88
|
+
Note
|
|
89
|
+
----
|
|
90
|
+
Pasting an API key into a chat constructor (e.g., `ChatDeepSeek(api_key="...")`)
|
|
91
|
+
is the simplest way to get started, and is fine for interactive use, but is
|
|
92
|
+
problematic for code that may be shared with others.
|
|
93
|
+
|
|
94
|
+
Instead, consider using environment variables or a configuration file to manage
|
|
95
|
+
your credentials. One popular way to manage credentials is to use a `.env` file
|
|
96
|
+
to store your credentials, and then use the `python-dotenv` package to load them
|
|
97
|
+
into your environment.
|
|
98
|
+
|
|
99
|
+
```shell
|
|
100
|
+
pip install python-dotenv
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
```shell
|
|
104
|
+
# .env
|
|
105
|
+
DEEPSEEK_API_KEY=...
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
```python
|
|
109
|
+
from chatlas import ChatDeepSeek
|
|
110
|
+
from dotenv import load_dotenv
|
|
111
|
+
|
|
112
|
+
load_dotenv()
|
|
113
|
+
chat = ChatDeepSeek()
|
|
114
|
+
chat.console()
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
Another, more general, solution is to load your environment variables into the shell
|
|
118
|
+
before starting Python (maybe in a `.bashrc`, `.zshrc`, etc. file):
|
|
119
|
+
|
|
120
|
+
```shell
|
|
121
|
+
export DEEPSEEK_API_KEY=...
|
|
122
|
+
```
|
|
123
|
+
"""
|
|
124
|
+
if model is None:
|
|
125
|
+
model = log_model_default("deepseek-chat")
|
|
126
|
+
|
|
127
|
+
if api_key is None:
|
|
128
|
+
api_key = os.getenv("DEEPSEEK_API_KEY")
|
|
129
|
+
|
|
130
|
+
if isinstance(seed, MISSING_TYPE):
|
|
131
|
+
seed = 1014 if is_testing() else None
|
|
132
|
+
|
|
133
|
+
return Chat(
|
|
134
|
+
provider=DeepSeekProvider(
|
|
135
|
+
api_key=api_key,
|
|
136
|
+
model=model,
|
|
137
|
+
base_url=base_url,
|
|
138
|
+
seed=seed,
|
|
139
|
+
name="DeepSeek",
|
|
140
|
+
kwargs=kwargs,
|
|
141
|
+
),
|
|
142
|
+
system_prompt=system_prompt,
|
|
143
|
+
)
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
class DeepSeekProvider(OpenAIProvider):
|
|
147
|
+
@staticmethod
|
|
148
|
+
def _as_message_param(turns: list[Turn]) -> list["ChatCompletionMessageParam"]:
|
|
149
|
+
from openai.types.chat import (
|
|
150
|
+
ChatCompletionAssistantMessageParam,
|
|
151
|
+
ChatCompletionUserMessageParam,
|
|
152
|
+
)
|
|
153
|
+
|
|
154
|
+
params = OpenAIProvider._as_message_param(turns)
|
|
155
|
+
|
|
156
|
+
# Content must be a string
|
|
157
|
+
for i, param in enumerate(params):
|
|
158
|
+
if param["role"] in ["assistant", "user"]:
|
|
159
|
+
param = cast(
|
|
160
|
+
ChatCompletionAssistantMessageParam
|
|
161
|
+
| ChatCompletionUserMessageParam,
|
|
162
|
+
param,
|
|
163
|
+
)
|
|
164
|
+
contents = param.get("content", None)
|
|
165
|
+
if not isinstance(contents, list):
|
|
166
|
+
continue
|
|
167
|
+
params[i]["content"] = "".join(
|
|
168
|
+
content.get("text", "") for content in contents
|
|
169
|
+
)
|
|
170
|
+
|
|
171
|
+
return params
|
chatlas/_provider_github.py
CHANGED
|
@@ -3,9 +3,11 @@ from __future__ import annotations
|
|
|
3
3
|
import os
|
|
4
4
|
from typing import TYPE_CHECKING, Optional
|
|
5
5
|
|
|
6
|
+
import requests
|
|
7
|
+
|
|
6
8
|
from ._chat import Chat
|
|
7
9
|
from ._logging import log_model_default
|
|
8
|
-
from ._provider_openai import OpenAIProvider
|
|
10
|
+
from ._provider_openai import ModelInfo, OpenAIProvider
|
|
9
11
|
from ._utils import MISSING, MISSING_TYPE, is_testing
|
|
10
12
|
|
|
11
13
|
if TYPE_CHECKING:
|
|
@@ -18,7 +20,7 @@ def ChatGithub(
|
|
|
18
20
|
system_prompt: Optional[str] = None,
|
|
19
21
|
model: Optional[str] = None,
|
|
20
22
|
api_key: Optional[str] = None,
|
|
21
|
-
base_url: str = "https://models.
|
|
23
|
+
base_url: str = "https://models.github.ai/inference/",
|
|
22
24
|
seed: Optional[int] | MISSING_TYPE = MISSING,
|
|
23
25
|
kwargs: Optional["ChatClientArgs"] = None,
|
|
24
26
|
) -> Chat["SubmitInputArgs", ChatCompletion]:
|
|
@@ -125,7 +127,7 @@ def ChatGithub(
|
|
|
125
127
|
seed = 1014 if is_testing() else None
|
|
126
128
|
|
|
127
129
|
return Chat(
|
|
128
|
-
provider=
|
|
130
|
+
provider=GitHubProvider(
|
|
129
131
|
api_key=api_key,
|
|
130
132
|
model=model,
|
|
131
133
|
base_url=base_url,
|
|
@@ -135,3 +137,61 @@ def ChatGithub(
|
|
|
135
137
|
),
|
|
136
138
|
system_prompt=system_prompt,
|
|
137
139
|
)
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
class GitHubProvider(OpenAIProvider):
|
|
143
|
+
def __init__(self, base_url: str, **kwargs):
|
|
144
|
+
super().__init__(**kwargs)
|
|
145
|
+
self._base_url = base_url
|
|
146
|
+
|
|
147
|
+
def list_models(self) -> list[ModelInfo]:
|
|
148
|
+
# For some reason the OpenAI SDK API fails here? So perform request manually
|
|
149
|
+
# models = self._client.models.list()
|
|
150
|
+
|
|
151
|
+
base_url = self._base_url
|
|
152
|
+
if not base_url.endswith("/"):
|
|
153
|
+
base_url += "/"
|
|
154
|
+
|
|
155
|
+
if "azure" in base_url:
|
|
156
|
+
# i.e., https://models.inference.ai.azure.com
|
|
157
|
+
return list_models_gh_azure(base_url)
|
|
158
|
+
else:
|
|
159
|
+
# i.e., https://models.github.ai/inference/
|
|
160
|
+
return list_models_gh(base_url)
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def list_models_gh(base_url: str = "https://models.github.ai/inference/"):
|
|
164
|
+
# replace /inference endpoint with /catalog
|
|
165
|
+
base_url = base_url.replace("/inference", "/catalog")
|
|
166
|
+
response = requests.get(f"{base_url}models")
|
|
167
|
+
response.raise_for_status()
|
|
168
|
+
models = response.json()
|
|
169
|
+
|
|
170
|
+
res: list[ModelInfo] = []
|
|
171
|
+
for m in models:
|
|
172
|
+
_id = m["id"].split("/")[-1]
|
|
173
|
+
info: ModelInfo = {
|
|
174
|
+
"id": _id,
|
|
175
|
+
"name": m["name"],
|
|
176
|
+
"provider": m["publisher"],
|
|
177
|
+
"url": m["html_url"],
|
|
178
|
+
}
|
|
179
|
+
res.append(info)
|
|
180
|
+
|
|
181
|
+
return res
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def list_models_gh_azure(base_url: str = "https://models.inference.ai.azure.com"):
|
|
185
|
+
response = requests.get(f"{base_url}models")
|
|
186
|
+
response.raise_for_status()
|
|
187
|
+
models = response.json()
|
|
188
|
+
|
|
189
|
+
res: list[ModelInfo] = []
|
|
190
|
+
for m in models:
|
|
191
|
+
info: ModelInfo = {
|
|
192
|
+
"id": m["name"],
|
|
193
|
+
"provider": m["publisher"]
|
|
194
|
+
}
|
|
195
|
+
res.append(info)
|
|
196
|
+
|
|
197
|
+
return res
|
chatlas/_provider_google.py
CHANGED
|
@@ -21,8 +21,8 @@ from ._content import (
|
|
|
21
21
|
)
|
|
22
22
|
from ._logging import log_model_default
|
|
23
23
|
from ._merge import merge_dicts
|
|
24
|
-
from ._provider import Provider, StandardModelParamNames, StandardModelParams
|
|
25
|
-
from ._tokens import tokens_log
|
|
24
|
+
from ._provider import ModelInfo, Provider, StandardModelParamNames, StandardModelParams
|
|
25
|
+
from ._tokens import get_token_pricing, tokens_log
|
|
26
26
|
from ._tools import Tool
|
|
27
27
|
from ._turn import Turn, user_turn
|
|
28
28
|
|
|
@@ -180,6 +180,30 @@ class GoogleProvider(
|
|
|
180
180
|
|
|
181
181
|
self._client = genai.Client(**kwargs_full)
|
|
182
182
|
|
|
183
|
+
def list_models(self):
|
|
184
|
+
models = self._client.models.list()
|
|
185
|
+
|
|
186
|
+
res: list[ModelInfo] = []
|
|
187
|
+
for m in models:
|
|
188
|
+
name = m.name or "[unknown]"
|
|
189
|
+
pricing = get_token_pricing(self.name, name) or {}
|
|
190
|
+
info: ModelInfo = {
|
|
191
|
+
"id": name,
|
|
192
|
+
"name": m.display_name or "[unknown]",
|
|
193
|
+
"input": pricing.get("input"),
|
|
194
|
+
"output": pricing.get("output"),
|
|
195
|
+
"cached_input": pricing.get("cached_input"),
|
|
196
|
+
}
|
|
197
|
+
res.append(info)
|
|
198
|
+
|
|
199
|
+
# Sort list by created_by field (more recent first)
|
|
200
|
+
res.sort(
|
|
201
|
+
key=lambda x: x.get("created", 0),
|
|
202
|
+
reverse=True,
|
|
203
|
+
)
|
|
204
|
+
|
|
205
|
+
return res
|
|
206
|
+
|
|
183
207
|
@overload
|
|
184
208
|
def chat_perform(
|
|
185
209
|
self,
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
from typing import TYPE_CHECKING, Optional
|
|
5
|
+
|
|
6
|
+
from ._chat import Chat
|
|
7
|
+
from ._logging import log_model_default
|
|
8
|
+
from ._provider_openai import OpenAIProvider
|
|
9
|
+
|
|
10
|
+
if TYPE_CHECKING:
|
|
11
|
+
from openai.types.chat import ChatCompletion
|
|
12
|
+
|
|
13
|
+
from .types.openai import ChatClientArgs, SubmitInputArgs
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def ChatHuggingFace(
|
|
17
|
+
*,
|
|
18
|
+
system_prompt: Optional[str] = None,
|
|
19
|
+
model: Optional[str] = None,
|
|
20
|
+
api_key: Optional[str] = None,
|
|
21
|
+
kwargs: Optional["ChatClientArgs"] = None,
|
|
22
|
+
) -> Chat["SubmitInputArgs", ChatCompletion]:
|
|
23
|
+
"""
|
|
24
|
+
Chat with a model hosted on Hugging Face Inference API.
|
|
25
|
+
|
|
26
|
+
[Hugging Face](https://huggingface.co/) hosts a variety of open-source
|
|
27
|
+
and proprietary AI models available via their Inference API.
|
|
28
|
+
To use the Hugging Face API, you must have an Access Token, which you can obtain
|
|
29
|
+
from your [Hugging Face account](https://huggingface.co/settings/tokens).
|
|
30
|
+
Ensure that at least "Make calls to Inference Providers" and
|
|
31
|
+
"Make calls to your Inference Endpoints" is checked.
|
|
32
|
+
|
|
33
|
+
Prerequisites
|
|
34
|
+
--------------
|
|
35
|
+
|
|
36
|
+
::: {.callout-note}
|
|
37
|
+
## API key
|
|
38
|
+
|
|
39
|
+
You will need to create a Hugging Face account and generate an API token
|
|
40
|
+
from your [account settings](https://huggingface.co/settings/tokens).
|
|
41
|
+
Make sure to enable "Make calls to Inference Providers" permission.
|
|
42
|
+
:::
|
|
43
|
+
|
|
44
|
+
Examples
|
|
45
|
+
--------
|
|
46
|
+
```python
|
|
47
|
+
import os
|
|
48
|
+
from chatlas import ChatHuggingFace
|
|
49
|
+
|
|
50
|
+
chat = ChatHuggingFace(api_key=os.getenv("HUGGINGFACE_API_KEY"))
|
|
51
|
+
chat.chat("What is the capital of France?")
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
Parameters
|
|
55
|
+
----------
|
|
56
|
+
system_prompt
|
|
57
|
+
A system prompt to set the behavior of the assistant.
|
|
58
|
+
model
|
|
59
|
+
The model to use for the chat. The default, None, will pick a reasonable
|
|
60
|
+
default, and warn you about it. We strongly recommend explicitly
|
|
61
|
+
choosing a model for all but the most casual use.
|
|
62
|
+
api_key
|
|
63
|
+
The API key to use for authentication. You generally should not supply
|
|
64
|
+
this directly, but instead set the `HUGGINGFACE_API_KEY` environment
|
|
65
|
+
variable.
|
|
66
|
+
kwargs
|
|
67
|
+
Additional arguments to pass to the underlying OpenAI client
|
|
68
|
+
constructor.
|
|
69
|
+
|
|
70
|
+
Returns
|
|
71
|
+
-------
|
|
72
|
+
Chat
|
|
73
|
+
A chat object that retains the state of the conversation.
|
|
74
|
+
|
|
75
|
+
Known limitations
|
|
76
|
+
-----------------
|
|
77
|
+
|
|
78
|
+
* Some models do not support the chat interface or parts of it, for example
|
|
79
|
+
`google/gemma-2-2b-it` does not support a system prompt. You will need to
|
|
80
|
+
carefully choose the model.
|
|
81
|
+
* Tool calling support varies by model - many models do not support it.
|
|
82
|
+
|
|
83
|
+
Note
|
|
84
|
+
----
|
|
85
|
+
This function is a lightweight wrapper around [](`~chatlas.ChatOpenAI`), with
|
|
86
|
+
the defaults tweaked for Hugging Face.
|
|
87
|
+
|
|
88
|
+
Note
|
|
89
|
+
----
|
|
90
|
+
Pasting an API key into a chat constructor (e.g., `ChatHuggingFace(api_key="...")`)
|
|
91
|
+
is the simplest way to get started, and is fine for interactive use, but is
|
|
92
|
+
problematic for code that may be shared with others.
|
|
93
|
+
|
|
94
|
+
Instead, consider using environment variables or a configuration file to manage
|
|
95
|
+
your credentials. One popular way to manage credentials is to use a `.env` file
|
|
96
|
+
to store your credentials, and then use the `python-dotenv` package to load them
|
|
97
|
+
into your environment.
|
|
98
|
+
|
|
99
|
+
```shell
|
|
100
|
+
pip install python-dotenv
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
```shell
|
|
104
|
+
# .env
|
|
105
|
+
HUGGINGFACE_API_KEY=...
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
```python
|
|
109
|
+
from chatlas import ChatHuggingFace
|
|
110
|
+
from dotenv import load_dotenv
|
|
111
|
+
|
|
112
|
+
load_dotenv()
|
|
113
|
+
chat = ChatHuggingFace()
|
|
114
|
+
chat.console()
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
Another, more general, solution is to load your environment variables into the shell
|
|
118
|
+
before starting Python (maybe in a `.bashrc`, `.zshrc`, etc. file):
|
|
119
|
+
|
|
120
|
+
```shell
|
|
121
|
+
export HUGGINGFACE_API_KEY=...
|
|
122
|
+
```
|
|
123
|
+
"""
|
|
124
|
+
if api_key is None:
|
|
125
|
+
api_key = os.getenv("HUGGINGFACE_API_KEY")
|
|
126
|
+
|
|
127
|
+
if model is None:
|
|
128
|
+
model = log_model_default("meta-llama/Llama-3.1-8B-Instruct")
|
|
129
|
+
|
|
130
|
+
return Chat(
|
|
131
|
+
provider=HuggingFaceProvider(
|
|
132
|
+
api_key=api_key,
|
|
133
|
+
model=model,
|
|
134
|
+
kwargs=kwargs,
|
|
135
|
+
),
|
|
136
|
+
system_prompt=system_prompt,
|
|
137
|
+
)
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
class HuggingFaceProvider(OpenAIProvider):
|
|
141
|
+
def __init__(
|
|
142
|
+
self,
|
|
143
|
+
*,
|
|
144
|
+
api_key: Optional[str] = None,
|
|
145
|
+
model: str,
|
|
146
|
+
kwargs: Optional["ChatClientArgs"] = None,
|
|
147
|
+
):
|
|
148
|
+
# https://huggingface.co/docs/inference-providers/en/index?python-clients=requests#http--curl
|
|
149
|
+
super().__init__(
|
|
150
|
+
name="HuggingFace",
|
|
151
|
+
model=model,
|
|
152
|
+
api_key=api_key,
|
|
153
|
+
base_url="https://router.huggingface.co/v1",
|
|
154
|
+
kwargs=kwargs,
|
|
155
|
+
)
|
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
from typing import TYPE_CHECKING, Optional
|
|
5
|
+
|
|
6
|
+
from ._chat import Chat
|
|
7
|
+
from ._logging import log_model_default
|
|
8
|
+
from ._provider_openai import OpenAIProvider
|
|
9
|
+
from ._utils import MISSING, MISSING_TYPE, is_testing
|
|
10
|
+
|
|
11
|
+
if TYPE_CHECKING:
|
|
12
|
+
from openai.types.chat import ChatCompletion
|
|
13
|
+
|
|
14
|
+
from .types.openai import ChatClientArgs, SubmitInputArgs
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def ChatMistral(
|
|
18
|
+
*,
|
|
19
|
+
system_prompt: Optional[str] = None,
|
|
20
|
+
model: Optional[str] = None,
|
|
21
|
+
api_key: Optional[str] = None,
|
|
22
|
+
base_url: str = "https://api.mistral.ai/v1/",
|
|
23
|
+
seed: int | None | MISSING_TYPE = MISSING,
|
|
24
|
+
kwargs: Optional["ChatClientArgs"] = None,
|
|
25
|
+
) -> Chat["SubmitInputArgs", ChatCompletion]:
|
|
26
|
+
"""
|
|
27
|
+
Chat with a model hosted on Mistral's La Plateforme.
|
|
28
|
+
|
|
29
|
+
Mistral AI provides high-performance language models through their API platform.
|
|
30
|
+
|
|
31
|
+
Prerequisites
|
|
32
|
+
-------------
|
|
33
|
+
|
|
34
|
+
::: {.callout-note}
|
|
35
|
+
## API credentials
|
|
36
|
+
|
|
37
|
+
Get your API key from https://console.mistral.ai/api-keys.
|
|
38
|
+
:::
|
|
39
|
+
|
|
40
|
+
Examples
|
|
41
|
+
--------
|
|
42
|
+
```python
|
|
43
|
+
import os
|
|
44
|
+
from chatlas import ChatMistral
|
|
45
|
+
|
|
46
|
+
chat = ChatMistral(api_key=os.getenv("MISTRAL_API_KEY"))
|
|
47
|
+
chat.chat("Tell me three jokes about statisticians")
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
Known limitations
|
|
51
|
+
-----------------
|
|
52
|
+
|
|
53
|
+
* Tool calling may be unstable.
|
|
54
|
+
* Images require a model that supports vision.
|
|
55
|
+
|
|
56
|
+
Parameters
|
|
57
|
+
----------
|
|
58
|
+
system_prompt
|
|
59
|
+
A system prompt to set the behavior of the assistant.
|
|
60
|
+
model
|
|
61
|
+
The model to use for the chat. The default, None, will pick a reasonable
|
|
62
|
+
default, and warn you about it. We strongly recommend explicitly
|
|
63
|
+
choosing a model for all but the most casual use.
|
|
64
|
+
api_key
|
|
65
|
+
The API key to use for authentication. You generally should not supply
|
|
66
|
+
this directly, but instead set the `MISTRAL_API_KEY` environment
|
|
67
|
+
variable.
|
|
68
|
+
base_url
|
|
69
|
+
The base URL to the endpoint; the default uses Mistral AI.
|
|
70
|
+
seed
|
|
71
|
+
Optional integer seed that Mistral uses to try and make output more
|
|
72
|
+
reproducible.
|
|
73
|
+
kwargs
|
|
74
|
+
Additional arguments to pass to the `openai.OpenAI()` client
|
|
75
|
+
constructor (Mistral uses OpenAI-compatible API).
|
|
76
|
+
|
|
77
|
+
Returns
|
|
78
|
+
-------
|
|
79
|
+
Chat
|
|
80
|
+
A chat object that retains the state of the conversation.
|
|
81
|
+
|
|
82
|
+
Note
|
|
83
|
+
----
|
|
84
|
+
Pasting an API key into a chat constructor (e.g., `ChatMistral(api_key="...")`)
|
|
85
|
+
is the simplest way to get started, and is fine for interactive use, but is
|
|
86
|
+
problematic for code that may be shared with others.
|
|
87
|
+
|
|
88
|
+
Instead, consider using environment variables or a configuration file to manage
|
|
89
|
+
your credentials. One popular way to manage credentials is to use a `.env` file
|
|
90
|
+
to store your credentials, and then use the `python-dotenv` package to load them
|
|
91
|
+
into your environment.
|
|
92
|
+
|
|
93
|
+
```shell
|
|
94
|
+
pip install python-dotenv
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
```shell
|
|
98
|
+
# .env
|
|
99
|
+
MISTRAL_API_KEY=...
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
```python
|
|
103
|
+
from chatlas import ChatMistral
|
|
104
|
+
from dotenv import load_dotenv
|
|
105
|
+
|
|
106
|
+
load_dotenv()
|
|
107
|
+
chat = ChatMistral()
|
|
108
|
+
chat.console()
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
Another, more general, solution is to load your environment variables into the shell
|
|
112
|
+
before starting Python (maybe in a `.bashrc`, `.zshrc`, etc. file):
|
|
113
|
+
|
|
114
|
+
```shell
|
|
115
|
+
export MISTRAL_API_KEY=...
|
|
116
|
+
```
|
|
117
|
+
"""
|
|
118
|
+
if isinstance(seed, MISSING_TYPE):
|
|
119
|
+
seed = 1014 if is_testing() else None
|
|
120
|
+
|
|
121
|
+
if model is None:
|
|
122
|
+
model = log_model_default("mistral-large-latest")
|
|
123
|
+
|
|
124
|
+
if api_key is None:
|
|
125
|
+
api_key = os.getenv("MISTRAL_API_KEY")
|
|
126
|
+
|
|
127
|
+
return Chat(
|
|
128
|
+
provider=MistralProvider(
|
|
129
|
+
api_key=api_key,
|
|
130
|
+
model=model,
|
|
131
|
+
base_url=base_url,
|
|
132
|
+
seed=seed,
|
|
133
|
+
kwargs=kwargs,
|
|
134
|
+
),
|
|
135
|
+
system_prompt=system_prompt,
|
|
136
|
+
)
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
class MistralProvider(OpenAIProvider):
|
|
140
|
+
def __init__(
|
|
141
|
+
self,
|
|
142
|
+
*,
|
|
143
|
+
api_key: Optional[str] = None,
|
|
144
|
+
model: str,
|
|
145
|
+
base_url: str = "https://api.mistral.ai/v1/",
|
|
146
|
+
seed: Optional[int] = None,
|
|
147
|
+
name: str = "Mistral",
|
|
148
|
+
kwargs: Optional["ChatClientArgs"] = None,
|
|
149
|
+
):
|
|
150
|
+
super().__init__(
|
|
151
|
+
api_key=api_key,
|
|
152
|
+
model=model,
|
|
153
|
+
base_url=base_url,
|
|
154
|
+
seed=seed,
|
|
155
|
+
name=name,
|
|
156
|
+
kwargs=kwargs,
|
|
157
|
+
)
|
|
158
|
+
|
|
159
|
+
# Mistral is essentially OpenAI-compatible, with a couple small differences.
|
|
160
|
+
# We _could_ bring in the Mistral SDK and use it directly for more precise typing,
|
|
161
|
+
# etc., but for now that doesn't seem worth it.
|
|
162
|
+
def _chat_perform_args(
|
|
163
|
+
self, stream, turns, tools, data_model=None, kwargs=None
|
|
164
|
+
) -> "SubmitInputArgs":
|
|
165
|
+
# Get the base arguments from OpenAI provider
|
|
166
|
+
kwargs2 = super()._chat_perform_args(stream, turns, tools, data_model, kwargs)
|
|
167
|
+
|
|
168
|
+
# Mistral doesn't support stream_options
|
|
169
|
+
if "stream_options" in kwargs2:
|
|
170
|
+
del kwargs2["stream_options"]
|
|
171
|
+
|
|
172
|
+
# Mistral wants random_seed, not seed
|
|
173
|
+
if seed := kwargs2.pop("seed", None):
|
|
174
|
+
if isinstance(seed, int):
|
|
175
|
+
kwargs2["extra_body"] = {"random_seed": seed}
|
|
176
|
+
elif seed is not None:
|
|
177
|
+
raise ValueError(
|
|
178
|
+
"MistralProvider only accepts an integer seed, or None."
|
|
179
|
+
)
|
|
180
|
+
|
|
181
|
+
return kwargs2
|