client.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import argparse
  2. import requests
  3. import json
  4. BASE_URL = "http://localhost:5666"
  5. def chat_with_server(client_id: str, prompt: str, history: str):
  6. url = f"{BASE_URL}/chat"
  7. print(history)
  8. print(type(history))
  9. history = '[{"role":"user", "content":"你好"}]'
  10. data = {
  11. "client_id": client_id,
  12. "prompt": prompt,
  13. "history": history
  14. }
  15. response = requests.post(url, data=data)
  16. return response.json()
  17. def upload_file_to_server(client_id: str, file_path: str):
  18. url = f"{BASE_URL}/uploadfile/"
  19. files = {"file": open(file_path, "rb")}
  20. data = {"client_id": client_id}
  21. response = requests.post(url, files=files, data=data)
  22. return response.json()
  23. def main():
  24. parser = argparse.ArgumentParser()
  25. parser.add_argument("--mode", choices=["chat", "upload"], required=True, help="选择调用的接口")
  26. parser.add_argument("--client_id", required=True, help="客户端ID")
  27. parser.add_argument("--prompt", help="用户输入的问题,仅用于chat模式")
  28. parser.add_argument("--history", default='[]', help="历史消息JSON字符串,仅用于chat模式")
  29. parser.add_argument("--file", help="上传的文件或文件夹路径,仅用于upload模式")
  30. args = parser.parse_args()
  31. if args.mode == "chat":
  32. if not args.prompt:
  33. print("Error: --prompt 参数在 chat 模式下是必须的!")
  34. return
  35. response = chat_with_server(args.client_id, args.prompt, args.history)
  36. print("Chat Response:", response)
  37. elif args.mode == "upload":
  38. if not args.file:
  39. print("Error: --file 参数在 upload 模式下是必须的!")
  40. return
  41. import os
  42. if os.path.isfile(args.file):
  43. files = [args.file]
  44. elif os.path.isdir(args.file):
  45. files = [os.path.join(args.file, f) for f in os.listdir(args.file)
  46. if os.path.isfile(os.path.join(args.file, f))]
  47. else:
  48. print(f"Error: 路径 {args.file} 不存在或不可访问!")
  49. return
  50. for file_path in files:
  51. try:
  52. print(f"\n正在上传文件: {file_path}")
  53. response = upload_file_to_server(args.client_id, file_path)
  54. print(f"上传结果: {response}")
  55. except Exception as e:
  56. print(f"文件 {file_path} 上传失败: {str(e)}")
  57. if __name__ == "__main__":
  58. main()