XFE Git
XFE Studio Git
Git 首页 全局搜索
XFE 主站 文档 NuGet
公开
关注 0 Fork 0 Star 1
返回提交历史

XFEstudio/gpt4free

feat(/Provider/AmigoChat.py): add retry mechanism for API requests

69d0d2b2
kqlio67 <kqlio67@users.noreply.github.com>
提交于

代码差异

1 个文件 +93 -81
Modified g4f/Provider/AmigoChat.py +93 -81
@@ -2,7 +2,7 @@ from __future__ import annotations
2 2
3 3 import json
4 4 import uuid
5 from aiohttp import ClientSession, ClientTimeout
5 from aiohttp import ClientSession, ClientTimeout, ClientResponseError
6 6
7 7 from ..typing import AsyncResult, Messages
8 8 from .base_provider import AsyncGeneratorProvider, ProviderModelMixin
@@ -92,87 +92,99 @@ class AmigoChat(AsyncGeneratorProvider, ProviderModelMixin):
92 92 model = cls.get_model(model)
93 93
94 94 device_uuid = str(uuid.uuid4())
95 max_retries = 3
96 retry_count = 0
95 97
96 headers = {
97 "accept": "*/*",
98 "accept-language": "en-US,en;q=0.9",
99 "authorization": "Bearer", # You need to implement proper authorization
100 "cache-control": "no-cache",
101 "content-type": "application/json",
102 "origin": cls.url,
103 "pragma": "no-cache",
104 "priority": "u=1, i",
105 "referer": f"{cls.url}/",
106 "sec-ch-ua": '"Chromium";v="129", "Not=A?Brand";v="8"',
107 "sec-ch-ua-mobile": "?0",
108 "sec-ch-ua-platform": '"Linux"',
109 "user-agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36",
110 "x-device-language": "en-US",
111 "x-device-platform": "web",
112 "x-device-uuid": device_uuid,
113 "x-device-version": "1.0.32"
114 }
115
116 async with ClientSession(headers=headers) as session:
117 if model in cls.chat_models:
118 # Chat completion
119 data = {
120 "messages": [{"role": m["role"], "content": m["content"]} for m in messages],
121 "model": model,
122 "personaId": cls.get_personaId(model),
123 "frequency_penalty": 0,
124 "max_tokens": 4000,
125 "presence_penalty": 0,
126 "stream": stream,
127 "temperature": 0.5,
128 "top_p": 0.95
98 while retry_count < max_retries:
99 try:
100 headers = {
101 "accept": "*/*",
102 "accept-language": "en-US,en;q=0.9",
103 "authorization": "Bearer",
104 "cache-control": "no-cache",
105 "content-type": "application/json",
106 "origin": cls.url,
107 "pragma": "no-cache",
108 "priority": "u=1, i",
109 "referer": f"{cls.url}/",
110 "sec-ch-ua": '"Chromium";v="129", "Not=A?Brand";v="8"',
111 "sec-ch-ua-mobile": "?0",
112 "sec-ch-ua-platform": '"Linux"',
113 "user-agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36",
114 "x-device-language": "en-US",
115 "x-device-platform": "web",
116 "x-device-uuid": device_uuid,
117 "x-device-version": "1.0.32"
129 118 }
130 119
131 timeout = ClientTimeout(total=300) # 5 minutes timeout
132 async with session.post(cls.chat_api_endpoint, json=data, proxy=proxy, timeout=timeout) as response:
133 if response.status not in (200, 201):
134 error_text = await response.text()
135 raise Exception(f"Error {response.status}: {error_text}")
136
137 async for line in response.content:
138 line = line.decode('utf-8').strip()
139 if line.startswith('data: '):
140 if line == 'data: [DONE]':
141 break
142 try:
143 chunk = json.loads(line[6:]) # Remove 'data: ' prefix
144 if 'choices' in chunk and len(chunk['choices']) > 0:
145 choice = chunk['choices'][0]
146 if 'delta' in choice:
147 content = choice['delta'].get('content')
148 elif 'text' in choice:
149 content = choice['text']
150 else:
151 content = None
152 if content:
153 yield content
154 except json.JSONDecodeError:
155 pass
156 else:
157 # Image generation
158 prompt = messages[0]['content']
159 data = {
160 "prompt": prompt,
161 "model": model,
162 "personaId": cls.get_personaId(model)
163 }
164 async with session.post(cls.image_api_endpoint, json=data, proxy=proxy) as response:
165 response.raise_for_status()
166
167 response_data = await response.json()
168
169 if "data" in response_data:
170 image_urls = []
171 for item in response_data["data"]:
172 if "url" in item:
173 image_url = item["url"]
174 image_urls.append(image_url)
175 if image_urls:
176 yield ImageResponse(image_urls, prompt)
120 async with ClientSession(headers=headers) as session:
121 if model in cls.chat_models:
122 # Chat completion
123 data = {
124 "messages": [{"role": m["role"], "content": m["content"]} for m in messages],
125 "model": model,
126 "personaId": cls.get_personaId(model),
127 "frequency_penalty": 0,
128 "max_tokens": 4000,
129 "presence_penalty": 0,
130 "stream": stream,
131 "temperature": 0.5,
132 "top_p": 0.95
133 }
134
135 timeout = ClientTimeout(total=300) # 5 minutes timeout
136 async with session.post(cls.chat_api_endpoint, json=data, proxy=proxy, timeout=timeout) as response:
137 if response.status not in (200, 201):
138 error_text = await response.text()
139 raise Exception(f"Error {response.status}: {error_text}")
140
141 async for line in response.content:
142 line = line.decode('utf-8').strip()
143 if line.startswith('data: '):
144 if line == 'data: [DONE]':
145 break
146 try:
147 chunk = json.loads(line[6:]) # Remove 'data: ' prefix
148 if 'choices' in chunk and len(chunk['choices']) > 0:
149 choice = chunk['choices'][0]
150 if 'delta' in choice:
151 content = choice['delta'].get('content')
152 elif 'text' in choice:
153 content = choice['text']
154 else:
155 content = None
156 if content:
157 yield content
158 except json.JSONDecodeError:
159 pass
177 160 else:
178 yield None
161 # Image generation
162 prompt = messages[0]['content']
163 data = {
164 "prompt": prompt,
165 "model": model,
166 "personaId": cls.get_personaId(model)
167 }
168 async with session.post(cls.image_api_endpoint, json=data, proxy=proxy) as response:
169 response.raise_for_status()
170
171 response_data = await response.json()
172
173 if "data" in response_data:
174 image_urls = []
175 for item in response_data["data"]:
176 if "url" in item:
177 image_url = item["url"]
178 image_urls.append(image_url)
179 if image_urls:
180 yield ImageResponse(image_urls, prompt)
181 else:
182 yield None
183
184 break
185
186 except (ClientResponseError, Exception) as e:
187 retry_count += 1
188 if retry_count >= max_retries:
189 raise e
190 device_uuid = str(uuid.uuid4())