test_fix.py 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. #!/usr/bin/env python3
  2. """测试修复后的chat接口"""
  3. import asyncio
  4. import json
  5. import httpx
  6. import os
  7. from datetime import datetime
  8. async def test_chat_api():
  9. """测试聊天API"""
  10. # 检查环境变量
  11. if not os.getenv("MES_AI_OPENAI_API_KEY"):
  12. print("❌ 请设置 MES_AI_OPENAI_API_KEY 环境变量")
  13. return
  14. base_url = "http://localhost:8000"
  15. # 测试健康检查
  16. print("🔍 测试健康检查...")
  17. try:
  18. async with httpx.AsyncClient() as client:
  19. response = await client.get(f"{base_url}/api/v1/health")
  20. if response.status_code == 200:
  21. print("✅ 健康检查通过")
  22. print(f" 响应: {response.json()}")
  23. else:
  24. print(f"❌ 健康检查失败: {response.status_code}")
  25. return
  26. except Exception as e:
  27. print(f"❌ 无法连接到服务器: {e}")
  28. print(" 请确保服务已启动: python main.py")
  29. return
  30. # 测试聊天接口
  31. test_messages = [
  32. "你好",
  33. "我想进行物料入库",
  34. "如何使用MES系统",
  35. "今天的生产情况如何",
  36. "谢谢"
  37. ]
  38. session_id = f"test_{datetime.now().strftime('%Y%m%d_%H%M%S')}"
  39. print(f"\n🤖 开始测试聊天功能 (会话ID: {session_id})...")
  40. for i, message in enumerate(test_messages, 1):
  41. print(f"\n--- 测试 {i}/{len(test_messages)} ---")
  42. print(f"👤 用户: {message}")
  43. try:
  44. async with httpx.AsyncClient(timeout=30.0) as client:
  45. response = await client.post(
  46. f"{base_url}/api/v1/chat",
  47. json={
  48. "message": message,
  49. "session_id": session_id,
  50. "context": {}
  51. }
  52. )
  53. if response.status_code == 200:
  54. data = response.json()
  55. print(f"🤖 AI: {data['message']}")
  56. print(f"📊 问题类型: {data['question_type']}")
  57. print(f"🔍 需要RAG: {data['need_rag']}")
  58. print(f"🛠️ 需要工具调用: {data['need_tool_call']}")
  59. if data.get('metadata'):
  60. metadata = data['metadata']
  61. if 'classification_confidence' in metadata:
  62. print(f"📈 分类置信度: {metadata['classification_confidence']:.2f}")
  63. else:
  64. print(f"❌ 请求失败: {response.status_code}")
  65. print(f" 错误信息: {response.text}")
  66. except Exception as e:
  67. print(f"❌ 请求异常: {e}")
  68. # 稍作延迟
  69. await asyncio.sleep(1)
  70. # 测试会话历史
  71. print(f"\n📚 测试会话历史...")
  72. try:
  73. async with httpx.AsyncClient() as client:
  74. response = await client.get(f"{base_url}/api/v1/chat/history/{session_id}")
  75. if response.status_code == 200:
  76. history = response.json()
  77. print(f"✅ 会话历史获取成功")
  78. print(f" 消息数量: {history['message_count']}")
  79. print(f" 会话ID: {history['session_id']}")
  80. else:
  81. print(f"❌ 获取会话历史失败: {response.status_code}")
  82. except Exception as e:
  83. print(f"❌ 获取会话历史异常: {e}")
  84. print("\n🎉 测试完成!")
  85. def main():
  86. """主函数"""
  87. print("🧪 MES AI 聊天接口测试工具")
  88. print("=" * 50)
  89. # 运行异步测试
  90. asyncio.run(test_chat_api())
  91. if __name__ == "__main__":
  92. main()