bobocup commited on
Commit
b860111
·
verified ·
1 Parent(s): 61ea9f0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +26 -8
app.py CHANGED
@@ -132,32 +132,43 @@ async def access_control(request: Request, call_next):
132
 
133
  return await call_next(request)
134
 
135
- # 流式响应生成器
136
  async def stream_generator(response):
 
 
137
  try:
138
  async for chunk in response.aiter_bytes():
 
 
 
 
 
 
 
 
139
  chunk_str = chunk.decode('utf-8')
140
- for line in chunk_str.split('\n'):
 
 
 
141
  line = line.strip()
142
  if line:
143
  if line.startswith('data: '):
144
  yield f"{line}\n\n"
145
  else:
146
  yield f"data: {line}\n\n"
147
- # 添加小延迟以保持连接
148
- await asyncio.sleep(0.01)
149
  except Exception as e:
150
  print(f"Stream error: {str(e)}")
151
  yield f"data: [ERROR] {str(e)}\n\n"
152
 
153
- # 处理API请求
154
  async def handle_api_request(url: str, headers: dict, method: str = "GET", body: dict = None, for_chat: bool = False):
155
  max_retries = 3
156
  current_try = 0
157
 
158
  while current_try < max_retries:
159
  try:
160
- # 获取key
161
  if for_chat:
162
  key = get_chat_key()
163
  else:
@@ -168,8 +179,15 @@ async def handle_api_request(url: str, headers: dict, method: str = "GET", body:
168
 
169
  headers["Authorization"] = f"Bearer {key}"
170
 
171
- # 修改超时设置
172
- async with httpx.AsyncClient(timeout=httpx.Timeout(30.0, read=None)) as client:
 
 
 
 
 
 
 
173
  response = await client.request(
174
  method=method,
175
  url=url,
 
132
 
133
  return await call_next(request)
134
 
135
+ # 修改 stream_generator 函数
136
  async def stream_generator(response):
137
+ buffer = ""
138
+ first_chunk = True
139
  try:
140
  async for chunk in response.aiter_bytes():
141
+ if first_chunk:
142
+ # 第一个响应来得快一些
143
+ await asyncio.sleep(0.1)
144
+ first_chunk = False
145
+ else:
146
+ # 后续响应平滑输出
147
+ await asyncio.sleep(0.05)
148
+
149
  chunk_str = chunk.decode('utf-8')
150
+ buffer += chunk_str
151
+
152
+ while '\n' in buffer:
153
+ line, buffer = buffer.split('\n', 1)
154
  line = line.strip()
155
  if line:
156
  if line.startswith('data: '):
157
  yield f"{line}\n\n"
158
  else:
159
  yield f"data: {line}\n\n"
160
+
 
161
  except Exception as e:
162
  print(f"Stream error: {str(e)}")
163
  yield f"data: [ERROR] {str(e)}\n\n"
164
 
165
+ # 修改 handle_api_request 函数中的超时设置
166
  async def handle_api_request(url: str, headers: dict, method: str = "GET", body: dict = None, for_chat: bool = False):
167
  max_retries = 3
168
  current_try = 0
169
 
170
  while current_try < max_retries:
171
  try:
 
172
  if for_chat:
173
  key = get_chat_key()
174
  else:
 
179
 
180
  headers["Authorization"] = f"Bearer {key}"
181
 
182
+ # 减少连接超时,增加读取超时
183
+ timeout = httpx.Timeout(
184
+ connect=5.0, # 连接超时5秒
185
+ read=60.0, # 读取超时60秒
186
+ write=5.0, # 写入超时5秒
187
+ pool=5.0 # 连接池超时5秒
188
+ )
189
+
190
+ async with httpx.AsyncClient(timeout=timeout) as client:
191
  response = await client.request(
192
  method=method,
193
  url=url,