chatlas 0.9.1__py3-none-any.whl → 0.10.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 +21 -9
- chatlas/_auto.py +9 -9
- chatlas/_chat.py +38 -9
- chatlas/{_anthropic.py → _provider_anthropic.py} +13 -5
- chatlas/_provider_cloudflare.py +165 -0
- chatlas/{_databricks.py → _provider_databricks.py} +13 -2
- chatlas/_provider_deepseek.py +171 -0
- chatlas/{_github.py → _provider_github.py} +2 -2
- chatlas/{_google.py → _provider_google.py} +5 -5
- chatlas/{_groq.py → _provider_groq.py} +2 -2
- chatlas/_provider_huggingface.py +155 -0
- chatlas/_provider_mistral.py +181 -0
- chatlas/{_ollama.py → _provider_ollama.py} +2 -2
- chatlas/{_openai.py → _provider_openai.py} +28 -9
- chatlas/_provider_openrouter.py +149 -0
- chatlas/{_perplexity.py → _provider_perplexity.py} +2 -2
- chatlas/_provider_portkey.py +123 -0
- chatlas/{_snowflake.py → _provider_snowflake.py} +3 -3
- chatlas/_tokens.py +27 -12
- chatlas/_turn.py +3 -4
- chatlas/_typing_extensions.py +3 -3
- chatlas/_version.py +16 -3
- chatlas/data/prices.json +2769 -163
- chatlas/types/__init__.py +3 -3
- chatlas/types/anthropic/_client.py +1 -1
- chatlas/types/anthropic/_client_bedrock.py +1 -1
- chatlas/types/anthropic/_submit.py +5 -5
- chatlas/types/google/_submit.py +23 -29
- chatlas/types/openai/_client.py +1 -1
- chatlas/types/openai/_client_azure.py +1 -1
- chatlas/types/openai/_submit.py +28 -3
- {chatlas-0.9.1.dist-info → chatlas-0.10.0.dist-info}/METADATA +4 -4
- chatlas-0.10.0.dist-info/RECORD +54 -0
- chatlas-0.9.1.dist-info/RECORD +0 -48
- {chatlas-0.9.1.dist-info → chatlas-0.10.0.dist-info}/WHEEL +0 -0
- {chatlas-0.9.1.dist-info → chatlas-0.10.0.dist-info}/licenses/LICENSE +0 -0
|
@@ -5,11 +5,11 @@ from typing import TYPE_CHECKING, Optional
|
|
|
5
5
|
|
|
6
6
|
from ._chat import Chat
|
|
7
7
|
from ._logging import log_model_default
|
|
8
|
-
from .
|
|
8
|
+
from ._provider_openai import OpenAIProvider
|
|
9
9
|
from ._utils import MISSING, MISSING_TYPE, is_testing
|
|
10
10
|
|
|
11
11
|
if TYPE_CHECKING:
|
|
12
|
-
from .
|
|
12
|
+
from ._provider_openai import ChatCompletion
|
|
13
13
|
from .types.openai import ChatClientArgs, SubmitInputArgs
|
|
14
14
|
|
|
15
15
|
|
|
@@ -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
|
|
@@ -7,11 +7,11 @@ from typing import TYPE_CHECKING, Optional
|
|
|
7
7
|
import orjson
|
|
8
8
|
|
|
9
9
|
from ._chat import Chat
|
|
10
|
-
from .
|
|
10
|
+
from ._provider_openai import OpenAIProvider
|
|
11
11
|
from ._utils import MISSING_TYPE, is_testing
|
|
12
12
|
|
|
13
13
|
if TYPE_CHECKING:
|
|
14
|
-
from .
|
|
14
|
+
from ._provider_openai import ChatCompletion
|
|
15
15
|
from .types.openai import ChatClientArgs, SubmitInputArgs
|
|
16
16
|
|
|
17
17
|
|
|
@@ -310,8 +310,7 @@ class OpenAIProvider(
|
|
|
310
310
|
del kwargs_full["tools"]
|
|
311
311
|
|
|
312
312
|
if stream and "stream_options" not in kwargs_full:
|
|
313
|
-
|
|
314
|
-
kwargs_full["stream_options"] = {"include_usage": True}
|
|
313
|
+
kwargs_full["stream_options"] = {"include_usage": True}
|
|
315
314
|
|
|
316
315
|
return kwargs_full
|
|
317
316
|
|
|
@@ -411,7 +410,9 @@ class OpenAIProvider(
|
|
|
411
410
|
if isinstance(x, ContentText):
|
|
412
411
|
content_parts.append({"type": "text", "text": x.text})
|
|
413
412
|
elif isinstance(x, ContentJson):
|
|
414
|
-
content_parts.append(
|
|
413
|
+
content_parts.append(
|
|
414
|
+
{"type": "text", "text": "<structured data/>"}
|
|
415
|
+
)
|
|
415
416
|
elif isinstance(x, ContentToolRequest):
|
|
416
417
|
tool_calls.append(
|
|
417
418
|
{
|
|
@@ -450,7 +451,7 @@ class OpenAIProvider(
|
|
|
450
451
|
if isinstance(x, ContentText):
|
|
451
452
|
contents.append({"type": "text", "text": x.text})
|
|
452
453
|
elif isinstance(x, ContentJson):
|
|
453
|
-
contents.append({"type": "text", "text": ""})
|
|
454
|
+
contents.append({"type": "text", "text": "<structured data/>"})
|
|
454
455
|
elif isinstance(x, ContentPDF):
|
|
455
456
|
contents.append(
|
|
456
457
|
{
|
|
@@ -522,7 +523,10 @@ class OpenAIProvider(
|
|
|
522
523
|
contents: list[Content] = []
|
|
523
524
|
if message.content is not None:
|
|
524
525
|
if has_data_model:
|
|
525
|
-
data =
|
|
526
|
+
data = message.content
|
|
527
|
+
# Some providers (e.g., Cloudflare) may already provide a dict
|
|
528
|
+
if not isinstance(data, dict):
|
|
529
|
+
data = orjson.loads(data)
|
|
526
530
|
contents = [ContentJson(value=data)]
|
|
527
531
|
else:
|
|
528
532
|
contents = [ContentText(text=message.content)]
|
|
@@ -531,6 +535,8 @@ class OpenAIProvider(
|
|
|
531
535
|
|
|
532
536
|
if tool_calls is not None:
|
|
533
537
|
for call in tool_calls:
|
|
538
|
+
if call.type != "function":
|
|
539
|
+
continue
|
|
534
540
|
func = call.function
|
|
535
541
|
if func is None:
|
|
536
542
|
continue
|
|
@@ -557,14 +563,27 @@ class OpenAIProvider(
|
|
|
557
563
|
|
|
558
564
|
usage = completion.usage
|
|
559
565
|
if usage is None:
|
|
560
|
-
tokens = (0, 0)
|
|
566
|
+
tokens = (0, 0, 0)
|
|
561
567
|
else:
|
|
562
|
-
|
|
568
|
+
if usage.prompt_tokens_details is not None:
|
|
569
|
+
cached_tokens = (
|
|
570
|
+
usage.prompt_tokens_details.cached_tokens
|
|
571
|
+
if usage.prompt_tokens_details.cached_tokens
|
|
572
|
+
else 0
|
|
573
|
+
)
|
|
574
|
+
else:
|
|
575
|
+
cached_tokens = 0
|
|
576
|
+
tokens = (
|
|
577
|
+
usage.prompt_tokens - cached_tokens,
|
|
578
|
+
usage.completion_tokens,
|
|
579
|
+
cached_tokens,
|
|
580
|
+
)
|
|
563
581
|
|
|
564
582
|
# For some reason ChatGroq() includes tokens under completion.x_groq
|
|
583
|
+
# Groq does not support caching, so we set cached_tokens to 0
|
|
565
584
|
if usage is None and hasattr(completion, "x_groq"):
|
|
566
585
|
usage = completion.x_groq["usage"] # type: ignore
|
|
567
|
-
tokens = usage["prompt_tokens"], usage["completion_tokens"]
|
|
586
|
+
tokens = usage["prompt_tokens"], usage["completion_tokens"], 0
|
|
568
587
|
|
|
569
588
|
tokens_log(self, tokens)
|
|
570
589
|
|
|
@@ -703,7 +722,7 @@ class OpenAIAzureProvider(OpenAIProvider):
|
|
|
703
722
|
api_version: Optional[str] = None,
|
|
704
723
|
api_key: Optional[str] = None,
|
|
705
724
|
seed: int | None = None,
|
|
706
|
-
name: str = "
|
|
725
|
+
name: str = "Azure/OpenAI",
|
|
707
726
|
model: Optional[str] = "UnusedValue",
|
|
708
727
|
kwargs: Optional["ChatAzureClientArgs"] = None,
|
|
709
728
|
):
|
|
@@ -0,0 +1,149 @@
|
|
|
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 ._provider_openai import ChatCompletion
|
|
13
|
+
from .types.openai import ChatClientArgs, SubmitInputArgs
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def ChatOpenRouter(
|
|
17
|
+
*,
|
|
18
|
+
system_prompt: Optional[str] = None,
|
|
19
|
+
model: Optional[str] = None,
|
|
20
|
+
api_key: Optional[str] = None,
|
|
21
|
+
base_url: str = "https://openrouter.ai/api/v1",
|
|
22
|
+
seed: Optional[int] | MISSING_TYPE = MISSING,
|
|
23
|
+
kwargs: Optional["ChatClientArgs"] = None,
|
|
24
|
+
) -> Chat["SubmitInputArgs", ChatCompletion]:
|
|
25
|
+
"""
|
|
26
|
+
Chat with one of the many models hosted on OpenRouter.
|
|
27
|
+
|
|
28
|
+
OpenRouter provides access to a wide variety of language models from different providers
|
|
29
|
+
through a unified API. Support for features depends on the underlying model that you use.
|
|
30
|
+
|
|
31
|
+
Prerequisites
|
|
32
|
+
-------------
|
|
33
|
+
|
|
34
|
+
::: {.callout-note}
|
|
35
|
+
## API key
|
|
36
|
+
|
|
37
|
+
Sign up at <https://openrouter.ai> to get an API key.
|
|
38
|
+
:::
|
|
39
|
+
|
|
40
|
+
Examples
|
|
41
|
+
--------
|
|
42
|
+
|
|
43
|
+
```python
|
|
44
|
+
import os
|
|
45
|
+
from chatlas import ChatOpenRouter
|
|
46
|
+
|
|
47
|
+
chat = ChatOpenRouter(api_key=os.getenv("OPENROUTER_API_KEY"))
|
|
48
|
+
chat.chat("What is the capital of France?")
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
Parameters
|
|
52
|
+
----------
|
|
53
|
+
system_prompt
|
|
54
|
+
A system prompt to set the behavior of the assistant.
|
|
55
|
+
model
|
|
56
|
+
The model to use for the chat. The default, None, will pick a reasonable
|
|
57
|
+
default, and warn you about it. We strongly recommend explicitly choosing
|
|
58
|
+
a model for all but the most casual use. See <https://openrouter.ai/models>
|
|
59
|
+
for available models.
|
|
60
|
+
api_key
|
|
61
|
+
The API key to use for authentication. You generally should not supply
|
|
62
|
+
this directly, but instead set the `OPENROUTER_API_KEY` environment variable.
|
|
63
|
+
base_url
|
|
64
|
+
The base URL to the endpoint; the default uses OpenRouter's API.
|
|
65
|
+
seed
|
|
66
|
+
Optional integer seed that the model uses to try and make output more
|
|
67
|
+
reproducible.
|
|
68
|
+
kwargs
|
|
69
|
+
Additional arguments to pass to the `openai.OpenAI()` client constructor.
|
|
70
|
+
|
|
71
|
+
Returns
|
|
72
|
+
-------
|
|
73
|
+
Chat
|
|
74
|
+
A chat object that retains the state of the conversation.
|
|
75
|
+
|
|
76
|
+
Note
|
|
77
|
+
----
|
|
78
|
+
This function is a lightweight wrapper around [](`~chatlas.ChatOpenAI`) with
|
|
79
|
+
the defaults tweaked for OpenRouter.
|
|
80
|
+
|
|
81
|
+
Note
|
|
82
|
+
----
|
|
83
|
+
Pasting an API key into a chat constructor (e.g., `ChatOpenRouter(api_key="...")`)
|
|
84
|
+
is the simplest way to get started, and is fine for interactive use, but is
|
|
85
|
+
problematic for code that may be shared with others.
|
|
86
|
+
|
|
87
|
+
Instead, consider using environment variables or a configuration file to manage
|
|
88
|
+
your credentials. One popular way to manage credentials is to use a `.env` file
|
|
89
|
+
to store your credentials, and then use the `python-dotenv` package to load them
|
|
90
|
+
into your environment.
|
|
91
|
+
|
|
92
|
+
```shell
|
|
93
|
+
pip install python-dotenv
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
```shell
|
|
97
|
+
# .env
|
|
98
|
+
OPENROUTER_API_KEY=...
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
```python
|
|
102
|
+
from chatlas import ChatOpenRouter
|
|
103
|
+
from dotenv import load_dotenv
|
|
104
|
+
|
|
105
|
+
load_dotenv()
|
|
106
|
+
chat = ChatOpenRouter()
|
|
107
|
+
chat.console()
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
Another, more general, solution is to load your environment variables into the shell
|
|
111
|
+
before starting Python (maybe in a `.bashrc`, `.zshrc`, etc. file):
|
|
112
|
+
|
|
113
|
+
```shell
|
|
114
|
+
export OPENROUTER_API_KEY=...
|
|
115
|
+
```
|
|
116
|
+
"""
|
|
117
|
+
if model is None:
|
|
118
|
+
model = log_model_default("gpt-4.1")
|
|
119
|
+
|
|
120
|
+
if api_key is None:
|
|
121
|
+
api_key = os.getenv("OPENROUTER_API_KEY")
|
|
122
|
+
|
|
123
|
+
if isinstance(seed, MISSING_TYPE):
|
|
124
|
+
seed = 1014 if is_testing() else None
|
|
125
|
+
|
|
126
|
+
kwargs2 = add_default_headers(kwargs or {})
|
|
127
|
+
|
|
128
|
+
return Chat(
|
|
129
|
+
provider=OpenAIProvider(
|
|
130
|
+
api_key=api_key,
|
|
131
|
+
model=model,
|
|
132
|
+
base_url=base_url,
|
|
133
|
+
seed=seed,
|
|
134
|
+
name="OpenRouter",
|
|
135
|
+
kwargs=kwargs2,
|
|
136
|
+
),
|
|
137
|
+
system_prompt=system_prompt,
|
|
138
|
+
)
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def add_default_headers(kwargs: "ChatClientArgs") -> "ChatClientArgs":
|
|
142
|
+
headers = kwargs.get("default_headers", None)
|
|
143
|
+
# https://openrouter.ai/docs/api-keys
|
|
144
|
+
default_headers = {
|
|
145
|
+
"HTTP-Referer": "https://posit-dev.github.io/chatlas",
|
|
146
|
+
"X-Title": "chatlas",
|
|
147
|
+
**(headers or {}),
|
|
148
|
+
}
|
|
149
|
+
return {"default_headers": default_headers, **kwargs}
|
|
@@ -5,11 +5,11 @@ from typing import TYPE_CHECKING, Optional
|
|
|
5
5
|
|
|
6
6
|
from ._chat import Chat
|
|
7
7
|
from ._logging import log_model_default
|
|
8
|
-
from .
|
|
8
|
+
from ._provider_openai import OpenAIProvider
|
|
9
9
|
from ._utils import MISSING, MISSING_TYPE, is_testing
|
|
10
10
|
|
|
11
11
|
if TYPE_CHECKING:
|
|
12
|
-
from .
|
|
12
|
+
from ._provider_openai import ChatCompletion
|
|
13
13
|
from .types.openai import ChatClientArgs, SubmitInputArgs
|
|
14
14
|
|
|
15
15
|
|