DeepLearning101 commited on
Commit
d021e73
·
verified ·
1 Parent(s): 5099281

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +50 -38
app.py CHANGED
@@ -11,6 +11,16 @@ LLM_API = os.environ.get("LLM_API")
11
  LLM_URL = os.environ.get("LLM_URL")
12
  USER_ID = "HuggingFace Space" # Placeholder user ID
13
 
 
 
 
 
 
 
 
 
 
 
14
  async def send_chat_message(LLM_URL, LLM_API, user_input):
15
  payload = {
16
  "inputs": {},
@@ -21,45 +31,47 @@ async def send_chat_message(LLM_URL, LLM_API, user_input):
21
  }
22
  print("Sending chat message payload:", payload) # Debug information
23
 
24
- async with aiohttp.ClientSession() as session:
25
- try:
26
- async with session.post(
27
- url=f"{LLM_URL}/chat-messages",
28
- headers={"Authorization": f"Bearer {LLM_API}"},
29
- json=payload,
30
- timeout=aiohttp.ClientTimeout(total=60)
31
- ) as response:
32
- if response.status != 200:
33
- print(f"Error: {response.status}")
34
- return f"Error: {response.status}"
35
-
36
- full_response = []
37
-
38
- async for line in response.content.iter_chunked(1024): # 設置分段大小為 1024 bytes
39
- line = line.decode('utf-8').strip()
40
- if not line:
41
- continue
42
- if "data: " not in line:
43
- continue
44
- try:
45
- print("Received line:", line) # Debug information
46
- data = json.loads(line.split("data: ")[1])
47
- if "answer" in data:
48
- decoded_answer = urllib.parse.unquote(data["answer"])
49
- full_response.append(decoded_answer)
50
- except (IndexError, json.JSONDecodeError) as e:
51
- print(f"Error parsing line: {line}, error: {e}") # Debug information
52
- continue
53
-
54
- if full_response:
55
- return ''.join(full_response).strip()
 
 
 
 
 
 
 
56
  else:
57
- return "Error: No response found in the response"
58
- except Exception as e:
59
- # 捕捉完整的異常訊息並打印出堆疊資訊
60
- print("Exception occurred in send_chat_message:")
61
- print(traceback.format_exc()) # 使用 traceback 輸出完整的錯誤堆疊
62
- return f"Exception: {e}"
63
 
64
  async def handle_input(user_input):
65
  print(f"Handling input: {user_input}")
 
11
  LLM_URL = os.environ.get("LLM_URL")
12
  USER_ID = "HuggingFace Space" # Placeholder user ID
13
 
14
+ import traceback
15
+ import aiohttp
16
+ import asyncio
17
+ import urllib.parse
18
+
19
+ # 設置重試次數和延遲
20
+ MAX_RETRIES = 3
21
+ RETRY_DELAY = 2 # 每次重試之間的延遲秒數
22
+ TIMEOUT_DURATION = 120 # 超時時間設定為 120 秒
23
+
24
  async def send_chat_message(LLM_URL, LLM_API, user_input):
25
  payload = {
26
  "inputs": {},
 
31
  }
32
  print("Sending chat message payload:", payload) # Debug information
33
 
34
+ for attempt in range(MAX_RETRIES):
35
+ async with aiohttp.ClientSession() as session:
36
+ try:
37
+ async with session.post(
38
+ url=f"{LLM_URL}/chat-messages",
39
+ headers={"Authorization": f"Bearer {LLM_API}"},
40
+ json=payload,
41
+ timeout=aiohttp.ClientTimeout(total=TIMEOUT_DURATION) # 增加超時時間
42
+ ) as response:
43
+ if response.status != 200:
44
+ print(f"Error: {response.status}")
45
+ return f"Error: {response.status}"
46
+
47
+ full_response = []
48
+ async for line in response.content.iter_chunked(1024):
49
+ line = line.decode('utf-8').strip()
50
+ if not line:
51
+ continue
52
+ if "data: " not in line:
53
+ continue
54
+ try:
55
+ print("Received line:", line) # Debug information
56
+ data = json.loads(line.split("data: ")[1])
57
+ if "answer" in data:
58
+ decoded_answer = urllib.parse.unquote(data["answer"])
59
+ full_response.append(decoded_answer)
60
+ except (IndexError, json.JSONDecodeError) as e:
61
+ print(f"Error parsing line: {line}, error: {e}")
62
+ continue
63
+
64
+ if full_response:
65
+ return ''.join(full_response).strip()
66
+ else:
67
+ return "Error: No response found in the response"
68
+ except (asyncio.TimeoutError, aiohttp.ClientError) as e:
69
+ print(f"Attempt {attempt + 1} failed with error: {e}")
70
+ print(traceback.format_exc()) # 顯示詳細的錯誤堆疊
71
+ if attempt < MAX_RETRIES - 1:
72
+ await asyncio.sleep(RETRY_DELAY) # 延遲後重試
73
  else:
74
+ return f"Exception: {e}"
 
 
 
 
 
75
 
76
  async def handle_input(user_input):
77
  print(f"Handling input: {user_input}")