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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +44 -44
app.py CHANGED
@@ -17,9 +17,10 @@ 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 = {
@@ -29,49 +30,48 @@ async def send_chat_message(LLM_URL, LLM_API, user_input):
29
  "conversation_id": "",
30
  "user": USER_ID,
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}")
 
17
  import urllib.parse
18
 
19
  # 設置重試次數和延遲
20
+ MAX_RETRIES = 2
21
+ RETRY_DELAY = 1 # 每次重試之間的延遲秒數
22
  TIMEOUT_DURATION = 120 # 超時時間設定為 120 秒
23
+ MAX_RESPONSES = 10 # 設置最大接收數量,避免無限等待
24
 
25
  async def send_chat_message(LLM_URL, LLM_API, user_input):
26
  payload = {
 
30
  "conversation_id": "",
31
  "user": USER_ID,
32
  }
33
+ print("Sending chat message payload:", payload)
34
+
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
+
49
+ async for line in response.content.iter_chunked(2048): # 增大分段大小
50
+ line = line.decode('utf-8').strip()
51
+ if not line:
52
+ continue
53
+ if "data: " not in line:
54
+ continue
55
+ try:
56
+ print("Received line:", line)
57
+ data = json.loads(line.split("data: ")[1])
58
+ if "answer" in data:
59
+ decoded_answer = urllib.parse.unquote(data["answer"])
60
+ full_response.append(decoded_answer)
61
+ if len(full_response) >= MAX_RESPONSES: # 接收上限,避免無限等待
62
+ break
63
+ except (IndexError, json.JSONDecodeError) as e:
64
+ print(f"Error parsing line: {line}, error: {e}")
65
+ continue
66
+
67
+ if full_response:
68
+ return ''.join(full_response).strip()
 
 
 
 
 
69
  else:
70
+ return "Error: No response found in the response"
71
+ except Exception as e:
72
+ print("Exception occurred in send_chat_message:")
73
+ print(traceback.format_exc())
74
+ return f"Exception: {e}"
75
 
76
  async def handle_input(user_input):
77
  print(f"Handling input: {user_input}")