返回提交历史
Added
g4f/Provider/Qwen.py
+199
-0
XFEstudio/gpt4free
feat: Add provider for chat.qwen.ai
da403350
代码差异
1 个文件
+199
-0
@@ -0,0 +1,199 @@
1
import asyncio
2
import json
3
import re
4
import uuid
5
from time import time
6
7
import aiohttp
8
from ..errors import RateLimitError
9
from .base_provider import AsyncGeneratorProvider, ProviderModelMixin
10
from ..typing import AsyncResult, Messages
11
12
class Qwen(AsyncGeneratorProvider, ProviderModelMixin):
13
"""
14
Provider for Qwen's chat service (chat.qwen.ai), with configurable
15
parameters (stream, enable_thinking) and print logs.
16
"""
17
url = "https://chat.qwen.ai"
18
working = True
19
supports_stream = True
20
supports_message_history = False
21
22
# Complete list of models, extracted from the API
23
models = [
24
"qwen3-235b-a22b",
25
"qwen3-coder-plus",
26
"qwen3-30b-a3b",
27
"qwen3-coder-30b-a3b-instruct",
28
"qwen-max-latest",
29
"qwen-plus-2025-01-25",
30
"qwq-32b",
31
"qwen-turbo-2025-02-11",
32
"qwen2.5-omni-7b",
33
"qvq-72b-preview-0310",
34
"qwen2.5-vl-32b-instruct",
35
"qwen2.5-14b-instruct-1m",
36
"qwen2.5-coder-32b-instruct",
37
"qwen2.5-72b-instruct",
38
]
39
default_model = "qwen3-235b-a22b"
40
41
_midtoken: str = None
42
_midtoken_uses: int = 0
43
44
@classmethod
45
async def create_async_generator(
46
cls,
47
model: str,
48
messages: Messages,
49
proxy: str = None,
50
timeout: int = 120,
51
stream: bool = True,
52
enable_thinking: bool = True,
53
**kwargs
54
) -> AsyncResult:
55
56
model_name = cls.get_model(model)
57
58
headers = {
59
'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36',
60
'Accept': '*/*',
61
'Accept-Language': 'en-US,en;q=0.5',
62
'Origin': cls.url,
63
'Referer': f'{cls.url}/',
64
'Content-Type': 'application/json',
65
'Sec-Fetch-Dest': 'empty',
66
'Sec-Fetch-Mode': 'cors',
67
'Sec-Fetch-Site': 'same-origin',
68
'Connection': 'keep-alive',
69
'Authorization': 'Bearer',
70
'Source': 'web'
71
}
72
73
prompt = messages[-1]["content"]
74
75
async with aiohttp.ClientSession(headers=headers) as session:
76
for attempt in range(5):
77
try:
78
if not cls._midtoken:
79
print("[Qwen] INFO: No active midtoken. Fetching a new one...")
80
async with session.get('https://sg-wum.alibaba.com/w/wu.json', proxy=proxy) as r:
81
r.raise_for_status()
82
text = await r.text()
83
match = re.search(r"(?:umx\.wu|__fycb)\('([^']+)'\)", text)
84
if not match:
85
raise RuntimeError("Failed to extract bx-umidtoken.")
86
cls._midtoken = match.group(1)
87
cls._midtoken_uses = 1
88
print(f"[Qwen] INFO: New midtoken obtained. Use count: {cls._midtoken_uses}. Midtoken: {cls._midtoken}")
89
else:
90
cls._midtoken_uses += 1
91
print(f"[Qwen] INFO: Reusing midtoken. Use count: {cls._midtoken_uses}")
92
93
req_headers = session.headers.copy()
94
req_headers['bx-umidtoken'] = cls._midtoken
95
req_headers['bx-v'] = '2.5.31'
96
97
chat_payload = {
98
"title": "New Chat",
99
"models": [model_name],
100
"chat_mode": "normal",
101
"chat_type": "t2t",
102
"timestamp": int(time() * 1000)
103
}
104
async with session.post(
105
f'{cls.url}/api/v2/chats/new', json=chat_payload, headers=req_headers, proxy=proxy
106
) as resp:
107
resp.raise_for_status()
108
data = await resp.json()
109
if not (data.get('success') and data['data'].get('id')):
110
raise RuntimeError(f"Failed to create chat: {data}")
111
chat_id = data['data']['id']
112
113
msg_payload = {
114
"stream": stream,
115
"incremental_output": stream,
116
"chat_id": chat_id,
117
"chat_mode": "normal",
118
"model": model_name,
119
"parent_id": None,
120
"messages": [
121
{
122
"fid": str(uuid.uuid4()),
123
"parentId": None,
124
"childrenIds": [],
125
"role": "user",
126
"content": prompt,
127
"user_action": "chat",
128
"files": [],
129
"models": [model_name],
130
"chat_type": "t2t",
131
"feature_config": {
132
"thinking_enabled": enable_thinking,
133
"output_schema": "phase",
134
"thinking_budget": 81920
135
},
136
"extra": {
137
"meta": {
138
"subChatType": "t2t"
139
}
140
},
141
"sub_chat_type": "t2t",
142
"parent_id": None
143
}
144
]
145
}
146
147
async with session.post(
148
f'{cls.url}/api/v2/chat/completions?chat_id={chat_id}', json=msg_payload,
149
headers=req_headers, proxy=proxy, timeout=timeout
150
) as resp:
151
first_line = await resp.content.readline()
152
line_str = first_line.decode().strip()
153
if line_str.startswith('{'):
154
error_data = json.loads(line_str)
155
if error_data.get("data", {}).get("code") == "RateLimited":
156
raise RuntimeError("RateLimited by JSON response")
157
158
buffer = first_line
159
thinking_started = False
160
async for chunk in resp.content:
161
buffer += chunk
162
while b'\n' in buffer:
163
line, buffer = buffer.split(b'\n', 1)
164
line_str = line.decode().strip()
165
if not line_str.startswith("data: "): continue
166
try:
167
data_json = json.loads(line_str.lstrip("data: "))
168
choices = data_json.get("choices", [])
169
if not choices: continue
170
delta = choices[0].get("delta", {})
171
phase = delta.get("phase")
172
content = delta.get("content")
173
if phase == "think" and not thinking_started:
174
yield "<think>"
175
thinking_started = True
176
elif phase == "answer" and thinking_started:
177
yield "</think>"
178
thinking_started = False
179
if content:
180
yield content
181
except (json.JSONDecodeError, KeyError, IndexError):
182
continue
183
if thinking_started:
184
yield "</think>"
185
return
186
187
except (aiohttp.ClientResponseError, RuntimeError) as e:
188
is_rate_limit = (isinstance(e, aiohttp.ClientResponseError) and e.status == 429) or \
189
("RateLimited" in str(e))
190
if is_rate_limit:
191
print(f"[Qwen] WARNING: Rate limit detected (attempt {attempt + 1}/5). Invalidating current midtoken.")
192
cls._midtoken = None
193
cls._midtoken_uses = 0
194
await asyncio.sleep(2)
195
continue
196
else:
197
raise e
198
199
raise RateLimitError("The Qwen provider reached the request limit after 5 attempts.")