alanchen1115 commited on
Commit
5eb369d
·
verified ·
1 Parent(s): 5d2a72b

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +44 -26
main.py CHANGED
@@ -194,29 +194,47 @@ def handle_message(event):
194
  agent_input = {"messages": [{"role": "user", "content": user_text}]}
195
  try:
196
  response = agent_executor.invoke(agent_input)
197
- raw_content = response["messages"][-1].content
198
- print(f"原始內容: {raw_content}")
199
-
200
  out = ""
201
- # 1. 判斷並提取內容
202
- if isinstance(raw_content, str):
203
- out = raw_content
204
- elif isinstance(raw_content, list):
205
- # 串接所有文字區塊
206
- out = "".join([block.get("text", "") for block in raw_content if isinstance(block, dict) and block.get("type") == "text"])
207
- elif isinstance(raw_content, dict):
208
- # 如果直接回傳字典 (如您的 Log 所示)
209
- # 優先抓取內容,如果沒內容就轉成字串避免出錯
210
- out = raw_content.get("imageUrl", str(raw_content))
211
-
212
- # 2. 搜尋 URL 邏輯 (修正 Regex 並過濾)
213
- # 使用 str(out) 確保處理的是字串
214
- urls = re.findall(r'https?://[^\s<>"\)]+|www\.[^\s<>"\)]+', str(out))
215
- image_url = next((u for u in urls if any(ext in u.lower() for ext in ['.png', '.jpg', '.jpeg', '.gif'])), None)
216
-
217
- # 3. 回覆邏輯
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
218
  if image_url:
219
- image_url = image_url.split(')')[0]
220
  line_bot_api.reply_message(
221
  event.reply_token,
222
  [
@@ -224,15 +242,15 @@ def handle_message(event):
224
  ImageSendMessage(original_content_url=image_url, preview_image_url=image_url)
225
  ]
226
  )
 
 
227
  else:
228
- # 確保 out 不是空的,否則 LINE 會報 400 錯誤
229
- final_text = out.strip() if out else "處理完成,但沒有文字內容。"
230
- line_bot_api.reply_message(event.reply_token, TextSendMessage(text=final_text))
231
 
232
  except Exception as e:
233
  print(f"Agent Error: {e}")
234
- # 同樣確保錯誤回覆不是空的
235
- line_bot_api.reply_message(event.reply_token, TextSendMessage(text="抱歉,系統處理時發生錯誤。"))
236
 
237
  if __name__ == "__main__":
238
  uvicorn.run(app, host="0.0.0.0", port=7860)
 
194
  agent_input = {"messages": [{"role": "user", "content": user_text}]}
195
  try:
196
  response = agent_executor.invoke(agent_input)
197
+ messages = response.get("messages", [])
198
+
 
199
  out = ""
200
+ image_url = None
201
+
202
+ # 1. 由後往前找,優先找出包含 imageUrl 的訊息
203
+ for msg in reversed(messages):
204
+ content = msg.content
205
+
206
+ # 如果內容是字典 (工具回傳的格式)
207
+ if isinstance(content, dict) and "imageUrl" in content:
208
+ image_url = content["imageUrl"]
209
+ break
210
+
211
+ # 如果內容是字串,嘗試從中提取網址
212
+ elif isinstance(content, str) and content.strip():
213
+ # 這裡用我們先前的 Regex 找找看
214
+ found_urls = re.findall(r'https?://[^\s<>"\)]+|www\.[^\s<>"\)]+', content)
215
+ img = next((u for u in found_urls if any(ext in u.lower() for ext in ['.png', '.jpg', '.jpeg', '.gif'])), None)
216
+ if img:
217
+ image_url = img.split(')')[0]
218
+ out = content # 保留文字內容
219
+ break
220
+ elif not out: # 如果還沒找到圖片,先暫存文字內容
221
+ out = content
222
+
223
+ # 如果內容是列表 (Gemini 2.5 有時會回傳 block list)
224
+ elif isinstance(content, list):
225
+ for block in content:
226
+ if isinstance(block, dict):
227
+ # 找圖片網址
228
+ text = block.get("text", "")
229
+ found_urls = re.findall(r'https?://[^\s<>"\)]+|www\.[^\s<>"\)]+', text)
230
+ img = next((u for u in found_urls if any(ext in u.lower() for ext in ['.png', '.jpg', '.jpeg', '.gif'])), None)
231
+ if img:
232
+ image_url = img.split(')')[0]
233
+ if text:
234
+ out += text
235
+
236
+ # 2. 最終回覆邏輯
237
  if image_url:
 
238
  line_bot_api.reply_message(
239
  event.reply_token,
240
  [
 
242
  ImageSendMessage(original_content_url=image_url, preview_image_url=image_url)
243
  ]
244
  )
245
+ elif out.strip():
246
+ line_bot_api.reply_message(event.reply_token, TextSendMessage(text=out.strip()))
247
  else:
248
+ # 萬一真什麼都沒有回報一個預設訊息,避免 LINE 400 錯誤
249
+ line_bot_api.reply_message(event.reply_token, TextSendMessage(text="圖片已生成,但我暫時無法取得連結,請稍後再試。"))
 
250
 
251
  except Exception as e:
252
  print(f"Agent Error: {e}")
253
+ line_bot_api.reply_message(event.reply_token, TextSendMessage(text="抱歉,我現在無法處理這個請求。"))
 
254
 
255
  if __name__ == "__main__":
256
  uvicorn.run(app, host="0.0.0.0", port=7860)