summaryrefslogtreecommitdiffstats
path: root/g4f/Provider/ChatGpt.py
blob: fc34fc2bb6c02fc75cc62293abb40edf0e92af4a (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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
from __future__ import annotations

from ..typing import Messages, CreateResult
from ..providers.base_provider import AbstractProvider, ProviderModelMixin

import time, uuid, random, json
from requests import Session

from .openai.new import (
    get_config,
    get_answer_token,
    process_turnstile,
    get_requirements_token
)

def format_conversation(messages: list):
    conversation = []
    
    for message in messages:
        conversation.append({
            'id': str(uuid.uuid4()),
            'author': {
                'role': message['role'],
            },
            'content': {
                'content_type': 'text',
                'parts': [
                    message['content'],
                ],
            },
            'metadata': {
                'serialization_metadata': {
                    'custom_symbol_offsets': [],
                },
            },
            'create_time': round(time.time(), 3),
        })
    
    return conversation

def init_session(user_agent):
    session = Session()

    cookies = {
        '_dd_s': '',
    }

    headers = {
        'accept': '*/*',
        'accept-language': 'en-US,en;q=0.8',
        'cache-control': 'no-cache',
        'pragma': 'no-cache',
        'priority': 'u=0, i',
        'sec-ch-ua': '"Not)A;Brand";v="99", "Google Chrome";v="127", "Chromium";v="127"',
        'sec-ch-ua-arch': '"arm"',
        'sec-ch-ua-bitness': '"64"',
        'sec-ch-ua-mobile': '?0',
        'sec-ch-ua-model': '""',
        'sec-ch-ua-platform': '"macOS"',
        'sec-ch-ua-platform-version': '"14.4.0"',
        'sec-fetch-dest': 'document',
        'sec-fetch-mode': 'navigate',
        'sec-fetch-site': 'none',
        'sec-fetch-user': '?1',
        'upgrade-insecure-requests': '1',
        'user-agent': user_agent,
    }

    session.get('https://chatgpt.com/', cookies=cookies, headers=headers)
    
    return session

class ChatGpt(AbstractProvider, ProviderModelMixin):
    label = "ChatGpt"
    working = True
    supports_message_history = True
    supports_system_message = True
    supports_stream = True
    models = [
        'gpt-4o',
        'gpt-4o-mini',
        'gpt-4',
        'gpt-4-turbo',
        'chatgpt-4o-latest',
    ]

    @classmethod
    def create_completion(
        cls,
        model: str,
        messages: Messages,
        stream: bool,
        **kwargs
    ) -> CreateResult:
        
        if model in [
            'gpt-4o',
            'gpt-4o-mini',
            'gpt-4',
            'gpt-4-turbo',
            'chatgpt-4o-latest'
        ]:
            model = 'auto'
        
        elif model in [
            'gpt-3.5-turbo'
        ]:
            model = 'text-davinci-002-render-sha'
            
        else:
            raise ValueError(f"Invalid model: {model}")
        
        user_agent       = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36'
        session: Session = init_session(user_agent)
        
        config   = get_config(user_agent)
        pow_req  = get_requirements_token(config)
        headers  = { 
            'accept': '*/*',
            'accept-language': 'en-US,en;q=0.8',
            'content-type': 'application/json',
            'oai-device-id': f'{uuid.uuid4()}',
            'oai-language': 'en-US',
            'origin': 'https://chatgpt.com',
            'priority': 'u=1, i',
            'referer': 'https://chatgpt.com/',
            'sec-ch-ua-mobile': '?0',
            'sec-ch-ua-platform': '"Linux"',
            'sec-fetch-dest': 'empty',
            'sec-fetch-mode': 'cors',
            'sec-fetch-site': 'same-origin',
            'sec-gpc': '1',
            'user-agent': f'{user_agent}'
        }
        
        response = session.post('https://chatgpt.com/backend-anon/sentinel/chat-requirements',
            headers=headers, json={'p': pow_req}).json()

        turnstile          = response.get('turnstile', {})
        turnstile_required = turnstile.get('required')
        pow_conf           = response.get('proofofwork', {})

        if turnstile_required:
            turnstile_dx    = turnstile.get('dx')
            turnstile_token = process_turnstile(turnstile_dx, pow_req)
        
        headers = headers | {
            'openai-sentinel-turnstile-token'        : turnstile_token,
            'openai-sentinel-chat-requirements-token': response.get('token'),
            'openai-sentinel-proof-token'            : get_answer_token(
                pow_conf.get('seed'), pow_conf.get('difficulty'), config
            )
        }
        
        json_data = {
            'action': 'next',
            'messages': format_conversation(messages),
            'parent_message_id': str(uuid.uuid4()),
            'model': 'auto',
            'timezone_offset_min': -120,
            'suggestions': [
                'Can you help me create a personalized morning routine that would help increase my productivity throughout the day? Start by asking me about my current habits and what activities energize me in the morning.',
                'Could you help me plan a relaxing day that focuses on activities for rejuvenation? To start, can you ask me what my favorite forms of relaxation are?',
                'I have a photoshoot tomorrow. Can you recommend me some colors and outfit options that will look good on camera?',
                'Make up a 5-sentence story about "Sharky", a tooth-brushing shark superhero. Make each sentence a bullet point.',
            ],
            'history_and_training_disabled': False,
            'conversation_mode': {
                'kind': 'primary_assistant',
            },
            'force_paragen': False,
            'force_paragen_model_slug': '',
            'force_nulligen': False,
            'force_rate_limit': False,
            'reset_rate_limits': False,
            'websocket_request_id': str(uuid.uuid4()),
            'system_hints': [],
            'force_use_sse': True,
            'conversation_origin': None,
            'client_contextual_info': {
                'is_dark_mode': True,
                'time_since_loaded': random.randint(22,33),
                'page_height': random.randint(600, 900),
                'page_width': random.randint(500, 800),
                'pixel_ratio': 2,
                'screen_height': random.randint(800, 1200),
                'screen_width': random.randint(1200, 2000),
            },
        }
        
        response = session.post('https://chatgpt.com/backend-anon/conversation',
            headers=headers, json=json_data, stream=True)
        
        replace = ''
        for line in response.iter_lines():
            if line:
                if 'DONE' in line.decode():
                    break
                
                data = json.loads(line.decode()[6:])
                if data.get('message').get('author').get('role') == 'assistant':
                    tokens = (data.get('message').get('content').get('parts')[0])
                    
                    yield tokens.replace(replace, '')
                    
                    replace = tokens