app.py 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. import os
  2. import time
  3. import json
  4. import random
  5. from g4f import Model, ChatCompletion, Provider
  6. from flask import Flask, request, Response
  7. from flask_cors import CORS
  8. app = Flask(__name__)
  9. CORS(app)
  10. @app.route("/chat/completions", methods=['POST'])
  11. def chat_completions():
  12. streaming = request.json.get('stream', False)
  13. model = request.json.get('model', 'gpt-3.5-turbo')
  14. messages = request.json.get('messages')
  15. models = {
  16. 'gpt-3.5-turbo': 'gpt-3.5-turbo-0301'
  17. }
  18. response = ChatCompletion.create(model=Model.gpt_35_turbo, stream=streaming,
  19. messages=messages)
  20. if not streaming:
  21. while 'curl_cffi.requests.errors.RequestsError' in response:
  22. response = ChatCompletion.create(model=Model.gpt_35_turbo, stream=streaming,
  23. messages=messages)
  24. completion_timestamp = int(time.time())
  25. completion_id = ''.join(random.choices(
  26. 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789', k=28))
  27. return {
  28. 'id': 'chatcmpl-%s' % completion_id,
  29. 'object': 'chat.completion',
  30. 'created': completion_timestamp,
  31. 'model': models[model],
  32. 'usage': {
  33. 'prompt_tokens': None,
  34. 'completion_tokens': None,
  35. 'total_tokens': None
  36. },
  37. 'choices': [{
  38. 'message': {
  39. 'role': 'assistant',
  40. 'content': response
  41. },
  42. 'finish_reason': 'stop',
  43. 'index': 0
  44. }]
  45. }
  46. def stream():
  47. for token in response:
  48. completion_timestamp = int(time.time())
  49. completion_id = ''.join(random.choices(
  50. 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789', k=28))
  51. completion_data = {
  52. 'id': f'chatcmpl-{completion_id}',
  53. 'object': 'chat.completion.chunk',
  54. 'created': completion_timestamp,
  55. 'model': 'gpt-3.5-turbo-0301',
  56. 'choices': [
  57. {
  58. 'delta': {
  59. 'content': token
  60. },
  61. 'index': 0,
  62. 'finish_reason': None
  63. }
  64. ]
  65. }
  66. yield 'data: %s\n\n' % json.dumps(completion_data, separators=(',' ':'))
  67. time.sleep(0.1)
  68. return app.response_class(stream(), mimetype='text/event-stream')
  69. if __name__ == '__main__':
  70. config = {
  71. 'host': '0.0.0.0',
  72. 'port': 1337,
  73. 'debug': True
  74. }
  75. app.run(**config)