Repository navigation
Expand file tree
/
Copy pathproviders.py
More file actions
105 lines (94 loc) · 3.21 KB
/
Copy pathproviders.py
File metadata and controls
105 lines (94 loc) · 3.21 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
"""Unified multi-provider AI client — Groq, Mistral, NVIDIA NIM (all OpenAI-compatible)."""
from __future__ import annotations
import os
from typing import Iterator
from openai import OpenAI, APIError, APITimeoutError, RateLimitError
from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential
PROVIDER_CONFIG: dict[str, dict] = {
"groq": {
"base_url": "https://api.groq.com/openai/v1",
"env_key": "GROQ_API_KEY",
"default_model": "llama-3.3-70b-versatile",
"label": "Groq · Llama 3.3 70B",
"emoji": "🔍",
},
"mistral": {
"base_url": "https://api.mistral.ai/v1",
"env_key": "MISTRAL_API_KEY",
"default_model": "mistral-large-latest",
"label": "Mistral · Large Latest",
"emoji": "🧐",
},
"nvidia": {
"base_url": "https://integrate.api.nvidia.com/v1",
"env_key": "NVIDIA_API_KEY",
"default_model": "meta/llama-3.1-70b-instruct",
"label": "NVIDIA NIM · Llama 3.1 70B",
"emoji": "⚖️",
},
}
def get_client(provider: str, api_key: str | None = None) -> OpenAI:
cfg = PROVIDER_CONFIG.get(provider)
if cfg is None:
raise ValueError(f"Unknown provider '{provider}'. Valid: {list(PROVIDER_CONFIG)}")
key = api_key or os.getenv(cfg["env_key"])
if not key:
raise ValueError(
f"{cfg['env_key']} is not set. "
f"Add it to your .env file or enter it in the UI."
)
return OpenAI(api_key=key, base_url=cfg["base_url"])
def available_providers(api_keys: dict[str, str] | None = None) -> list[str]:
"""Return providers that have an API key configured."""
keys = api_keys or {}
result = []
for name, cfg in PROVIDER_CONFIG.items():
if keys.get(name) or os.getenv(cfg["env_key"]):
result.append(name)
return result
@retry(
retry=retry_if_exception_type((APIError, APITimeoutError, RateLimitError)),
stop=stop_after_attempt(3),
wait=wait_exponential(multiplier=1, min=2, max=10),
reraise=True,
)
def chat(
provider: str,
messages: list[dict],
model: str | None = None,
api_key: str | None = None,
temperature: float = 0.2,
) -> str:
cfg = PROVIDER_CONFIG[provider]
client = get_client(provider, api_key)
response = client.chat.completions.create(
model=model or cfg["default_model"],
messages=messages,
temperature=temperature,
)
return response.choices[0].message.content or ""
@retry(
retry=retry_if_exception_type((APIError, APITimeoutError, RateLimitError)),
stop=stop_after_attempt(3),
wait=wait_exponential(multiplier=1, min=2, max=10),
reraise=True,
)
def chat_stream(
provider: str,
messages: list[dict],
model: str | None = None,
api_key: str | None = None,
temperature: float = 0.2,
) -> Iterator[str]:
cfg = PROVIDER_CONFIG[provider]
client = get_client(provider, api_key)
stream = client.chat.completions.create(
model=model or cfg["default_model"],
messages=messages,
temperature=temperature,
stream=True,
)
for chunk in stream:
delta = chunk.choices[0].delta.content
if delta:
yield delta