radeon-cloud-mcp 0.1.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.
- radeon_cloud_mcp/__init__.py +3 -0
- radeon_cloud_mcp/__main__.py +4 -0
- radeon_cloud_mcp/client.py +316 -0
- radeon_cloud_mcp/config.py +93 -0
- radeon_cloud_mcp/errors.py +109 -0
- radeon_cloud_mcp/files.py +92 -0
- radeon_cloud_mcp/model_matrix.py +174 -0
- radeon_cloud_mcp/server.py +110 -0
- radeon_cloud_mcp/ssh.py +233 -0
- radeon_cloud_mcp/tools_instance.py +328 -0
- radeon_cloud_mcp/tools_tf.py +358 -0
- radeon_cloud_mcp-0.1.0.dist-info/METADATA +99 -0
- radeon_cloud_mcp-0.1.0.dist-info/RECORD +16 -0
- radeon_cloud_mcp-0.1.0.dist-info/WHEEL +4 -0
- radeon_cloud_mcp-0.1.0.dist-info/entry_points.txt +2 -0
- radeon_cloud_mcp-0.1.0.dist-info/licenses/LICENSE +202 -0
|
@@ -0,0 +1,316 @@
|
|
|
1
|
+
"""Async HTTP client for the Token Factory API.
|
|
2
|
+
|
|
3
|
+
Cross-cutting behaviour (docs: api/rate-limits, api/errors, api/chat-completions):
|
|
4
|
+
- concurrency semaphore (default 8, the typical per-key allowance)
|
|
5
|
+
- client-side RPM pacing; limit learned from X-RateLimit-Limit-User-RPM headers
|
|
6
|
+
- retry only 429/502/503, honouring Retry-After plus jittered exponential backoff
|
|
7
|
+
- error envelopes normalized via errors.unwrap_error
|
|
8
|
+
- quota headers captured from every response
|
|
9
|
+
- chat can run non-streaming or internally stream-and-aggregate (the platform
|
|
10
|
+
cuts non-streaming requests at ~10 min; streams may run ~30 min)
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import asyncio
|
|
16
|
+
import json
|
|
17
|
+
import random
|
|
18
|
+
import time
|
|
19
|
+
from collections import deque
|
|
20
|
+
from typing import Any
|
|
21
|
+
|
|
22
|
+
import httpx
|
|
23
|
+
|
|
24
|
+
from .config import Config
|
|
25
|
+
from .errors import RadeonError, hint_for, setup_error, unwrap_error
|
|
26
|
+
|
|
27
|
+
RETRY_STATUSES = (429, 502, 503)
|
|
28
|
+
QUOTA_HEADERS = {
|
|
29
|
+
"rpm_limit": "X-RateLimit-Limit-User-RPM",
|
|
30
|
+
"rpm_remaining": "X-RateLimit-Remaining-User-RPM",
|
|
31
|
+
"rpm_reset": "X-RateLimit-Reset",
|
|
32
|
+
"daily_limit_pts": "X-RateLimit-Limit-User-Daily-USD",
|
|
33
|
+
"daily_used_pts": "X-RateLimit-Used-User-Daily-USD",
|
|
34
|
+
"daily_remaining_pts": "X-RateLimit-Remaining-User-Daily-USD",
|
|
35
|
+
"daily_reset": "X-RateLimit-Reset-User-Daily-USD",
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _retry_after(resp: httpx.Response) -> float | None:
|
|
40
|
+
raw = resp.headers.get("Retry-After")
|
|
41
|
+
if raw is None:
|
|
42
|
+
return None
|
|
43
|
+
try:
|
|
44
|
+
return max(0.0, float(raw))
|
|
45
|
+
except ValueError:
|
|
46
|
+
return None
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _safe_json(resp: httpx.Response) -> Any:
|
|
50
|
+
try:
|
|
51
|
+
return resp.json()
|
|
52
|
+
except ValueError:
|
|
53
|
+
return resp.text
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _api_error(resp: httpx.Response) -> RadeonError:
|
|
57
|
+
body = _safe_json(resp)
|
|
58
|
+
code, message = unwrap_error(body)
|
|
59
|
+
return RadeonError(
|
|
60
|
+
message or f"HTTP {resp.status_code}",
|
|
61
|
+
status=resp.status_code,
|
|
62
|
+
code=code,
|
|
63
|
+
retry_after=_retry_after(resp),
|
|
64
|
+
hint=hint_for(resp.status_code, code, message or ""),
|
|
65
|
+
body=body,
|
|
66
|
+
)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
class RadeonClient:
|
|
70
|
+
def __init__(self, config: Config, *, transport: httpx.AsyncBaseTransport | None = None) -> None:
|
|
71
|
+
self.config = config
|
|
72
|
+
self._http = httpx.AsyncClient(
|
|
73
|
+
base_url=config.base_url,
|
|
74
|
+
headers={"Content-Type": "application/json"},
|
|
75
|
+
timeout=httpx.Timeout(config.request_timeout, connect=15.0),
|
|
76
|
+
transport=transport,
|
|
77
|
+
follow_redirects=True,
|
|
78
|
+
)
|
|
79
|
+
self._sem = asyncio.Semaphore(config.max_concurrency)
|
|
80
|
+
self._pace_lock = asyncio.Lock()
|
|
81
|
+
self._recent: deque[float] = deque()
|
|
82
|
+
self._rpm_limit = config.rpm_default
|
|
83
|
+
self.last_quota: dict[str, Any] = {}
|
|
84
|
+
self._models_cache: list[dict] | None = None
|
|
85
|
+
self._models_cached_at = 0.0
|
|
86
|
+
|
|
87
|
+
async def aclose(self) -> None:
|
|
88
|
+
await self._http.aclose()
|
|
89
|
+
|
|
90
|
+
# -- auth / pacing ----------------------------------------------------
|
|
91
|
+
|
|
92
|
+
def _auth_headers(self) -> dict[str, str]:
|
|
93
|
+
if not self.config.api_key:
|
|
94
|
+
raise setup_error(
|
|
95
|
+
"Token Factory 工具不可用",
|
|
96
|
+
"RADEON_API_KEY",
|
|
97
|
+
"key 在控制台 Token Factory 页「Your API key」卡片复制(rc- 开头)。",
|
|
98
|
+
)
|
|
99
|
+
return {"Authorization": f"Bearer {self.config.api_key}"}
|
|
100
|
+
|
|
101
|
+
def _note_quota(self, resp: httpx.Response) -> None:
|
|
102
|
+
quota: dict[str, Any] = {}
|
|
103
|
+
for key, header in QUOTA_HEADERS.items():
|
|
104
|
+
value = resp.headers.get(header)
|
|
105
|
+
if value is not None:
|
|
106
|
+
try:
|
|
107
|
+
quota[key] = float(value) if "." in value else int(value)
|
|
108
|
+
except ValueError:
|
|
109
|
+
quota[key] = value
|
|
110
|
+
if quota:
|
|
111
|
+
self.last_quota = quota
|
|
112
|
+
limit = quota.get("rpm_limit")
|
|
113
|
+
if isinstance(limit, int) and limit > 0:
|
|
114
|
+
self._rpm_limit = limit
|
|
115
|
+
|
|
116
|
+
async def _pace(self) -> None:
|
|
117
|
+
async with self._pace_lock:
|
|
118
|
+
now = time.monotonic()
|
|
119
|
+
while self._recent and now - self._recent[0] > 60.0:
|
|
120
|
+
self._recent.popleft()
|
|
121
|
+
if len(self._recent) >= self._rpm_limit:
|
|
122
|
+
wait = 60.0 - (now - self._recent[0]) + 0.05
|
|
123
|
+
await asyncio.sleep(max(0.0, wait))
|
|
124
|
+
now = time.monotonic()
|
|
125
|
+
while self._recent and now - self._recent[0] > 60.0:
|
|
126
|
+
self._recent.popleft()
|
|
127
|
+
self._recent.append(time.monotonic())
|
|
128
|
+
|
|
129
|
+
# -- core request -----------------------------------------------------
|
|
130
|
+
|
|
131
|
+
async def request(
|
|
132
|
+
self,
|
|
133
|
+
method: str,
|
|
134
|
+
path: str,
|
|
135
|
+
*,
|
|
136
|
+
json_body: Any = None,
|
|
137
|
+
params: dict | None = None,
|
|
138
|
+
max_retries: int = 4,
|
|
139
|
+
timeout: float | None = None,
|
|
140
|
+
) -> httpx.Response:
|
|
141
|
+
headers = self._auth_headers()
|
|
142
|
+
attempt = 0
|
|
143
|
+
while True:
|
|
144
|
+
async with self._sem:
|
|
145
|
+
await self._pace()
|
|
146
|
+
try:
|
|
147
|
+
resp = await self._http.request(
|
|
148
|
+
method, path, json=json_body, params=params, headers=headers,
|
|
149
|
+
timeout=httpx.USE_CLIENT_DEFAULT if timeout is None else timeout,
|
|
150
|
+
)
|
|
151
|
+
except httpx.HTTPError as exc:
|
|
152
|
+
raise RadeonError(
|
|
153
|
+
f"网络错误:{exc}", code="network_error",
|
|
154
|
+
hint="检查到 developer.amd.com.cn 的连通性;瞬时故障可重试。",
|
|
155
|
+
) from exc
|
|
156
|
+
self._note_quota(resp)
|
|
157
|
+
if resp.status_code in RETRY_STATUSES and attempt < max_retries:
|
|
158
|
+
ra = _retry_after(resp)
|
|
159
|
+
wait = (ra if ra is not None else 5.0) + random.uniform(0, 1.5) * (2 ** attempt)
|
|
160
|
+
await asyncio.sleep(min(wait, 120.0))
|
|
161
|
+
attempt += 1
|
|
162
|
+
continue
|
|
163
|
+
if resp.status_code >= 400:
|
|
164
|
+
raise _api_error(resp)
|
|
165
|
+
return resp
|
|
166
|
+
|
|
167
|
+
async def get_json(self, path: str, *, params: dict | None = None) -> Any:
|
|
168
|
+
resp = await self.request("GET", path, params=params)
|
|
169
|
+
return resp.json()
|
|
170
|
+
|
|
171
|
+
async def post_json(self, path: str, payload: dict, *, timeout: float | None = None) -> Any:
|
|
172
|
+
resp = await self.request("POST", path, json_body=payload, timeout=timeout)
|
|
173
|
+
return resp.json()
|
|
174
|
+
|
|
175
|
+
# -- catalog / quota ----------------------------------------------------
|
|
176
|
+
|
|
177
|
+
async def get_models(self, *, force: bool = False) -> list[dict]:
|
|
178
|
+
now = time.monotonic()
|
|
179
|
+
if not force and self._models_cache is not None and now - self._models_cached_at < 300.0:
|
|
180
|
+
return self._models_cache
|
|
181
|
+
data = await self.get_json("/models")
|
|
182
|
+
models = data.get("data") if isinstance(data, dict) else data
|
|
183
|
+
self._models_cache = models or []
|
|
184
|
+
self._models_cached_at = now
|
|
185
|
+
return self._models_cache
|
|
186
|
+
|
|
187
|
+
async def get_utilization(self, model: str | None = None) -> Any:
|
|
188
|
+
path = "/models/utilization" + (f"/{model}" if model else "")
|
|
189
|
+
return await self.get_json(path)
|
|
190
|
+
|
|
191
|
+
async def get_usage(self, include_recent: bool = False) -> Any:
|
|
192
|
+
params = {"include_recent": "true"} if include_recent else None
|
|
193
|
+
return await self.get_json("/usage", params=params)
|
|
194
|
+
|
|
195
|
+
# -- chat ---------------------------------------------------------------
|
|
196
|
+
|
|
197
|
+
async def chat_nonstream(self, payload: dict) -> dict:
|
|
198
|
+
resp = await self.request("POST", "/chat/completions", json_body=payload)
|
|
199
|
+
result = resp.json()
|
|
200
|
+
result["_quota"] = dict(self.last_quota)
|
|
201
|
+
return result
|
|
202
|
+
|
|
203
|
+
async def chat_stream(self, payload: dict, *, max_retries: int = 4) -> dict:
|
|
204
|
+
"""Stream internally and aggregate into a chat.completion-shaped dict.
|
|
205
|
+
|
|
206
|
+
Avoids the ~10-minute non-streaming cutoff for long generations.
|
|
207
|
+
Note: the gateway rebuilds request bodies, so stream_options may be
|
|
208
|
+
dropped and usage can be absent in stream mode; treat usage as best-effort.
|
|
209
|
+
"""
|
|
210
|
+
headers = self._auth_headers()
|
|
211
|
+
body = {**payload, "stream": True}
|
|
212
|
+
attempt = 0
|
|
213
|
+
while True:
|
|
214
|
+
retry_wait: float | None = None
|
|
215
|
+
async with self._sem:
|
|
216
|
+
await self._pace()
|
|
217
|
+
try:
|
|
218
|
+
async with self._http.stream(
|
|
219
|
+
"POST", "/chat/completions", json=body, headers=headers
|
|
220
|
+
) as resp:
|
|
221
|
+
self._note_quota(resp)
|
|
222
|
+
if resp.status_code in RETRY_STATUSES and attempt < max_retries:
|
|
223
|
+
await resp.aread()
|
|
224
|
+
ra = _retry_after(resp)
|
|
225
|
+
retry_wait = min(
|
|
226
|
+
(ra if ra is not None else 5.0) + random.uniform(0, 1.5) * (2 ** attempt),
|
|
227
|
+
120.0,
|
|
228
|
+
)
|
|
229
|
+
elif resp.status_code >= 400:
|
|
230
|
+
await resp.aread()
|
|
231
|
+
raise _api_error(resp)
|
|
232
|
+
else:
|
|
233
|
+
result = await self._aggregate_sse(resp)
|
|
234
|
+
result["_quota"] = dict(self.last_quota)
|
|
235
|
+
return result
|
|
236
|
+
except httpx.HTTPError as exc:
|
|
237
|
+
raise RadeonError(
|
|
238
|
+
f"流式连接错误:{exc}", code="network_error",
|
|
239
|
+
hint="长生成可重试;持续失败检查网络或改用较小 max_tokens。",
|
|
240
|
+
) from exc
|
|
241
|
+
# backoff outside the semaphore so slots aren't held during sleep
|
|
242
|
+
if retry_wait is None:
|
|
243
|
+
raise RadeonError("流式请求未返回结果", code="stream_incomplete")
|
|
244
|
+
await asyncio.sleep(retry_wait)
|
|
245
|
+
attempt += 1
|
|
246
|
+
|
|
247
|
+
@staticmethod
|
|
248
|
+
async def _aggregate_sse(resp: httpx.Response) -> dict:
|
|
249
|
+
content: list[str] = []
|
|
250
|
+
reasoning: list[str] = []
|
|
251
|
+
tool_calls: dict[int, dict] = {}
|
|
252
|
+
finish_reason = None
|
|
253
|
+
usage = None
|
|
254
|
+
model = None
|
|
255
|
+
completion_id = None
|
|
256
|
+
async for line in resp.aiter_lines():
|
|
257
|
+
line = line.strip()
|
|
258
|
+
if not line.startswith("data:"):
|
|
259
|
+
continue
|
|
260
|
+
data = line[5:].strip()
|
|
261
|
+
if data == "[DONE]":
|
|
262
|
+
break
|
|
263
|
+
try:
|
|
264
|
+
chunk = json.loads(data)
|
|
265
|
+
except ValueError:
|
|
266
|
+
continue
|
|
267
|
+
model = chunk.get("model") or model
|
|
268
|
+
completion_id = chunk.get("id") or completion_id
|
|
269
|
+
if chunk.get("usage"):
|
|
270
|
+
usage = chunk["usage"]
|
|
271
|
+
choices = chunk.get("choices") or []
|
|
272
|
+
if not choices:
|
|
273
|
+
continue
|
|
274
|
+
choice = choices[0]
|
|
275
|
+
delta = choice.get("delta") or {}
|
|
276
|
+
if delta.get("content"):
|
|
277
|
+
content.append(delta["content"])
|
|
278
|
+
think = delta.get("reasoning") or delta.get("reasoning_content")
|
|
279
|
+
if think:
|
|
280
|
+
reasoning.append(think)
|
|
281
|
+
for tc in delta.get("tool_calls") or []:
|
|
282
|
+
idx = tc.get("index", 0)
|
|
283
|
+
slot = tool_calls.setdefault(
|
|
284
|
+
idx, {"id": None, "type": "function", "function": {"name": "", "arguments": ""}}
|
|
285
|
+
)
|
|
286
|
+
if tc.get("id"):
|
|
287
|
+
slot["id"] = tc["id"]
|
|
288
|
+
fn = tc.get("function") or {}
|
|
289
|
+
if fn.get("name"):
|
|
290
|
+
slot["function"]["name"] += fn["name"]
|
|
291
|
+
if fn.get("arguments"):
|
|
292
|
+
slot["function"]["arguments"] += fn["arguments"]
|
|
293
|
+
if choice.get("finish_reason"):
|
|
294
|
+
finish_reason = choice["finish_reason"]
|
|
295
|
+
message: dict[str, Any] = {"role": "assistant", "content": "".join(content)}
|
|
296
|
+
if reasoning:
|
|
297
|
+
message["reasoning"] = "".join(reasoning)
|
|
298
|
+
if tool_calls:
|
|
299
|
+
message["tool_calls"] = [tool_calls[i] for i in sorted(tool_calls)]
|
|
300
|
+
return {
|
|
301
|
+
"id": completion_id,
|
|
302
|
+
"model": model,
|
|
303
|
+
"choices": [{"index": 0, "message": message, "finish_reason": finish_reason}],
|
|
304
|
+
"usage": usage,
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
# -- special endpoints ----------------------------------------------------
|
|
308
|
+
|
|
309
|
+
async def ocr(self, payload: dict) -> dict:
|
|
310
|
+
return await self.post_json("/ocr", payload)
|
|
311
|
+
|
|
312
|
+
async def speech(self, payload: dict) -> httpx.Response:
|
|
313
|
+
return await self.request("POST", "/audio/speech", json_body=payload)
|
|
314
|
+
|
|
315
|
+
async def decide(self, payload: dict) -> dict:
|
|
316
|
+
return await self.post_json("/systemone", payload)
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
"""Configuration: environment variables first, then a 600-permission JSON auth file.
|
|
2
|
+
|
|
3
|
+
Secrets never go into code, logs, or tool results. ModelScope hosted deployments
|
|
4
|
+
inject RADEON_API_KEY / RCC_TOKEN through the service detail page.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import json
|
|
10
|
+
import os
|
|
11
|
+
from dataclasses import dataclass, field
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from typing import Mapping
|
|
14
|
+
|
|
15
|
+
DEFAULT_BASE_URL = "https://developer.amd.com.cn/radeon/api/v1"
|
|
16
|
+
DEFAULT_AUTH_FILE = Path.home() / ".config" / "radeon-cloud-mcp" / "auth.json"
|
|
17
|
+
DEFAULT_OUTPUT_DIRNAME = "radeon-output"
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def mask_secret(value: str | None) -> str | None:
|
|
21
|
+
"""Mask a credential for safe display: keep prefix and last 4 chars only."""
|
|
22
|
+
if not value:
|
|
23
|
+
return None
|
|
24
|
+
if len(value) <= 8:
|
|
25
|
+
return value[:2] + "***"
|
|
26
|
+
return f"{value[:4]}...{value[-4:]}"
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@dataclass
|
|
30
|
+
class Config:
|
|
31
|
+
api_key: str | None = None
|
|
32
|
+
base_url: str = DEFAULT_BASE_URL
|
|
33
|
+
rcc_token: str | None = None
|
|
34
|
+
output_dir: Path = field(default_factory=lambda: Path.cwd() / DEFAULT_OUTPUT_DIRNAME)
|
|
35
|
+
auth_file: Path = DEFAULT_AUTH_FILE
|
|
36
|
+
request_timeout: float = 600.0
|
|
37
|
+
max_concurrency: int = 8
|
|
38
|
+
rpm_default: int = 20
|
|
39
|
+
# SSH access to GPU instances (operation / training tools)
|
|
40
|
+
ssh_identity: str | None = None # path to a local private key (local mode)
|
|
41
|
+
ssh_private_key: str | None = None # raw private key content (hosted mode, via env)
|
|
42
|
+
ssh_known_hosts: str | None = None # known_hosts path; None disables host-key verification
|
|
43
|
+
|
|
44
|
+
@classmethod
|
|
45
|
+
def load(cls, environ: Mapping[str, str] | None = None) -> "Config":
|
|
46
|
+
env = os.environ if environ is None else environ
|
|
47
|
+
auth_path = Path(env.get("RADEON_MCP_AUTH_FILE") or str(DEFAULT_AUTH_FILE)).expanduser()
|
|
48
|
+
file_data: dict = {}
|
|
49
|
+
if auth_path.is_file():
|
|
50
|
+
try:
|
|
51
|
+
loaded = json.loads(auth_path.read_text(encoding="utf-8"))
|
|
52
|
+
if isinstance(loaded, dict):
|
|
53
|
+
file_data = loaded
|
|
54
|
+
except (OSError, ValueError):
|
|
55
|
+
file_data = {}
|
|
56
|
+
|
|
57
|
+
def pick(env_key: str, file_key: str, default: str | None = None) -> str | None:
|
|
58
|
+
return env.get(env_key) or file_data.get(file_key) or default
|
|
59
|
+
|
|
60
|
+
base_url = (pick("RADEON_BASE_URL", "base_url", DEFAULT_BASE_URL) or DEFAULT_BASE_URL).rstrip("/")
|
|
61
|
+
output_dir = Path(
|
|
62
|
+
pick("RADEON_OUTPUT_DIR", "output_dir", str(Path.cwd() / DEFAULT_OUTPUT_DIRNAME))
|
|
63
|
+
).expanduser()
|
|
64
|
+
try:
|
|
65
|
+
timeout = float(env.get("RADEON_REQUEST_TIMEOUT") or file_data.get("request_timeout") or 600.0)
|
|
66
|
+
except (TypeError, ValueError):
|
|
67
|
+
timeout = 600.0
|
|
68
|
+
try:
|
|
69
|
+
concurrency = int(env.get("RADEON_MAX_CONCURRENCY") or file_data.get("max_concurrency") or 8)
|
|
70
|
+
except (TypeError, ValueError):
|
|
71
|
+
concurrency = 8
|
|
72
|
+
|
|
73
|
+
return cls(
|
|
74
|
+
api_key=pick("RADEON_API_KEY", "api_key"),
|
|
75
|
+
base_url=base_url,
|
|
76
|
+
rcc_token=pick("RCC_TOKEN", "rcc_token"),
|
|
77
|
+
output_dir=output_dir,
|
|
78
|
+
auth_file=auth_path,
|
|
79
|
+
request_timeout=timeout,
|
|
80
|
+
max_concurrency=max(1, concurrency),
|
|
81
|
+
ssh_identity=pick("RADEON_SSH_IDENTITY", "ssh_identity"),
|
|
82
|
+
ssh_private_key=pick("SSH_PRIVATE_KEY", "ssh_private_key"),
|
|
83
|
+
ssh_known_hosts=pick("RADEON_SSH_KNOWN_HOSTS", "ssh_known_hosts"),
|
|
84
|
+
)
|
|
85
|
+
|
|
86
|
+
def public_summary(self) -> dict:
|
|
87
|
+
"""Non-secret configuration summary, safe to return from tools."""
|
|
88
|
+
return {
|
|
89
|
+
"base_url": self.base_url,
|
|
90
|
+
"api_key": mask_secret(self.api_key) or "(not configured)",
|
|
91
|
+
"rcc_token": mask_secret(self.rcc_token) or "(not configured; rcc local login may still work)",
|
|
92
|
+
"output_dir": str(self.output_dir),
|
|
93
|
+
}
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
"""Error normalization across Radeon Cloud's three error envelopes.
|
|
2
|
+
|
|
3
|
+
Shapes (see docs api/errors):
|
|
4
|
+
- gateway OpenAI: {"error": {"message", "type", "code", ...}}
|
|
5
|
+
- platform wrapped: {"detail": {"error": {...}}} or {"detail": "text"}
|
|
6
|
+
- Anthropic envelope: {"type": "error", "error": {"type", "message"}}
|
|
7
|
+
- model service/vLLM: verbatim backend body (usually OpenAI-shaped)
|
|
8
|
+
|
|
9
|
+
Read body.error first, then body.detail.error, then body.detail as message.
|
|
10
|
+
HTTP status and Retry-After are reliable in every case.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import json
|
|
16
|
+
from typing import Any
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class RadeonError(Exception):
|
|
20
|
+
"""Structured error that renders as agent-actionable text for MCP isError results."""
|
|
21
|
+
|
|
22
|
+
def __init__(
|
|
23
|
+
self,
|
|
24
|
+
message: str,
|
|
25
|
+
*,
|
|
26
|
+
status: int | None = None,
|
|
27
|
+
code: str | None = None,
|
|
28
|
+
retry_after: float | None = None,
|
|
29
|
+
hint: str | None = None,
|
|
30
|
+
body: Any = None,
|
|
31
|
+
) -> None:
|
|
32
|
+
super().__init__(message)
|
|
33
|
+
self.message = message
|
|
34
|
+
self.status = status
|
|
35
|
+
self.code = code
|
|
36
|
+
self.retry_after = retry_after
|
|
37
|
+
self.hint = hint
|
|
38
|
+
self.body = body
|
|
39
|
+
|
|
40
|
+
def __str__(self) -> str:
|
|
41
|
+
parts = [self.message]
|
|
42
|
+
if self.status is not None:
|
|
43
|
+
parts.append(f"HTTP {self.status}")
|
|
44
|
+
if self.code:
|
|
45
|
+
parts.append(f"code={self.code}")
|
|
46
|
+
if self.retry_after is not None:
|
|
47
|
+
parts.append(f"retry_after={self.retry_after:g}s")
|
|
48
|
+
if self.hint:
|
|
49
|
+
parts.append(f"hint: {self.hint}")
|
|
50
|
+
return " | ".join(parts)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def unwrap_error(body: Any) -> tuple[str | None, str]:
|
|
54
|
+
"""Return (code, message) from any of the known error envelopes."""
|
|
55
|
+
if isinstance(body, dict):
|
|
56
|
+
err = body.get("error")
|
|
57
|
+
if isinstance(err, dict):
|
|
58
|
+
return err.get("code"), str(err.get("message") or json.dumps(err, ensure_ascii=False))
|
|
59
|
+
if isinstance(err, str):
|
|
60
|
+
return None, err
|
|
61
|
+
detail = body.get("detail")
|
|
62
|
+
if isinstance(detail, dict):
|
|
63
|
+
inner = detail.get("error")
|
|
64
|
+
if isinstance(inner, dict):
|
|
65
|
+
return inner.get("code"), str(
|
|
66
|
+
inner.get("message") or json.dumps(inner, ensure_ascii=False)
|
|
67
|
+
)
|
|
68
|
+
return detail.get("code"), str(
|
|
69
|
+
detail.get("message") or json.dumps(detail, ensure_ascii=False)
|
|
70
|
+
)
|
|
71
|
+
if isinstance(detail, str):
|
|
72
|
+
return None, detail
|
|
73
|
+
if body.get("message"):
|
|
74
|
+
return body.get("code"), str(body["message"])
|
|
75
|
+
return body.get("code"), json.dumps(body, ensure_ascii=False)
|
|
76
|
+
if body is None:
|
|
77
|
+
return None, "(empty error body)"
|
|
78
|
+
return None, str(body)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def hint_for(status: int | None, code: str | None, message: str) -> str | None:
|
|
82
|
+
msg = (message or "").lower()
|
|
83
|
+
if status == 401:
|
|
84
|
+
return "检查 RADEON_API_KEY(rc- 开头,48 位 hex);key 可能已轮换或未配置。实例管理需 RCC_TOKEN(rcc_ 开头)。"
|
|
85
|
+
if status == 403 and code == "account_not_verified":
|
|
86
|
+
return "账号仍在审核中,无法调用;审核通过后再试。"
|
|
87
|
+
if status == 400 and "not supported" in msg and "model" in msg:
|
|
88
|
+
return "模型不在当前目录(目录会变动):调用 list_models 重新解析可用模型。"
|
|
89
|
+
if status == 400 and "one active instance" in msg:
|
|
90
|
+
return "每账户同时只能有 1 个实例:先 instance_delete 再创建。"
|
|
91
|
+
if status == 400 and "insufficient credits" in msg:
|
|
92
|
+
return "credits 不足:用开发者积分兑换算力券(见 README 激励计划部分)。"
|
|
93
|
+
if status == 429 and "daily usage limit" in msg:
|
|
94
|
+
return "今日 pts 配额已耗尽,等待 daily_reset_at(北京时间 00:00)重置;可用 usage 工具查询。"
|
|
95
|
+
if status == 429:
|
|
96
|
+
return "限流:遵守 retry_after 后重试;客户端已自动退避,仍失败说明持续超限,降低调用频率。"
|
|
97
|
+
if status in (502, 503):
|
|
98
|
+
return "平台/后端瞬时不可用或容量饱和:稍后重试;持续数分钟则为平台故障。"
|
|
99
|
+
if status == 404:
|
|
100
|
+
return "路径/资源不存在:确认模型名或端点;Token Factory 未提供该路径时返回 404。"
|
|
101
|
+
return None
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def setup_error(what: str, env_var: str, extra: str = "") -> RadeonError:
|
|
105
|
+
hint = (
|
|
106
|
+
f"配置 {env_var} 环境变量(ModelScope 托管:服务详情页填入;本地:export 或写入 "
|
|
107
|
+
f"~/.config/radeon-cloud-mcp/auth.json,权限 600)。{extra}"
|
|
108
|
+
).strip()
|
|
109
|
+
return RadeonError(f"{what}:缺少凭证 {env_var}", code="not_configured", hint=hint)
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
"""File helpers: local path -> data URL, size pre-checks, output saving.
|
|
2
|
+
|
|
3
|
+
Remote (ModelScope hosted) clients should pass URLs or data URLs; local paths
|
|
4
|
+
only resolve in local mode. Outputs (audio/OCR images) are saved to disk and
|
|
5
|
+
returned as paths; `return_base64` opts into inline data URLs for remote use.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import base64
|
|
11
|
+
import json
|
|
12
|
+
import uuid
|
|
13
|
+
from datetime import datetime
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
|
|
16
|
+
from .errors import RadeonError
|
|
17
|
+
|
|
18
|
+
MAX_BODY_BYTES = 5 * 1024 * 1024 # speech / systemone request body limit
|
|
19
|
+
|
|
20
|
+
MIME_BY_SUFFIX = {
|
|
21
|
+
".png": "image/png",
|
|
22
|
+
".jpg": "image/jpeg",
|
|
23
|
+
".jpeg": "image/jpeg",
|
|
24
|
+
".webp": "image/webp",
|
|
25
|
+
".gif": "image/gif",
|
|
26
|
+
".pdf": "application/pdf",
|
|
27
|
+
".mp4": "video/mp4",
|
|
28
|
+
".webm": "video/webm",
|
|
29
|
+
".mov": "video/quicktime",
|
|
30
|
+
".mkv": "video/x-matroska",
|
|
31
|
+
".wav": "audio/wav",
|
|
32
|
+
".flac": "audio/flac",
|
|
33
|
+
".ogg": "audio/ogg",
|
|
34
|
+
".mp3": "audio/mpeg",
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
AUDIO_SUFFIX = {"wav": ".wav", "mp3": ".mp3", "opus": ".ogg", "flac": ".flac", "pcm": ".pcm"}
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def guess_mime(path: Path) -> str:
|
|
41
|
+
return MIME_BY_SUFFIX.get(path.suffix.lower(), "application/octet-stream")
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def to_data_url(src: str, *, max_bytes: int | None = None) -> str:
|
|
45
|
+
"""Pass through http(s)/data URLs; convert an existing local file to a data URL."""
|
|
46
|
+
if src.startswith(("http://", "https://", "data:")):
|
|
47
|
+
return src
|
|
48
|
+
path = Path(src).expanduser()
|
|
49
|
+
if not path.is_file():
|
|
50
|
+
raise RadeonError(
|
|
51
|
+
f"文件不存在:{src}",
|
|
52
|
+
code="file_not_found",
|
|
53
|
+
hint="远程/托管模式请传 URL 或 data: URL;本地路径仅在本地模式有效。",
|
|
54
|
+
)
|
|
55
|
+
data = path.read_bytes()
|
|
56
|
+
if max_bytes is not None and len(data) > max_bytes:
|
|
57
|
+
raise RadeonError(
|
|
58
|
+
f"文件 {path.name} 为 {len(data)} 字节,超过限制 {max_bytes}",
|
|
59
|
+
code="file_too_large",
|
|
60
|
+
)
|
|
61
|
+
return f"data:{guess_mime(path)};base64,{base64.b64encode(data).decode()}"
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def check_json_size(payload: dict, limit: int = MAX_BODY_BYTES) -> None:
|
|
65
|
+
size = len(json.dumps(payload, ensure_ascii=False).encode("utf-8"))
|
|
66
|
+
if size > limit:
|
|
67
|
+
raise RadeonError(
|
|
68
|
+
f"请求体约 {size} 字节,超过平台 {limit} 字节上限",
|
|
69
|
+
code="body_too_large",
|
|
70
|
+
hint="减小输入(更短的文本/更小的图片/更少的媒体),或改用 URL 引用。",
|
|
71
|
+
)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def save_output(data: bytes, suffix: str, output_dir: Path, prefix: str = "radeon") -> Path:
|
|
75
|
+
output_dir.mkdir(parents=True, exist_ok=True)
|
|
76
|
+
stamp = datetime.now().strftime("%Y%m%d-%H%M%S")
|
|
77
|
+
name = f"{prefix}-{stamp}-{uuid.uuid4().hex[:8]}{suffix}"
|
|
78
|
+
path = output_dir / name
|
|
79
|
+
path.write_bytes(data)
|
|
80
|
+
return path
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def build_ocr_document(document: str) -> dict:
|
|
84
|
+
"""MinerU accepts {"type":"document_url",...} (URL or data:) or {"type":"image_url",...}."""
|
|
85
|
+
url = to_data_url(document)
|
|
86
|
+
path_part = document.split("?", 1)[0].split("#", 1)[0].lower()
|
|
87
|
+
is_image = path_part.endswith((".png", ".jpg", ".jpeg", ".webp", ".gif")) or url.startswith(
|
|
88
|
+
("data:image/",)
|
|
89
|
+
)
|
|
90
|
+
if is_image:
|
|
91
|
+
return {"type": "image_url", "image_url": url}
|
|
92
|
+
return {"type": "document_url", "document_url": url}
|