ftjc2021 commited on
Commit
dad4031
·
verified ·
1 Parent(s): f60fbb3

Upload 3 files

Browse files
Files changed (2) hide show
  1. dify_api_client.py +32 -18
  2. requirements.txt +2 -1
dify_api_client.py CHANGED
@@ -18,6 +18,7 @@ import logging
18
  import configparser
19
  from typing import Dict, Any, Optional, Union
20
  from datetime import datetime
 
21
 
22
 
23
  # 配置日志
@@ -126,9 +127,14 @@ class DifyAPIClient:
126
  print(f"读取文件时出错: {str(e)}")
127
  sys.exit(1)
128
 
 
 
 
 
 
129
  def send_request_blocking(self, content: str, conversation_id: str = None, user: str = "user") -> Dict[str, Any]:
130
  """
131
- 发送阻塞模式请求
132
 
133
  Args:
134
  content: 请求内容
@@ -158,7 +164,8 @@ class DifyAPIClient:
158
  logging.debug(f"请求负载: {json.dumps(payload, ensure_ascii=False)}")
159
 
160
  try:
161
- response = requests.post(url, headers=self.headers, json=payload)
 
162
  response.raise_for_status()
163
  response_data = response.json()
164
  logging.info("API请求成功")
@@ -169,12 +176,12 @@ class DifyAPIClient:
169
  if hasattr(response, 'text'):
170
  logging.error(f"API响应内容: {response.text}")
171
  raise Exception(f"HTTP错误: {e}")
172
- except requests.exceptions.ConnectionError:
173
- logging.error("连接错误: 无法连接到API服务器")
174
- raise Exception("连接错误: 无法连接到API服务器")
175
- except requests.exceptions.Timeout:
176
- logging.error("超时错误: API请求超时")
177
- raise Exception("超时错误: API请求超时")
178
  except requests.exceptions.RequestException as e:
179
  logging.error(f"请求错误: {str(e)}", exc_info=True)
180
  raise Exception(f"请求错误: {e}")
@@ -187,9 +194,14 @@ class DifyAPIClient:
187
  logging.error(f"未知错误: {str(e)}", exc_info=True)
188
  raise Exception(f"发送请求时发生未知错误: {str(e)}")
189
 
 
 
 
 
 
190
  async def send_request_blocking_async(self, content: str, conversation_id: str = None, user: str = "user") -> Dict[str, Any]:
191
  """
192
- 异步发送阻塞模式请求
193
 
194
  Args:
195
  content: 请求内容
@@ -219,7 +231,9 @@ class DifyAPIClient:
219
  logging.debug(f"请求负载: {json.dumps(payload, ensure_ascii=False)}")
220
 
221
  try:
222
- async with httpx.AsyncClient() as client:
 
 
223
  response = await client.post(url, headers=self.headers, json=payload)
224
  response.raise_for_status()
225
  response_data = response.json()
@@ -231,12 +245,12 @@ class DifyAPIClient:
231
  if hasattr(e.response, 'text'):
232
  logging.error(f"API响应内容: {e.response.text}")
233
  raise Exception(f"HTTP错误: {e}")
234
- except httpx.ConnectError:
235
- logging.error("连接错误: 无法连接到API服务器")
236
- raise Exception("连接错误: 无法连接到API服务器")
237
- except httpx.TimeoutException:
238
- logging.error("超时错误: API请求超时")
239
- raise Exception("超时错误: API请求超时")
240
  except httpx.RequestError as e:
241
  logging.error(f"请求错误: {str(e)}", exc_info=True)
242
  raise Exception(f"请求错误: {e}")
@@ -279,8 +293,8 @@ class DifyAPIClient:
279
  logging.debug(f"请求负载: {json.dumps(payload, ensure_ascii=False)}")
280
 
281
  try:
282
- # 使用流式请求
283
- response = requests.post(url, headers=self.headers, json=payload, stream=True)
284
  response.raise_for_status()
285
 
286
  # 创建SSE客户端
 
18
  import configparser
19
  from typing import Dict, Any, Optional, Union
20
  from datetime import datetime
21
+ from tenacity import retry, stop_after_attempt, wait_exponential, retry_if_exception_type
22
 
23
 
24
  # 配置日志
 
127
  print(f"读取文件时出错: {str(e)}")
128
  sys.exit(1)
129
 
