返回提交历史
Modified
g4f/Provider/HuggingChat.py
+21
-15
XFEstudio/gpt4free
fix(g4f/Provider/HuggingChat.py): handle JSON decode errors and response status
29835d95
代码差异
1 个文件
+21
-15
@@ -1,6 +1,7 @@
1
1
from __future__ import annotations
2
2
3
import json, requests, re
3
import json
4
import requests
4
5
5
6
from curl_cffi import requests as cf_reqs
6
7
from ..typing import CreateResult, Messages
@@ -73,17 +74,18 @@ class HuggingChat(AbstractProvider, ProviderModelMixin):
73
74
'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36',
74
75
}
75
76
76
print(model)
77
77
json_data = {
78
78
'model': model,
79
79
}
80
80
81
81
response = session.post('https://huggingface.co/chat/conversation', json=json_data)
82
conversationId = response.json()['conversationId']
82
if response.status_code != 200:
83
raise RuntimeError(f"Request failed with status code: {response.status_code}, response: {response.text}")
83
84
84
response = session.get(f'https://huggingface.co/chat/conversation/{conversationId}/__data.json?x-sveltekit-invalidated=11',)
85
conversationId = response.json().get('conversationId')
86
response = session.get(f'https://huggingface.co/chat/conversation/{conversationId}/__data.json?x-sveltekit-invalidated=11')
85
87
86
data: list = (response.json())["nodes"][1]["data"]
88
data: list = response.json()["nodes"][1]["data"]
87
89
keys: list[int] = data[data[0]["messages"]]
88
90
message_keys: dict = data[keys[0]]
89
91
messageId: str = data[message_keys["id"]]
@@ -124,22 +126,26 @@ class HuggingChat(AbstractProvider, ProviderModelMixin):
124
126
files=files,
125
127
)
126
128
127
first_token = True
129
full_response = ""
128
130
for line in response.iter_lines():
129
line = json.loads(line)
131
if not line:
132
continue
133
try:
134
line = json.loads(line)
135
except json.JSONDecodeError as e:
136
print(f"Failed to decode JSON: {line}, error: {e}")
137
continue
130
138
131
139
if "type" not in line:
132
140
raise RuntimeError(f"Response: {line}")
133
141
134
142
elif line["type"] == "stream":
135
token = line["token"]
136
if first_token:
137
token = token.lstrip().replace('\u0000', '')
138
first_token = False
139
else:
140
token = token.replace('\u0000', '')
141
142
yield token
143
token = line["token"].replace('\u0000', '')
144
full_response += token
143
145
144
146
elif line["type"] == "finalAnswer":
145
147
break
148
149
full_response = full_response.replace('<|im_end|', '').replace('\u0000', '').strip()
150
151
yield full_response