backend.py 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. import json
  2. from flask import request, Flask
  3. from g4f.image import is_allowed_extension, to_image
  4. from .api import Api
  5. class Backend_Api(Api):
  6. """
  7. Handles various endpoints in a Flask application for backend operations.
  8. This class provides methods to interact with models, providers, and to handle
  9. various functionalities like conversations, error handling, and version management.
  10. Attributes:
  11. app (Flask): A Flask application instance.
  12. routes (dict): A dictionary mapping API endpoints to their respective handlers.
  13. """
  14. def __init__(self, app: Flask) -> None:
  15. """
  16. Initialize the backend API with the given Flask application.
  17. Args:
  18. app (Flask): Flask application instance to attach routes to.
  19. """
  20. self.app: Flask = app
  21. self.routes = {
  22. '/backend-api/v2/models': {
  23. 'function': self.get_models,
  24. 'methods': ['GET']
  25. },
  26. '/backend-api/v2/models/<provider>': {
  27. 'function': self.get_provider_models,
  28. 'methods': ['GET']
  29. },
  30. '/backend-api/v2/image_models': {
  31. 'function': self.get_image_models,
  32. 'methods': ['GET']
  33. },
  34. '/backend-api/v2/providers': {
  35. 'function': self.get_providers,
  36. 'methods': ['GET']
  37. },
  38. '/backend-api/v2/version': {
  39. 'function': self.get_version,
  40. 'methods': ['GET']
  41. },
  42. '/backend-api/v2/conversation': {
  43. 'function': self.handle_conversation,
  44. 'methods': ['POST']
  45. },
  46. '/backend-api/v2/error': {
  47. 'function': self.handle_error,
  48. 'methods': ['POST']
  49. },
  50. '/images/<path:name>': {
  51. 'function': self.serve_images,
  52. 'methods': ['GET']
  53. }
  54. }
  55. def handle_error(self):
  56. """
  57. Initialize the backend API with the given Flask application.
  58. Args:
  59. app (Flask): Flask application instance to attach routes to.
  60. """
  61. print(request.json)
  62. return 'ok', 200
  63. def handle_conversation(self):
  64. """
  65. Handles conversation requests and streams responses back.
  66. Returns:
  67. Response: A Flask response object for streaming.
  68. """
  69. kwargs = {}
  70. if "file" in request.files:
  71. file = request.files['file']
  72. if file.filename != '' and is_allowed_extension(file.filename):
  73. kwargs['image'] = to_image(file.stream, file.filename.endswith('.svg'))
  74. kwargs['image_name'] = file.filename
  75. if "json" in request.form:
  76. json_data = json.loads(request.form['json'])
  77. else:
  78. json_data = request.json
  79. kwargs = self._prepare_conversation_kwargs(json_data, kwargs)
  80. return self.app.response_class(
  81. self._create_response_stream(kwargs, json_data.get("conversation_id"), json_data.get("provider")),
  82. mimetype='text/event-stream'
  83. )
  84. def get_provider_models(self, provider: str):
  85. models = super().get_provider_models(provider)
  86. if models is None:
  87. return 404, "Provider not found"
  88. return models
  89. def _format_json(self, response_type: str, content) -> str:
  90. """
  91. Formats and returns a JSON response.
  92. Args:
  93. response_type (str): The type of the response.
  94. content: The content to be included in the response.
  95. Returns:
  96. str: A JSON formatted string.
  97. """
  98. return json.dumps(super()._format_json(response_type, content)) + "\n"