feat: add /test endpoint for connectivity check, disable auto-run

This commit is contained in:
z3st
2026-07-21 19:53:28 +08:00
parent 3975a3370a
commit 09ac80f1ec

111
main.py
View File

@@ -483,6 +483,8 @@ class AgentHandler(BaseHTTPRequestHandler):
'last_run': state['last_run'], 'last_run': state['last_run'],
'last_result': state['last_result'], 'last_result': state['last_result'],
}) })
elif path == '/test':
self._json(self._run_connectivity_test())
elif path == '/status': elif path == '/status':
self._json({ self._json({
'running': state['running'], 'running': state['running'],
@@ -534,6 +536,85 @@ class AgentHandler(BaseHTTPRequestHandler):
else: else:
self._json({'error': 'not found'}, 404) self._json({'error': 'not found'}, 404)
def _run_connectivity_test(self) -> dict:
"""测试各 API 连通性"""
results = {}
# 1. ModelScope 搜索 API
try:
resp = requests.get(
'https://modelscope.cn/openapi/v1/models',
params={'search': 'qwen', 'page_size': 2, 'sort': 'downloads'},
timeout=10,
headers={'User-Agent': 'Mozilla/5.0'}
)
results['modelscope_search'] = {
'status': resp.status_code,
'ok': resp.status_code == 200,
'body_preview': resp.text[:200] if resp.status_code == 200 else resp.text[:100],
}
except Exception as e:
results['modelscope_search'] = {'ok': False, 'error': str(e)}
# 2. ModelScope config.json API
try:
resp = requests.get(
'https://modelscope.cn/api/v1/models/Qwen/Qwen3-8B/repo?Revision=master&FilePath=config.json',
timeout=10,
)
results['modelscope_config'] = {
'status': resp.status_code,
'ok': resp.status_code == 200,
'body_preview': resp.text[:200] if resp.status_code == 200 else resp.text[:100],
}
except Exception as e:
results['modelscope_config'] = {'ok': False, 'error': str(e)}
# 3. ModelHub 查询 API
try:
token = list(ACCOUNTS.values())[0]
resp = requests.get(
'https://modelhub.org.cn/api/adapt/task/page',
headers={'Xc-Token': token, 'Accept': 'application/json'},
params={'current': 1, 'pageSize': 1, 'onlyMine': 'true'},
timeout=10,
)
data = resp.json()
results['modelhub_query'] = {
'ok': data.get('code') == 0,
'code': data.get('code'),
'total': data.get('data', {}).get('total'),
}
except Exception as e:
results['modelhub_query'] = {'ok': False, 'error': str(e)}
# 4. ModelHub 提交 API (dry test)
try:
token = list(ACCOUNTS.values())[0]
resp = requests.post(
'https://modelhub.org.cn/api/adapt/task/add',
headers={'Xc-Token': token, 'Accept': 'application/json', 'Content-Type': 'application/json'},
json={
'modelAddress': 'https://www.modelscope.cn/models/Qwen/Qwen3-8B',
'taskType': 'text-generation',
'targetGpu': 'Kunlunxin_p-800',
'framework': 'vllm',
'strategyId': STRATEGY_ID,
'configParams': 'framework: vllm\n',
},
timeout=10,
)
data = resp.json()
results['modelhub_submit'] = {
'ok': data.get('code') == 0,
'code': data.get('code'),
'message': data.get('message', '')[:100],
}
except Exception as e:
results['modelhub_submit'] = {'ok': False, 'error': str(e)}
return results
def _json(self, body: dict, status: int = 200): def _json(self, body: dict, status: int = 200):
payload = json.dumps(body, ensure_ascii=False).encode() payload = json.dumps(body, ensure_ascii=False).encode()
self.send_response(status) self.send_response(status)
@@ -572,22 +653,22 @@ def main():
log(f"STRATEGY_ID: {STRATEGY_ID}") log(f"STRATEGY_ID: {STRATEGY_ID}")
log(f"GPU: {', '.join(GPU_CONFIGS.keys())}") log(f"GPU: {', '.join(GPU_CONFIGS.keys())}")
# 启动后自动执行一次提交流程 # 启动后自动执行一次提交流程(暂时禁用,用于测试连通性)
def _auto_run(): # def _auto_run():
time.sleep(3) # 等 HTTP 服务就绪 # time.sleep(3)
log("自动触发提交流程...") # log("自动触发提交流程...")
try: # try:
state['running'] = True # state['running'] = True
state['last_run'] = datetime.now().isoformat() # state['last_run'] = datetime.now().isoformat()
count = run_pipeline(submit_limit=30) # count = run_pipeline(submit_limit=30)
state['last_result'] = {'submitted': count, 'success': True} # state['last_result'] = {'submitted': count, 'success': True}
except Exception as e: # except Exception as e:
log(f"流程异常: {traceback.format_exc()}") # log(f"流程异常: {traceback.format_exc()}")
state['last_result'] = {'error': str(e), 'success': False} # state['last_result'] = {'error': str(e), 'success': False}
finally: # finally:
state['running'] = False # state['running'] = False
threading.Thread(target=_auto_run, daemon=True).start() # threading.Thread(target=_auto_run, daemon=True).start()
while not shutdown_requested: while not shutdown_requested:
server.handle_request() server.handle_request()