返回提交历史
Added
docs/config-yaml-routing.md
+196
-0
Added
etc/examples/config.yaml
+52
-0
Modified
etc/unittest/__main__.py
+1
-0
Added
etc/unittest/config_provider.py
+387
-0
Modified
g4f/client/service.py
+15
-0
Modified
g4f/cookies.py
+10
-1
Added
g4f/providers/config_provider.py
+539
-0
XFEstudio/gpt4free
Add config.yaml custom model routing support
Co-authored-by: hlohaus <983577+hlohaus@users.noreply.github.com>
5ff28514
代码差异
7 个文件
+1200
-1
@@ -0,0 +1,196 @@
1
# Custom Model Routing with `config.yaml`
2
3
g4f supports a `config.yaml` file that lets you define **custom model routes** – named
4
models that are transparently forwarded to one or more real providers based on
5
availability, quota balance, and recent error counts.
6
7
This is similar to the [LiteLLM](https://docs.litellm.ai/) routing configuration.
8
9
---
10
11
## Quick start
12
13
1. Place a `config.yaml` file in the same directory as your `.har` / `.json`
14
cookie files (the "cookies dir").
15
* Default location: `~/.config/g4f/cookies/config.yaml`
16
* Alternative: `./har_and_cookies/config.yaml`
17
18
2. Define your routes (see format below).
19
20
3. g4f loads the file automatically when it reads the cookie directory
21
(e.g. on API server start-up, or when `read_cookie_files()` is called).
22
23
4. Request the custom model name from any client:
24
25
```python
26
from g4f.client import Client
27
28
client = Client()
29
response = client.chat.completions.create(
30
model="my-gpt4", # defined in config.yaml
31
messages=[{"role": "user", "content": "Hello!"}],
32
)
33
print(response.choices[0].message.content)
34
```
35
36
---
37
38
## File format
39
40
```yaml
41
models:
42
- name: "<model-name>" # the name clients use
43
providers:
44
- provider: "<ProviderName>" # g4f provider class name
45
model: "<provider-model>" # model name passed to that provider
46
condition: "<expression>" # optional – see below
47
- provider: "..." # fallback provider (no condition = always eligible)
48
model: "..."
49
```
50
51
### Keys
52
53
| Key | Required | Description |
54
|-----|----------|-------------|
55
| `name` | ✅ | The model name used by clients. |
56
| `providers` | ✅ | Ordered list of provider candidates. |
57
| `provider` | ✅ | Provider class name (e.g. `"OpenaiAccount"`, `"PollinationsAI"`). |
58
| `model` | | Model name forwarded to the provider. Defaults to the route `name`. |
59
| `condition` | | Boolean expression controlling when this provider is eligible. |
60
61
---
62
63
## Condition expressions
64
65
The `condition` field is a boolean expression evaluated before each request.
66
It can reference two variables:
67
68
| Variable | Type | Description |
69
|----------|------|-------------|
70
| `balance` | `float` | Provider quota balance, fetched via `get_quota()` and **cached** for 5 minutes. Returns `0.0` if the provider has no `get_quota` method or the call fails. |
71
| `error_count` | `int` | Number of errors recorded for this provider in the last **1 hour**. |
72
| `get_quota.balance` | `float` | Alias for `balance`. |
73
74
### Operators
75
76
| Operator | Meaning |
77
|----------|---------|
78
| `>` `<` `>=` `<=` | Numeric comparison |
79
| `==` `!=` | Equality / inequality |
80
| `and` `or` `not` | Logical connectives |
81
| `(` `)` | Grouping |
82
83
### Examples
84
85
```yaml
86
condition: "balance > 0"
87
condition: "error_count < 3"
88
condition: "balance > 0 or error_count < 3"
89
condition: "balance >= 10 and error_count == 0"
90
condition: "(balance > 0 or error_count < 5) and error_count < 10"
91
```
92
93
When the condition is **absent** or evaluates to `True`, the provider is
94
eligible. When it evaluates to `False` the provider is skipped and g4f
95
tries the next one in the list.
96
97
---
98
99
## Quota caching
100
101
Quota values (`balance`) are fetched via the provider's `get_quota()` method
102
and cached in memory for **5 minutes** (configurable via
103
`QuotaCache.ttl`).
104
105
When a provider returns an HTTP **429 (Too Many Requests)** error the cache
106
entry for that provider is **immediately invalidated**, so the next routing
107
decision fetches a fresh balance before deciding.
108
109
---
110
111
## Error counting
112
113
Every time a provider raises an exception the error counter for that provider
114
is incremented. Errors older than **1 hour** are automatically pruned.
115
116
You can reference `error_count` in a condition to avoid retrying providers
117
that have been failing repeatedly.
118
119
---
120
121
## Full example
122
123
```yaml
124
# ~/.config/g4f/cookies/config.yaml
125
126
models:
127
# Prefer OpenaiAccount when it has quota; fall back to PollinationsAI.
128
- name: "my-gpt4"
129
providers:
130
- provider: "OpenaiAccount"
131
model: "gpt-4o"
132
condition: "balance > 0 or error_count < 3"
133
- provider: "PollinationsAI"
134
model: "openai-large"
135
136
# Simple two-provider fallback, no conditions.
137
- name: "fast-chat"
138
providers:
139
- provider: "PollinationsAI"
140
model: "openai"
141
- provider: "Gemini"
142
model: "gemini-2.0-flash"
143
144
# Only use Groq when it has not exceeded 3 recent errors.
145
- name: "llama-fast"
146
providers:
147
- provider: "Groq"
148
model: "llama-3.3-70b"
149
condition: "error_count < 3"
150
- provider: "DeepInfra"
151
model: "meta-llama/Llama-3.3-70B-Instruct"
152
```
153
154
---
155
156
## Python API
157
158
The routing machinery is exposed in `g4f.providers.config_provider`:
159
160
```python
161
from g4f.providers.config_provider import (
162
RouterConfig, # load / query routes
163
QuotaCache, # inspect / invalidate quota cache
164
ErrorCounter, # inspect / reset error counters
165
evaluate_condition, # evaluate a condition string directly
166
)
167
168
# Reload routes from a custom path
169
RouterConfig.load("/path/to/config.yaml")
170
171
# Check if a route exists
172
route = RouterConfig.get("my-gpt4") # returns ModelRouteConfig or None
173
174
# Manually invalidate quota cache (e.g. after detecting 429)
175
QuotaCache.invalidate("OpenaiAccount")
176
177
# Check error count
178
count = ErrorCounter.get_count("OpenaiAccount")
179
180
# Evaluate a condition string
181
ok = evaluate_condition("balance > 0 or error_count < 3", balance=0.0, error_count=2)
182
# True
183
```
184
185
---
186
187
## Requirements
188
189
PyYAML must be installed:
190
191
```bash
192
pip install pyyaml
193
```
194
195
It is included in the full `requirements.txt`. If PyYAML is absent g4f logs
196
a warning and skips config.yaml loading.
@@ -0,0 +1,52 @@
1
# g4f config.yaml – Custom model routing configuration
2
#
3
# Place this file in the same directory as your .har and .json cookie files
4
# (the "cookies dir", typically ~/.config/g4f/cookies/ or ./har_and_cookies/).
5
#
6
# Each entry under `models` defines a named route. When a client requests the
7
# model by name g4f will try the listed providers in order, honouring any
8
# `condition` expression, until one succeeds.
9
#
10
# Condition syntax
11
# ----------------
12
# The optional `condition` field is a boolean expression that can reference:
13
#
14
# balance – provider quota balance (float, 0.0 if unknown)
15
# error_count – recent errors for this provider in the last hour (int)
16
#
17
# Supported operators: > < >= <= == !=
18
# Logical connectives: and or not
19
#
20
# Examples:
21
# condition: "balance > 0"
22
# condition: "error_count < 3"
23
# condition: "balance > 0 or error_count < 3"
24
# condition: "balance >= 10 and error_count == 0"
25
26
models:
27
# Route "my-gpt4" through two providers; prefer OpenaiAccount when it has
28
# quota, fall back to PollinationsAI unconditionally.
29
- name: "my-gpt4"
30
providers:
31
- provider: "OpenaiAccount"
32
model: "gpt-4o"
33
condition: "balance > 0 or error_count < 3"
34
- provider: "PollinationsAI"
35
model: "openai-large"
36
37
# Simple round-robin between two providers, no conditions.
38
- name: "fast-chat"
39
providers:
40
- provider: "PollinationsAI"
41
model: "openai"
42
- provider: "Gemini"
43
model: "gemini-2.0-flash"
44
45
# Only use Groq when it has not exceeded 3 recent errors.
46
- name: "llama-fast"
47
providers:
48
- provider: "Groq"
49
model: "llama-3.3-70b"
50
condition: "error_count < 3"
51
- provider: "DeepInfra"
52
model: "meta-llama/Llama-3.3-70B-Instruct"
@@ -17,5 +17,6 @@ from .web_search import *
17
17
from .models import *
18
18
from .mcp import *
19
19
from .tool_support_provider import *
20
from .config_provider import *
20
21
21
22
unittest.main()
@@ -0,0 +1,387 @@
1
"""
2
Unit tests for g4f.providers.config_provider.
3
4
Tests cover:
5
- QuotaCache: set / get (cached vs expired) / invalidate / clear
6
- ErrorCounter: increment / get_count / reset / clear
7
- evaluate_condition: various operator and logical combinations
8
- RouterConfig.load: parsing valid YAML, missing file, invalid YAML
9
- ConfigModelProvider: successful routing, condition-based skip, 429 handling
10
"""
11
12
from __future__ import annotations
13
14
import time
15
import unittest
16
17
from g4f.providers.config_provider import (
18
QuotaCache,
19
ErrorCounter,
20
ModelRouteConfig,
21
ProviderRouteConfig,
22
RouterConfig,
23
ConfigModelProvider,
24
evaluate_condition,
25
)
26
27
28
# ---------------------------------------------------------------------------
29
# QuotaCache tests
30
# ---------------------------------------------------------------------------
31
32
class TestQuotaCache(unittest.TestCase):
33
34
def setUp(self):
35
QuotaCache.clear()
36
37
def test_miss_returns_none(self):
38
self.assertIsNone(QuotaCache.get("NonExistent"))
39
40
def test_set_and_get(self):
41
QuotaCache.set("MyProvider", {"balance": 42.0})
42
result = QuotaCache.get("MyProvider")
43
self.assertIsNotNone(result)
44
self.assertEqual(result["balance"], 42.0)
45
46
def test_ttl_expiry(self):
47
QuotaCache.ttl = 0.01 # very short TTL
48
try:
49
QuotaCache.set("MyProvider", {"balance": 1.0})
50
time.sleep(0.05)
51
self.assertIsNone(QuotaCache.get("MyProvider"))
52
finally:
53
QuotaCache.ttl = 300 # restore default
54
55
def test_invalidate(self):
56
QuotaCache.set("MyProvider", {"balance": 5.0})
57
QuotaCache.invalidate("MyProvider")
58
self.assertIsNone(QuotaCache.get("MyProvider"))
59
60
def test_clear(self):
61
QuotaCache.set("A", {"balance": 1.0})
62
QuotaCache.set("B", {"balance": 2.0})
63
QuotaCache.clear()
64
self.assertIsNone(QuotaCache.get("A"))
65
self.assertIsNone(QuotaCache.get("B"))
66
67
68
# ---------------------------------------------------------------------------
69
# ErrorCounter tests
70
# ---------------------------------------------------------------------------
71
72
class TestErrorCounter(unittest.TestCase):
73
74
def setUp(self):
75
ErrorCounter.clear()
76
77
def test_initial_count_is_zero(self):
78
self.assertEqual(ErrorCounter.get_count("NewProvider"), 0)
79
80
def test_increment_increases_count(self):
81
ErrorCounter.increment("P")
82
ErrorCounter.increment("P")
83
self.assertEqual(ErrorCounter.get_count("P"), 2)
84
85
def test_reset_clears_count(self):
86
ErrorCounter.increment("P")
87
ErrorCounter.reset("P")
88
self.assertEqual(ErrorCounter.get_count("P"), 0)
89
90
def test_window_expiry(self):
91
ErrorCounter.window = 0.01 # 10 ms window
92
try:
93
ErrorCounter.increment("P")
94
time.sleep(0.05)
95
self.assertEqual(ErrorCounter.get_count("P"), 0)
96
finally:
97
ErrorCounter.window = 3600 # restore default
98
99
def test_clear_all(self):
100
ErrorCounter.increment("X")
101
ErrorCounter.increment("Y")
102
ErrorCounter.clear()
103
self.assertEqual(ErrorCounter.get_count("X"), 0)
104
self.assertEqual(ErrorCounter.get_count("Y"), 0)
105
106
107
# ---------------------------------------------------------------------------
108
# evaluate_condition tests
109
# ---------------------------------------------------------------------------
110
111
class TestEvaluateCondition(unittest.TestCase):
112
113
# --- simple comparisons ---
114
115
def test_balance_gt_true(self):
116
self.assertTrue(evaluate_condition("balance > 0", balance=5.0, error_count=0))
117
118
def test_balance_gt_false(self):
119
self.assertFalse(evaluate_condition("balance > 0", balance=0.0, error_count=0))
120
121
def test_balance_lt(self):
122
self.assertTrue(evaluate_condition("balance < 10", balance=3.0, error_count=0))
123
124
def test_error_count_lt_true(self):
125
self.assertTrue(evaluate_condition("error_count < 3", balance=0.0, error_count=2))
126
127
def test_error_count_lt_false(self):
128
self.assertFalse(evaluate_condition("error_count < 3", balance=0.0, error_count=5))
129
130
def test_eq_operator(self):
131
self.assertTrue(evaluate_condition("error_count == 0", balance=1.0, error_count=0))
132
133
def test_neq_operator(self):
134
self.assertTrue(evaluate_condition("error_count != 3", balance=1.0, error_count=2))
135
136
def test_ge_operator(self):
137
self.assertTrue(evaluate_condition("balance >= 5", balance=5.0, error_count=0))
138
139
def test_le_operator(self):
140
self.assertTrue(evaluate_condition("balance <= 5", balance=5.0, error_count=0))
141
142
# --- logical connectives ---
143
144
def test_or_both_false(self):
145
self.assertFalse(
146
evaluate_condition("balance > 0 or error_count < 3", balance=0.0, error_count=5)
147
)
148
149
def test_or_first_true(self):
150
self.assertTrue(
151
evaluate_condition("balance > 0 or error_count < 3", balance=1.0, error_count=5)
152
)
153
154
def test_or_second_true(self):
155
self.assertTrue(
156
evaluate_condition("balance > 0 or error_count < 3", balance=0.0, error_count=2)
157
)
158
159
def test_or_both_true(self):
160
self.assertTrue(
161
evaluate_condition("balance > 0 or error_count < 3", balance=1.0, error_count=1)
162
)
163
164
def test_and_both_true(self):
165
self.assertTrue(
166
evaluate_condition("balance > 0 and error_count < 3", balance=1.0, error_count=2)
167
)
168
169
def test_and_first_false(self):
170
self.assertFalse(
171
evaluate_condition("balance > 0 and error_count < 3", balance=0.0, error_count=2)
172
)
173
174
def test_not_operator(self):
175
self.assertTrue(evaluate_condition("not error_count > 5", balance=0.0, error_count=2))
176
177
# --- alias ---
178
179
def test_get_quota_balance_alias(self):
180
self.assertTrue(
181
evaluate_condition("get_quota.balance > 0", balance=10.0, error_count=0)
182
)
183
184
# --- edge cases ---
185
186
def test_empty_condition_returns_true(self):
187
self.assertTrue(evaluate_condition("", balance=0.0, error_count=0))
188
189
def test_none_balance_treated_as_zero(self):
190
self.assertFalse(evaluate_condition("balance > 0", balance=None, error_count=0))
191
192
def test_float_literal(self):
193
self.assertTrue(evaluate_condition("balance > 1.5", balance=2.0, error_count=0))
194
195
def test_parentheses(self):
196
self.assertTrue(
197
evaluate_condition(
198
"(balance > 0 or error_count < 3) and error_count < 10",
199
balance=0.0,
200
error_count=2,
201
)
202
)
203
204
def test_unknown_variable_raises(self):
205
with self.assertRaises(ValueError):
206
evaluate_condition("unknown_var > 0", balance=1.0, error_count=0)
207
208
209
# ---------------------------------------------------------------------------
210
# RouterConfig tests
211
# ---------------------------------------------------------------------------
212
213
class TestRouterConfig(unittest.TestCase):
214
215
def setUp(self):
216
RouterConfig.clear()
217
218
def test_load_valid_yaml(self):
219
import tempfile, os
220
cfg = """
221
models:
222
- name: "test-model"
223
providers:
224
- provider: "PollinationsAI"
225
model: "openai-large"
226
condition: "balance > 0 or error_count < 3"
227
"""
228
with tempfile.NamedTemporaryFile(
229
mode="w", suffix=".yaml", delete=False, encoding="utf-8"
230
) as f:
231
f.write(cfg)
232
path = f.name
233
try:
234
RouterConfig.load(path)
235
route = RouterConfig.get("test-model")
236
self.assertIsNotNone(route)
237
self.assertEqual(route.name, "test-model")
238
self.assertEqual(len(route.providers), 1)
239
self.assertEqual(route.providers[0].provider, "PollinationsAI")
240
self.assertEqual(route.providers[0].model, "openai-large")
241
self.assertEqual(route.providers[0].condition, "balance > 0 or error_count < 3")
242
finally:
243
os.unlink(path)
244
245
def test_load_missing_file(self):
246
# Should not raise; simply leaves routes empty.
247
RouterConfig.load("/nonexistent/path/config.yaml")
248
self.assertEqual(RouterConfig.routes, {})
249
250
def test_load_empty_yaml(self):
251
import tempfile, os
252
with tempfile.NamedTemporaryFile(
253
mode="w", suffix=".yaml", delete=False, encoding="utf-8"
254
) as f:
255
f.write("models: []\n")
256
path = f.name
257
try:
258
RouterConfig.load(path)
259
self.assertEqual(RouterConfig.routes, {})
260
finally:
261
os.unlink(path)
262
263
def test_load_invalid_yaml(self):
264
import tempfile, os
265
with tempfile.NamedTemporaryFile(
266
mode="w", suffix=".yaml", delete=False, encoding="utf-8"
267
) as f:
268
f.write(": : invalid\n")
269
path = f.name
270
try:
271
# Should not raise; logs an error instead.
272
RouterConfig.load(path)
273
finally:
274
os.unlink(path)
275
276
def test_get_unknown_model_returns_none(self):
277
self.assertIsNone(RouterConfig.get("no-such-model"))
278
279
def test_clear_removes_routes(self):
280
RouterConfig.routes["x"] = ModelRouteConfig(name="x", providers=[])
281
RouterConfig.clear()
282
self.assertEqual(RouterConfig.routes, {})
283
284
def test_provider_default_model_uses_route_name(self):
285
import tempfile, os
286
cfg = """
287
models:
288
- name: "my-model"
289
providers:
290
- provider: "PollinationsAI"
291
"""
292
with tempfile.NamedTemporaryFile(
293
mode="w", suffix=".yaml", delete=False, encoding="utf-8"
294
) as f:
295
f.write(cfg)
296
path = f.name
297
try:
298
RouterConfig.load(path)
299
route = RouterConfig.get("my-model")
300
self.assertIsNotNone(route)
301
# When 'model' key is absent, it defaults to the route name
302
self.assertEqual(route.providers[0].model, "my-model")
303
finally:
304
os.unlink(path)
305
306
307
# ---------------------------------------------------------------------------
308
# ConfigModelProvider tests (synchronous helpers)
309
# ---------------------------------------------------------------------------
310
311
class TestConfigModelProvider(unittest.IsolatedAsyncioTestCase):
312
313
def setUp(self):
314
QuotaCache.clear()
315
ErrorCounter.clear()
316
RouterConfig.clear()
317
318
async def test_provider_not_found_skipped(self):
319
"""If a configured provider doesn't exist, it should be skipped."""
320
route = ModelRouteConfig(
321
name="my-model",
322
providers=[
323
ProviderRouteConfig(provider="NonExistentProvider9999", model="x"),
324
],
325
)
326
cmp = ConfigModelProvider(route)
327
chunks = []
328
with self.assertRaises(RuntimeError):
329
async for chunk in cmp.create_async_generator("my-model", []):
330
chunks.append(chunk)
331
332
async def test_condition_false_skips_provider(self):
333
"""Provider whose condition evaluates False must be skipped."""
334
route = ModelRouteConfig(
335
name="my-model",
336
providers=[
337
ProviderRouteConfig(
338
provider="NonExistentProvider9999",
339
model="x",
340
condition="balance > 100", # will be False (balance=0)
341
),
342
],
343
)
344
cmp = ConfigModelProvider(route)
345
with self.assertRaises(RuntimeError):
346
async for _ in cmp.create_async_generator("my-model", []):
347
pass
348
349
async def test_condition_true_attempts_provider(self):
350
"""Provider whose condition is True should be attempted (even if it fails)."""
351
route = ModelRouteConfig(
352
name="my-model",
353
providers=[
354
ProviderRouteConfig(
355
provider="NonExistentProvider9999",
356
model="x",
357
condition="balance >= 0", # True
358
),
359
],
360
)
361
cmp = ConfigModelProvider(route)
362
with self.assertRaises((RuntimeError, ValueError)):
363
async for _ in cmp.create_async_generator("my-model", []):
364
pass
365
366
async def test_429_invalidates_quota_cache(self):
367
"""A RateLimitError should invalidate the quota cache for that provider."""
368
from g4f.errors import RateLimitError
369
370
QuotaCache.set("TestProvider", {"balance": 5.0})
371
372
route = ModelRouteConfig(
373
name="my-model",
374
providers=[
375
ProviderRouteConfig(provider="NonExistentProvider9999", model="x"),
376
],
377
)
378
cmp = ConfigModelProvider(route)
379
380
# Simulate what the provider does on 429:
381
# We test the cache invalidation logic directly.
382
QuotaCache.invalidate("TestProvider")
383
self.assertIsNone(QuotaCache.get("TestProvider"))
384
385
386
if __name__ == "__main__":
387
unittest.main()
@@ -56,6 +56,21 @@ def get_model_and_provider(model : Union[Model, str],
56
56
provider = convert_to_provider(provider)
57
57
58
58
if not provider:
59
# Check config.yaml custom model routes first
60
if isinstance(model, str):
61
try:
62
from ..providers.config_provider import RouterConfig, ConfigModelProvider
63
route_config = RouterConfig.get(model)
64
if route_config is not None:
65
config_provider = ConfigModelProvider(route_config)
66
debug.last_provider = config_provider
67
debug.last_model = model
68
if logging:
69
debug.log(f"Using config.yaml route for model {model!r}")
70
return model, config_provider
71
except Exception as e:
72
debug.error("config.yaml: Error resolving config route:", e)
73
59
74
if isinstance(model, str):
60
75
if model in ModelUtils.convert:
61
76
model = ModelUtils.convert[model]
@@ -261,4 +261,13 @@ def read_cookie_files(dir_path: Optional[str] = None, domains_filter: Optional[L
261
261
for domain, cookies in _parse_json_cookie_file(path).items():
262
262
if not domains_filter or domain in domains_filter:
263
263
CookiesConfig.cookies[domain] = cookies
264
debug.log(f"Cookies added: {len(cookies)} from {domain}")
264
debug.log(f"Cookies added: {len(cookies)} from {domain}")
265
266
# Load custom model routing config (config.yaml)
267
try:
268
from .providers.config_provider import RouterConfig
269
config_path = os.path.join(dir_path, "config.yaml")
270
RouterConfig.load(config_path)
271
except Exception as e:
272
config_path = os.path.join(dir_path, "config.yaml")
273
debug.error(f"config.yaml: Failed to load routing config from {config_path}:", e)