130
+ @retry(
131
+ stop=stop_after_attempt(3), # 最多重试3次
132
+ wait=wait_exponential(multiplier=1, min=2, max=10), # 指数退避策略
133
+ retry=retry_if_exception_type((requests.exceptions.Timeout, requests.exceptions.ConnectionError))
134
+ )
135
  def send_request_blocking(self, content: str, conversation_id: str = None, user: str = "user") -> Dict[str, Any]:
136
  """
137
+ 发送阻塞模式请求,带有自动重试机制
138
 
139
  Args:
140
  content: 请求内容
 
164
  logging.debug(f"请求负载: {json.dumps(payload, ensure_ascii=False)}")
165
 
166
  try:
167
+ # 设置更长的超时时间:60秒连接超时,120秒读取超时
168
+ response = requests.post(url, headers=self.headers, json=payload, timeout=(60, 120))
169
  response.raise_for_status()
170
  response_data = response.json()
171
  logging.info("API请求成功")
 
176
  if hasattr(response, 'text'):
177
  logging.error(f"API响应内容: {response.text}")
178
  raise Exception(f"HTTP错误: {e}")
179
+ except requests.exceptions.ConnectionError as e:
180
+ logging.error(f"连接错误: 无法连接到API服务器: {e}")
181
+ raise # 重新抛出异常以触发重试
182
+ except requests.exceptions.Timeout as e:
183
+ logging.error(f"超时错误: API请求超时: {e}")
184
+ raise # 重新抛出异常以触发重试
185
  except requests.exceptions.RequestException as e:
186
  logging.error(f"请求错误: {str(e)}", exc_info=True)
187
  raise Exception(f"请求错误: {e}")
 
194
  logging.error(f"未知错误: {str(e)}", exc_info=True)
195
  raise Exception(f"发送请求时发生未知错误: {str(e)}")
196
 
197
+ @retry(
198
+ stop=stop_after_attempt(3), # 最多重试3次
199
+ wait=wait_exponential(multiplier=1, min=2, max=10), # 指数退避策略
200
+ retry=retry_if_exception_type((httpx.TimeoutException, httpx.ConnectError))
201
+ )
202
  async def send_request_blocking_async(self, content: str, conversation_id: str = None, user: str = "user") -> Dict[str, Any]:
203
  """
204
+ 异步发送阻塞模式请求,带有自动重试机制
205
 
206
  Args:
207
  content: 请求内容
 
231
  logging.debug(f"请求负载: {json.dumps(payload, ensure_ascii=False)}")
232
 
233
  try:
234
+ # 设置更长的超时时间:60秒连接超时,120秒读取超时
235
+ timeout = httpx.Timeout(60.0, read=120.0)
236
+ async with httpx.AsyncClient(timeout=timeout) as client:
237
  response = await client.post(url, headers=self.headers, json=payload)
238
  response.raise_for_status()
239
  response_data = response.json()
 
245
  if hasattr(e.response, 'text'):
246
  logging.error(f"API响应内容: {e.response.text}")
247
  raise Exception(f"HTTP错误: {e}")
248
+ except httpx.ConnectError as e:
249
+ logging.error(f"连接错误: 无法连接到API服务器: {e}")
250
+ raise # 重新抛出异常以触发重试
251
+ except httpx.TimeoutException as e:
252
+ logging.error(f"超时错误: API请求超时: {e}")
253
+ raise # 重新抛出异常以触发重试
254
  except httpx.RequestError as e:
255
  logging.error(f"请求错误: {str(e)}", exc_info=True)
256
  raise Exception(f"请求错误: {e}")
 
293
  logging.debug(f"请求负载: {json.dumps(payload, ensure_ascii=False)}")
294
 
295
  try:
296
+ # 使用流式请求,设置更长的超时时间:60秒连接超时,300秒读取超时(流式响应可能需要更长时间)
297
+ response = requests.post(url, headers=self.headers, json=payload, stream=True, timeout=(60, 300))
298
  response.raise_for_status()
299
 
300
  # 创建SSE客户端
requirements.txt CHANGED
@@ -5,4 +5,5 @@ uvicorn>=0.21.0
5
  python-multipart>=0.0.6
6
  pydantic>=1.10.7
7
  httpx>=0.24.0
8
- aiofiles>=0.8.0
 
 
5
  python-multipart>=0.0.6
6
  pydantic>=1.10.7
7
  httpx>=0.24.0
8
+ aiofiles>=0.8.0
9
+ tenacity>=8.0.0