test_rerank_api_curl.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. """
  4. 使用curl测试重排序API
  5. """
  6. import subprocess
  7. import json
  8. import sys
  9. import os
  10. def test_rerank_api_with_curl():
  11. """
  12. 使用curl命令测试重排序API
  13. """
  14. print("=== 使用curl测试重排序API ===")
  15. # 构建curl命令
  16. curl_command = [
  17. "curl",
  18. "--location",
  19. "http://192.168.91.253:9005/v1/rerank",
  20. "--header", "Content-Type: application/json",
  21. "--data", json.dumps({
  22. "model": "bge-reranker-v2-m3",
  23. "query": "乔布斯是谁?",
  24. "candidates": [
  25. "大模型是一类具有大量参数的人工智能模型。",
  26. "苹果是一家科技公司",
  27. "大模型用于深度学习任务"
  28. ]
  29. })
  30. ]
  31. try:
  32. print("执行命令:")
  33. print(" ".join(curl_command))
  34. print()
  35. # 执行curl命令
  36. result = subprocess.run(
  37. curl_command,
  38. capture_output=True,
  39. text=True,
  40. timeout=30
  41. )
  42. print(f"返回状态码: {result.returncode}")
  43. print("=" * 50)
  44. print("标准输出:")
  45. print(result.stdout)
  46. if result.stderr:
  47. print("=" * 50)
  48. print("标准错误:")
  49. print(result.stderr)
  50. # 尝试解析JSON响应
  51. if result.stdout:
  52. try:
  53. response_data = json.loads(result.stdout)
  54. print("=" * 50)
  55. print("解析后的JSON响应:")
  56. print(json.dumps(response_data, ensure_ascii=False, indent=2))
  57. # 检查响应格式
  58. if "results" in response_data:
  59. print("\n✓ API响应格式正确,包含results字段")
  60. results = response_data["results"]
  61. print(f"✓ 返回了 {len(results)} 个重排序结果")
  62. for i, item in enumerate(results, 1):
  63. text = item.get("text", "")
  64. score = item.get("score", "")
  65. print(f" {i}. 分数: {score} | 内容: {text}")
  66. else:
  67. print("\n✗ API响应格式异常,缺少results字段")
  68. except json.JSONDecodeError as e:
  69. print(f"\n✗ JSON解析失败: {str(e)}")
  70. else:
  71. print("\n✗ 没有收到任何响应")
  72. return result.returncode == 0
  73. except subprocess.TimeoutExpired:
  74. print("✗ 请求超时")
  75. return False
  76. except Exception as e:
  77. print(f"✗ 执行curl命令时发生异常: {str(e)}")
  78. return False
  79. def test_different_queries():
  80. """
  81. 测试不同的查询请求
  82. """
  83. print("\n=== 测试不同的查询请求 ===")
  84. test_cases = [
  85. {
  86. "query": "什么是人工智能?",
  87. "candidates": [
  88. "人工智能是计算机科学的一个分支。",
  89. "机器学习是人工智能的核心技术。",
  90. "深度学习使用神经网络进行学习。"
  91. ]
  92. },
  93. {
  94. "query": "大模型有什么特点?",
  95. "candidates": [
  96. "大模型具有数百万到数十亿的参数。",
  97. "苹果公司生产iPhone手机。",
  98. "Transformer是大模型的基础架构。"
  99. ]
  100. },
  101. {
  102. "query": "机器学习和深度学习的区别",
  103. "candidates": [
  104. "深度学习是机器学习的一个子集。",
  105. "机器学习需要人工特征工程。",
  106. "深度学习可以自动学习特征。"
  107. ]
  108. }
  109. ]
  110. for i, test_case in enumerate(test_cases, 1):
  111. print(f"\n--- 测试用例 {i}: {test_case['query']} ---")
  112. curl_command = [
  113. "curl",
  114. "--location",
  115. "http://192.168.91.253:9005/v1/rerank",
  116. "--header", "Content-Type: application/json",
  117. "--data", json.dumps({
  118. "model": "bge-reranker-v2-m3",
  119. "query": test_case["query"],
  120. "candidates": test_case["candidates"]
  121. })
  122. ]
  123. try:
  124. result = subprocess.run(
  125. curl_command,
  126. capture_output=True,
  127. text=True,
  128. timeout=30
  129. )
  130. if result.returncode == 0 and result.stdout:
  131. try:
  132. response_data = json.loads(result.stdout)
  133. if "results" in response_data:
  134. results = response_data["results"]
  135. print(f"✓ 成功返回 {len(results)} 个结果")
  136. # 显示前3个结果
  137. for j, item in enumerate(results[:3], 1):
  138. text = item.get("text", "")
  139. score = item.get("score", "")
  140. print(f" {j}. [{score}] {text[:50]}...")
  141. else:
  142. print("✗ 响应格式异常")
  143. except json.JSONDecodeError:
  144. print("✗ JSON解析失败")
  145. else:
  146. print(f"✗ 请求失败: 状态码 {result.returncode}")
  147. except Exception as e:
  148. print(f"✗ 测试失败: {str(e)}")
  149. def main():
  150. """
  151. 主函数
  152. """
  153. print("开始使用curl测试重排序API")
  154. print("=" * 60)
  155. # 基本测试
  156. success = test_rerank_api_with_curl()
  157. if success:
  158. print("\n🎉 基本API测试成功!")
  159. # 测试不同查询
  160. test_different_queries()
  161. print("\n" + "=" * 60)
  162. print("所有测试完成!")
  163. else:
  164. print("\n❌ 基本API测试失败!")
  165. print("请检查:")
  166. print("1. 重排序服务是否在 192.168.91.253:9005 运行")
  167. print("2. 服务是否支持 /v1/rerank 端点")
  168. print("3. 网络连接是否正常")
  169. return 1
  170. return 0
  171. if __name__ == "__main__":
  172. sys.exit(main())