test_jimeng.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
  1. """测试 ji_meng 任务工具 — 通过 Router API 调用(范本同 test_liblibai_tool.py)
  2. 用法:
  3. 1. 先启动 Router:uv run python -m tool_agent
  4. 2. 运行测试:python tests/test_jimeng.py
  5. 需已注册 ji_meng_add_task、ji_meng_query_task(或改下方常量);搜索关键词默认可匹配二者。
  6. """
  7. import sys
  8. import time
  9. if sys.platform == 'win32':
  10. sys.stdout.reconfigure(encoding='utf-8')
  11. import httpx
  12. ROUTER_URL = "http://127.0.0.1:8001"
  13. POLL_INTERVAL_S = 2
  14. POLL_MAX_WAIT_S = 300
  15. def _extract_task_id(data: dict):
  16. for key in ("task_id", "taskId", "id", "job_id", "jobId"):
  17. v = data.get(key)
  18. if v is not None and str(v).strip():
  19. return str(v).strip()
  20. inner = data.get("data")
  21. if isinstance(inner, dict):
  22. return _extract_task_id(inner)
  23. return None
  24. def _terminal_success(data: dict) -> bool:
  25. status = (
  26. data.get("status")
  27. or data.get("task_status")
  28. or data.get("taskStatus")
  29. or data.get("state")
  30. )
  31. if status is None and isinstance(data.get("data"), dict):
  32. status = data["data"].get("status") or data["data"].get("task_status")
  33. if status is None:
  34. return False
  35. s = str(status).lower()
  36. return s in ("completed", "success", "done", "finished", "succeed", "complete")
  37. def _terminal_failure(data: dict) -> bool:
  38. status = data.get("status") or data.get("task_status") or data.get("state")
  39. if status is None and isinstance(data.get("data"), dict):
  40. status = data["data"].get("status")
  41. if status is None:
  42. return False
  43. s = str(status).lower()
  44. return s in ("failed", "error", "cancelled", "canceled")
  45. def main():
  46. print("=" * 50)
  47. print("测试 ji_meng 任务工具")
  48. print("=" * 50)
  49. # 1. 检查 Router 是否在线
  50. try:
  51. resp = httpx.get(f"{ROUTER_URL}/health", timeout=3)
  52. print(f"Router 状态: {resp.json()}")
  53. except httpx.ConnectError:
  54. print(f"无法连接 Router ({ROUTER_URL})")
  55. print("请先启动: uv run python -m tool_agent")
  56. sys.exit(1)
  57. # 2. 搜索工具,确认已注册
  58. print("\n--- 搜索工具 ---")
  59. resp = httpx.post(f"{ROUTER_URL}/search_tools", json={"keyword": "ji_meng"})
  60. tools = resp.json()
  61. print(f"找到 {tools['total']} 个工具")
  62. for t in tools["tools"]:
  63. print(f" {t['tool_id']}: {t['name']} (state={t['state']})")
  64. # 3. 创建 ji_meng_add_task 工具
  65. print("\n--- 调用 ji_meng_add_task 工具创建任务 ---")
  66. print(f"提示词: simple white line art, cat, black background")
  67. print("提交中...")
  68. resp = httpx.post(
  69. f"{ROUTER_URL}/select_tool",
  70. json={
  71. "tool_id": "ji_meng_add_task",
  72. "params": {
  73. "task_type": "image",
  74. "prompt": "simple white line art, cat, black background",
  75. },
  76. },
  77. timeout=120,
  78. )
  79. result = resp.json()
  80. print(f"\n响应状态: {result.get('status')}")
  81. if result.get("code") != 0:
  82. print(f"错误: {result.get('msg')}")
  83. sys.exit(1)
  84. task_id = result.get("data", {}).get("task_id")
  85. if not task_id:
  86. print("错误: 无法从创建任务响应中解析 task_id")
  87. sys.exit(1)
  88. print(f"任务 ID: {task_id}")
  89. # 4. 轮询查询任务
  90. print("\n--- 调用 ji_meng_query_task 工具查询任务 ---")
  91. deadline = time.monotonic() + POLL_MAX_WAIT_S
  92. last = {}
  93. while time.monotonic() < deadline:
  94. resp = httpx.post(
  95. f"{ROUTER_URL}/select_tool",
  96. json={
  97. "tool_id": "ji_meng_query_task",
  98. "params": {"task_id": task_id},
  99. },
  100. timeout=60,
  101. )
  102. result = resp.json()
  103. print(f"\n响应状态: {result.get('status')}")
  104. if result.get("status") != "success":
  105. print(f"错误: {result.get('error')}")
  106. sys.exit(1)
  107. last = result.get("result", {})
  108. if not isinstance(last, dict):
  109. print(f"非 dict 结果: {last}")
  110. time.sleep(POLL_INTERVAL_S)
  111. continue
  112. if last.get("status") == "error":
  113. print(f"错误: {last.get('error')}")
  114. sys.exit(1)
  115. print(f"任务状态: {last.get('status')}")
  116. print(f"最终结果: {last}")
  117. print("\n测试通过!")
  118. return
  119. time.sleep(POLL_INTERVAL_S)
  120. print(f"\n等待超时 ({POLL_MAX_WAIT_S}s),最后一次响应: {last}")
  121. sys.exit(1)
  122. if __name__ == "__main__":
  123. main()