2023-10-06 18:52:17 +00:00
|
|
|
import g4f
|
|
|
|
|
|
|
|
from flask import request
|
|
|
|
from .internet import search
|
|
|
|
from .config import special_instructions
|
2023-10-09 22:46:02 +00:00
|
|
|
from .provider import get_provider
|
|
|
|
|
|
|
|
g4f.logging = True
|
2023-10-06 18:52:17 +00:00
|
|
|
|
|
|
|
class Backend_Api:
|
|
|
|
def __init__(self, app) -> None:
|
|
|
|
self.app = app
|
|
|
|
self.routes = {
|
|
|
|
'/backend-api/v2/conversation': {
|
|
|
|
'function': self._conversation,
|
|
|
|
'methods': ['POST']
|
|
|
|
},
|
|
|
|
'/backend-api/v2/gen.set.summarize:title': {
|
|
|
|
'function': self._gen_title,
|
|
|
|
'methods': ['POST']
|
|
|
|
},
|
|
|
|
}
|
|
|
|
|
|
|
|
def _gen_title(self):
|
|
|
|
return {
|
|
|
|
'title': ''
|
|
|
|
}
|
|
|
|
|
|
|
|
def _conversation(self):
|
|
|
|
try:
|
|
|
|
jailbreak = request.json['jailbreak']
|
|
|
|
internet_access = request.json['meta']['content']['internet_access']
|
|
|
|
conversation = request.json['meta']['content']['conversation']
|
|
|
|
prompt = request.json['meta']['content']['parts'][0]
|
|
|
|
model = request.json['model']
|
2023-10-10 14:48:56 +00:00
|
|
|
provider = request.json.get('provider').split('g4f.Provider.')[1]
|
2023-10-06 18:52:17 +00:00
|
|
|
|
|
|
|
messages = special_instructions[jailbreak] + conversation + search(internet_access, prompt) + [prompt]
|
|
|
|
|
|
|
|
def stream():
|
2023-10-09 22:46:02 +00:00
|
|
|
if provider:
|
|
|
|
answer = g4f.ChatCompletion.create(model=model,
|
2023-10-10 13:11:17 +00:00
|
|
|
provider=get_provider(provider), messages=messages, stream=True)
|
2023-10-09 22:46:02 +00:00
|
|
|
else:
|
|
|
|
answer = g4f.ChatCompletion.create(model=model,
|
2023-10-10 13:11:17 +00:00
|
|
|
messages=messages, stream=True)
|
2023-10-06 18:52:17 +00:00
|
|
|
|
|
|
|
for token in answer:
|
|
|
|
yield token
|
2023-10-09 22:46:02 +00:00
|
|
|
|
2023-10-06 18:52:17 +00:00
|
|
|
return self.app.response_class(stream(), mimetype='text/event-stream')
|
|
|
|
|
2023-10-09 22:46:02 +00:00
|
|
|
except Exception as e:
|
2023-10-06 18:52:17 +00:00
|
|
|
return {
|
2023-10-10 14:48:56 +00:00
|
|
|
'code' : 'G4F_ERROR',
|
2023-10-06 18:52:17 +00:00
|
|
|
'_action': '_ask',
|
|
|
|
'success': False,
|
2023-10-11 03:35:49 +00:00
|
|
|
'error' : f'an error occurred {str(e)}'}, 400
|