api_server.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import logging
  2. from flask import Flask, jsonify, request
  3. from embedchain import App
  4. app = Flask(__name__)
  5. @app.route("/add", methods=["POST"])
  6. def add():
  7. data = request.get_json()
  8. data_type = data.get("data_type")
  9. url_or_text = data.get("url_or_text")
  10. if data_type and url_or_text:
  11. try:
  12. App().add(url_or_text, data_type=data_type)
  13. return jsonify({"data": f"Added {data_type}: {url_or_text}"}), 200
  14. except Exception:
  15. logging.exception(f"Failed to add {data_type=}: {url_or_text=}")
  16. return jsonify({"error": f"Failed to add {data_type}: {url_or_text}"}), 500
  17. return jsonify({"error": "Invalid request. Please provide 'data_type' and 'url_or_text' in JSON format."}), 400
  18. @app.route("/query", methods=["POST"])
  19. def query():
  20. data = request.get_json()
  21. question = data.get("question")
  22. if question:
  23. try:
  24. response = App().query(question)
  25. return jsonify({"data": response}), 200
  26. except Exception:
  27. logging.exception(f"Failed to query {question=}")
  28. return jsonify({"error": "An error occurred. Please try again!"}), 500
  29. return jsonify({"error": "Invalid request. Please provide 'question' in JSON format."}), 400
  30. @app.route("/chat", methods=["POST"])
  31. def chat():
  32. data = request.get_json()
  33. question = data.get("question")
  34. if question:
  35. try:
  36. response = App().chat(question)
  37. return jsonify({"data": response}), 200
  38. except Exception:
  39. logging.exception(f"Failed to chat {question=}")
  40. return jsonify({"error": "An error occurred. Please try again!"}), 500
  41. return jsonify({"error": "Invalid request. Please provide 'question' in JSON format."}), 400
  42. if __name__ == "__main__":
  43. app.run(host="0.0.0.0", port=5000, debug=False)