Spaces:
Sleeping
Sleeping
Commit ·
dddc990
1
Parent(s): e9b2abf
feat: add toolmessage result
Browse filesFiles changed (2)
- services/agents.py+30-43
- services/linebot.py+12-9
5 unmodified lines67891011121314151617181920212223194 unmodified lines2182192202212222232242252262272282292302312322332342352362372382392405 unmodified lines2462472482492502512522532542552562572 unmodified lines2602612622632642652662672682692702712722732742752762772782795 unmodified linesimport json # 匯入 json 庫用於序列化# LangChain 相關匯入#from langchain_core.prompts import ChatPromptTemplate # 匯入 LangChain 的聊天提示模板#from langchain_core.tools import tool # 匯入 LangChain 的工具裝飾器#from langchain_google_genai import ChatGoogleGenerativeAI # 匯入 LangChain 的 Google GenAI 聊天模型#from langchain.agents import create_tool_calling_agent#from langchain.agents import AgentExecutor # (若此行仍錯誤,則要改用 Runnable 方式)#from langchain.agents import initialize_agent#from langchain.agents import AgentTypefrom langchain.agents import create_agentfrom langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholderfrom langchain.tools import toolfrom langchain.messages import SystemMessage, HumanMessagefrom langchain_google_genai import ChatGoogleGenerativeAI194 unmodified linestemperature=0.2)# 建立提示模板#prompt_template = ChatPromptTemplate([# ("system",# """# 你是一個強大的圖像生成、圖像去模糊與問答助理,可以根據用戶的請求使用提供的工具。# ### 核心輸出規範# * **結果呈現**:當你執行以下任一圖像處理工具成功後,你最終的回答 output **必須包含該 URL 的完整資訊**:# * `generate_and_upload_image`# * `deblur_image_from_url` (或其他任何產生圖像輸出的工具)## * **錯誤處理**:如果工具有產生錯誤訊息,請解讀錯誤並以自然語言回應給用戶。# """# ), # 系統提示 (System Prompt)# ("user", "{input}"), # 用戶輸入的佔位符# ("placeholder", "{agent_scratchpad}"), # 代理人思考過程的佔位符#])# ✅ 建立 Prompt (新版語法)sys_prompt = """你是一個強大的圖像生成、圖像去模糊與問答助理,可以根據用戶的請求使用提供的工具。5 unmodified lines* **錯誤處理**:如果工具有產生錯誤訊息,請解讀錯誤並以自然語言回應給用戶。"""# 建立工具調用代理人 (Tool Calling Agent)#agent = create_tool_calling_agent(llm, tools, prompt_template)# 建立代理人執行器 (Agent Executor)#agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True) # verbose=True 會在終端印出代理人的思考過程# ✅ 使用 initialize_agent 取代 create_tool_calling_agent + AgentExecutor# --- 4. 建立代理人與執行器 ---# 建立工具調用代理人 (Tool Calling Agent)agent = create_agent(2 unmodified linessystem_prompt=sys_prompt)def run_agent(user_input: str):"""呼叫此函式來執行 Agent"""#human_msg = HumanMessage( user_input )#sys_msg = SystemMessage(sys_prompt)#messages = [# sys_msg,# human_msg#]print(f"UserInput:{user_input}")result = agent.invoke({"messages": [{"role": "user", "content": user_input }]})print(f"result:{result}")return {"output": result["messages"][-1].content}5 unmodified lines67891011121314194 unmodified lines2092102112122132145 unmodified lines2202212222232242252 unmodified lines2282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652665 unmodified linesimport json # 匯入 json 庫用於序列化# LangChain 相關匯入from langchain.agents import create_agentfrom langchain.tools import toolfrom langchain.messages import AIMessage, HumanMessage, ToolMessagefrom langchain_google_genai import ChatGoogleGenerativeAI194 unmodified linestemperature=0.2)# ✅ 建立 Prompt (新版語法)sys_prompt = """你是一個強大的圖像生成、圖像去模糊與問答助理,可以根據用戶的請求使用提供的工具。5 unmodified lines* **錯誤處理**:如果工具有產生錯誤訊息,請解讀錯誤並以自然語言回應給用戶。"""# --- 4. 建立代理人與執行器 ---# 建立工具調用代理人 (Tool Calling Agent)agent = create_agent(2 unmodified linessystem_prompt=sys_prompt)def format_agent_result(result):output = {"user": None,"tool_call": None,"tool_result": None,"final_response": None}for msg in result["messages"]:if isinstance(msg, HumanMessage):output["user"] = msg.contentelif isinstance(msg, AIMessage) and msg.additional_kwargs.get("function_call"):fn = msg.additional_kwargs["function_call"]output["tool_call"] = {"name": fn["name"],"arguments": fn["arguments"]}elif isinstance(msg, ToolMessage):output["tool_result"] = json.loads(msg.content)elif isinstance(msg, AIMessage) and not msg.additional_kwargs.get("function_call"):output["final_response"] = msg.contentreturn outputdef run_agent(user_input: str):"""呼叫此函式來執行 Agent"""print(f"UserInput:{user_input}")result = agent.invoke({"messages": [{"role": "user", "content": user_input }]})print(f"result:{result}")return { "output": format_agent_result( result ) }
140 unmodified lines14114214314414514614714814915015115215315415515615715811 unmodified lines170171172173174175176177178179180140 unmodified linesresponse = run_agent(agent_input)# Agent 的輸出是 JSON 字串 (無論成功或失敗)out_str = response["output"]# 2. 嘗試解析 JSON 輸出result = json.loads(out_str)if "error" in result:# 3A. 處理錯誤情況 (例如:圖片下載失敗、API 錯誤)error_msg = result["error"]reply_text = f"🚫 圖片工具執行失敗:\n{error_msg}"line_bot_api.reply_message(event.reply_token, TextSendMessage(text=reply_text))elif "image_url" in result:# 3B. 處理成功情況 (帶有圖片 URL,例如:圖片生成或去模糊工具)image_url = result["image_url"]text_result = result.get("text_result", "圖片處理完成。")# Line 要求圖片 URL 必須是 HTTPS# 由於 HF_SPACE 預設是 https,這裡做一個保險轉換11 unmodified lines])elif "text_result" in result:# 3C. 處理純文字結果 (例如:多模態分析工具)text_result = result["text_result"]line_bot_api.reply_message(event.reply_token, TextSendMessage(text=text_result))else:# 3D. 處理意外的 JSON 結構line_bot_api.reply_message(140 unmodified lines14114214314414514614714814915015115215315415515615715811 unmodified lines170171172173174175176177178179180181182183140 unmodified linesresponse = run_agent(agent_input)# Agent 的輸出是 JSON 字串 (無論成功或失敗)out_str = response["output"]tool_result = out_str.get("tool_result", {})final_response = out_str.get("final_response")if "error" in tool_result:# 3A. 處理錯誤情況 (例如:圖片下載失敗、API 錯誤)error_msg = tool_result["error"]reply_text = f"🚫 圖片工具執行失敗:\n{error_msg}"line_bot_api.reply_message(event.reply_token, TextSendMessage(text=reply_text))elif "image_url" in tool_result:# 3B. 處理成功情況 (帶有圖片 URL,例如:圖片生成或去模糊工具)image_url = tool_result["image_url"]text_result = tool_result.get("text_result", "圖片處理完成。")# Line 要求圖片 URL 必須是 HTTPS# 由於 HF_SPACE 預設是 https,這裡做一個保險轉換11 unmodified lines])elif "text_result" in tool_result:# 3C. 處理純文字結果 (例如:多模態分析工具)text_result = tool_result["text_result"]line_bot_api.reply_message(event.reply_token, TextSendMessage(text=text_result))elif final_response:line_bot_api.reply_message(event.reply_token, TextSendMessage(text=final_response))else:# 3D. 處理意外的 JSON 結構line_bot_api.reply_message(
services/agents.py+30-43
services/linebot.py+12-9