返回提交历史
Modified
g4f/Provider/GLM.py
+183
-6
Modified
setup.py
+3
-2
XFEstudio/gpt4free
Enhance GLM provider with authentication signature generation and caching; update setup.py dependencies
a727866c
代码差异
2 个文件
+186
-8
@@ -1,20 +1,170 @@
1
1
from __future__ import annotations
2
2
3
import os
4
import json
5
import time
6
import hashlib
7
import hmac
3
8
import uuid
4
9
import requests
10
import urllib.parse
5
11
6
12
from ..typing import AsyncResult, Messages
7
13
from ..providers.response import Usage, Reasoning
8
14
from ..requests import StreamSession, raise_for_status
9
from .base_provider import AsyncGeneratorProvider, ProviderModelMixin
15
from ..errors import ModelNotFoundError, ProviderException
16
from .base_provider import AsyncGeneratorProvider, ProviderModelMixin, AuthFileMixin
10
17
11
class GLM(AsyncGeneratorProvider, ProviderModelMixin):
18
class GLM(AsyncGeneratorProvider, ProviderModelMixin, AuthFileMixin):
12
19
url = "https://chat.z.ai"
13
20
api_endpoint = "https://chat.z.ai/api/chat/completions"
14
21
working = True
15
22
active_by_default = True
16
23
default_model = "GLM-4.5"
24
17
25
api_key = None
26
auth_user_id = None
27
28
@classmethod
29
def create_signature_with_timestamp(cls,e: str, t: str):
30
current_time = int(time.time() * 1000) # Current time in milliseconds
31
current_time_string = str(current_time)
32
data_string = f"{e}|{t}|{current_time_string}"
33
time_window = current_time // (5 * 60 * 1000) # 5 minutes in milliseconds
34
35
base_signature = hmac.new(
36
"junjie".encode("utf-8"),
37
str(time_window).encode("utf-8"),
38
hashlib.sha256
39
).hexdigest()
40
41
signature = hmac.new(
42
base_signature.encode("utf-8"),
43
data_string.encode("utf-8"),
44
hashlib.sha256
45
).hexdigest()
46
47
return {
48
"signature": signature,
49
"timestamp": current_time
50
}
51
52
@classmethod
53
def prepare_auth_params(cls, token: str, user_id: str):
54
# Basic parameters
55
current_time = str(int(time.time() * 1000))
56
request_id = str(uuid.uuid1()) # Using uuid1 which is equivalent to v1
57
58
basic_params = {
59
"timestamp": current_time,
60
"requestId": request_id,
61
"user_id": user_id,
62
}
63
64
# Additional parameters
65
additional_params = {
66
"version": "0.0.1",
67
"platform": "web",
68
"token": token,
69
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",
70
"language": "en-US",
71
"languages": "en-US,en",
72
"timezone": "Asia/Jakarta",
73
"cookie_enabled": "true",
74
"screen_width": "1920",
75
"screen_height": "1080",
76
"screen_resolution": "1920x1080",
77
"viewport_height": "900",
78
"viewport_width": "1440",
79
"viewport_size": "1440x900",
80
"color_depth": "24",
81
"pixel_ratio": "1",
82
"current_url": "https://chat.z.ai/c/e1295904-98d3-4d85-b6ee-a211471101e9",
83
"pathname": "/",
84
"search": "",
85
"hash": "",
86
"host": "z.ai",
87
"hostname": "chat.z.ai",
88
"protocol": "https",
89
"referrer": "https://accounts.google.com/",
90
"title": "A Little House Keeping",
91
"timezone_offset": str(-(time.timezone if time.daylight == 0 else time.altzone) // 60),
92
"local_time": time.strftime('%Y-%m-%dT%H:%M:%S.%fZ', time.gmtime()),
93
"utc_time": time.strftime('%a, %d %b %Y %H:%M:%S GMT', time.gmtime()),
94
"is_mobile": "false",
95
"is_touch": "false",
96
"max_touch_points": "5",
97
"browser_name": "Chrome",
98
"os_name": "Linux",
99
}
100
101
# Combine parameters
102
all_params = {**basic_params, **additional_params}
103
104
# Create URLSearchParams equivalent
105
url_params_string = urllib.parse.urlencode(all_params)
106
107
# Create sorted payload (basic params only, sorted by key)
108
sorted_payload = ','.join([f"{k},{v}" for k, v in sorted(basic_params.items())])
109
110
return {
111
"sortedPayload": sorted_payload,
112
"urlParams": url_params_string
113
}
114
115
@classmethod
116
def get_endpoint_signature(cls, token: str, user_id: str, user_prompt: str):
117
# Get auth parameters
118
auth_params = cls.prepare_auth_params(token, user_id)
119
sorted_payload = auth_params["sortedPayload"]
120
url_params = auth_params["urlParams"]
121
122
# debug.log(f"Prompt:{user_prompt}")
123
last_user_prompt = user_prompt.strip()
124
125
# Create signature with timestamp
126
signature_data = cls.create_signature_with_timestamp(sorted_payload, last_user_prompt)
127
signature = signature_data["signature"]
128
timestamp = signature_data["timestamp"]
129
130
# Construct the endpoint URL
131
endpoint = f"{cls.api_endpoint}?{url_params}&signature_timestamp={timestamp}"
132
133
return (endpoint, signature, timestamp)
134
135
@classmethod
136
def get_auth_from_cache(cls):
137
cache_file_path = cls.get_cache_file()
138
#get file mtime
139
#if time compared by now is less than 5 minutes
140
# read cache_file_path and return json
141
#else return none
142
if cache_file_path.is_file():
143
# Get the modification time of the file
144
file_mtime = cache_file_path.stat().st_mtime
145
# Get current time
146
current_time = time.time()
147
# Calculate the difference in seconds
148
time_diff = current_time - file_mtime
149
# Check if the file is less than 30 minutes old (30 * 60 seconds)
150
if time_diff < 5 * 60:
151
try:
152
with open(cache_file_path, 'r') as file:
153
return json.load(file)
154
except (json.JSONDecodeError, IOError):
155
# If there's an error reading or parsing the file, delete it and return None
156
try:
157
os.remove(cache_file_path)
158
except OSError:
159
pass # If we can't delete the file, just return None
160
return None
161
return None
162
163
@classmethod
164
def save_auth_to_cache(cls,data):
165
cache_file_path = cls.get_cache_file()
166
with cache_file_path.open('w') as file:
167
json.dump(data, file)
18
168
19
169
@classmethod
20
170
def get_models(cls, **kwargs) -> str:
@@ -27,6 +177,18 @@ class GLM(AsyncGeneratorProvider, ProviderModelMixin):
27
177
cls.models = list(cls.model_aliases.keys())
28
178
return cls.models
29
179
180
@classmethod
181
def get_last_user_message_content(cls, messages):
182
"""
183
Get the content of the last message with role 'user'
184
"""
185
# Iterate through messages in reverse order to find the last user message
186
for message in reversed(messages):
187
if message.get('role') == 'user':
188
return message.get('content')
189
# Return None if no user message is found
190
return None
191
30
192
@classmethod
31
193
async def create_async_generator(
32
194
cls,
@@ -36,7 +198,18 @@ class GLM(AsyncGeneratorProvider, ProviderModelMixin):
36
198
**kwargs
37
199
) -> AsyncResult:
38
200
cls.get_models()
39
model = cls.get_model(model)
201
try:
202
model = cls.get_model(model)
203
except ModelNotFoundError:
204
# If get_model fails, use the provided model directly
205
model = model
206
207
# Ensure we have an API key before proceeding
208
if not cls.api_key:
209
raise ProviderException("Failed to obtain API key from authentication endpoint")
210
211
user_prompt = cls.get_last_user_message_content(messages)
212
endpoint, signature, timestamp = cls.get_endpoint_signature(cls.api_key,cls.auth_user_id,user_prompt)
40
213
data = {
41
214
"chat_id": "local",
42
215
"id": str(uuid.uuid4()),
@@ -54,9 +227,13 @@ class GLM(AsyncGeneratorProvider, ProviderModelMixin):
54
227
proxy=proxy,
55
228
) as session:
56
229
async with session.post(
57
cls.api_endpoint,
230
endpoint,
58
231
json=data,
59
headers={"Authorization": f"Bearer {cls.api_key}", "x-fe-version": "prod-fe-1.0.57"},
232
headers={
233
"Authorization": f"Bearer {cls.api_key}",
234
"x-fe-version": "prod-fe-1.0.95",
235
"x-signature": signature
236
},
60
237
) as response:
61
238
await raise_for_status(response)
62
239
usage = None
@@ -78,4 +255,4 @@ class GLM(AsyncGeneratorProvider, ProviderModelMixin):
78
255
else:
79
256
delta_content = chunk.get("data", {}).get("delta_content")
80
257
if delta_content:
81
yield delta_content
258
yield delta_content
@@ -53,7 +53,8 @@ EXTRA_REQUIRE = {
53
53
"nodriver",
54
54
"python-multipart",
55
55
"a2wsgi",
56
"markitdown[docx,pdf,pptx]",
56
"pypdf2",
57
"python-docx",
57
58
"python-dotenv",
58
59
"aiofile"
59
60
],
@@ -72,11 +73,11 @@ EXTRA_REQUIRE = {
72
73
"loguru", "fastapi",
73
74
"uvicorn",
74
75
"python-multipart",
76
"a2wsgi",
75
77
],
76
78
"gui": [
77
79
"werkzeug", "flask",
78
80
"beautifulsoup4", "pillow",
79
"ddgs",
80
81
],
81
82
"search": [
82
83
"beautifulsoup4",