summaryrefslogtreecommitdiffstats
path: root/g4f/gui/server/backend.py
blob: 3d7bfedc592a71250e82c463605122a239913fe9 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import g4f

from flask      import request
from .internet  import search
from .config    import special_instructions
from .provider  import get_provider

g4f.logging = True

class Backend_Api:
    def __init__(self, app) -> None:
        self.app = app
        self.routes = {
            '/backend-api/v2/models': {
                'function': self.models,
                'methods' : ['GET']
            },
            '/backend-api/v2/conversation': {
                'function': self._conversation,
                'methods': ['POST']
            },
            '/backend-api/v2/gen.set.summarize:title': {
                'function': self._gen_title,
                'methods': ['POST']
            },
            '/backend-api/v2/error': {
                'function': self.error,
                'methods': ['POST']
            }
        }
    
    def error(self):
        print(request.json)
        
        return 'ok', 200
    
    def models(self):
        return g4f._all_models
    
    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']
            model           = request.json['model']
            provider        = request.json.get('provider').split('g4f.Provider.')[1]

            messages = prompt
            print(messages)

            def stream():
                yield from g4f.ChatCompletion.create(
                    model=model,
                    provider=get_provider(provider),
                    messages=messages,
                    stream=True,
                ) if provider else g4f.ChatCompletion.create(
                    model=model, messages=messages, stream=True
                )

            return self.app.response_class(stream(), mimetype='text/event-stream')

        except Exception as e:    
            return {
                'code'   : 'G4F_ERROR',
                '_action': '_ask',
                'success': False,
                'error'  : f'an error occurred {str(e)}'}, 400