flexgate 0.12.1__tar.gz → 0.12.2__tar.gz
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.
- {flexgate-0.12.1 → flexgate-0.12.2}/CLAUDE.md +2 -2
- {flexgate-0.12.1 → flexgate-0.12.2}/PKG-INFO +3 -3
- {flexgate-0.12.1 → flexgate-0.12.2}/README.md +2 -2
- {flexgate-0.12.1 → flexgate-0.12.2}/docs/api.md +3 -2
- {flexgate-0.12.1 → flexgate-0.12.2}/docs/usage.md +1 -1
- {flexgate-0.12.1 → flexgate-0.12.2}/flexgate/__init__.py +1 -1
- {flexgate-0.12.1 → flexgate-0.12.2}/flexgate/responses.py +27 -3
- {flexgate-0.12.1 → flexgate-0.12.2}/flexgate/usage.py +32 -45
- flexgate-0.12.2/tests/test_dispatch_translation.py +107 -0
- {flexgate-0.12.1 → flexgate-0.12.2}/.github/workflows/docs.yml +0 -0
- {flexgate-0.12.1 → flexgate-0.12.2}/.github/workflows/release.yml +0 -0
- {flexgate-0.12.1 → flexgate-0.12.2}/.gitignore +0 -0
- {flexgate-0.12.1 → flexgate-0.12.2}/config.yaml.template +0 -0
- {flexgate-0.12.1 → flexgate-0.12.2}/docs/Makefile +0 -0
- {flexgate-0.12.1 → flexgate-0.12.2}/docs/_static/.gitkeep +0 -0
- {flexgate-0.12.1 → flexgate-0.12.2}/docs/cli.md +0 -0
- {flexgate-0.12.1 → flexgate-0.12.2}/docs/conf.py +0 -0
- {flexgate-0.12.1 → flexgate-0.12.2}/docs/configuration.md +0 -0
- {flexgate-0.12.1 → flexgate-0.12.2}/docs/development.md +0 -0
- {flexgate-0.12.1 → flexgate-0.12.2}/docs/index.md +0 -0
- {flexgate-0.12.1 → flexgate-0.12.2}/docs/quickstart.md +0 -0
- {flexgate-0.12.1 → flexgate-0.12.2}/docs/requirements.txt +0 -0
- {flexgate-0.12.1 → flexgate-0.12.2}/flexgate/__main__.py +0 -0
- {flexgate-0.12.1 → flexgate-0.12.2}/flexgate/cli.py +0 -0
- {flexgate-0.12.1 → flexgate-0.12.2}/flexgate/config.py +0 -0
- {flexgate-0.12.1 → flexgate-0.12.2}/flexgate/doctor.py +0 -0
- {flexgate-0.12.1 → flexgate-0.12.2}/flexgate/fallback.py +0 -0
- {flexgate-0.12.1 → flexgate-0.12.2}/flexgate/healthcheck.py +0 -0
- {flexgate-0.12.1 → flexgate-0.12.2}/flexgate/images.py +0 -0
- {flexgate-0.12.1 → flexgate-0.12.2}/flexgate/main.py +0 -0
- {flexgate-0.12.1 → flexgate-0.12.2}/flexgate/migrate.py +0 -0
- {flexgate-0.12.1 → flexgate-0.12.2}/flexgate/proxy.py +0 -0
- {flexgate-0.12.1 → flexgate-0.12.2}/flexgate/router.py +0 -0
- {flexgate-0.12.1 → flexgate-0.12.2}/flexgate/server.py +0 -0
- {flexgate-0.12.1 → flexgate-0.12.2}/flexgate/service.py +0 -0
- {flexgate-0.12.1 → flexgate-0.12.2}/flexgate/settings.py +0 -0
- {flexgate-0.12.1 → flexgate-0.12.2}/flexgate/sync.py +0 -0
- {flexgate-0.12.1 → flexgate-0.12.2}/flexgate/ui.py +0 -0
- {flexgate-0.12.1 → flexgate-0.12.2}/flexgate/update.py +0 -0
- {flexgate-0.12.1 → flexgate-0.12.2}/pyproject.toml +0 -0
- {flexgate-0.12.1 → flexgate-0.12.2}/test.png +0 -0
- {flexgate-0.12.1 → flexgate-0.12.2}/test_multimodal.py +0 -0
- {flexgate-0.12.1 → flexgate-0.12.2}/test_multimodal_gateway.py +0 -0
|
@@ -59,7 +59,7 @@ flexgate update --config-only # only migrate the config schema
|
|
|
59
59
|
flexgate service reload
|
|
60
60
|
```
|
|
61
61
|
|
|
62
|
-
There is no
|
|
62
|
+
Run offline regression tests with `uv run python -m unittest discover -s tests`. There is no configured linter. CI is a single GitHub Actions
|
|
63
63
|
release workflow (`.github/workflows/release.yml`): pushing a `v*` tag verifies
|
|
64
64
|
the tag matches `__version__`, builds sdist/wheel, and publishes to PyPI via
|
|
65
65
|
trusted publishing. The canonical repo is
|
|
@@ -127,7 +127,7 @@ OpenAI-style client → POST /v1/images/generations
|
|
|
127
127
|
- **Key fallback** (`proxy.py`): a provider's `api_keys` list holds one or more keys for the same upstream (entries are key strings or `{key, note}` mappings — plus optional `organization`/`project` on GLM team keys, used only by the usage check; `note` is a free-form label shown by `flexgate status` and in fallback logs). Multiple accounts on one upstream — e.g. several MiniMax subscriptions — belong in ONE provider, not separate ones. GLM coding plans are the documented exception: z.ai (api.z.ai) and zhipu (open.bigmodel.cn) share one account system — the same keys work on both endpoints, so a provider's `base_url` can be swapped freely when one endpoint is unstable (convention: one provider per key set, `zhipu`/`zhipu-team` on bigmodel). Each *route* has an active-key pointer (`active_key` in YAML, 1-based; `RouteConfig.key_index` 0-based, default first key): requests on that route start from the pointed key, and on a retryable failure (HTTP 401/402/403/429/500/502/503/529, connect error, or timeout) the next key is tried and the pointer advances with it (in memory only, wrapping around — it is not written back to the file); every key is tried at most once and a full circle of failures returns the last error. The pointer is set interactively via `flexgate config edit` → "api keys" (pick a route, with live per-key usage) or by editing the route's `active_key` directly. `resolve()` (`router.py`) returns the matched `RouteConfig` so the proxy can read/advance its pointer. Streaming requests can only fall back before the upstream returns 200. `_regular_proxy`/`_stream_proxy` return `(response, retryable)`; `handle_request` owns the loop and returns the last error when all keys fail. The legacy `api_key` + `fallback_keys` schema is still parsed (`config._parse_api_keys`); migration v3 → v4 rewrites it to `api_keys`. `ProviderConfig.api_key` remains as a first-key property (getter/setter) for the settings import code.
|
|
128
128
|
- **Usage inspection** (`usage.py`): `flexgate status` maps `base_url` to a platform adapter (`_ADAPTERS`): MiniMax → `{origin}/v1/api/openplatform/coding_plan/remains` (only the "general" text-model quota entry is used; its counts are usually 0/0, so usage is read from the `*_remaining_percent` fields), Kimi Code → `{base}/v1/usages` (undocumented, same endpoint as the CLI's `/usage`; reports weekly quota, 5-hour window and parallel limit), GLM (z.ai / bigmodel.cn, one account system — same keys on both endpoints) → adapter picked per key entry: without `organization`/`project` it is a personal coding-plan key → `{origin}/api/monitor/usage/quota/limit` (undocumented but used by z.ai's own plugin; both endpoints serve it), with them it is a team key → the same endpoint with `?type=2` plus `bigmodel-organization`/`bigmodel-project` headers and the team subscription detail for plan name/expiry (both endpoints serve it too), USTC/LiteLLM → `{origin}/key/info`, DeepSeek → `{origin}/user/balance` (prepaid total per currency normalized into `QuotaInfo.balance`, shown next to the key in the unified summary). Hosts in `_PROBE_ONLY_MARKERS` (e.g. xiaomimimo.com — no key-based usage API) and unknown platforms get the minimal chat probe: `POST /v1/messages` with input `"hi"`, `max_tokens=128`. A failed adapter call also degrades to the probe. Any key whose usage query errored — a hard failure (adapter AND probe), or an adapter error merely recovered by the probe — is recorded in `~/.flexgate/usage-cache.json` (sha256 fingerprint of `base_url|key`, never key material — scoped by endpoint so the same key under two providers caches independently; entry keeps the `ok` flag and output lines) and skipped by later `status`/`usage` runs, shown as `cached (… ago)` / `cached failure (… ago)` with a hint; `flexgate usage --force` rechecks them and a clean success clears the entry. Placeholder keys are never cached.
|
|
129
129
|
- **Multimodal degradation**: `MULTIMODAL_MODELS` (currently `{"MiniMax-M3", "glm-4.6v"}`) is the allowlist. Requests carrying image blocks aimed at any other model have images stripped and a `[flexgate]` text note injected into both the outgoing request and the returned response, so non-multimodal backends don't 4xx.
|
|
130
|
-
- **Responses translation** (`responses.py`): `/v1/responses` serves every provider, not just `wire: responses` ones. Anthropic-wire providers get a translated request (`instructions` + system/developer items → `system`; input items → role-merged `messages`; `max_output_tokens` → `max_tokens`, default
|
|
130
|
+
- **Responses translation** (`responses.py`): `/v1/responses` serves every provider, not just `wire: responses` ones. Anthropic-wire providers get a translated request (`instructions` + system/developer items → `system`; input items → role-merged `messages`; `max_output_tokens` → `max_tokens`, model-specific default; `function`/`local_shell`/`custom` tools → Anthropic `tools`; `tool_choice: none` drops the tools; `parallel_tool_calls: false` → `disable_parallel_tool_use`; temperature clamped to 0–1) and a re-framed answer (text → `message`, thinking → `reasoning`, `tool_use` → `function_call`/`custom_tool_call`, `stop_reason: max_tokens` → `status: incomplete`, cache tokens folded into `input_tokens`). Streaming is rebuilt as Responses SSE (`response.created` → per-item added/delta/done → `response.completed`/`incomplete`/`failed`) with continuous `sequence_number`s and a terminal event even when the upstream stream is cut; a non-SSE 200 body is framed as a single completed response; upstream non-200 answers keep their status and body. `include`, `store`, `previous_response_id` are ignored. The translated request goes through the normal proxy path, so key fallback, image stripping and hot reload all apply unchanged.
|
|
131
131
|
- **Usage dedupe** (`usage.py`): a key listed under several providers (e.g. `zai-responses` sharing keys with `zhipu`) is queried once and reported under one owner — adapter-capable beats probe-only, anthropic wire beats responses wire, then config order. Non-owning providers whose keys are all duplicates are left out of the terminal output; `--json` still exposes the mapping as `usage.duplicates`.
|
|
132
132
|
- **Schedule-based overrides**: Optional time windows (e.g. 22:00-06:00) override default routes. Overnight wrap is supported.
|
|
133
133
|
- **Service-first lifecycle**: `flexgate.service` is the sole persistent runtime. systemd owns restart, boot startup, logs, and process state.
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: flexgate
|
|
3
|
-
Version: 0.12.
|
|
3
|
+
Version: 0.12.2
|
|
4
4
|
Summary: Flexible local API gateway for Claude Code — route models to different providers
|
|
5
5
|
Project-URL: Homepage, https://github.com/Agony5757/flexible-gateway
|
|
6
6
|
Project-URL: Repository, https://github.com/Agony5757/flexible-gateway
|
|
@@ -54,13 +54,13 @@ Codex CLI(≥0.84)只说 OpenAI Responses 协议(`wire_api = "chat"` 已
|
|
|
54
54
|
|
|
55
55
|
转换覆盖:`instructions`/system 消息 → `system`;input items(消息、`function_call`、
|
|
56
56
|
`function_call_output`、`input_image`、`input_file`)→ `messages`;`max_output_tokens` →
|
|
57
|
-
`max_tokens
|
|
57
|
+
`max_tokens`(缺省时 MiniMax-M4 / M3.1-Flash 为 65,536,GLM-5.3 / 5.3-Flash 为 32,768,其他模型为 8,192);`tools`(`function` / `local_shell` / `custom`)→ Anthropic
|
|
58
58
|
`tools`;`tool_choice` / `parallel_tool_calls` → Anthropic `tool_choice`;上游 `text` /
|
|
59
59
|
`thinking` / `tool_use` 块 → `message` / `reasoning` / `function_call`(custom 工具为
|
|
60
60
|
`custom_tool_call`)item;`stop_reason: max_tokens` → `status: incomplete`;usage 含缓存
|
|
61
61
|
token 折算进 `input_tokens` / `input_tokens_details.cached_tokens`。流式按
|
|
62
62
|
`response.created` → 逐 item 的 added/delta/done → `response.completed` 重新成帧,上游
|
|
63
|
-
|
|
63
|
+
流被截断时也会发出终止事件。MiniMax-M4 和 MiniMax-M3.1-Flash 将 `reasoning.effort` 转为 `output_config.effort`;省略时由上游选择强度。其他模型沿用原有的强度处理。`include`、`store`、
|
|
64
64
|
`previous_response_id` 等字段被忽略(上游无对应能力)。
|
|
65
65
|
|
|
66
66
|
`~/.codex/config.toml` 接入方式(配合 `~/.codex/models.json` 模型目录):
|
|
@@ -37,13 +37,13 @@ Codex CLI(≥0.84)只说 OpenAI Responses 协议(`wire_api = "chat"` 已
|
|
|
37
37
|
|
|
38
38
|
转换覆盖:`instructions`/system 消息 → `system`;input items(消息、`function_call`、
|
|
39
39
|
`function_call_output`、`input_image`、`input_file`)→ `messages`;`max_output_tokens` →
|
|
40
|
-
`max_tokens
|
|
40
|
+
`max_tokens`(缺省时 MiniMax-M4 / M3.1-Flash 为 65,536,GLM-5.3 / 5.3-Flash 为 32,768,其他模型为 8,192);`tools`(`function` / `local_shell` / `custom`)→ Anthropic
|
|
41
41
|
`tools`;`tool_choice` / `parallel_tool_calls` → Anthropic `tool_choice`;上游 `text` /
|
|
42
42
|
`thinking` / `tool_use` 块 → `message` / `reasoning` / `function_call`(custom 工具为
|
|
43
43
|
`custom_tool_call`)item;`stop_reason: max_tokens` → `status: incomplete`;usage 含缓存
|
|
44
44
|
token 折算进 `input_tokens` / `input_tokens_details.cached_tokens`。流式按
|
|
45
45
|
`response.created` → 逐 item 的 added/delta/done → `response.completed` 重新成帧,上游
|
|
46
|
-
|
|
46
|
+
流被截断时也会发出终止事件。MiniMax-M4 和 MiniMax-M3.1-Flash 将 `reasoning.effort` 转为 `output_config.effort`;省略时由上游选择强度。其他模型沿用原有的强度处理。`include`、`store`、
|
|
47
47
|
`previous_response_id` 等字段被忽略(上游无对应能力)。
|
|
48
48
|
|
|
49
49
|
`~/.codex/config.toml` 接入方式(配合 `~/.codex/models.json` 模型目录):
|
|
@@ -43,7 +43,8 @@ OpenAI Responses API 端点,Codex CLI 用的协议。请求体中的 `model`
|
|
|
43
43
|
|----------------|----------------|
|
|
44
44
|
| `instructions`、system/developer 消息 | `system` |
|
|
45
45
|
| input items(消息 / `function_call` / `function_call_output` / `input_image` / `input_file`) | `messages`(相邻同角色合并,工具结果并入同一条 user 消息) |
|
|
46
|
-
| `max_output_tokens` | `max_tokens
|
|
46
|
+
| `max_output_tokens` | `max_tokens`。显式正整数原样转发;缺省时按实际路由模型选取,MiniMax-M4 / M3.1-Flash 用 65,536,GLM-5.3 / 5.3-Flash 用 32,768,其他模型用 8,192。 |
|
|
47
|
+
| `reasoning.effort` | MiniMax-M4、MiniMax-M3.1-Flash 转为 `output_config.effort`。`low/medium/high/xhigh/max` 原样转发,`minimal` 对应 `low`,显式禁用或无效值返回 400;缺省时沿用上游默认值。其他模型忽略此字段。 |
|
|
47
48
|
| `tools`:`function` / `local_shell` / `custom` | `tools`(`input_schema`) |
|
|
48
49
|
| `tool_choice`(`none` 时整体去掉 tools)、`parallel_tool_calls: false` | `tool_choice`(含 `disable_parallel_tool_use`) |
|
|
49
50
|
| `temperature` / `top_p` | 同名(temperature 钳制到 0–1) |
|
|
@@ -62,7 +63,7 @@ OpenAI Responses API 端点,Codex CLI 用的协议。请求体中的 `model`
|
|
|
62
63
|
→ `response.completed`(或 `response.incomplete` / `response.failed`)重新
|
|
63
64
|
成帧,`sequence_number` 连续;上游流被截断或中途报错时也会发出终止事件。
|
|
64
65
|
上游返回非 200 时保留原状态码与错误体(key fallback 行为不变)。
|
|
65
|
-
- **忽略的字段**:`
|
|
66
|
+
- **忽略的字段**:`include`、`store`、`previous_response_id`、
|
|
66
67
|
`metadata`、`truncation`、`text.format` 等(上游无对应能力);`input` 中的
|
|
67
68
|
`reasoning` item 不会回放给上游。
|
|
68
69
|
- **多模态**:`input_image` 会转成 Anthropic image 块,因此
|
|
@@ -13,7 +13,7 @@
|
|
|
13
13
|
|
|
14
14
|
| 平台 | 查询方式 | 说明 |
|
|
15
15
|
|------|----------|------|
|
|
16
|
-
| MiniMax(api.minimaxi.com / api.minimax.io) | `GET /v1/api/openplatform/coding_plan/remains`(Bearer 认证,复用 provider key) |
|
|
16
|
+
| MiniMax(api.minimaxi.com / api.minimax.io) | `GET /v1/api/openplatform/coding_plan/remains`(Bearer 认证,复用 provider key) | 优先读取文本池 `general` 的五小时和周剩余百分比;兼容旧池 `MiniMax-M*`。仅有次数时按 `*_usage_count / *_total_count` 算剩余比例,已用次数为总数减剩余次数。 |
|
|
17
17
|
| Kimi Code(api.kimi.com) | `GET {base}/v1/usages`(Bearer 认证,复用 provider key) | 未公开文档、与 Kimi Code CLI `/usage` 相同的接口,返回周配额、5 小时滚动窗口剩余量和并发上限 |
|
|
18
18
|
| GLM 个人版(api.z.ai / open.bigmodel.cn) | `GET /api/monitor/usage/quota/limit`(Authorization 直接带 key) | 未公开文档、但 z.ai 官方 coding 插件在用的接口,返回各窗口已用百分比与重置时间。z.ai 和智谱(bigmodel.cn)是同一账号体系,**两个端点都响应**此接口。仅对 GLM Coding Plan 个人订阅有效:按量付费 key 或团队 key 会返回"当前用户不存在coding plan"并退化为 probe(团队 key 需在条目上配 `organization`/`project`) |
|
|
19
19
|
| GLM 团队版(api.z.ai / open.bigmodel.cn) | `GET /api/monitor/usage/quota/limit?type=2`,带 `bigmodel-organization`/`bigmodel-project` 头(取自 key 条目的 `organization`/`project` 字段) | 同一 monitor 接口的团队版变体,返回 5 小时/每周窗口的积分用量(绝对值 + 百分比 + 重置时间);另查 `querySubscribeDetail` 显示套餐名与有效期。**两个端点都响应**;key 条目未配 `organization`/`project` 时按个人版 key 处理 |
|
|
@@ -17,7 +17,8 @@ Responses request Anthropic request
|
|
|
17
17
|
=============================== ==========================================
|
|
18
18
|
``instructions``, system/developer ``system``
|
|
19
19
|
input items ``messages`` (adjacent same-role merged)
|
|
20
|
-
``max_output_tokens`` ``max_tokens`` (default
|
|
20
|
+
``max_output_tokens`` ``max_tokens`` (model-specific default)
|
|
21
|
+
``reasoning.effort`` ``output_config.effort`` on supported MiniMax models
|
|
21
22
|
``tools`` function/local_shell/ ``tools`` (``input_schema``)
|
|
22
23
|
custom
|
|
23
24
|
``tool_choice`` ``tool_choice`` (``none`` drops the tools)
|
|
@@ -59,6 +60,17 @@ logger = logging.getLogger("flexgate.responses")
|
|
|
59
60
|
|
|
60
61
|
# Anthropic requires max_tokens; Responses clients may omit max_output_tokens.
|
|
61
62
|
DEFAULT_MAX_TOKENS = 8192
|
|
63
|
+
_MINIMAX_EFFORT_MODELS = {"minimax-m4", "minimax-m3.1-flash"}
|
|
64
|
+
_MODEL_OUTPUT_BUDGETS = {
|
|
65
|
+
**dict.fromkeys(_MINIMAX_EFFORT_MODELS, 65536),
|
|
66
|
+
"glm-5.3": 32768,
|
|
67
|
+
"glm-5.3-flash": 32768,
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def default_max_tokens(model: str) -> int:
|
|
72
|
+
"""Messages requires a budget even when the Responses client leaves it unset."""
|
|
73
|
+
return _MODEL_OUTPUT_BUDGETS.get(model.casefold(), DEFAULT_MAX_TOKENS)
|
|
62
74
|
|
|
63
75
|
# Anthropic tool names are restricted to this shape.
|
|
64
76
|
_LOCAL_SHELL_SCHEMA: dict[str, Any] = {
|
|
@@ -423,10 +435,22 @@ def responses_request_to_anthropic(
|
|
|
423
435
|
out["system"] = "\n\n".join(system_parts)
|
|
424
436
|
|
|
425
437
|
max_tokens = body.get("max_output_tokens")
|
|
426
|
-
if
|
|
427
|
-
max_tokens =
|
|
438
|
+
if max_tokens is None:
|
|
439
|
+
max_tokens = default_max_tokens(ctx.model)
|
|
440
|
+
elif type(max_tokens) is not int or max_tokens <= 0:
|
|
441
|
+
raise TranslationError("max_output_tokens must be a positive integer")
|
|
428
442
|
out["max_tokens"] = max_tokens
|
|
429
443
|
|
|
444
|
+
reasoning = body.get("reasoning")
|
|
445
|
+
if ctx.model.casefold() in _MINIMAX_EFFORT_MODELS and isinstance(reasoning, dict):
|
|
446
|
+
effort = reasoning.get("effort")
|
|
447
|
+
if effort is not None:
|
|
448
|
+
if effort == "minimal":
|
|
449
|
+
effort = "low"
|
|
450
|
+
if effort not in ("low", "medium", "high", "xhigh", "max"):
|
|
451
|
+
raise TranslationError(f"Unsupported reasoning.effort for {ctx.model}")
|
|
452
|
+
out["output_config"] = {"effort": effort}
|
|
453
|
+
|
|
430
454
|
tools = _anthropic_tools(body.get("tools"), ctx)
|
|
431
455
|
choice = body.get("tool_choice")
|
|
432
456
|
if isinstance(choice, str) and choice == "none":
|
|
@@ -245,13 +245,6 @@ def _pct_from_counts(part, total) -> float | None:
|
|
|
245
245
|
return max(0.0, min(100.0, part_f / total_f * 100.0))
|
|
246
246
|
|
|
247
247
|
|
|
248
|
-
def _remaining_from_used_counts(used, total) -> float | None:
|
|
249
|
-
try:
|
|
250
|
-
return float(total) - float(used)
|
|
251
|
-
except (TypeError, ValueError):
|
|
252
|
-
return None
|
|
253
|
-
|
|
254
|
-
|
|
255
248
|
def _epoch_ms(value) -> float | None:
|
|
256
249
|
"""Epoch milliseconds → epoch seconds; None when missing/invalid/zero."""
|
|
257
250
|
if not value:
|
|
@@ -296,6 +289,22 @@ async def _get_json(
|
|
|
296
289
|
# ── platform adapters ───────────────────────────────────────────────
|
|
297
290
|
|
|
298
291
|
|
|
292
|
+
def _minimax_window(row: dict, prefix: str, reset: str, hours: float | None = None) -> WindowQuota:
|
|
293
|
+
quota = WindowQuota(window_hours=hours, reset_epoch=_epoch_ms(row.get(reset)))
|
|
294
|
+
quota.remaining_percent = _clamp_pct(row.get(f"{prefix}_remaining_percent"))
|
|
295
|
+
# Despite its name, usage_count is the remaining count in the upstream JSON.
|
|
296
|
+
try:
|
|
297
|
+
total = float(row[f"{prefix}_total_count"])
|
|
298
|
+
remaining = float(row[f"{prefix}_usage_count"])
|
|
299
|
+
except (KeyError, TypeError, ValueError):
|
|
300
|
+
return quota
|
|
301
|
+
if total > 0 and 0 <= remaining <= total:
|
|
302
|
+
quota.used_text = f"{total - remaining:g}/{total:g}"
|
|
303
|
+
if quota.remaining_percent is None:
|
|
304
|
+
quota.remaining_percent = _pct_from_counts(remaining, total)
|
|
305
|
+
return quota
|
|
306
|
+
|
|
307
|
+
|
|
299
308
|
async def _usage_minimax(
|
|
300
309
|
client: httpx.AsyncClient, provider: ProviderConfig, entry: ApiKey, timeout: float
|
|
301
310
|
) -> tuple[list[str], QuotaInfo | None, str | None]:
|
|
@@ -308,45 +317,23 @@ async def _usage_minimax(
|
|
|
308
317
|
base_resp = data.get("base_resp", {})
|
|
309
318
|
if base_resp.get("status_code", 0) != 0:
|
|
310
319
|
return [], None, f"platform error {base_resp.get('status_code')}: {base_resp.get('status_msg', '')}"
|
|
311
|
-
|
|
320
|
+
# General is the current text pool. Older count-based plans call it MiniMax-M*.
|
|
321
|
+
rows = {row.get("model_name"): row for row in data.get("model_remains", [])
|
|
322
|
+
if isinstance(row, dict) and isinstance(row.get("model_name"), str)}
|
|
323
|
+
row = rows.get("general") or rows.get("MiniMax-M*")
|
|
312
324
|
quota = QuotaInfo()
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
pct = entry.get("current_interval_remaining_percent")
|
|
326
|
-
five = WindowQuota(window_hours=5.0, reset_epoch=_epoch_ms(entry.get("end_time")))
|
|
327
|
-
if total:
|
|
328
|
-
parts.append(f"5h window used {used}/{total} (reset {_fmt_epoch_ms(entry.get('end_time'))})")
|
|
329
|
-
five.used_text = f"{used}/{total}"
|
|
330
|
-
five.remaining_percent = _pct_from_counts(_remaining_from_used_counts(used, total), total)
|
|
331
|
-
elif pct is not None:
|
|
332
|
-
parts.append(f"5h window remaining {pct}% (reset {_fmt_epoch_ms(entry.get('end_time'))})")
|
|
333
|
-
five.remaining_percent = _clamp_pct(pct)
|
|
334
|
-
w_total = entry.get("current_weekly_total_count")
|
|
335
|
-
w_used = entry.get("current_weekly_usage_count")
|
|
336
|
-
w_pct = entry.get("current_weekly_remaining_percent")
|
|
337
|
-
weekly = WindowQuota(reset_epoch=_epoch_ms(entry.get("weekly_end_time")))
|
|
338
|
-
if w_total:
|
|
339
|
-
parts.append(f"weekly used {w_used}/{w_total} (reset {_fmt_epoch_ms(entry.get('weekly_end_time'))})")
|
|
340
|
-
weekly.used_text = f"{w_used}/{w_total}"
|
|
341
|
-
weekly.remaining_percent = _pct_from_counts(_remaining_from_used_counts(w_used, w_total), w_total)
|
|
342
|
-
elif w_pct is not None:
|
|
343
|
-
parts.append(f"weekly remaining {w_pct}% (reset {_fmt_epoch_ms(entry.get('weekly_end_time'))})")
|
|
344
|
-
weekly.remaining_percent = _clamp_pct(w_pct)
|
|
345
|
-
quota.five_hour = five
|
|
346
|
-
quota.weekly = weekly
|
|
347
|
-
if parts:
|
|
348
|
-
lines.append("; ".join(parts))
|
|
349
|
-
return (lines or ["plan active (no text-model quota data)"]), quota, None
|
|
325
|
+
if row is None:
|
|
326
|
+
return ["plan active (no text-model quota data)"], quota, None
|
|
327
|
+
quota.five_hour = _minimax_window(row, "current_interval", "end_time", 5.0)
|
|
328
|
+
quota.weekly = _minimax_window(row, "current_weekly", "weekly_end_time")
|
|
329
|
+
parts = []
|
|
330
|
+
for label, window, reset in (("5h window", quota.five_hour, "end_time"),
|
|
331
|
+
("weekly", quota.weekly, "weekly_end_time")):
|
|
332
|
+
if window.remaining_percent is not None:
|
|
333
|
+
used = f", used {window.used_text}" if window.used_text else ""
|
|
334
|
+
parts.append(f"{label} remaining {window.remaining_percent:g}%{used} "
|
|
335
|
+
f"(reset {_fmt_epoch_ms(row.get(reset))})")
|
|
336
|
+
return ["; ".join(parts) or "plan active (no text-model quota data)"], quota, None
|
|
350
337
|
|
|
351
338
|
|
|
352
339
|
async def _usage_glm_personal(
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import re
|
|
3
|
+
import unittest
|
|
4
|
+
from unittest.mock import patch
|
|
5
|
+
|
|
6
|
+
import httpx
|
|
7
|
+
|
|
8
|
+
from flexgate.config import ApiKey, GatewayConfig, ProviderConfig, RouteConfig
|
|
9
|
+
from flexgate.responses import (StreamTranslator, TranslationContext, TranslationError,
|
|
10
|
+
responses_request_to_anthropic)
|
|
11
|
+
from flexgate.server import create_app
|
|
12
|
+
from flexgate.usage import _usage_minimax
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class DispatchTranslationTests(unittest.IsolatedAsyncioTestCase):
|
|
16
|
+
async def test_routed_model_sets_upstream_budget_and_effort(self):
|
|
17
|
+
provider = ProviderConfig("up", "https://mock.invalid", [ApiKey("test")])
|
|
18
|
+
cfg = GatewayConfig(providers={"up": provider}, routes=[
|
|
19
|
+
RouteConfig(re.compile("^worker$"), "up", "MiniMax-M4"),
|
|
20
|
+
])
|
|
21
|
+
sent = []
|
|
22
|
+
|
|
23
|
+
def upstream(request):
|
|
24
|
+
sent.append(json.loads(request.content))
|
|
25
|
+
return httpx.Response(200, json={
|
|
26
|
+
"type": "message", "content": [{"type": "text", "text": "ok"}],
|
|
27
|
+
"stop_reason": "end_turn",
|
|
28
|
+
})
|
|
29
|
+
|
|
30
|
+
async with httpx.AsyncClient(transport=httpx.MockTransport(upstream)) as proxy:
|
|
31
|
+
with patch("flexgate.server.httpx.AsyncClient", return_value=proxy):
|
|
32
|
+
app = create_app(cfg)
|
|
33
|
+
app.state.client, app.state.config = proxy, cfg
|
|
34
|
+
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app),
|
|
35
|
+
base_url="http://local") as client:
|
|
36
|
+
for extra in ({}, {"max_output_tokens": 2048}):
|
|
37
|
+
res = await client.post("/v1/responses", json={
|
|
38
|
+
"model": "worker", "input": "test", "reasoning": {"effort": "low"}, **extra,
|
|
39
|
+
})
|
|
40
|
+
self.assertEqual(res.json()["status"], "completed")
|
|
41
|
+
self.assertEqual([r["model"] for r in sent], ["MiniMax-M4"] * 2)
|
|
42
|
+
self.assertEqual([r["max_tokens"] for r in sent], [65536, 2048])
|
|
43
|
+
self.assertEqual([r["output_config"]["effort"] for r in sent], ["low", "low"])
|
|
44
|
+
|
|
45
|
+
def test_defaults_are_model_specific(self):
|
|
46
|
+
for model, limit in [("MiniMax-M3.1-Flash", 65536), ("glm-5.3", 32768),
|
|
47
|
+
("glm-5.3-flash", 32768), ("other", 8192)]:
|
|
48
|
+
with self.subTest(model=model):
|
|
49
|
+
req, _ = responses_request_to_anthropic({"model": model, "input": "test"})
|
|
50
|
+
self.assertEqual(req["max_tokens"], limit)
|
|
51
|
+
self.assertNotIn("output_config", req)
|
|
52
|
+
for model in ("MiniMax-M3", "other"):
|
|
53
|
+
req, _ = responses_request_to_anthropic({
|
|
54
|
+
"model": model, "input": "test", "reasoning": {"effort": "xhigh"},
|
|
55
|
+
})
|
|
56
|
+
self.assertNotIn("output_config", req)
|
|
57
|
+
|
|
58
|
+
def test_caller_controls(self):
|
|
59
|
+
for effort in ("minimal", "low", "medium", "high", "xhigh", "max"):
|
|
60
|
+
body = {"model": "MiniMax-M3.1-Flash", "input": "test",
|
|
61
|
+
"reasoning": {"effort": effort}, "max_output_tokens": 777}
|
|
62
|
+
req, _ = responses_request_to_anthropic(body)
|
|
63
|
+
self.assertEqual(req["output_config"]["effort"], "low" if effort == "minimal" else effort)
|
|
64
|
+
self.assertEqual(req["max_tokens"], 777)
|
|
65
|
+
for extra in ({"max_output_tokens": 0}, {"max_output_tokens": True},
|
|
66
|
+
{"max_output_tokens": "2048"}, {"reasoning": {"effort": "none"}}):
|
|
67
|
+
with self.subTest(extra=extra), self.assertRaises(TranslationError):
|
|
68
|
+
responses_request_to_anthropic({"model": "MiniMax-M4", "input": "test", **extra})
|
|
69
|
+
|
|
70
|
+
async def test_only_real_token_stop_becomes_incomplete(self):
|
|
71
|
+
for stop, terminal in [("end_turn", "response.completed"),
|
|
72
|
+
("max_tokens", "response.incomplete")]:
|
|
73
|
+
async def chunks():
|
|
74
|
+
for event in [{"type": "message_start", "message": {"id": "msg_1"}},
|
|
75
|
+
{"type": "message_delta", "delta": {"stop_reason": stop}},
|
|
76
|
+
{"type": "message_stop"}]:
|
|
77
|
+
yield ("data: " + json.dumps(event) + "\n\n").encode()
|
|
78
|
+
stream = StreamTranslator(TranslationContext(model="MiniMax-M4"))
|
|
79
|
+
frames = [json.loads(x.decode().split("data: ", 1)[1])
|
|
80
|
+
async for x in stream.translate(chunks())]
|
|
81
|
+
self.assertEqual(frames[-1]["type"], terminal)
|
|
82
|
+
if stop == "max_tokens":
|
|
83
|
+
self.assertEqual(frames[-1]["response"]["incomplete_details"]["reason"],
|
|
84
|
+
"max_output_tokens")
|
|
85
|
+
|
|
86
|
+
async def test_minimax_remaining_counts_and_percentages(self):
|
|
87
|
+
provider = ProviderConfig("up", "https://mock.invalid", [ApiKey("test")])
|
|
88
|
+
for name, total, remaining, pct, expected in [
|
|
89
|
+
("general", 100, 90, None, 90), ("MiniMax-M*", 1500, 1444, None, 1444 / 15),
|
|
90
|
+
("general", 0, 0, 0, 0), ("general", 0, 0, 86, 86),
|
|
91
|
+
("general", 100, 60, 55, 55),
|
|
92
|
+
]:
|
|
93
|
+
with self.subTest(name=name, remaining=remaining, pct=pct):
|
|
94
|
+
row = {"model_name": name, "current_interval_total_count": total,
|
|
95
|
+
"current_interval_usage_count": remaining, "current_interval_remaining_percent": pct,
|
|
96
|
+
"current_weekly_total_count": 100, "current_weekly_usage_count": 25}
|
|
97
|
+
video = {"model_name": "video", "current_interval_remaining_percent": 100}
|
|
98
|
+
async with httpx.AsyncClient(transport=httpx.MockTransport(
|
|
99
|
+
lambda req: httpx.Response(200, json={"model_remains": [row, video] + (
|
|
100
|
+
[{"model_name": "MiniMax-M*", "current_interval_remaining_percent": 99}]
|
|
101
|
+
if name == "general" else [])}),
|
|
102
|
+
)) as client:
|
|
103
|
+
_, quota, err = await _usage_minimax(client, provider, provider.api_keys[0], 3)
|
|
104
|
+
self.assertIsNone(err)
|
|
105
|
+
self.assertAlmostEqual(quota.five_hour.remaining_percent, expected)
|
|
106
|
+
self.assertEqual(quota.weekly.remaining_percent, 25)
|
|
107
|
+
self.assertEqual(quota.weekly.used_text, "75/100")
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|