run_lianqi_server_flask.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. import sys
  2. import importlib
  3. from pydantic import BaseModel
  4. from flask import Flask, Response, request
  5. from flask_cors import CORS
  6. import json
  7. sys.path.append("../")
  8. from qwen_agent.planning.plan_executor import PlanExecutor
  9. from qwen_agent.planning.plan_continue_executor import PlanContinueExecutor
  10. prompt_lan = "CN"
  11. llm_name = "qwen-plus"
  12. max_ref_token = 4000
  13. model_server = "http://10.10.0.10:7907/v1"
  14. api_key = ""
  15. server_host = "127.0.0.1"
  16. app = Flask(__name__)
  17. CORS(app)
  18. rspHeaders = {
  19. "Cache-Control": "no-cache",
  20. "Connection": "keep-alive",
  21. "Transfer-Encoding": "chunked",
  22. }
  23. if model_server.startswith("http"):
  24. source = "local"
  25. elif model_server.startswith("dashscope"):
  26. source = "dashscope"
  27. if llm_name.startswith("gpt"):
  28. module = "qwen_agent.llm.gpt"
  29. llm = importlib.import_module(module).GPT(llm_name)
  30. elif llm_name.startswith("Qwen") or llm_name.startswith("qwen"):
  31. module = "qwen_agent.llm.qwen"
  32. llm = importlib.import_module(module).Qwen(
  33. llm_name, model_server=model_server, api_key=api_key
  34. )
  35. else:
  36. raise NotImplementedError
  37. planContinueExecutor = PlanContinueExecutor(enable_critic=False, llm=llm, stream=True)
  38. planExecutor = PlanExecutor(enable_critic=False, llm=llm, stream=True)
  39. @app.route("/subscribe/<question>", methods=["GET", "POST"])
  40. def subscribe(question: str):
  41. return Response(
  42. call_with_stream(question),
  43. mimetype="text/event-stream",
  44. headers=rspHeaders,
  45. )
  46. class ClarificationRequest(BaseModel):
  47. data: str
  48. @app.route("/clarification/", methods=["GET", "POST"])
  49. def clarification():
  50. print("clarification request: ", request)
  51. data = request.get_json("data")
  52. print("clarification: ", data)
  53. return Response(
  54. call_with_stream(json.dumps(data), True),
  55. mimetype="text/event-stream",
  56. headers=rspHeaders,
  57. )
  58. def call_with_stream(question, isClarification=False):
  59. if isClarification:
  60. executor = planContinueExecutor
  61. else:
  62. executor = planExecutor
  63. try:
  64. for rsp in executor.run(question, []):
  65. yield f"data:{rsp}"
  66. yield "data: [DONE]"
  67. except Exception as error:
  68. print("error: ", error)
  69. yield "data: [DONE]"
  70. if __name__ == "__main__":
  71. # app.run(host="0.0.0.0", port=20020, debug=False, processes=10, threaded=False)
  72. app.run(host="0.0.0.0", port=20020, debug=False)