From d78a437de12702ed906cd320519f4000e50fd892 Mon Sep 17 00:00:00 2001 From: Logan Date: Tue, 17 Nov 2026 21:46:40 +0800 Subject: [PATCH 1/3] docs(zh-TW): translate the complete Agents Course for Taiwan --- units/zh-TW/_toctree.yml | 172 ++++++ units/zh-TW/bonus-unit1/conclusion.mdx | 13 + units/zh-TW/bonus-unit1/fine-tuning.mdx | 48 ++ units/zh-TW/bonus-unit1/introduction.mdx | 53 ++ .../bonus-unit1/what-is-function-calling.mdx | 77 +++ units/zh-TW/bonus-unit2/introduction.mdx | 33 ++ ...itoring-and-evaluating-agents-notebook.mdx | 433 +++++++++++++++ units/zh-TW/bonus-unit2/quiz.mdx | 132 +++++ ...-is-agent-observability-and-evaluation.mdx | 92 ++++ .../building_your_pokemon_agent.mdx | 259 +++++++++ units/zh-TW/bonus-unit3/conclusion.mdx | 18 + .../zh-TW/bonus-unit3/from-llm-to-agents.mdx | 37 ++ units/zh-TW/bonus-unit3/introduction.mdx | 26 + .../bonus-unit3/launching_agent_battle.mdx | 68 +++ units/zh-TW/bonus-unit3/state-of-art.mdx | 53 ++ units/zh-TW/communication/live1.mdx | 7 + units/zh-TW/unit0/discord101.mdx | 52 ++ units/zh-TW/unit0/introduction.mdx | 156 ++++++ units/zh-TW/unit0/onboarding.mdx | 94 ++++ units/zh-TW/unit1/README.md | 19 + units/zh-TW/unit1/actions.mdx | 121 +++++ .../zh-TW/unit1/agent-steps-and-structure.mdx | 150 ++++++ units/zh-TW/unit1/conclusion.mdx | 19 + units/zh-TW/unit1/dummy-agent-library.mdx | 329 ++++++++++++ units/zh-TW/unit1/final-quiz.mdx | 34 ++ units/zh-TW/unit1/introduction.mdx | 38 ++ .../unit1/messages-and-special-tokens.mdx | 228 ++++++++ units/zh-TW/unit1/observations.mdx | 44 ++ units/zh-TW/unit1/quiz1.mdx | 163 ++++++ units/zh-TW/unit1/quiz2.mdx | 119 +++++ units/zh-TW/unit1/thoughts.mdx | 83 +++ units/zh-TW/unit1/tools.mdx | 321 +++++++++++ units/zh-TW/unit1/tutorial.mdx | 244 +++++++++ units/zh-TW/unit1/what-are-agents.mdx | 158 ++++++ units/zh-TW/unit1/what-are-llms.mdx | 219 ++++++++ units/zh-TW/unit2/introduction.mdx | 40 ++ .../zh-TW/unit2/langgraph/building_blocks.mdx | 126 +++++ units/zh-TW/unit2/langgraph/conclusion.mdx | 21 + .../langgraph/document_analysis_agent.mdx | 267 ++++++++++ units/zh-TW/unit2/langgraph/first_graph.mdx | 374 +++++++++++++ units/zh-TW/unit2/langgraph/introduction.mdx | 31 ++ units/zh-TW/unit2/langgraph/quiz1.mdx | 118 +++++ .../unit2/langgraph/when_to_use_langgraph.mdx | 68 +++ units/zh-TW/unit2/llama-index/README.md | 15 + units/zh-TW/unit2/llama-index/agents.mdx | 161 ++++++ units/zh-TW/unit2/llama-index/components.mdx | 245 +++++++++ units/zh-TW/unit2/llama-index/conclusion.mdx | 13 + .../zh-TW/unit2/llama-index/introduction.mdx | 29 + units/zh-TW/unit2/llama-index/llama-hub.mdx | 56 ++ units/zh-TW/unit2/llama-index/quiz1.mdx | 117 ++++ units/zh-TW/unit2/llama-index/quiz2.mdx | 111 ++++ units/zh-TW/unit2/llama-index/tools.mdx | 142 +++++ units/zh-TW/unit2/llama-index/workflows.mdx | 280 ++++++++++ units/zh-TW/unit2/smolagents/code_agents.mdx | 394 ++++++++++++++ units/zh-TW/unit2/smolagents/conclusion.mdx | 11 + units/zh-TW/unit2/smolagents/final_quiz.mdx | 25 + units/zh-TW/unit2/smolagents/introduction.mdx | 66 +++ .../unit2/smolagents/multi_agent_systems.mdx | 412 +++++++++++++++ units/zh-TW/unit2/smolagents/quiz1.mdx | 142 +++++ units/zh-TW/unit2/smolagents/quiz2.mdx | 147 ++++++ .../unit2/smolagents/retrieval_agents.mdx | 167 ++++++ .../unit2/smolagents/tool_calling_agents.mdx | 73 +++ units/zh-TW/unit2/smolagents/tools.mdx | 322 +++++++++++ .../zh-TW/unit2/smolagents/vision_agents.mdx | 221 ++++++++ .../unit2/smolagents/why_use_smolagents.mdx | 66 +++ units/zh-TW/unit3/README.md | 0 units/zh-TW/unit3/agentic-rag/agent.mdx | 499 ++++++++++++++++++ units/zh-TW/unit3/agentic-rag/agentic-rag.mdx | 28 + units/zh-TW/unit3/agentic-rag/conclusion.mdx | 19 + .../zh-TW/unit3/agentic-rag/introduction.mdx | 39 ++ units/zh-TW/unit3/agentic-rag/invitees.mdx | 455 ++++++++++++++++ units/zh-TW/unit3/agentic-rag/tools.mdx | 431 +++++++++++++++ units/zh-TW/unit4/additional-readings.mdx | 30 ++ units/zh-TW/unit4/conclusion.mdx | 11 + units/zh-TW/unit4/get-your-certificate.mdx | 21 + units/zh-TW/unit4/hands-on.mdx | 52 ++ units/zh-TW/unit4/introduction.mdx | 23 + units/zh-TW/unit4/what-is-gaia.mdx | 70 +++ 78 files changed, 10050 insertions(+) create mode 100644 units/zh-TW/_toctree.yml create mode 100644 units/zh-TW/bonus-unit1/conclusion.mdx create mode 100644 units/zh-TW/bonus-unit1/fine-tuning.mdx create mode 100644 units/zh-TW/bonus-unit1/introduction.mdx create mode 100644 units/zh-TW/bonus-unit1/what-is-function-calling.mdx create mode 100644 units/zh-TW/bonus-unit2/introduction.mdx create mode 100644 units/zh-TW/bonus-unit2/monitoring-and-evaluating-agents-notebook.mdx create mode 100644 units/zh-TW/bonus-unit2/quiz.mdx create mode 100644 units/zh-TW/bonus-unit2/what-is-agent-observability-and-evaluation.mdx create mode 100644 units/zh-TW/bonus-unit3/building_your_pokemon_agent.mdx create mode 100644 units/zh-TW/bonus-unit3/conclusion.mdx create mode 100644 units/zh-TW/bonus-unit3/from-llm-to-agents.mdx create mode 100644 units/zh-TW/bonus-unit3/introduction.mdx create mode 100644 units/zh-TW/bonus-unit3/launching_agent_battle.mdx create mode 100644 units/zh-TW/bonus-unit3/state-of-art.mdx create mode 100644 units/zh-TW/communication/live1.mdx create mode 100644 units/zh-TW/unit0/discord101.mdx create mode 100644 units/zh-TW/unit0/introduction.mdx create mode 100644 units/zh-TW/unit0/onboarding.mdx create mode 100644 units/zh-TW/unit1/README.md create mode 100644 units/zh-TW/unit1/actions.mdx create mode 100644 units/zh-TW/unit1/agent-steps-and-structure.mdx create mode 100644 units/zh-TW/unit1/conclusion.mdx create mode 100644 units/zh-TW/unit1/dummy-agent-library.mdx create mode 100644 units/zh-TW/unit1/final-quiz.mdx create mode 100644 units/zh-TW/unit1/introduction.mdx create mode 100644 units/zh-TW/unit1/messages-and-special-tokens.mdx create mode 100644 units/zh-TW/unit1/observations.mdx create mode 100644 units/zh-TW/unit1/quiz1.mdx create mode 100644 units/zh-TW/unit1/quiz2.mdx create mode 100644 units/zh-TW/unit1/thoughts.mdx create mode 100644 units/zh-TW/unit1/tools.mdx create mode 100644 units/zh-TW/unit1/tutorial.mdx create mode 100644 units/zh-TW/unit1/what-are-agents.mdx create mode 100644 units/zh-TW/unit1/what-are-llms.mdx create mode 100644 units/zh-TW/unit2/introduction.mdx create mode 100644 units/zh-TW/unit2/langgraph/building_blocks.mdx create mode 100644 units/zh-TW/unit2/langgraph/conclusion.mdx create mode 100644 units/zh-TW/unit2/langgraph/document_analysis_agent.mdx create mode 100644 units/zh-TW/unit2/langgraph/first_graph.mdx create mode 100644 units/zh-TW/unit2/langgraph/introduction.mdx create mode 100644 units/zh-TW/unit2/langgraph/quiz1.mdx create mode 100644 units/zh-TW/unit2/langgraph/when_to_use_langgraph.mdx create mode 100644 units/zh-TW/unit2/llama-index/README.md create mode 100644 units/zh-TW/unit2/llama-index/agents.mdx create mode 100644 units/zh-TW/unit2/llama-index/components.mdx create mode 100644 units/zh-TW/unit2/llama-index/conclusion.mdx create mode 100644 units/zh-TW/unit2/llama-index/introduction.mdx create mode 100644 units/zh-TW/unit2/llama-index/llama-hub.mdx create mode 100644 units/zh-TW/unit2/llama-index/quiz1.mdx create mode 100644 units/zh-TW/unit2/llama-index/quiz2.mdx create mode 100644 units/zh-TW/unit2/llama-index/tools.mdx create mode 100644 units/zh-TW/unit2/llama-index/workflows.mdx create mode 100644 units/zh-TW/unit2/smolagents/code_agents.mdx create mode 100644 units/zh-TW/unit2/smolagents/conclusion.mdx create mode 100644 units/zh-TW/unit2/smolagents/final_quiz.mdx create mode 100644 units/zh-TW/unit2/smolagents/introduction.mdx create mode 100644 units/zh-TW/unit2/smolagents/multi_agent_systems.mdx create mode 100644 units/zh-TW/unit2/smolagents/quiz1.mdx create mode 100644 units/zh-TW/unit2/smolagents/quiz2.mdx create mode 100644 units/zh-TW/unit2/smolagents/retrieval_agents.mdx create mode 100644 units/zh-TW/unit2/smolagents/tool_calling_agents.mdx create mode 100644 units/zh-TW/unit2/smolagents/tools.mdx create mode 100644 units/zh-TW/unit2/smolagents/vision_agents.mdx create mode 100644 units/zh-TW/unit2/smolagents/why_use_smolagents.mdx create mode 100644 units/zh-TW/unit3/README.md create mode 100644 units/zh-TW/unit3/agentic-rag/agent.mdx create mode 100644 units/zh-TW/unit3/agentic-rag/agentic-rag.mdx create mode 100644 units/zh-TW/unit3/agentic-rag/conclusion.mdx create mode 100644 units/zh-TW/unit3/agentic-rag/introduction.mdx create mode 100644 units/zh-TW/unit3/agentic-rag/invitees.mdx create mode 100644 units/zh-TW/unit3/agentic-rag/tools.mdx create mode 100644 units/zh-TW/unit4/additional-readings.mdx create mode 100644 units/zh-TW/unit4/conclusion.mdx create mode 100644 units/zh-TW/unit4/get-your-certificate.mdx create mode 100644 units/zh-TW/unit4/hands-on.mdx create mode 100644 units/zh-TW/unit4/introduction.mdx create mode 100644 units/zh-TW/unit4/what-is-gaia.mdx diff --git a/units/zh-TW/_toctree.yml b/units/zh-TW/_toctree.yml new file mode 100644 index 000000000..1ea391ce9 --- /dev/null +++ b/units/zh-TW/_toctree.yml @@ -0,0 +1,172 @@ +- title: 第 0 單元:歡迎加入課程 + sections: + - local: unit0/introduction + title: 歡迎加入課程 🤗 + - local: unit0/onboarding + title: 課前準備 + - local: unit0/discord101 + title: (選修)Discord 入門 +- title: 直播 1:課程進行方式與問答 + sections: + - local: communication/live1 + title: 直播 1:課程進行方式與問答 +- title: 第 1 單元:agent 入門 + sections: + - local: unit1/introduction + title: 簡介 + - local: unit1/what-are-agents + title: 什麼是 agent? + - local: unit1/quiz1 + title: 隨堂測驗 1 + - local: unit1/what-are-llms + title: 什麼是 LLM? + - local: unit1/messages-and-special-tokens + title: 訊息與特殊 token + - local: unit1/tools + title: 什麼是工具? + - local: unit1/quiz2 + title: 隨堂測驗 2 + - local: unit1/agent-steps-and-structure + title: 透過思考、行動與觀察循環理解 AI agent + - local: unit1/thoughts + title: 思考、內部推理與 Re-Act 方法 + - local: unit1/actions + title: 行動:讓 agent 與環境互動 + - local: unit1/observations + title: 觀察:整合回饋以反思與調整 + - local: unit1/dummy-agent-library + title: 簡易 agent 函式庫 + - local: unit1/tutorial + title: 使用 smolagents 建立第一個 agent + - local: unit1/final-quiz + title: 第 1 單元總測驗 + - local: unit1/conclusion + title: 結語 +- title: 第 2 單元:AI agent 框架 + sections: + - local: unit2/introduction + title: AI agent 框架 +- title: 第 2.1 單元:smolagents 框架 + sections: + - local: unit2/smolagents/introduction + title: smolagents 簡介 + - local: unit2/smolagents/why_use_smolagents + title: 為什麼使用 smolagents? + - local: unit2/smolagents/quiz1 + title: 隨堂測驗 1 + - local: unit2/smolagents/code_agents + title: 建立使用程式碼的 agent + - local: unit2/smolagents/tool_calling_agents + title: 以程式碼片段或 JSON 撰寫行動 + - local: unit2/smolagents/tools + title: 工具 + - local: unit2/smolagents/retrieval_agents + title: 檢索 agent + - local: unit2/smolagents/quiz2 + title: 隨堂測驗 2 + - local: unit2/smolagents/multi_agent_systems + title: 多 agent 系統 + - local: unit2/smolagents/vision_agents + title: 視覺與瀏覽器 agent + - local: unit2/smolagents/final_quiz + title: 總測驗 + - local: unit2/smolagents/conclusion + title: 結語 +- title: 第 2.2 單元:LlamaIndex 框架 + sections: + - local: unit2/llama-index/introduction + title: LlamaIndex 簡介 + - local: unit2/llama-index/llama-hub + title: LlamaHub 簡介 + - local: unit2/llama-index/components + title: LlamaIndex 中的元件是什麼? + - local: unit2/llama-index/tools + title: 在 LlamaIndex 中使用工具 + - local: unit2/llama-index/quiz1 + title: 隨堂測驗 1 + - local: unit2/llama-index/agents + title: 在 LlamaIndex 中使用 agent + - local: unit2/llama-index/workflows + title: 在 LlamaIndex 中建立 agentic 工作流程 + - local: unit2/llama-index/quiz2 + title: 隨堂測驗 2 + - local: unit2/llama-index/conclusion + title: 結語 +- title: 第 2.3 單元:LangGraph 框架 + sections: + - local: unit2/langgraph/introduction + title: LangGraph 簡介 + - local: unit2/langgraph/when_to_use_langgraph + title: 什麼是 LangGraph? + - local: unit2/langgraph/building_blocks + title: LangGraph 的基本元件 + - local: unit2/langgraph/first_graph + title: 建立第一個 LangGraph + - local: unit2/langgraph/document_analysis_agent + title: 文件分析圖 + - local: unit2/langgraph/quiz1 + title: 隨堂測驗 1 + - local: unit2/langgraph/conclusion + title: 結語 +- title: 第 3 單元:Agentic RAG 應用案例 + sections: + - local: unit3/agentic-rag/introduction + title: Agentic RAG 應用案例簡介 + - local: unit3/agentic-rag/agentic-rag + title: Agentic 檢索增強生成(RAG) + - local: unit3/agentic-rag/invitees + title: 為賓客故事建立 RAG 工具 + - local: unit3/agentic-rag/tools + title: 為 agent 建立並整合工具 + - local: unit3/agentic-rag/agent + title: 建立晚宴 agent + - local: unit3/agentic-rag/conclusion + title: 結語 +- title: 第 4 單元:期末專案——建立、測試並認證你的 agent + sections: + - local: unit4/introduction + title: 最後一個單元簡介 + - local: unit4/what-is-gaia + title: 什麼是 GAIA? + - local: unit4/hands-on + title: 期末實作 + - local: unit4/get-your-certificate + title: 取得卓越證書 + - local: unit4/conclusion + title: 課程結語 + - local: unit4/additional-readings + title: 接下來該學什麼? +- title: 加碼單元 1:微調 LLM 以支援函式呼叫 + sections: + - local: bonus-unit1/introduction + title: 簡介 + - local: bonus-unit1/what-is-function-calling + title: 什麼是函式呼叫? + - local: bonus-unit1/fine-tuning + title: 微調模型以支援函式呼叫 + - local: bonus-unit1/conclusion + title: 結語 +- title: 加碼單元 2:agent 可觀測性與評估 + sections: + - local: bonus-unit2/introduction + title: 簡介 + - local: bonus-unit2/what-is-agent-observability-and-evaluation + title: 什麼是 agent 可觀測性與評估? + - local: bonus-unit2/monitoring-and-evaluating-agents-notebook + title: 監控與評估 agent + - local: bonus-unit2/quiz + title: 測驗 +- title: 加碼單元 3:寶可夢遊戲中的 agent + sections: + - local: bonus-unit3/introduction + title: 簡介 + - local: bonus-unit3/state-of-art + title: 在遊戲中運用 LLM 的最新進展 + - local: bonus-unit3/from-llm-to-agents + title: 從 LLM 到 AI agent + - local: bonus-unit3/building_your_pokemon_agent + title: 建立自己的寶可夢對戰 agent + - local: bonus-unit3/launching_agent_battle + title: 啟動寶可夢對戰 agent + - local: bonus-unit3/conclusion + title: 結語 diff --git a/units/zh-TW/bonus-unit1/conclusion.mdx b/units/zh-TW/bonus-unit1/conclusion.mdx new file mode 100644 index 000000000..a4d109414 --- /dev/null +++ b/units/zh-TW/bonus-unit1/conclusion.mdx @@ -0,0 +1,13 @@ +# 結語 [[conclusion]] + +恭喜你完成第一個附加單元 🥳 + +你已經**了解函式呼叫的原理,也學會如何微調模型,讓它具備函式呼叫能力**! + +接下來,我們建議你試著**微調不同的模型**。**親自嘗試,就是最好的學習方式。** + +在下一個單元,你將學習使用 **`smolagents`、`LlamaIndex` 和 `LangGraph` 等先進框架**。 + +最後,我們很想**聽聽你對課程的想法,以及有哪些地方可以改進**。如果你有任何建議,請 👉 [填寫這份表單](https://docs.google.com/forms/d/e/1FAIpQLSe9VaONn0eglax0uTwi29rIn4tM7H2sYmmybmG5jJNlE5v0xA/viewform?usp=dialog) + +### 持續學習,繼續發光 🤗 \ No newline at end of file diff --git a/units/zh-TW/bonus-unit1/fine-tuning.mdx b/units/zh-TW/bonus-unit1/fine-tuning.mdx new file mode 100644 index 000000000..277939c1e --- /dev/null +++ b/units/zh-TW/bonus-unit1/fine-tuning.mdx @@ -0,0 +1,48 @@ +# 微調模型,讓它學會函式呼叫 + +現在,我們準備好微調第一個具備函式呼叫能力的模型了 🔥。 + +## 如何訓練模型進行函式呼叫? + +> 答案:我們需要**資料** + +模型訓練可以分成 3 個步驟: + +1. **先以大量資料預訓練模型**,得到**預訓練模型**,例如 [google/gemma-2-2b](https://huggingface.co/google/gemma-2-2b)。這是基礎模型,只會**預測下一個 token,還不太能遵循指令**。 + +2. 為了用於對話,模型接著需要經過**微調**,學會遵循指令。這一步可以由模型開發者、開源社群、你,或任何人來訓練。例如,[google/gemma-2-2b-it](https://huggingface.co/google/gemma-2-2b-it) 就是 Gemma 專案的 Google 團隊完成指令微調的模型。 + +3. 接著,可以讓模型**對齊**開發者的偏好。例如,客服聊天模型必須始終禮貌地對待客戶。 + +通常,Gemini 或 Mistral 這類完整產品**會經過全部 3 個步驟**;你在 Hugging Face 上找到的模型,則可能完成了其中一個或多個步驟。 + +在本教學中,我們會以 [google/gemma-2-2b-it](https://huggingface.co/google/gemma-2-2b-it) 為基礎,建立函式呼叫模型。我們選擇經過微調的 [google/gemma-2-2b-it](https://huggingface.co/google/gemma-2-2b-it),而非基礎模型 [google/gemma-2-2b](https://huggingface.co/google/gemma-2-2b),因為微調後的模型更適合我們的使用情境。 + +如果從預訓練模型開始,**就需要更多訓練,才能學會遵循指令、對話,以及函式呼叫**。 + +從完成指令微調的模型開始,**就能盡量減少模型還需要學習的資訊量**。 + +## LoRA(大型語言模型的低秩適應) + +LoRA 是一種常見的輕量訓練技術,能大幅**減少需要訓練的參數數量**。 + +它的做法是**在待訓練的模型中插入少量新權重,作為 adapter(適配器)**。這讓 LoRA 訓練更快、更節省記憶體,產生的模型權重也更小(數百 MB),便於儲存與分享。 + +LoRA inference + +LoRA 會在 Transformer 層中加入成對的秩分解矩陣,通常以線性層為主。訓練時,我們會「凍結」模型的其餘部分,只更新新增 adapter 的權重。 + +因為只需要更新 adapter 的權重,需要訓練的**參數**數量就能大幅減少。 + +推論時,輸入會送入 adapter 和基礎模型;也可以先將 adapter 的權重合併到基礎模型中,這樣就不會增加額外延遲。 + +LoRA 特別適合讓**大型**語言模型適應特定任務或領域,同時將資源需求控制在可負擔的範圍內,也能減少訓練模型**所需**的記憶體。 + +如果想進一步了解 LoRA 的運作原理,可以參考這份[教學](https://huggingface.co/learn/nlp-course/chapter11/4?fw=pt)。 + +## 微調模型,加入函式呼叫能力 + +你可以在 👉 [這裡](https://huggingface.co/agents-course/notebooks/blob/main/bonus-unit1/bonus-unit1.ipynb) 開啟教學 notebook。 + +接著點選 [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/#fileId=https://huggingface.co/agents-course/notebooks/blob/main/bonus-unit1/bonus-unit1.ipynb),就能在 Colab Notebook 中執行。 + diff --git a/units/zh-TW/bonus-unit1/introduction.mdx b/units/zh-TW/bonus-unit1/introduction.mdx new file mode 100644 index 000000000..590c0b111 --- /dev/null +++ b/units/zh-TW/bonus-unit1/introduction.mdx @@ -0,0 +1,53 @@ +# 簡介 + +![附加單元 1 縮圖](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/bonus-unit1/thumbnail.jpg) + +歡迎來到第一個**附加單元**!你將學習**微調大型語言模型(LLM),讓它具備函式呼叫能力**。 + +對 LLM 而言,函式呼叫正迅速成為一項*必備*技術。 + +我們在第 1 單元只依靠 prompt 來引導模型;函式呼叫則讓模型在**訓練階段就學會採取行動、解讀觀察結果**,使 AI 更穩健。 + +> **什麼時候適合學習這個附加單元?** +> +> 本單元為**選修**,內容比第 1 單元進階。你可以現在開始,也可以等透過課程累積更多知識後再回來學習。 +> +> 不用擔心,本單元會提供所需的資訊。即使你還不了解微調的內部原理,我們也會帶你認識微調函式呼叫模型的每個核心概念。 + +如果具備以下知識,學習本單元會更順利: + +1. 知道如何使用 Transformers 微調 LLM。如果還不熟悉,請[參考這份教學](https://huggingface.co/learn/nlp-course/chapter3/1?fw=pt)。 + +2. 知道如何使用 `SFTTrainer` 微調模型。詳情請[參閱這份文件](https://huggingface.co/learn/nlp-course/en/chapter11/1)。 + +--- + +## 你將學到什麼 + +1. **函式呼叫(Function Calling)** + 現代 LLM 如何組織對話,讓模型能夠觸發**工具**。 + +2. **LoRA(低秩適應)** + 一種**輕量、高效率**的微調方法,能減少運算與儲存需求。LoRA 讓大型模型的訓練*更快、成本更低,也更容易*部署。 + +3. **函式呼叫模型中的思考 → 行動 → 觀察循環** + 以簡單而強大的方式,組織模型決定何時及如何呼叫函式、追蹤中間步驟,以及解讀外部工具或 API 結果的流程。 + +4. **新的特殊 token** + 我們會介紹**特殊標記**,幫助模型區分: + - 內部的「思維鏈」推理 + - 對外發出的函式呼叫 + - 外部工具回傳的回應 + +--- + +完成本附加單元後,你將能夠: + +- **了解**工具相關 API 的內部運作原理。 +- 使用 LoRA 技術**微調**模型。 +- **實作**與**修改**思考 → 行動 → 觀察循環,建立穩健、容易維護的函式呼叫工作流程。 +- **設計與使用**特殊 token,明確區分模型的內部推理與對外行動。 + +你也將**親手微調出具備函式呼叫能力的模型。** 🔥 + +一起來認識**函式呼叫**吧! diff --git a/units/zh-TW/bonus-unit1/what-is-function-calling.mdx b/units/zh-TW/bonus-unit1/what-is-function-calling.mdx new file mode 100644 index 000000000..2d960e7a1 --- /dev/null +++ b/units/zh-TW/bonus-unit1/what-is-function-calling.mdx @@ -0,0 +1,77 @@ +# 什麼是函式呼叫? + +函式呼叫是 **LLM 對環境採取行動的一種方式**。這項功能最早[於 GPT-4 推出](https://openai.com/index/function-calling-and-other-api-updates/),後來其他模型也陸續採用。 + +如同 agent 使用工具,函式呼叫讓模型能夠**對環境採取行動**。不過,函式呼叫能力是**模型透過學習取得的**,**對 prompt 的依賴比其他 agent 技術更少**。 + +在第 1 單元,agent **並未經過使用工具的訓練**。我們只是提供工具清單,再仰賴模型**將既有能力泛化,規劃如何使用這些工具**。 + +這裡則會**透過微調(訓練),讓 agent 學會使用工具,進行函式呼叫**。 + +## 模型如何「學會」採取行動? + +在第 1 單元,我們探討過 agent 的一般工作流程。使用者提供工具,再以查詢作為 prompt 後,模型便會重複以下循環: + +1. *思考*:為了達成目標,需要採取哪些行動? +2. *行動*:以正確的參數格式輸出行動,然後停止生成。 +3. *觀察*:取得執行結果。 + +透過 API 與模型進行「一般」對話時,使用者與助理的訊息會交替出現,如下所示: + +```python +conversation = [ + {"role": "user", "content": "I need help with my order"}, + {"role": "assistant", "content": "I'd be happy to help. Could you provide your order number?"}, + {"role": "user", "content": "It's ORDER-123"}, +] +``` + +函式呼叫為對話帶來了**新的角色**! + +1. 一個代表**行動**的新角色 +2. 一個代表**觀察**的新角色 + +以 [Mistral API](https://docs.mistral.ai/capabilities/function_calling/) 為例,對話會像這樣: + +```python +conversation = [ + { + "role": "user", + "content": "What's the status of my transaction T1001?" + }, + { + "role": "assistant", + "content": "", + "function_call": { + "name": "retrieve_payment_status", + "arguments": "{\"transaction_id\": \"T1001\"}" + } + }, + { + "role": "tool", + "name": "retrieve_payment_status", + "content": "{\"status\": \"Paid\"}" + }, + { + "role": "assistant", + "content": "Your transaction T1001 has been successfully paid." + } +] +``` + +> ……可是,你不是說函式呼叫會有新的角色嗎? + +**是,也不完全是。** 在這個例子和許多其他 API 中,模型會將要採取的行動格式化為「assistant」訊息。聊天範本接著會以函式呼叫的**特殊 token** 表示它。 + +- `[AVAILABLE_TOOLS]` – 可用工具清單的起點 +- `[/AVAILABLE_TOOLS]` – 可用工具清單的終點 +- `[TOOL_CALLS]` – 呼叫工具(也就是採取「行動」) +- `[TOOL_RESULTS]` – 「觀察」行動結果 +- `[/TOOL_RESULTS]` – 觀察結束(模型可以再次解碼) + +課程後續還會談到函式呼叫。如果想深入了解,也可以參閱[這份詳盡的文件](https://docs.mistral.ai/capabilities/function_calling/)。 + +--- +現在,我們已經了解函式呼叫的概念與運作方式。接下來,要在模型中加入新的特殊 token,**讓原本還不具備這項能力的模型學會函式呼叫**:[google/gemma-2-2b-it](https://huggingface.co/google/gemma-2-2b-it)。 + +在開始之前,**我們得先了解微調與 LoRA**。 diff --git a/units/zh-TW/bonus-unit2/introduction.mdx b/units/zh-TW/bonus-unit2/introduction.mdx new file mode 100644 index 000000000..2e4fa9a3c --- /dev/null +++ b/units/zh-TW/bonus-unit2/introduction.mdx @@ -0,0 +1,33 @@ +# AI agent 的可觀測性與評估 + +![附加單元 2 縮圖](https://langfuse.com/images/cookbook/huggingface-agent-course/agent-observability-and-evaluation.png) + +歡迎來到**附加單元 2**!本章將介紹觀察、評估 agent 的進階策略,幫助你持續改善 agent 的表現。 + +--- + +## 📚 什麼時候適合學習這個附加單元? + +如果你有以下需求,這個單元很適合你: +- **開發與部署 AI agent:** 希望確保 agent 在正式環境中穩定可靠。 +- **深入了解運作細節:** 想要診斷問題、改善效能,或了解 agent 的內部運作。 +- **降低維運負擔:** 透過監控 agent 的成本、延遲與執行細節,有效率地管理資源。 +- **持續改進:** 希望在 AI 應用程式中整合即時使用者回饋與自動化評估。 + +也就是說,只要你想讓使用者實際使用 agent,這個單元就適合你! + +--- + +## 🤓 你將學到什麼 + +在本單元,你將學習: +- **為 agent 加入監測:** 透過 OpenTelemetry,將可觀測性工具與 *smolagents* 框架整合。 +- **監控指標:** 追蹤 token 用量(成本)、延遲、錯誤追蹤等效能指標。 +- **即時評估:** 了解線上評估技巧,包括收集使用者回饋,以及讓 LLM 擔任評審。 +- **離線分析:** 使用 GSM8K 等基準資料集,測試與比較 agent 的表現。 + +--- + +## 🚀 準備好開始了嗎? + +下一節會介紹 agent 可觀測性與評估的基礎概念,接著就一起動手實作! \ No newline at end of file diff --git a/units/zh-TW/bonus-unit2/monitoring-and-evaluating-agents-notebook.mdx b/units/zh-TW/bonus-unit2/monitoring-and-evaluating-agents-notebook.mdx new file mode 100644 index 000000000..b1000d813 --- /dev/null +++ b/units/zh-TW/bonus-unit2/monitoring-and-evaluating-agents-notebook.mdx @@ -0,0 +1,433 @@ + + +# 附加單元 2:agent 的可觀測性與評估 + +> [!TIP] +> 你可以在這份 notebook 中跟著程式碼練習,並使用 Google Colab 執行。 + +這份 notebook 將介紹如何使用開源可觀測性工具,**監控 AI agent 的內部步驟(trace)**,以及**評估它的表現**。 + +觀察與評估 agent 的行為,是完成下列工作的關鍵: +- 當任務失敗或結果不理想時除錯 +- 即時監控成本與效能 +- 透過持續回饋,提高可靠性與安全性 + +## 練習所需的先備知識 🏗️ + +執行這份 notebook 前,請確認你已經: + +🔲 📚 **學過** [agent 簡介](https://huggingface.co/learn/agents-course/unit1/introduction) + +🔲 📚 **學過** [smolagents 框架](https://huggingface.co/learn/agents-course/unit2/smolagents/introduction) + +## 步驟 0:安裝所需的函式庫 + +我們需要幾個函式庫,才能執行、監控與評估 agent: + +```python +%pip install langfuse 'smolagents[telemetry]' openinference-instrumentation-smolagents datasets 'smolagents[gradio]' gradio --upgrade +``` + +## 步驟 1:為 agent 加入監測 + +這份 notebook 使用 [Langfuse](https://langfuse.com/) 作為可觀測性工具,但你也可以使用**其他相容於 OpenTelemetry 的服務**。以下程式碼示範如何設定 Langfuse(或其他 OTel 端點)的環境變數,以及如何為 smolagent 加入監測。 + +**注意:** 如果你使用 LlamaIndex 或 LangGraph,可以分別參閱[這份](https://langfuse.com/docs/integrations/llama-index/workflows)與[這份](https://langfuse.com/docs/integrations/langchain/example-python-langgraph)監測整合文件。 + +首先,將 Langfuse 憑證設為環境變數。你可以註冊 [Langfuse Cloud](https://cloud.langfuse.com),或[自行架設 Langfuse](https://langfuse.com/self-hosting),取得 Langfuse API 金鑰。 + +```python +import os +# Get keys for your project from the project settings page: https://cloud.langfuse.com +os.environ["LANGFUSE_PUBLIC_KEY"] = "pk-lf-..." +os.environ["LANGFUSE_SECRET_KEY"] = "sk-lf-..." +os.environ["LANGFUSE_HOST"] = "https://cloud.langfuse.com" # 🇪🇺 EU region +# os.environ["LANGFUSE_HOST"] = "https://us.cloud.langfuse.com" # 🇺🇸 US region +``` +我們也需要設定 Hugging Face token,供推論呼叫使用。 + +```python +# Set your Hugging Face and other tokens/secrets as environment variable +os.environ["HF_TOKEN"] = "hf_..." +``` + +設定好環境變數後,就能初始化 Langfuse client。`get_client()` 會使用環境變數中的憑證初始化 client。 + +```python +from langfuse import get_client + +langfuse = get_client() + +# Verify connection +if langfuse.auth_check(): + print("Langfuse client is authenticated and ready!") +else: + print("Authentication failed. Please check your credentials and host.") +``` + +接著,設定 `SmolagentsInstrumentor()`,為 smolagent 加入監測,並將 trace 傳送到 Langfuse。 + +```python +from openinference.instrumentation.smolagents import SmolagentsInstrumentor + +SmolagentsInstrumentor().instrument() +``` + +## 步驟 2:測試監測是否正常 + +以下是一個簡單的 smolagents CodeAgent,用來計算 `1+1`。執行它,就能確認監測功能是否正常。如果設定正確,你會在可觀測性儀表板看到日誌與 span。 + +```python +from smolagents import InferenceClientModel, CodeAgent + +# Create a simple agent to test instrumentation +agent = CodeAgent( + tools=[], + model=InferenceClientModel() +) + +agent.run("1+1=") +``` + +查看 [Langfuse Traces 儀表板](https://cloud.langfuse.com)(或你選用的可觀測性工具),確認 span 與日誌已記錄下來。 + +以下是 Langfuse 的畫面範例: + +![Langfuse 中的 trace 範例](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/bonus-unit2/first-example-trace.png) + +_[查看 trace](https://cloud.langfuse.com/project/cloramnkj0002jz088vzn1ja4/traces/1b94d6888258e0998329cdb72a371155?timestamp=2025-03-10T11%3A59%3A41.743Z)_ + +## 步驟 3:觀察與評估更複雜的 agent + +確認監測功能正常後,來試試更複雜的查詢,看看 token 用量、延遲、成本等進階指標是如何追蹤的。 + +```python +from smolagents import (CodeAgent, DuckDuckGoSearchTool, InferenceClientModel) + +search_tool = DuckDuckGoSearchTool() +agent = CodeAgent(tools=[search_tool], model=InferenceClientModel()) + +agent.run("How many Rubik's Cubes could you fit inside the Notre Dame Cathedral?") +``` + +### Trace 結構 + +多數可觀測性工具會記錄包含多個 **span** 的 **trace**,每個 span 代表 agent 邏輯中的一個步驟。這裡的 trace 包含 agent 的完整執行過程,以及下列操作的子 span: +- 工具呼叫(DuckDuckGoSearchTool) +- LLM 呼叫(InferenceClientModel) + +你可以檢查這些紀錄,精確了解時間花在哪裡、用了多少 token 等資訊: + +![Langfuse 中的 trace 樹狀圖](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/bonus-unit2/trace-tree.png) + +_[查看 trace](https://cloud.langfuse.com/project/cloramnkj0002jz088vzn1ja4/traces/1ac33b89ffd5e75d4265b62900c348ed?timestamp=2025-03-07T13%3A45%3A09.149Z&display=preview)_ + +## 線上評估 + +上一節介紹了線上與離線評估的差異。現在,我們來看看如何在正式環境監控 agent,並即時評估它。 + +### 正式環境中常見的追蹤指標 + +1. **成本** — smolagents 的監測功能會記錄 token 用量。只要指定每個 token 的價格,就能換算出大約成本。 +2. **延遲** — 觀察每個步驟或整次執行所需的時間。 +3. **使用者回饋** — 使用者可以直接按讚或倒讚,幫助你調整或修正 agent。 +4. **LLM-as-a-Judge** — 使用另一個 LLM,近乎即時地評估 agent 的輸出,例如檢查有害內容或正確性。 + +以下會示範這些指標。 + +#### 1. 成本 + +下圖顯示呼叫 `Qwen2.5-Coder-32B-Instruct` 的用量,能幫助你找出成本較高的步驟,改善 agent。 + +![成本](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/bonus-unit2/smolagents-costs.png) + +_[查看 trace](https://cloud.langfuse.com/project/cloramnkj0002jz088vzn1ja4/traces/1ac33b89ffd5e75d4265b62900c348ed?timestamp=2025-03-07T13%3A45%3A09.149Z&display=preview)_ + +#### 2. 延遲 + +我們也能看到完成各步驟花了多久。下例的整段對話花了 32 秒,你可以進一步拆解各步驟的耗時,找出瓶頸並改善 agent。 + +![延遲](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/bonus-unit2/smolagents-latency.png) + +_[查看 trace](https://cloud.langfuse.com/project/cloramnkj0002jz088vzn1ja4/traces/1ac33b89ffd5e75d4265b62900c348ed?timestamp=2025-03-07T13%3A45%3A09.149Z&display=preview)_ + +#### 3. 額外屬性 + +你也可以傳入額外的 span 屬性,例如 `user_id`、`tags`、`session_id` 與自訂中繼資料。在 trace 中加入這些細節,有助於分析、除錯,以及監控應用程式在不同使用者或工作階段中的行為。 + +```python +from smolagents import (CodeAgent, DuckDuckGoSearchTool, InferenceClientModel) + +search_tool = DuckDuckGoSearchTool() +agent = CodeAgent( + tools=[search_tool], + model=InferenceClientModel() +) + +with langfuse.start_as_current_span( + name="Smolagent-Trace", + ) as span: + + # Run your application here + response = agent.run("What is the capital of Germany?") + + # Pass additional attributes to the span + span.update_trace( + input="What is the capital of Germany?", + output=response, + user_id="smolagent-user-123", + session_id="smolagent-session-123456789", + tags=["city-question", "testing-agents"], + metadata={"email": "user@langfuse.com"}, + ) + +# Flush events in short-lived applications +langfuse.flush() +``` + +![以額外指標補充 agent 的執行紀錄](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/bonus-unit2/smolagents-attributes.png) + +#### 4. 使用者回饋 + +如果 agent 嵌入在使用者介面中,就能記錄使用者的直接回饋,例如聊天介面中的按讚或倒讚。下例使用 [Gradio](https://gradio.app/),建立具有簡單回饋機制的聊天介面。 + +以下程式碼會在使用者傳送聊天訊息時,將 trace 記錄到 Langfuse。如果使用者對最後一則回答按讚或倒讚,我們就將分數附加到該 trace。 + +```python +import gradio as gr +from smolagents import (CodeAgent, InferenceClientModel) +from langfuse import get_client + +langfuse = get_client() + +model = InferenceClientModel() +agent = CodeAgent(tools=[], model=model, add_base_tools=True) + +trace_id = None + +def respond(prompt, history): + with langfuse.start_as_current_span( + name="Smolagent-Trace"): + + # Run your application here + output = agent.run(prompt) + + global trace_id + trace_id = langfuse.get_current_trace_id() + + history.append({"role": "assistant", "content": str(output)}) + return history + +def handle_like(data: gr.LikeData): + # For demonstration, we map user feedback to a 1 (like) or 0 (dislike) + if data.liked: + langfuse.create_score( + value=1, + name="user-feedback", + trace_id=trace_id + ) + else: + langfuse.create_score( + value=0, + name="user-feedback", + trace_id=trace_id + ) + +with gr.Blocks() as demo: + chatbot = gr.Chatbot(label="Chat", type="messages") + prompt_box = gr.Textbox(placeholder="Type your message...", label="Your message") + + # When the user presses 'Enter' on the prompt, we run 'respond' + prompt_box.submit( + fn=respond, + inputs=[prompt_box, chatbot], + outputs=chatbot + ) + + # When the user clicks a 'like' button on a message, we run 'handle_like' + chatbot.like(handle_like, None, None) + +demo.launch() +``` + +接著,你就能在可觀測性工具中看到使用者回饋: + +![Langfuse 收集到的使用者回饋](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/bonus-unit2/user-feedback-gradio.png) + +#### 5. LLM-as-a-Judge + +LLM-as-a-Judge 是另一種自動評估 agent 輸出的方法。你可以另外呼叫 LLM,依照正確性、有害程度、風格,或任何你在意的標準來評估輸出。 + +**工作流程**: +1. 定義**評估範本**,例如「檢查這段文字是否有害」。 +2. 每當 agent 產生輸出,就將輸出連同範本傳給擔任「評審」的 LLM。 +3. 評審 LLM 回傳評分或標籤,再將結果記錄到可觀測性工具。 + +以下是 Langfuse 的範例: + +![LLM-as-a-Judge 評估範本](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/bonus-unit2/evaluator-template.png) +![LLM-as-a-Judge 評估器](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/bonus-unit2/evaluator.png) + +```python +# Example: Checking if the agent’s output is toxic or not. +from smolagents import (CodeAgent, DuckDuckGoSearchTool, InferenceClientModel) + +search_tool = DuckDuckGoSearchTool() +agent = CodeAgent(tools=[search_tool], model=InferenceClientModel()) + +agent.run("Can eating carrots improve your vision?") +``` + +可以看到,這個範例的回答被判定為「無害」。 + +![LLM-as-a-Judge 評估分數](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/bonus-unit2/llm-as-a-judge-score.png) + +#### 6. 可觀測性指標總覽 + +這些指標都能整合到儀表板中呈現,讓你快速掌握 agent 在多個工作階段中的表現,並追蹤品質指標隨時間的變化。 + +![可觀測性指標總覽](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/bonus-unit2/langfuse-dashboard.png) + +## 離線評估 + +線上評估能取得即時回饋,但你也需要**離線評估**,在開發前或開發期間進行系統化檢查。這能在變更上線前,幫助你維持品質與可靠性。 + +### 資料集評估 + +離線評估通常包含以下步驟: +1. 準備基準資料集,其中包含成對的 prompt 與預期輸出 +2. 讓 agent 處理資料集 +3. 將輸出與預期結果比較,或使用額外的評分機制 + +以下使用包含數學題目與解答的 [GSM8K 資料集](https://huggingface.co/datasets/openai/gsm8k),示範這個做法。 + +```python +import pandas as pd +from datasets import load_dataset + +# Fetch GSM8K from Hugging Face +dataset = load_dataset("openai/gsm8k", 'main', split='train') +df = pd.DataFrame(dataset) +print("First few rows of GSM8K dataset:") +print(df.head()) +``` + +接著,在 Langfuse 中建立資料集實體來追蹤執行紀錄,再將資料集中的每個項目加入系統。如果你不使用 Langfuse,也可以直接存入自己的資料庫或本機檔案,供後續分析。 + +```python +from langfuse import get_client +langfuse = get_client() + +langfuse_dataset_name = "gsm8k_dataset_huggingface" + +# Create a dataset in Langfuse +langfuse.create_dataset( + name=langfuse_dataset_name, + description="GSM8K benchmark dataset uploaded from Huggingface", + metadata={ + "date": "2025-03-10", + "type": "benchmark" + } +) +``` + +```python +for idx, row in df.iterrows(): + langfuse.create_dataset_item( + dataset_name=langfuse_dataset_name, + input={"text": row["question"]}, + expected_output={"text": row["answer"]}, + metadata={"source_index": idx} + ) + if idx >= 9: # Upload only the first 10 items for demonstration + break +``` + +![Langfuse 中的資料集項目](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/bonus-unit2/example-dataset.png) + +#### 讓 agent 處理資料集 + +我們定義一個輔助函式 `run_smolagent()`,它會: +1. 啟動 Langfuse span +2. 讓 agent 處理 prompt +3. 在 Langfuse 中記錄 trace ID + +接著,逐一處理資料集項目,執行 agent,並將 trace 與對應項目連結。也可以視需要附加簡單的評估分數。 + +```python +from opentelemetry.trace import format_trace_id +from smolagents import (CodeAgent, InferenceClientModel, LiteLLMModel) +from langfuse import get_client + +langfuse = get_client() + + +# Example: using InferenceClientModel or LiteLLMModel to access openai, anthropic, gemini, etc. models: +model = InferenceClientModel() + +agent = CodeAgent( + tools=[], + model=model, + add_base_tools=True +) + +dataset_name = "gsm8k_dataset_huggingface" +current_run_name = "smolagent-notebook-run-01" # Identifies this specific evaluation run + +# Assume 'run_smolagent' is your instrumented application function +def run_smolagent(question): + with langfuse.start_as_current_generation(name="qna-llm-call") as generation: + # Simulate LLM call + result = agent.run(question) + + # Update the trace with the input and output + generation.update_trace( + input= question, + output=result, + ) + + return result + +dataset = langfuse.get_dataset(name=dataset_name) # Fetch your pre-populated dataset + +for item in dataset.items: + + # Use the item.run() context manager + with item.run( + run_name=current_run_name, + run_metadata={"model_provider": "Hugging Face", "temperature_setting": 0.7}, + run_description="Evaluation run for GSM8K dataset" + ) as root_span: # root_span is the root span of the new trace for this item and run. + # All subsequent langfuse operations within this block are part of this trace. + + # Call your application logic + generated_answer = run_smolagent(question=item.input["text"]) + + print(item.input) +``` + +你可以變更以下設定,重複執行這個流程: +- 模型(OpenAI GPT、本機 LLM 等) +- 工具(使用搜尋或不使用搜尋) +- prompt(不同的系統訊息) + +接著,在可觀測性工具中並排比較: + +![資料集執行總覽](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/bonus-unit2/dataset_runs.png) +![資料集執行比較](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/bonus-unit2/dataset-run-comparison.png) + +## 結語 + +這份 notebook 介紹了如何: +1. 使用 smolagents 與 OpenTelemetry 匯出器,**建立可觀測性** +2. 執行簡單的 agent,**確認監測正常** +3. 透過可觀測性工具,**記錄詳細指標**,例如成本、延遲等 +4. 透過 Gradio 介面,**收集使用者回饋** +5. **使用 LLM-as-a-Judge** 自動評估輸出 +6. 使用基準資料集,**進行離線評估** + +🤗 祝你寫程式愉快! diff --git a/units/zh-TW/bonus-unit2/quiz.mdx b/units/zh-TW/bonus-unit2/quiz.mdx new file mode 100644 index 000000000..d8d87c35f --- /dev/null +++ b/units/zh-TW/bonus-unit2/quiz.mdx @@ -0,0 +1,132 @@ +# 小測驗:評估 AI agent + +來確認你對本附加單元介紹的 agent 追蹤與評估概念有多熟悉。 + +本測驗為選修,不計分。 + +### Q1:AI agent 的可觀測性主要指什麼? +哪個敘述正確說明 AI agent 可觀測性的目的? + + + +### Q2:下列哪一項不是 agent 可觀測性常見的監控指標? +選出通常不屬於可觀測性範圍的指標。 + + + +### Q3:哪個敘述最能說明 AI agent 的離線評估? +選出正確描述離線評估核心概念的敘述。 + + + +### Q4:agent 的線上評估有什麼優點? +選出最能說明線上評估優點的敘述。 + + + +### Q5:OpenTelemetry 在 AI agent 可觀測性與評估中扮演什麼角色? +哪個敘述最能說明 OpenTelemetry 在 AI agent 監控中的作用? + + + +恭喜完成測驗!🎉 如果有答錯的題目,可以回顧本附加單元,加深理解。如果表現不錯,你就準備好繼續探索 agent 可觀測性與評估的進階主題了! diff --git a/units/zh-TW/bonus-unit2/what-is-agent-observability-and-evaluation.mdx b/units/zh-TW/bonus-unit2/what-is-agent-observability-and-evaluation.mdx new file mode 100644 index 000000000..e99accbba --- /dev/null +++ b/units/zh-TW/bonus-unit2/what-is-agent-observability-and-evaluation.mdx @@ -0,0 +1,92 @@ +# AI agent 的可觀測性與評估 + +## 🔎 什麼是可觀測性? + +可觀測性是指透過日誌、指標與追蹤紀錄等外部訊號,了解 AI agent 的內部狀況。對 AI agent 而言,這包括追蹤行動、工具使用、模型呼叫與回應,以便除錯並改善表現。 + +![可觀測性儀表板](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/bonus-unit2/langfuse-dashboard.png) + +## 🔭 為什麼 agent 的可觀測性很重要? + +缺乏可觀測性時,AI agent 就像「黑箱」。可觀測性工具能揭示 agent 的運作,讓你: + +- 了解成本與準確度之間的取捨 +- 測量延遲 +- 偵測有害語言與 prompt injection +- 監控使用者回饋 + +換句話說,可觀測性能幫助你的展示用 agent 準備好進入正式環境! + +## 🔨 可觀測性工具 + +常見的 AI agent 可觀測性工具包括 [Langfuse](https://langfuse.com) 與 [Arize](https://www.arize.com) 等平台。這些工具能收集詳細的追蹤紀錄,並提供儀表板來即時監控指標,讓你更容易發現問題、改善效能。 + +不同可觀測性工具的功能與能力差異很大。有些工具採用開源模式,龐大社群會參與規劃發展方向,並提供豐富的整合功能。有些工具專注於 LLMOps 的特定面向,例如可觀測性、評估或 prompt 管理;另一些則涵蓋完整的 LLMOps 工作流程。我們鼓勵你閱讀各種工具的文件,選出適合自己的方案。 + +許多 agent 框架,例如 [smolagents](https://huggingface.co/docs/smolagents/v1.12.0/en/index),會使用 [OpenTelemetry](https://opentelemetry.io/docs/) 標準,將中繼資料提供給可觀測性工具。此外,可觀測性工具也會開發自訂監測整合,以更靈活地因應快速演進的 LLM 技術。請查閱所用工具的文件,確認支援哪些功能。 + +## 🔬 Trace 與 span + +可觀測性工具通常會以 trace 和 span 表示 agent 的執行過程。 + +- **Trace(追蹤紀錄)** 代表 agent 從頭到尾的一次完整任務,例如處理使用者查詢。 +- **Span(追蹤區段)** 是 trace 中的個別步驟,例如呼叫語言模型或擷取資料。 + +![Langfuse 中的 smolagent trace 範例](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/bonus-unit2/trace-tree.png) + +## 📊 值得監控的關鍵指標 + +以下是可觀測性工具最常監控的一些指標: + +**延遲:** agent 回應有多快?等待過久會影響使用者體驗。你應透過追蹤 agent 的執行過程,測量整體任務與各步驟的延遲。例如,如果一次任務中所有模型呼叫共花費 20 秒,可以考慮使用更快的模型,或平行呼叫模型來加速。 + +**成本:** agent 每次執行的費用是多少?AI agent 會呼叫按 token 計費的 LLM 或外部 API。頻繁使用工具或多次送出 prompt,可能讓成本快速增加。例如,若 agent 呼叫 LLM 五次,品質卻只略有改善,就應評估這筆成本是否值得,以及能否減少呼叫次數或改用較便宜的模型。即時監控也能幫助你找出異常的成本飆升,例如程式錯誤造成 API 過度循環呼叫。 + +**請求錯誤:** agent 有多少請求失敗?這可能包括 API 錯誤或工具呼叫失敗。你可以設定備援方案或重試機制,讓 agent 在正式環境中更能承受這些問題。例如,LLM 供應商 A 的服務中斷時,就切換到供應商 B。 + +**使用者回饋:** 讓使用者直接評價能提供寶貴資訊,包括明確評分(👍/👎、⭐1 至 5 顆星)或文字意見。持續出現負面回饋時就該留意,因為這表示 agent 可能未如預期運作。 + +**隱性使用者回饋:** 即使使用者沒有明確評分,也能從行為取得間接回饋,例如立刻改寫問題、重複查詢或點選重試按鈕。若使用者反覆詢問同一個問題,就可能表示 agent 的表現未達預期。 + +**準確度:** agent 多常產生正確或符合期望的輸出?準確度的定義因情境而異,例如解題正確率、資訊檢索準確度或使用者滿意度。首先,要定義你的 agent 怎樣才算成功。接著可透過自動化檢查、評估分數或任務完成標籤追蹤準確度,例如將 trace 標記為「成功」或「失敗」。 + +**自動化評估指標:** 你也可以設定自動化評估,例如讓 LLM 為 agent 的輸出評分,判斷內容是否有幫助、是否正確。還有多種開源函式庫可以評估 agent 的不同面向,例如用於 RAG agent 的 [RAGAS](https://docs.ragas.io/),以及用來偵測有害語言或 prompt injection 的 [LLM Guard](https://llm-guard.com/)。 + +實務上,結合多種指標才能更全面地掌握 AI agent 的狀況。本章的[範例 notebook](https://colab.research.google.com/#fileId=https://huggingface.co/agents-course/notebooks/blob/main/bonus-unit2/monitoring-and-evaluating-agents.ipynb) 會展示這些指標的實際案例。不過,我們先來看看典型的評估流程。 + +## 👍 評估 AI agent + +可觀測性提供指標;評估則是分析這些資料、執行測試,判斷 AI agent 的表現以及可以改進的地方。換句話說,取得 trace 與指標後,要如何用它們來評斷 agent 並做出決策? + +定期評估很重要,因為 AI agent 的行為往往不具確定性,也可能因更新或模型行為漂移而改變。如果不評估,就無法知道你的「聰明 agent」是否確實完成工作,或表現是否退步。 + +AI agent 的評估分為**線上評估**與**離線評估**。兩者都有價值,也能互補。我們通常從離線評估開始,因為這是部署任何 agent 之前至少要完成的步驟。 + +### 🥷 離線評估 + +![Langfuse 中的資料集項目](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/bonus-unit2/example-dataset.png) + +離線評估是在受控環境中評估 agent,通常使用測試資料集,而非即時的使用者查詢。你會準備已知預期輸出或正確行為的資料集,再讓 agent 處理這些資料。 + +例如,若你開發了數學應用題 agent,可以準備一份包含 100 道已知答案題目的[測試資料集](https://huggingface.co/datasets/gsm8k)。離線評估通常在開發期間執行,也可以納入 CI/CD 流程,確認是否有所改善,並防止退步。優點是**可以重複執行,而且因為有標準答案,能取得明確的準確度指標**。你也可以模擬使用者查詢,將 agent 的回應與理想答案比較,或使用前述自動化指標。 + +離線評估的主要挑戰,是確保測試資料集涵蓋夠全面,而且持續符合實際需求。agent 可能在固定測試集上表現很好,卻在正式環境中遇到截然不同的查詢。因此,應持續加入新的邊界案例與反映真實情境的範例。結合少量「冒煙測試」案例與較大的評估集很有幫助:小型資料集用於快速檢查,大型資料集則提供更全面的效能指標。 + +### 🔄 線上評估 + +線上評估是在真實、即時的環境中,也就是正式環境的實際使用過程中,評估 agent。這包括持續監控 agent 與真實使用者互動時的表現,並分析結果。 + +例如,你可以追蹤實際流量中的成功率、使用者滿意度或其他指標。線上評估的優點是**能捕捉實驗環境中未預料到的情況**:你可以觀察模型隨時間產生的漂移,例如輸入模式改變後 agent 的效果是否變差,也能發現測試資料未涵蓋的意外查詢或情境。這能真實呈現 agent 在實際環境中的行為。 + +如前所述,線上評估通常會收集隱性與明確的使用者回饋,也可能進行影子測試或 A/B 測試,讓新版 agent 與舊版平行執行以便比較。挑戰是,實際互動往往不容易取得可靠的標籤或分數,因此可能需要依靠使用者回饋或後續指標,例如使用者是否點選結果。 + +### 🤝 結合兩種方法 + +實務上,成功的 AI agent 評估會結合**線上**與**離線**方法。你可以定期執行離線基準測試,量化 agent 在指定任務上的表現,同時持續監控實際使用狀況,找出基準測試遺漏的問題。例如,離線測試可以確認程式碼生成 agent 在已知題目集上的成功率是否提升;線上監控則可能提醒你,使用者開始詢問一類 agent 難以處理的新問題。結合兩者,才能更完整地掌握狀況。 + +許多團隊會採用這樣的循環:_離線評估 → 部署新版 agent → 監控線上指標並收集新的失敗案例 → 將案例加入離線測試集 → 持續迭代_。如此一來,評估就能持續進行、不斷改善。 + +## 🧑‍💻 看看實際怎麼做 + +下一節將以範例展示,如何使用可觀測性工具監控與評估 agent。 + diff --git a/units/zh-TW/bonus-unit3/building_your_pokemon_agent.mdx b/units/zh-TW/bonus-unit3/building_your_pokemon_agent.mdx new file mode 100644 index 000000000..df6901daa --- /dev/null +++ b/units/zh-TW/bonus-unit3/building_your_pokemon_agent.mdx @@ -0,0 +1,259 @@ +# 打造自己的寶可夢對戰 agent + +了解 Agentic AI 在遊戲中的潛力與限制後,現在就來動手實作。這一節,你將運用整門課學到的知識,**打造自己的 AI agent,參與寶可夢風格的回合制對戰**。 + +我們會把系統分成四個主要組件: + +- **Poke-env:** 用來訓練規則式或強化學習寶可夢機器人的 Python 函式庫。 + +- **Pokémon Showdown:** agent 進行對戰的線上模擬器。 + +- **LLMAgentBase:** 我們自訂的 Python 類別,負責連接 LLM 與 Poke-env 對戰環境。 + +- **TemplateAgent:** 供你完成的起始範本,用來打造獨一無二的對戰 agent。 + +接著逐一深入了解這些組件。 + +## 🧠 Poke-env + +![對戰動圖](https://github.com/hsahovic/poke-env/raw/master/rl-gif.gif) + +[Poke-env](https://github.com/hsahovic/poke-env) 是由 [Haris Sahovic](https://huggingface.co/hsahovic) 開發的 Python 介面,原本用來訓練強化學習機器人,我們則將它用於 Agentic AI。 +它讓 agent 能透過簡單的 API 與 Pokémon Showdown 互動。 + +它提供了 `Player` 類別,agent 將繼承這個類別,取得與圖形介面溝通所需的功能。 + +**文件**:[poke-env.readthedocs.io](https://poke-env.readthedocs.io/en/stable/) +**儲存庫**:[github.com/hsahovic/poke-env](https://github.com/hsahovic/poke-env) + +## ⚔️ Pokémon Showdown + +[Pokémon Showdown](https://pokemonshowdown.com/) 是[開源](https://github.com/smogon/Pokemon-Showdown)對戰模擬器,agent 將在這裡參與即時的寶可夢對戰。 +它提供完整介面,即時模擬並顯示戰況。在本挑戰中,你的機器人會像真人玩家一樣,每回合選擇招式。 + +我們已部署一台伺服器,供所有參與者對戰。看看誰能打造出最強的 AI 對戰 agent! + +**儲存庫**:[github.com/smogon/Pokemon-Showdown](https://github.com/smogon/Pokemon-Showdown) +**網站**:[pokemonshowdown.com](https://pokemonshowdown.com/) + +## 🔌 LLMAgentBase + +`LLMAgentBase` 是繼承 **Poke-env** 的 `Player` 類別而來的 Python 類別。 +它是 **LLM** 與**寶可夢對戰模擬器**之間的橋樑,負責處理輸入與輸出格式,並維護對戰的上下文。 + +這個基礎 agent 提供了一組工具(定義於 `STANDARD_TOOL_SCHEMA`),用來與環境互動,包括: + +- `choose_move`:選擇對戰時要使用的攻擊招式 +- `choose_switch`:替換寶可夢 + +LLM 應使用這些工具,在對戰中做出決策。 + +### 🧠 核心邏輯 + +- `choose_move(battle: Battle)`:每回合呼叫的主要方法。它接收 `Battle` 物件,並根據 LLM 的輸出回傳行動字串。 + +### 🔧 重要的內部方法 + +- `_format_battle_state(battle)`:將目前的對戰狀態轉成字串,以便傳送給 LLM。 + +- `_find_move_by_name(battle, move_name)`:根據名稱尋找招式,用於處理 LLM 呼叫 `choose_move` 的回應。 + +- `_find_pokemon_by_name(battle, pokemon_name)`:根據 LLM 的替換指令,找出要換上場的寶可夢。 + +- `_get_llm_decision(battle_state)`:這個方法在基礎類別中是抽象方法。你需要在自己的 agent 中實作它(見下一節),定義如何向 LLM 查詢並解析回應。 + +以下節錄展示決策流程的運作方式: + +```python +STANDARD_TOOL_SCHEMA = { + "choose_move": { + ... + }, + "choose_switch": { + ... + }, +} + +class LLMAgentBase(Player): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.standard_tools = STANDARD_TOOL_SCHEMA + self.battle_history = [] + + def _format_battle_state(self, battle: Battle) -> str: + active_pkmn = battle.active_pokemon + active_pkmn_info = f"Your active Pokemon: {active_pkmn.species} " \ + f"(Type: {'/'.join(map(str, active_pkmn.types))}) " \ + f"HP: {active_pkmn.current_hp_fraction * 100:.1f}% " \ + f"Status: {active_pkmn.status.name if active_pkmn.status else 'None'} " \ + f"Boosts: {active_pkmn.boosts}" + + opponent_pkmn = battle.opponent_active_pokemon + opp_info_str = "Unknown" + if opponent_pkmn: + opp_info_str = f"{opponent_pkmn.species} " \ + f"(Type: {'/'.join(map(str, opponent_pkmn.types))}) " \ + f"HP: {opponent_pkmn.current_hp_fraction * 100:.1f}% " \ + f"Status: {opponent_pkmn.status.name if opponent_pkmn.status else 'None'} " \ + f"Boosts: {opponent_pkmn.boosts}" + opponent_pkmn_info = f"Opponent's active Pokemon: {opp_info_str}" + + available_moves_info = "Available moves:\n" + if battle.available_moves: + available_moves_info += "\n".join( + [f"- {move.id} (Type: {move.type}, BP: {move.base_power}, Acc: {move.accuracy}, PP: {move.current_pp}/{move.max_pp}, Cat: {move.category.name})" + for move in battle.available_moves] + ) + else: + available_moves_info += "- None (Must switch or Struggle)" + + available_switches_info = "Available switches:\n" + if battle.available_switches: + available_switches_info += "\n".join( + [f"- {pkmn.species} (HP: {pkmn.current_hp_fraction * 100:.1f}%, Status: {pkmn.status.name if pkmn.status else 'None'})" + for pkmn in battle.available_switches] + ) + else: + available_switches_info += "- None" + + state_str = f"{active_pkmn_info}\n" \ + f"{opponent_pkmn_info}\n\n" \ + f"{available_moves_info}\n\n" \ + f"{available_switches_info}\n\n" \ + f"Weather: {battle.weather}\n" \ + f"Terrains: {battle.fields}\n" \ + f"Your Side Conditions: {battle.side_conditions}\n" \ + f"Opponent Side Conditions: {battle.opponent_side_conditions}" + return state_str.strip() + + def _find_move_by_name(self, battle: Battle, move_name: str) -> Optional[Move]: + normalized_name = normalize_name(move_name) + # Prioritize exact ID match + for move in battle.available_moves: + if move.id == normalized_name: + return move + # Fallback: Check display name (less reliable) + for move in battle.available_moves: + if move.name.lower() == move_name.lower(): + print(f"Warning: Matched move by display name '{move.name}' instead of ID '{move.id}'. Input was '{move_name}'.") + return move + return None + + def _find_pokemon_by_name(self, battle: Battle, pokemon_name: str) -> Optional[Pokemon]: + normalized_name = normalize_name(pokemon_name) + for pkmn in battle.available_switches: + # Normalize the species name for comparison + if normalize_name(pkmn.species) == normalized_name: + return pkmn + return None + + async def choose_move(self, battle: Battle) -> str: + battle_state_str = self._format_battle_state(battle) + decision_result = await self._get_llm_decision(battle_state_str) + print(decision_result) + decision = decision_result.get("decision") + error_message = decision_result.get("error") + action_taken = False + fallback_reason = "" + + if decision: + function_name = decision.get("name") + args = decision.get("arguments", {}) + if function_name == "choose_move": + move_name = args.get("move_name") + if move_name: + chosen_move = self._find_move_by_name(battle, move_name) + if chosen_move and chosen_move in battle.available_moves: + action_taken = True + chat_msg = f"AI Decision: Using move '{chosen_move.id}'." + print(chat_msg) + return self.create_order(chosen_move) + else: + fallback_reason = f"LLM chose unavailable/invalid move '{move_name}'." + else: + fallback_reason = "LLM 'choose_move' called without 'move_name'." + elif function_name == "choose_switch": + pokemon_name = args.get("pokemon_name") + if pokemon_name: + chosen_switch = self._find_pokemon_by_name(battle, pokemon_name) + if chosen_switch and chosen_switch in battle.available_switches: + action_taken = True + chat_msg = f"AI Decision: Switching to '{chosen_switch.species}'." + print(chat_msg) + return self.create_order(chosen_switch) + else: + fallback_reason = f"LLM chose unavailable/invalid switch '{pokemon_name}'." + else: + fallback_reason = "LLM 'choose_switch' called without 'pokemon_name'." + else: + fallback_reason = f"LLM called unknown function '{function_name}'." + + if not action_taken: + if not fallback_reason: + if error_message: + fallback_reason = f"API Error: {error_message}" + elif decision is None: + fallback_reason = "LLM did not provide a valid function call." + else: + fallback_reason = "Unknown error processing LLM decision." + + print(f"Warning: {fallback_reason} Choosing random action.") + + if battle.available_moves or battle.available_switches: + return self.choose_random_move(battle) + else: + print("AI Fallback: No moves or switches available. Using Struggle/Default.") + return self.choose_default_move(battle) + + async def _get_llm_decision(self, battle_state: str) -> Dict[str, Any]: + raise NotImplementedError("Subclasses must implement _get_llm_decision") +``` + +**完整原始碼**:[agents.py](https://huggingface.co/spaces/Jofthomas/twitch_streaming/blob/main/agents.py) + +## 🧪 TemplateAgent + +有趣的部分來了!以 LLMAgentBase 為基礎,現在就來實作自己的 agent,運用獨特策略挑戰排行榜。 + +你將從這個範本開始,建立自己的邏輯。我們也提供使用 **OpenAI**、**Mistral** 與 **Gemini** 模型的三個[完整範例](https://huggingface.co/spaces/Jofthomas/twitch_streaming/blob/main/agents.py),供你參考。 + +以下是簡化版範本: + +```python +class TemplateAgent(LLMAgentBase): + """Uses Template AI API for decisions.""" + def __init__(self, api_key: str = None, model: str = "model-name", *args, **kwargs): + super().__init__(*args, **kwargs) + self.model = model + self.template_client = TemplateModelProvider(api_key=...) + self.template_tools = list(self.standard_tools.values()) + + async def _get_llm_decision(self, battle_state: str) -> Dict[str, Any]: + """Sends state to the LLM and gets back the function call decision.""" + system_prompt = ( + "You are a ..." + ) + user_prompt = f"..." + + try: + response = await self.template_client.chat.completions.create( + model=self.model, + messages=[ + {"role": "system", "content": system_prompt}, + {"role": "user", "content": user_prompt}, + ], + ) + message = response.choices[0].message + + return {"decision": {"name": function_name, "arguments": arguments}} + + except Exception as e: + print(f"Unexpected error during call: {e}") + return {"error": f"Unexpected error: {e}"} +``` + +這段程式碼無法直接執行;它是供你實作自訂邏輯的架構範本。 + +所有組件都準備好了,接下來就輪到你打造有競爭力的 agent。下一節會示範如何將 agent 部署到我們的伺服器,與其他對手即時對戰。 + +開始對戰吧!🔥 diff --git a/units/zh-TW/bonus-unit3/conclusion.mdx b/units/zh-TW/bonus-unit3/conclusion.mdx new file mode 100644 index 000000000..3392891e5 --- /dev/null +++ b/units/zh-TW/bonus-unit3/conclusion.mdx @@ -0,0 +1,18 @@ +# 結語 + +恭喜你走到這裡!🥳 你已成功打造自己的寶可夢對戰 agent!⚔️🎮 + +你已掌握 **agentic 工作流程**的基礎,將 **LLM** 連接到遊戲環境,並部署了能迎接對戰挑戰的智慧 agent。 + +但旅程還沒結束! +既然第一個 agent 已經順利運作,接著想想如何讓它持續進化: +- 能否提升它的策略思考能力? +- 記憶機制或回饋循環會如何影響它的表現? +- 哪些實驗能讓它在對戰中更具競爭力? + +我們很想聽聽你對課程的看法,以及如何讓未來的學習者有更好的體驗。 +有建議嗎?👉 [填寫這份表單](https://docs.google.com/forms/d/e/1FAIpQLSe9VaONn0eglax0uTwi29rIn4tM7H2sYmmybmG5jJNlE5v0xA/viewform?usp=dialog) + +感謝你與我們一起學習,請記得: + +**持續學習、持續訓練、持續對戰,繼續發光!** 🤗 diff --git a/units/zh-TW/bonus-unit3/from-llm-to-agents.mdx b/units/zh-TW/bonus-unit3/from-llm-to-agents.mdx new file mode 100644 index 000000000..30ed0d70f --- /dev/null +++ b/units/zh-TW/bonus-unit3/from-llm-to-agents.mdx @@ -0,0 +1,37 @@ +# 從 LLM 到 AI agent + +在課程的[第 1 單元](https://huggingface.co/learn/agents-course/unit1/introduction),我們學到 AI agent 能夠規劃並做出決策。 +LLM 已經讓玩家與 NPC 的互動更加自然;Agentic AI 則更進一步,讓角色能自主決策、規劃行動,並適應環境變化。 + +以經典 RPG 遊戲中的 NPC 為例,就能看出兩者的差異: + +- 使用 LLM:NPC 能更自然、更多樣地回答你的問題。這很適合對話,但 NPC 依然被動,除非你先做些什麼,否則它不會行動。 +- 使用 Agentic AI:即使你沒有直接與 NPC 互動,它也能決定去尋求協助、設下陷阱,或完全避開你。 + +這個小小的轉變帶來了全面改變。遊戲角色從依腳本回應,轉變為遊戲世界中自主行動的參與者。 + +這代表 NPC 現在能透過目標導向的行為,直接與環境互動,帶來更有變化、更難以預測的玩法。 + +Agentic AI 賦予 NPC 以下能力: + +- **自主性**:根據遊戲狀態,獨立做出決策。 +- **適應性**:因應玩家行動調整策略。 +- **持續性**:記住過去的互動,作為未來行為的依據。 + +這讓 NPC 從只會回應玩家輸入的被動角色,轉變為遊戲世界中的主動參與者,開啟創新玩法的可能性。 + +## agent 的主要限制:**速度慢**(目前如此) + +不過,先別太樂觀。Agentic AI 雖然很有潛力,目前在即時應用中仍面臨挑戰。 + +推理與規劃過程會帶來延遲,因此較不適合 *Doom* 或 *Super Mario Bros.* 這類快節奏遊戲。 + +以 [_Claude Plays Pokémon_](https://www.twitch.tv/claudeplayspokemon) 為例。考量**思考**所需的 token,再加上**行動**所需的 token,就會發現:要讓即時遊玩成為可能,我們需要截然不同的解碼策略。 + +Claude plays Pokémon + +多數遊戲需要以約 30 FPS 執行,也就是即時 AI agent 每秒得採取 30 次行動。以目前的 agentic LLM 而言,還無法做到。 + +不過,*寶可夢*這類回合制遊戲是理想的應用情境,因為 AI 有足夠時間思考並制定策略。 + +因此,下一節你將打造自己的 AI agent,參與寶可夢風格的回合制對戰,甚至親自挑戰它。開始吧! diff --git a/units/zh-TW/bonus-unit3/introduction.mdx b/units/zh-TW/bonus-unit3/introduction.mdx new file mode 100644 index 000000000..5f5e7292e --- /dev/null +++ b/units/zh-TW/bonus-unit3/introduction.mdx @@ -0,0 +1,26 @@ +# 簡介 + +Bonus Unit 3 AI in Games + +🎶I want to be the very best ... 🎶 + +歡迎來到這個**附加單元**!我們將一起探索 **AI agent 與遊戲**結合的精彩可能性!🎮🤖 + +想像一款遊戲,裡面的非玩家角色(NPC)不只是照著腳本說話,而是能自然地與你對話、因應你的策略,並隨著劇情發展而改變。這就是在遊戲中結合 **LLM 與 agentic 行為**的力量:它能帶來**前所未有、自然湧現的故事與玩法**。 + +在本附加單元,你將: + +- 學習打造能參與**寶可夢風格回合制對戰**的 AI agent +- 親自與它對戰,甚至在線上挑戰其他 agent + +AI 社群已經有[一些](https://www.anthropic.com/research/visible-extended-thinking)使用 LLM 玩寶可夢的[範例](https://www.twitch.tv/gemini_plays_pokemon)。在本單元,你將運用課程中學到的概念,以自己的 agent 重現這些成果。 + +Claude plays Pokémon + +## 想進一步探索嗎? + +- 🎓 **掌握遊戲中的 LLM 應用**:透過完整的[遊戲機器學習課程](https://hf.co/learn/ml-games-course),深入了解遊戲開發。 + +- 📘 **閱讀 AI Playbook**:在 [AI Playbook for Game Developers](https://thomassimonini.substack.com/) 中,探索智慧遊戲設計的未來,取得觀點、靈感與實用技巧。 + +動手打造之前,先透過**四個值得借鏡的實際案例**,看看 LLM 已經如何應用在遊戲中。 diff --git a/units/zh-TW/bonus-unit3/launching_agent_battle.mdx b/units/zh-TW/bonus-unit3/launching_agent_battle.mdx new file mode 100644 index 000000000..ba9541a89 --- /dev/null +++ b/units/zh-TW/bonus-unit3/launching_agent_battle.mdx @@ -0,0 +1,68 @@ +# 啟動你的寶可夢對戰 agent + +準備開戰了!⚡️ + +## **挑戰直播中的 agent!** + +如果你暫時不想自己打造 agent,只是好奇 agent 在寶可夢對戰中有多少潛力,可以觀看我們在 [Twitch](https://www.twitch.tv/jofthomas) 上的自動直播。 + + + + +要挑戰直播中的 agent,請依照以下步驟: + +操作方式: +1. 前往 **Pokémon Showdown Space**:[點此開啟](https://huggingface.co/spaces/Jofthomas/Pokemon_showdown) +2. 在右上角**設定你的名稱**。 +3. 找出**目前 agent 的使用者名稱**。請查看: + * **直播畫面**:[點此開啟](https://www.twitch.tv/jofthomas) +4. 在 Showdown Space 中**搜尋**該使用者名稱,並**傳送對戰邀請**。 + +*提醒:* 一次只會有一個 agent 在線上,請確認名稱正確! + +## 寶可夢對戰 agent 挑戰平台 + +如果你已經在上一節打造自己的寶可夢對戰 agent,可能正想知道:**該怎麼測試它與其他對手交戰的實力?** 一起來看看! + +我們為此建立了專用的 [Hugging Face Space](https://huggingface.co/spaces/PShowdown/pokemon_agents): + + + +這個 Space 連接到我們自己的 **Pokémon Showdown 伺服器**,讓你的 agent 能與其他對手展開精彩的 AI 對戰。 + +### 如何啟動 agent + +依照以下步驟,讓你的 agent 登上競技場: + +1. **複製 Space** + 點選 Space 右上角選單的三個點,再選擇「Duplicate this Space」。 + +2. **將 agent 程式碼加入 `agent.py`** + 開啟檔案,貼上 agent 的實作。你可以參考這個[範例](https://huggingface.co/spaces/PShowdown/pokemon_agents/blob/main/agents.py),或查看[專案結構](https://huggingface.co/spaces/PShowdown/pokemon_agents/tree/main)。 + +3. **在 `app.py` 中註冊 agent** + 將 agent 的名稱與邏輯加入下拉式選單。可以參考[這段程式碼](https://huggingface.co/spaces/PShowdown/pokemon_agents/blob/main/app.py)。 + +4. **選擇 agent** + 加入後,agent 就會出現在「Select Agent」下拉式選單中。從清單中選取它!✅ + +5. **輸入你的 Pokémon Showdown 使用者名稱** + 請確認名稱與 iframe 中 **「Choose name」** 輸入欄位顯示的一致。你也可以使用正式帳號連線。 + +6. **點選「Send Battle Invitation」** + agent 會向選定的對手傳送邀請,邀請應該就會顯示在畫面上! + +7. **接受邀請,享受對戰!** + 開戰吧!願最聰明的 agent 獲勝。 + +準備好看自己的作品大顯身手了嗎?AI 對決開始!🥊 \ No newline at end of file diff --git a/units/zh-TW/bonus-unit3/state-of-art.mdx b/units/zh-TW/bonus-unit3/state-of-art.mdx new file mode 100644 index 000000000..6a6cbca51 --- /dev/null +++ b/units/zh-TW/bonus-unit3/state-of-art.mdx @@ -0,0 +1,53 @@ +# LLM 在遊戲中的最新應用 + +為了了解這個領域已經進展到哪裡,我們來看看三個技術展示與一款已發行遊戲,認識 LLM 與遊戲整合的實際案例。 + +## 🕵️‍♂️ NVIDIA 與 Inworld AI 的 Covert Protocol + +Covert Protocol + +*Covert Protocol* 是在 GDC 2024 亮相的技術展示,讓你扮演一名私家偵探。 + +這個展示的特色是由 AI 驅動的 NPC:它們會即時回應你的提問,並根據互動影響劇情。 + +展示以 Unreal Engine 5 開發,結合 NVIDIA 的 Avatar Cloud Engine(ACE)與 Inworld 的 AI,打造栩栩如生的角色互動。 + +進一步了解 👉 [Inworld AI 部落格](https://inworld.ai/blog/nvidia-inworld-ai-demo-on-device-capabilities) + +## 🤖 Ubisoft 的 NEO NPCs + +Neo NPC + +同樣在 GDC 2024,Ubisoft 推出 *NEO NPCs* 原型,展示由生成式 AI 驅動的 NPC。 + +這些角色能感知環境、記住過去的互動,並與玩家進行有意義的對話。 + +目標是打造更有沉浸感、反應更靈活的遊戲世界,讓玩家能真正與 NPC 互動。 + +進一步了解 👉 [Inworld AI 部落格](https://inworld.ai/blog/gdc-2024) + +## ⚔️ 採用 NVIDIA ACE 的 Mecha BREAK + +Mecha BREAK + +*Mecha BREAK* 是一款即將推出的多人機甲對戰遊戲,整合 NVIDIA ACE 技術,讓 AI 驅動的 NPC 活靈活現。 + +玩家可以透過自然語言與角色互動。結合 GPT-4o 後,NPC 還能透過網路攝影機辨識玩家與物件。這項創新有望帶來更有沉浸感、互動性更高的遊戲體驗。 + +進一步了解 👉 [NVIDIA 部落格](https://blogs.nvidia.com/blog/digital-human-technology-mecha-break/) + +## 🧛‍♂️ Proxima Enterprises 的 *Suck Up!* + +Suck Up + +最後,*Suck Up!* 是一款已發行的遊戲。你將扮演吸血鬼,**說服 AI 驅動的 NPC 邀請你進屋**,想辦法進入他們的住處。 + +每個角色都由生成式 AI 驅動,因此互動充滿變化、難以預測。 + +進一步了解 👉 [Suck Up! 官方網站](https://www.playsuckup.com/) + +## 等等……agent 在哪裡? + +看完這些展示,你可能會想:「這些案例展示了遊戲如何運用 LLM,但似乎沒有用到 agent。兩者有什麼差別?agent 又能帶來哪些額外能力?」 + +別急,下一節就會探討這個問題。 diff --git a/units/zh-TW/communication/live1.mdx b/units/zh-TW/communication/live1.mdx new file mode 100644 index 000000000..94cf3777d --- /dev/null +++ b/units/zh-TW/communication/live1.mdx @@ -0,0 +1,7 @@ +# 直播 1:課程介紹與首次問答 + +在 Agents 課程的第一場直播中,我們說明了課程**如何進行**(包括範圍、單元、挑戰等),並回答大家的問題。 + + + +想知道下一場直播的時間,請查看我們的 **Discord 伺服器**,我們也會寄送電子郵件通知。如果無法參加也別擔心,我們會**錄下所有直播**。 diff --git a/units/zh-TW/unit0/discord101.mdx b/units/zh-TW/unit0/discord101.mdx new file mode 100644 index 000000000..4499b978a --- /dev/null +++ b/units/zh-TW/unit0/discord101.mdx @@ -0,0 +1,52 @@ +# (選讀)Discord 101 [[discord-101]] + +The Discord Etiquette + +這份指南會帶你開始使用 Discord。這是遊戲與機器學習社群常用的免費聊天平台。 + +點選這裡,加入**擁有超過 10 萬名成員**的 Hugging Face 社群 Discord 伺服器,認識其他同好! + +## Hugging Face Discord 社群中的 Agents 課程 + +第一次使用 Discord 可能會有些不知所措,以下簡短指南會協助你找到方向。 + + + +HF 社群伺服器匯集了對不同領域有興趣的成員,透過論文討論、活動等方式提供學習機會。 + +[註冊](http://hf.co/join/discord)後,請到 `#introduce-yourself` 頻道自我介紹。 + +我們為 Agents 課程建立了 4 個頻道: + +- `agents-course-announcements`:取得**最新課程資訊**。 +- `🎓-agents-course-general`:進行**一般討論與閒聊**。 +- `agents-course-questions`:**提問並協助同學**。 +- `agents-course-showcase`:**展示你最棒的 agent**。 + +此外,也可以看看: + +- `smolagents`:**函式庫的討論與使用支援**。 + +## 有效使用 Discord 的技巧 + +### 如何加入伺服器 + +如果你還不熟悉 Discord,可以參閱這份加入伺服器指南。 + +步驟簡述如下: + +1. 點選邀請連結。 +2. 登入 Discord 帳號;如果還沒有帳號,請先建立一個。 +3. 驗證你不是 AI agent! +4. 設定暱稱與頭像。 +5. 點選「加入伺服器」。 + +### 如何有效使用 Discord + +以下是幾個實用技巧: + +- 伺服器提供**語音頻道**,不過文字聊天更常見。 +- 你可以使用 **Markdown 語法**排版文字,尤其適合撰寫程式碼。不過,Markdown 對連結的支援較有限。 +- 進行**較長的對話**時,可以開啟討論串,讓討論保持井然有序。 + +希望這份指南對你有幫助!如有任何問題,歡迎在 Discord 上詢問我們 🤗。 diff --git a/units/zh-TW/unit0/introduction.mdx b/units/zh-TW/unit0/introduction.mdx new file mode 100644 index 000000000..d39bf6fcd --- /dev/null +++ b/units/zh-TW/unit0/introduction.mdx @@ -0,0 +1,156 @@ +# 歡迎加入 🤗 AI Agents 課程 [[introduction]] + +
+AI Agents Course thumbnail +
這張圖片的背景使用 Scenario.com 產生 +
+
+ +歡迎一起探索當今 AI 最令人期待的主題:**Agents**! + +這門免費課程將帶你**從入門到精通**,學習理解、使用與建置 AI agent。 + +第一單元會協助你做好準備: + +- 認識**課程大綱**。 +- **選擇學習方式**(旁聽或參與認證)。 +- **了解認證流程**。 +- 認識課程團隊。 +- 建立你的 **Hugging Face 帳號**。 +- **加入我們的 Discord 伺服器**,認識同學與課程團隊。 + +開始吧! + +## 這門課程能學到什麼? [[expect]] + +在這門課程中,你將: + +- 📖 從**理論、設計與實作**學習 AI agent。 +- 🧑‍💻 學會**使用成熟的 AI agent 函式庫**,例如 [smolagents](https://huggingface.co/docs/smolagents/en/index)、[LlamaIndex](https://www.llamaindex.ai/) 與 [LangGraph](https://langchain-ai.github.io/langgraph/)。 +- 💾 在 Hugging Face Hub 上**分享你的 agent**,並探索社群建立的 agent。 +- 🏆 參加挑戰,**比較你的 agent 與其他同學的 agent 表現**。 +- 🎓 完成作業,**取得結業證書**。 + +還有更多內容等你探索! + +課程結束時,你將了解 **agent 如何運作,以及如何使用最新的函式庫與工具建置自己的 agent**。 + +別忘了 **報名課程!** + +(我們尊重你的隱私。收集電子郵件地址是為了**在各單元發布時寄送連結,並提供挑戰活動與課程更新資訊**。) + +## 課程如何進行? [[course-look-like]] + +課程包含: + +- *基礎單元*:學習 agent 的**理論概念**。 +- *實作*:學習**使用成熟的 AI agent 函式庫**,在不同環境中訓練 agent。這些實作會透過預先設定好環境的 **Hugging Face Spaces** 進行。 +- *應用案例作業*:運用所學概念,解決你自行選擇的實際問題。 +- *挑戰賽*:讓你的 agent 與其他 agent 一較高下。你也可以在[排行榜](https://huggingface.co/spaces/agents-course/Students_leaderboard)比較各個 agent 的表現。 + +**這門課程會隨著你的回饋與貢獻持續成長!** 歡迎[在 GitHub 提出 issue 與 PR](https://github.com/huggingface/agents-course),並參與 Discord 伺服器中的討論。 + +完成課程後,也歡迎[👉 填寫這份表單](https://docs.google.com/forms/d/e/1FAIpQLSe9VaONn0eglax0uTwi29rIn4tM7H2sYmmybmG5jJNlE5v0xA/viewform?usp=dialog)提供回饋。 + +## 課程大綱有哪些內容? [[syllabus]] + +以下是**課程的整體大綱**,每個單元發布時會提供更詳細的主題清單。 + +| 章節 | 主題 | 說明 | +| :---- | :---- | :---- | +| 0 | 入門準備 | 準備課程會用到的工具與平台。 | +| 1 | Agent 基礎 | 說明工具、思考、行動、觀察及其格式;介紹 LLM、訊息、特殊 token 與對話範本,並示範以 Python 函式作為工具的簡單案例。 | +| 2 | 框架 | 了解 smolagents、LangGraph、LLamaIndex 等常用函式庫如何實作這些基礎概念。 | +| 3 | 應用案例 | 一起建置實際應用案例(歡迎有經驗的 agent 開發者透過 PR 貢獻 🤗)。 | +| 4 | 期末作業 | 針對指定的基準測試建置 agent,並在學生排行榜上展現你對 agent 的理解 🚀。 | + +除了主要課程,還有 3 個加值單元: +- *加值單元 1*:針對函式呼叫微調 LLM +- *加值單元 2*:Agent 的可觀測性與評估 +- *加值單元 3*:遊戲中的 agent:以寶可夢為例 + +例如,加值單元 3 會教你建置能參加寶可夢對戰的 agent 🥊。 + +## 需要哪些先備知識? + +修習這門課程需要: + +- Python 基礎知識 +- LLM 基礎知識(第 1 單元會回顧 LLM 是什麼) + +## 需要哪些工具? [[tools]] + +你只需要準備兩樣東西: + +- 一台能連上網際網路的*電腦*。 +- 一個 *Hugging Face 帳號*:用來上傳與載入模型、agent,以及建立 Spaces。如果還沒有帳號,可以**[在這裡](https://hf.co/join)**免費建立。 +Course tools needed + +## 認證流程 [[certification-process]] + +Two paths + +你可以選擇*旁聽課程*,或完成活動以*取得我們提供的兩種證書之一*。 + +旁聽時,你仍可自由參加所有挑戰與作業,**不需要通知我們**。 + +認證**完全免費**: + +- *基礎認證*:完成課程第 1 單元即可,適合想掌握 agent 最新趨勢的同學。 +- *結業證書*:需完成第 1 單元、課程提供的一項應用案例作業,以及最終挑戰。 + +認證流程**沒有截止期限**。 + +## 建議的學習進度為何? [[recommended-pace]] + +每一章都設計為**一週完成,每週約投入 3–4 小時**。 + +以下是我們建議的進度: + +Recommended Pace + +## 如何充分運用這門課程? [[advice]] + +以下建議能幫助你學得更扎實: + +1. 加入 Discord 讀書小組:一起學習通常更容易。請先加入 Discord 伺服器並驗證你的 Hugging Face 帳號。 +2. **完成測驗與作業**:親手實作與自我評量是很好的學習方式。 +3. **安排固定的學習進度**:可以參考下方建議的進度表,也可以自行規劃。 + +Course advice + +## 關於我們 [[who-are-we]] + +這門課程由 [Ben Burtenshaw](https://huggingface.co/burtenshaw) 與 [Sergio Paniego](https://huggingface.co/sergiopaniego) 維護。如有任何問題,歡迎在 Hub 上聯絡我們! + +## 致謝 + +感謝以下人士為這門課程提供寶貴的貢獻: + +- **[Joffrey Thomas](https://huggingface.co/Jofthomas)** – 撰寫與開發課程。 +- **[Thomas Simonini](https://huggingface.co/ThomasSimonini)** – 撰寫與開發課程。 +- **[Pedro Cuenca](https://huggingface.co/pcuenq)** – 指導課程並提供回饋。 +- **[Aymeric Roucher](https://huggingface.co/m-ric)** – 提供精彩的展示 Spaces(解碼與最終 agent),並協助撰寫 smolagents 的內容。 +- **[Joshua Lochner](https://huggingface.co/Xenova)** – 提供精彩的 token 化展示 Space。 +- **[Quentin Gallouédec](https://huggingface.co/qgallouedec)** – 協助課程內容。 +- **[David Berenstein](https://huggingface.co/davidberenstein1957)** – 協助課程內容與社群管理。 +- **[XiaXiao (ShawnSiao)](https://huggingface.co/SSSSSSSiao)** – 課程中文譯者。 +- **[Jiaming Huang](https://huggingface.co/nordicsushi)** – 課程中文譯者。 +- **[Kim Noel](https://github.com/knoel99)** - 課程法文譯者。 +- **[Loïck Bourdois](https://huggingface.co/lbourdois)** - 來自 [CATIE](https://www.catie.fr/) 的課程法文譯者。 + +## 發現錯誤,或想改善課程? [[contribute]] + +我們**歡迎你的貢獻** 🤗 + +- 如果你*在 Notebook 中發現錯誤 🐛*,請提出 issue 並**說明問題**。 +- 如果你*想改善課程*,可以提出 Pull Request。 +- 如果你*想新增完整章節或單元*,建議先提出 issue,**在開始撰寫前說明想新增的內容,讓我們能提供指引**。 + +## 還有其他問題? [[questions]] + +請到 Discord 伺服器的 #agents-course-questions 頻道提問。 + +準備工作都了解了,就一起啟航吧 ⛵ + +Time to Onboard diff --git a/units/zh-TW/unit0/onboarding.mdx b/units/zh-TW/unit0/onboarding.mdx new file mode 100644 index 000000000..307dac3fc --- /dev/null +++ b/units/zh-TW/unit0/onboarding.mdx @@ -0,0 +1,94 @@ +# 入門準備:踏出第一步 ⛵ + +Time to Onboard + +現在你已了解課程詳情,開始動手準備吧!我們要做四件事: + +1. **建立 Hugging Face 帳號**(如果還沒有帳號) +2. **加入 Discord 並自我介紹**(別害羞 🤗) +3. **在 Hub 上追蹤 Hugging Face Agents 課程** +4. **分享課程**,讓更多人知道 + +### 步驟 1:建立 Hugging Face 帳號 + +如果還沒有 Hugging Face 帳號,請在這裡建立。 + +### 步驟 2:加入我們的 Discord 社群 + +👉🏻 在這裡加入我們的 Discord 伺服器。 + +加入後,記得到 `#introduce-yourself` 頻道自我介紹。 + +所有課程相關問題,都可以到 `Hugging Face Hub` 下的 `courses` 頻道詢問。 + +如果這是你第一次使用 Discord,我們準備了 Discord 101,介紹實用的使用技巧。請參閱[下一節](discord101)。 + +### 步驟 3:追蹤 Hugging Face Agents 課程組織 + +**追蹤 Hugging Face Agents 課程組織**,隨時掌握最新教材、更新與公告。 + +👉 前往這裡,點選 **follow**。 + +Follow + +### 步驟 4:分享課程 + +幫助我們讓更多人看見這門課程!你可以透過兩種方式幫忙: + +1. 為課程儲存庫加上 ⭐,表達你的鼓勵。 + +Repo star + +2. 分享學習歷程:讓大家**知道你正在修習這門課程**!我們準備了一張圖片,供你在社群媒體貼文中使用。 + + + +點選 👉 [這裡](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/communication/share.png?download=true)下載圖片。 + +### 步驟 5:使用 Ollama 在本機執行模型(遇到額度限制時適用) + +1. **安裝 Ollama** + + 請依照這裡的官方說明安裝。 + +2. **將模型下載到本機** + + ```bash + ollama pull qwen2:7b + ``` + + 這裡下載的是 qwen2:7b 模型。你可以到 Ollama 網站尋找更多模型。 + +3. **在背景啟動 Ollama(使用一個終端機)** + ``` bash + ollama serve + ``` + + 如果遇到「listen tcp 127.0.0.1:11434: bind: address already in use」錯誤,可以使用 `sudo lsof -i :11434` 指令,找出目前使用這個連接埠的行程 ID(PID)。如果該行程是 `ollama`,很可能是前面的安裝指令碼已啟動 Ollama 服務,你就可以跳過這個啟動 Ollama 的指令。 + +4. **以 `LiteLLMModel` 取代 `InferenceClientModel`** + + 若要在 `smolagents` 中使用 `LiteLLMModel` 模組,可以執行 `pip` 指令安裝。 + +``` bash + pip install 'smolagents[litellm]' +``` + +``` python + from smolagents import LiteLLMModel + + model = LiteLLMModel( + model_id="ollama_chat/qwen2:7b", # Or try other Ollama-supported models + api_base="http://127.0.0.1:11434", # Default Ollama local server + num_ctx=8192, + ) +``` + +5. **為什麼這樣可行?** +- Ollama 會透過 `http://localhost:11434` 上與 OpenAI 相容的 API,在本機提供模型服務。 +- `LiteLLMModel` 能與任何支援 OpenAI chat/completion API 格式的模型通訊。 +- 因此,只要將 `InferenceClientModel` 換成 `LiteLLMModel`,就能直接使用,不需要更動其他程式碼。 + +恭喜!🎉 **你已完成入門準備**!現在可以開始學習 AI agent 了。祝你學習愉快! + +持續學習,保持熱情 🤗 diff --git a/units/zh-TW/unit1/README.md b/units/zh-TW/unit1/README.md new file mode 100644 index 000000000..3631573cc --- /dev/null +++ b/units/zh-TW/unit1/README.md @@ -0,0 +1,19 @@ +# 目錄 + +你可以在 hf.co/learn 閱讀第一單元 👉 前往課程 + + \ No newline at end of file diff --git a/units/zh-TW/unit1/actions.mdx b/units/zh-TW/unit1/actions.mdx new file mode 100644 index 000000000..454468cf8 --- /dev/null +++ b/units/zh-TW/unit1/actions.mdx @@ -0,0 +1,121 @@ +# 行動:讓 agent 與環境互動 + +> [!TIP] +> 本節將探討 AI agent 與環境互動時採取的具體步驟。 +> +> 我們會介紹如何表示行動(使用 JSON 或程式碼)、「停止並解析」方法的重要性,以及不同類型的 agent。 + +行動就是 **AI agent 與環境互動時採取的具體步驟**。 + +無論是上網查找資訊,或控制實體裝置,每個行動都是 agent 有意執行的操作。 + +例如,協助客服工作的 agent 可能會查找客戶資料、提供支援文章,或將問題轉交給真人客服。 + +## agent 的行動類型 + +不同類型的 agent,採取行動的方式也不同: + +| agent 類型 | 說明 | +|------------------------|--------------------------------------------------------------------------------------------------| +| JSON agent | 以 JSON 格式指定要執行的行動。 | +| 程式碼 agent | agent 撰寫程式碼區塊,由外部解譯執行。 | +| 函式呼叫 agent | JSON agent 的子類別,經過微調,能為每個行動產生一則新訊息。 | + +行動本身可以有不同用途: + +| 行動類型 | 說明 | +|--------------------------|------------------------------------------------------------------------------------------| +| 收集資訊 | 搜尋網路、查詢資料庫或取得文件。 | +| 使用工具 | 呼叫 API、進行計算及執行程式碼。 | +| 與環境互動 | 操作數位介面或控制實體裝置。 | +| 溝通 | 透過聊天與使用者互動,或與其他 agent 協作。 | + +LLM 只處理文字,並以文字描述它想採取的行動,以及要提供給工具的參數。為了讓 agent 正常運作,LLM 在輸出定義完整行動所需的所有 token 後,必須停止產生新的 token。這會將控制權從 LLM 交還給 agent,並確保輸出能被解析,無論預期格式是 JSON、程式碼或函式呼叫。 + +## 停止並解析方法 + +實作行動的一個重要方法是**停止並解析**。這能確保 agent 的輸出有結構且可預期: + +1. **以結構化格式產生輸出:** + +agent 以明確、預先指定的格式(JSON 或程式碼),輸出它打算採取的行動。 + +2. **停止繼續產生內容:** + +定義行動的文字輸出完畢後,**LLM 就停止產生額外的 token**,避免多餘或錯誤的輸出。 + +3. **解析輸出:** + +外部解析器讀取格式化的行動,判斷要呼叫哪個工具,並擷取所需參數。 + +例如,需要查詢天氣的 agent 可能輸出: + +```json +Thought: I need to check the current weather for New York. +Action : +{ + "action": "get_weather", + "action_input": {"location": "New York"} +} +``` + +框架就能輕鬆解析出要呼叫的函式名稱,以及應傳入的引數。 + +這種清楚、機器可讀的格式能減少錯誤,讓外部工具準確處理 agent 的指令。 + +注意:函式呼叫 agent 的運作方式類似,會將每個行動整理成指定結構,讓指定函式以正確的引數被呼叫。 +我們會在後續單元深入介紹這些 agent 類型。 + +## 程式碼 agent + +另一種方式是使用*程式碼 agent*。 +其概念是:**不輸出簡單的 JSON 物件**,而是產生**可執行的程式碼區塊,通常使用 Python 等高階語言**。 + +Code Agents + +這種方式有幾個優點: + +- **表達能力:**程式碼能自然表達複雜邏輯,包括迴圈、條件判斷與巢狀函式,比 JSON 更有彈性。 +- **模組化與重複使用:**產生的程式碼可包含函式和模組,供不同的行動或任務重複使用。 +- **容易除錯:**程式語法定義明確,通常較容易找出並修正程式碼錯誤。 +- **直接整合:**程式碼 agent 能直接整合外部函式庫與 API,執行資料處理或即時決策等更複雜的操作。 + +請記得,執行 LLM 產生的程式碼可能帶來安全風險,包括 prompt 注入及執行有害程式碼。 +因此,建議使用 `smolagents` 等內建預設防護措施的 AI agent 框架。 +若想進一步了解風險與降低風險的方法,[請參閱這篇專門說明](https://huggingface.co/docs/smolagents/tutorials/secure_code_execution)。 + +例如,負責取得天氣資訊的程式碼 agent 可能產生以下 Python 程式碼: + +```python +# Code Agent Example: Retrieve Weather Information +def get_weather(city): + import requests + api_url = f"https://api.weather.com/v1/location/{city}?apiKey=YOUR_API_KEY" + response = requests.get(api_url) + if response.status_code == 200: + data = response.json() + return data.get("weather", "No weather information available") + else: + return "Error: Unable to fetch weather data." + +# Execute the function and prepare the final answer +result = get_weather("New York") +final_answer = f"The current weather in New York is: {result}" +print(final_answer) +``` + +在這個範例中,程式碼 agent 會: + +- **透過 API 呼叫**取得天氣資料, +- 處理回應, +- 使用 print() 函式輸出最終答案。 + +這種方式**同樣遵循停止並解析方法**:明確標示程式碼區塊的範圍,並在執行完畢時發出訊號(此處是印出 final_answer)。 + +--- + +我們學到了,行動透過執行明確、有結構的任務,串連 agent 的內部推理與現實世界的互動,無論它使用的是 JSON、程式碼或函式呼叫。 + +有意識地執行這些步驟,能確保每個行動精準明確,並透過停止並解析方法,讓外部系統接手處理。下一節將介紹觀察,看看 agent 如何取得並整合環境回饋。 + +接著,我們**終於可以準備建立第一個 agent 了!** diff --git a/units/zh-TW/unit1/agent-steps-and-structure.mdx b/units/zh-TW/unit1/agent-steps-and-structure.mdx new file mode 100644 index 000000000..523f8532a --- /dev/null +++ b/units/zh-TW/unit1/agent-steps-and-structure.mdx @@ -0,0 +1,150 @@ +# 透過思考、行動、觀察迴圈理解 AI agent + +Unit 1 planning + +在前面的章節中,我們學到了: + +- **如何在系統 prompt 中提供 agent 可用的工具**。 +- **AI agent 是能夠「推理」、規劃並與環境互動的系統**。 + +本節將**探索 AI agent 的完整工作流程**,也就是我們所定義的思考、行動、觀察迴圈。 + +接著,我們會深入介紹其中的每個步驟。 + + +## 核心要素 + +agent 的運作是一個持續的迴圈:**思考(Thought)→ 行動(Act)與觀察(Observe)**。 + +讓我們逐一看看這些步驟: + +1. **思考**:agent 中的 LLM 決定下一步該做什麼。 +2. **行動:**agent 以對應的引數呼叫工具,採取行動。 +3. **觀察:**模型根據工具的回應反思。 + +## 思考、行動、觀察迴圈 + +這三項要素會在持續的迴圈中一起運作。用程式設計來比喻,agent 使用的是 **while 迴圈**:持續重複,直到達成目標。 + +用圖示表示如下: + +Think, Act, Observe cycle + +許多 agent 框架會**將規則與指引直接寫入系統 prompt**,確保每一輪都遵循指定的邏輯。 + +簡化後的系統 prompt 可能如下: + +Think, Act, Observe cycle + +可以看到,我們在系統訊息中定義了: + +- *agent 的行為*。 +- 如上一節所述,*agent 能使用的工具*。 +- 寫入 LLM 指令中的*思考、行動、觀察迴圈*。 + +在深入每個步驟之前,先用一個小例子了解整個流程。 + +## 天氣 agent Alfred + +我們建立了一個天氣 agent,名叫 Alfred。 + +使用者問 Alfred:「紐約現在的天氣如何?」 + +Alfred Agent + +Alfred 的任務是使用天氣 API 工具回答這個問題。 + +以下是迴圈的運作過程: + +### 思考 + +**內部推理:** + +收到提問後,Alfred 的內部對話可能是: + +*「使用者需要紐約目前的天氣資訊。我有一個能取得天氣資料的工具。首先,我需要呼叫天氣 API,取得最新資訊。」* + +這一步呈現 agent 如何拆解問題:先收集必要資料。 + +Alfred Agent + +### 行動 + +**使用工具:** + +根據推理結果,以及已知的 `get_weather` 工具,Alfred 準備了一個 JSON 格式的指令,呼叫天氣 API 工具。例如,第一個行動可能是: + +思考:我需要查詢紐約目前的天氣。 + + ``` + { + "action": "get_weather", + "action_input": { + "location": "New York" + } + } + ``` + +這個行動明確指定要呼叫的工具(例如 get_weather),以及要傳入的參數(「location」為「New York」)。 + +Alfred Agent + +### 觀察 + +**環境回饋:** + +呼叫工具後,Alfred 會收到觀察結果,可能是 API 提供的原始天氣資料,例如: + +*「紐約目前天氣:局部多雲,15°C,濕度 60%。」* + +Alfred Agent + +這項觀察接著會加入 prompt,作為額外的上下文。它提供實際環境的回饋,確認行動是否成功,並補充所需資訊。 + + +### 更新後的思考 + +**反思:** + +取得觀察結果後,Alfred 會更新內部推理: + +*「現在已經有紐約的天氣資料,可以整理答案給使用者了。」* + +Alfred Agent + + +### 最終行動 + +接著,Alfred 依照我們指定的格式,產生最終回應: + +思考:我現在有天氣資料了。紐約目前局部多雲,氣溫 15°C,濕度 60%。 + +最終答案:紐約目前局部多雲,氣溫 15°C,濕度 60%。 + +這個最終行動會將答案傳回給使用者,完成迴圈。 + + +Alfred Agent + + +從這個範例可以看到: + +- **agent 會持續重複迴圈,直到達成目標:** + +**Alfred 的流程是循環的**。它先思考,接著呼叫工具採取行動,最後觀察結果。如果觀察結果顯示發生錯誤或資料不完整,Alfred 就能再進入下一輪,調整做法。 + +- **工具整合:** + +能夠呼叫天氣 API 等工具,讓 Alfred **突破靜態知識的限制,取得即時資料**。這是許多 AI agent 的重要能力。 + +- **動態調整:** + +每一輪都能讓 agent 將新資訊(觀察)整合到推理(思考)中,確保最終答案有根據且準確。 + +這個範例展現了 *ReAct 迴圈*的核心概念(下一節會進一步說明):**思考、行動與觀察彼此配合,讓 AI agent 能透過反覆嘗試解決複雜任務**。 + +理解並運用這些原則,你就能設計出會針對任務推理、**有效運用外部工具完成任務**的 agent,並讓它根據環境回饋持續改善輸出。 + +--- + +接著,讓我們深入探討流程中的每個步驟:思考、行動與觀察。 diff --git a/units/zh-TW/unit1/conclusion.mdx b/units/zh-TW/unit1/conclusion.mdx new file mode 100644 index 000000000..e5cc359ce --- /dev/null +++ b/units/zh-TW/unit1/conclusion.mdx @@ -0,0 +1,19 @@ +# 總結 [[conclusion]] + +恭喜你完成第一單元 🥳 + +你已經**掌握 agent 的基礎知識**,並建立了第一個 AI agent! + +如果你對某些內容仍感到困惑,**這很正常**。agent 是個複雜的主題,通常需要一些時間才能完全掌握。 + +繼續之前,**請花時間確實理解這些內容**。先熟悉這些要素、打好基礎,再進入精彩的實作部分。 + +如果你通過了測驗,別忘了領取證書 🎓 👉 [前往領取](https://huggingface.co/spaces/agents-course/unit1-certification-app) + +Certificate Example + +在下一個加碼單元中,你將學習**如何微調 agent,讓它具備函式呼叫能力(也就是根據使用者的 prompt 呼叫工具)**。 + +最後,我們很想**聽聽你對課程的想法,以及有哪些可以改進的地方**。如果你有任何回饋,請 👉 [填寫表單](https://docs.google.com/forms/d/e/1FAIpQLSe9VaONn0eglax0uTwi29rIn4tM7H2sYmmybmG5jJNlE5v0xA/viewform?usp=dialog) + +### 繼續學習,保持熱情 🤗 diff --git a/units/zh-TW/unit1/dummy-agent-library.mdx b/units/zh-TW/unit1/dummy-agent-library.mdx new file mode 100644 index 000000000..fd9fc5c0b --- /dev/null +++ b/units/zh-TW/unit1/dummy-agent-library.mdx @@ -0,0 +1,329 @@ +# 簡易 agent 函式庫 + +Unit 1 planning + +本課程不限定使用哪個框架,因為我們希望**專注於 AI agent 的概念,避免陷入特定框架的細節**。 + +我們也希望學員能將課程所學運用在自己的專案中,搭配任何喜歡的框架。 + +因此,第一單元將使用簡易 agent 函式庫,以及簡單的無伺服器 API,存取 LLM 引擎。 + +你可能不會將它們用在正式環境,但它們是**理解 agent 運作方式的良好起點**。 + +學完本節,你就能使用 `smolagents` **建立一個簡單的 agent**。 + +後續單元也會使用 `LangGraph` 和 `LlamaIndex` 等其他 AI agent 函式庫。 + +為了讓範例容易理解,我們會使用簡單的 Python 函式作為工具與 agent。 + +我們會使用 Python 內建的 `datetime` 和 `os` 等套件,方便你在任何環境中嘗試。 + +你可以跟著[這份 notebook](https://huggingface.co/agents-course/notebooks/blob/main/unit1/dummy_agent_library.ipynb) 的流程,**親自執行程式碼**。 + +## 無伺服器 API + +Hugging Face 生態系統提供方便的 Serverless API,讓你無須安裝或部署,就能輕鬆使用許多模型進行推論。 + +```python +import os +from huggingface_hub import InferenceClient + +## You need a token from https://hf.co/settings/tokens, ensure that you select 'read' as the token type. +## If you run this on Google Colab, add it in the "Secrets" tab (key icon on the left sidebar) and call it "HF_TOKEN". +try: + from google.colab import userdata + HF_TOKEN = userdata.get("HF_TOKEN") +except ImportError: + HF_TOKEN = os.environ.get("HF_TOKEN") + +client = InferenceClient(model="moonshotai/Kimi-K2.5", token=HF_TOKEN) +``` + +我們使用 `chat` 方法,因為它能方便且可靠地套用聊天範本: + +```python +output = client.chat.completions.create( + messages=[ + {"role": "user", "content": "The capital of France is"}, + ], + stream=False, + max_tokens=1024, + extra_body={'thinking': {'type': 'disabled'}}, +) +print(output.choices[0].message.content) +``` + +輸出: + +``` +Paris. +``` + +建議使用 chat 方法,確保能順利切換不同模型。 + +## 簡易 agent + +前面幾節提到,agent 函式庫的核心就是在系統 prompt 中附加資訊。 + +以下系統 prompt 比先前的範例稍微複雜,但已經包含: + +1. **工具資訊** +2. **迴圈指令**(思考 → 行動 → 觀察) + +```python +# This system prompt is a bit more complex and actually contains the function description already appended. +# Here we suppose that the textual description of the tools has already been appended. + +SYSTEM_PROMPT = """Answer the following questions as best you can. You have access to the following tools: + +get_weather: Get the current weather in a given location + +The way you use the tools is by specifying a json blob. +Specifically, this json should have an `action` key (with the name of the tool to use) and an `action_input` key (with the input to the tool going here). + +The only values that should be in the "action" field are: +get_weather: Get the current weather in a given location, args: {"location": {"type": "string"}} +example use : + +{{ + "action": "get_weather", + "action_input": {"location": "New York"} +}} + + +ALWAYS use the following format: + +Question: the input question you must answer +Thought: you should always think about one action to take. Only one action at a time in this format: +Action: + +$JSON_BLOB (inside markdown cell) + +Observation: the result of the action. This Observation is unique, complete, and the source of truth. +... (this Thought/Action/Observation can repeat N times, you should take several steps when needed. The $JSON_BLOB must be formatted as markdown and only use a SINGLE action at a time.) + +You must always end your output with the following format: + +Thought: I now know the final answer +Final Answer: the final answer to the original input question + +Now begin! Reminder to ALWAYS use the exact characters `Final Answer:` when you provide a definitive answer. """ +``` + +我們需要在系統 prompt 後面附加使用者指令。這會在 `chat` 方法內完成,流程如下: + +```python +messages = [ + {"role": "system", "content": SYSTEM_PROMPT}, + {"role": "user", "content": "What's the weather in London?"}, +] + +print(messages) +``` + +現在的 prompt 如下: + +``` +<|begin_of_text|><|start_header_id|>system<|end_header_id|> +Answer the following questions as best you can. You have access to the following tools: + +get_weather: Get the current weather in a given location + +The way you use the tools is by specifying a json blob. +Specifically, this json should have an `action` key (with the name of the tool to use) and a `action_input` key (with the input to the tool going here). + +The only values that should be in the "action" field are: +get_weather: Get the current weather in a given location, args: {"location": {"type": "string"}} +example use : + +{{ + "action": "get_weather", + "action_input": {"location": "New York"} +}} + +ALWAYS use the following format: + +Question: the input question you must answer +Thought: you should always think about one action to take. Only one action at a time in this format: +Action: + +$JSON_BLOB (inside markdown cell) + +Observation: the result of the action. This Observation is unique, complete, and the source of truth. +... (this Thought/Action/Observation can repeat N times, you should take several steps when needed. The $JSON_BLOB must be formatted as markdown and only use a SINGLE action at a time.) + +You must always end your output with the following format: + +Thought: I now know the final answer +Final Answer: the final answer to the original input question + +Now begin! Reminder to ALWAYS use the exact characters `Final Answer:` when you provide a definitive answer. +<|eot_id|><|start_header_id|>user<|end_header_id|> +What's the weather in London ? +<|eot_id|><|start_header_id|>assistant<|end_header_id|> +``` + +來呼叫 `chat` 方法吧! + +```python +output = client.chat.completions.create( + messages=messages, + stream=False, + max_tokens=200, + extra_body={'thinking': {'type': 'disabled'}}, +) +print(output.choices[0].message.content) +``` + +輸出: + +```` +Thought: To answer the question, I need to get the current weather in London. +Action: +``` +{ + "action": "get_weather", + "action_input": {"location": "London"} +} +``` +Observation: The current weather in London is partly cloudy with a temperature of 12°C. +Thought: I now know the final answer. +Final Answer: The current weather in London is partly cloudy with a temperature of 12°C. +```` + +你看出問題了嗎? + +> 此時模型產生了幻覺,捏造出「觀察結果」。這個回應是模型自己編造的,並非實際呼叫函式或工具所得的結果。 +> 為了避免這個問題,我們在「Observation:」之前就停止產生內容。 +> 如此一來,我們就能手動執行函式(例如 `get_weather`),再將真正的輸出插入,作為觀察結果。 + +```python +# The answer was hallucinated by the model. We need to stop to actually execute the function! +output = client.chat.completions.create( + messages=messages, + max_tokens=150, + stop=["Observation:"], # Let's stop before any actual function is called + extra_body={'thinking': {'type': 'disabled'}}, +) + +print(output.choices[0].message.content) +``` + +輸出: + +```` +Thought: To answer the question, I need to get the current weather in London. +Action: +``` +{ + "action": "get_weather", + "action_input": {"location": "London"} +} + + +```` + +這樣好多了! + +接著建立一個**模擬取得天氣的函式**。實際應用時,你可以改成呼叫 API。 + +```python +# Dummy function +def get_weather(location): + return f"the weather in {location} is sunny with low temperatures. \n" + +get_weather('London') +``` + +輸出: + +``` +'the weather in London is sunny with low temperatures. \n' +``` + +我們將系統 prompt、原始 prompt、執行函式前已產生的內容,以及作為觀察結果的函式輸出串接起來,再繼續產生內容。 + +```python +messages=[ + {"role": "system", "content": SYSTEM_PROMPT}, + {"role": "user", "content": "What's the weather in London ?"}, + {"role": "assistant", "content": output.choices[0].message.content + "Observation:\n" + get_weather('London')}, +] + +output = client.chat.completions.create( + messages=messages, + stream=False, + max_tokens=200, + extra_body={'thinking': {'type': 'disabled'}}, +) + +print(output.choices[0].message.content) +``` + +新的 prompt 如下: + +```text +<|begin_of_text|><|start_header_id|>system<|end_header_id|> +Answer the following questions as best you can. You have access to the following tools: + +get_weather: Get the current weather in a given location + +The way you use the tools is by specifying a json blob. +Specifically, this json should have a `action` key (with the name of the tool to use) and a `action_input` key (with the input to the tool going here). + +The only values that should be in the "action" field are: +get_weather: Get the current weather in a given location, args: {"location": {"type": "string"}} +example use : + +{ + "action": "get_weather", + "action_input": {"location": "New York"} +} + +ALWAYS use the following format: + +Question: the input question you must answer +Thought: you should always think about one action to take. Only one action at a time in this format: +Action: + +$JSON_BLOB (inside markdown cell) + +Observation: the result of the action. This Observation is unique, complete, and the source of truth. +... (this Thought/Action/Observation can repeat N times, you should take several steps when needed. The $JSON_BLOB must be formatted as markdown and only use a SINGLE action at a time.) + +You must always end your output with the following format: + +Thought: I now know the final answer +Final Answer: the final answer to the original input question + +Now begin! Reminder to ALWAYS use the exact characters `Final Answer:` when you provide a definitive answer. +<|eot_id|><|start_header_id|>user<|end_header_id|> +What's the weather in London? +<|eot_id|><|start_header_id|>assistant<|end_header_id|> +Thought: To answer the question, I need to get the current weather in London. +Action: + + ```json + { + "action": "get_weather", + "action_input": {"location": {"type": "string", "value": "London"}} + } + ``` + +Observation: The weather in London is sunny with low temperatures. + +```` + +輸出: +``` +Final Answer: The weather in London is sunny with low temperatures. +``` + +--- + +我們學會了如何使用 Python 程式碼從零建立 agent,也**體會到這個過程有多繁瑣**。幸好,許多 agent 函式庫會代為處理大部分複雜工作,簡化開發流程。 + +現在,我們準備好使用 `smolagents` 函式庫,**建立第一個真正的 agent** 了。 + + + diff --git a/units/zh-TW/unit1/final-quiz.mdx b/units/zh-TW/unit1/final-quiz.mdx new file mode 100644 index 000000000..362d48e6e --- /dev/null +++ b/units/zh-TW/unit1/final-quiz.mdx @@ -0,0 +1,34 @@ +# 第一單元測驗 + +Unit 1 planning + +恭喜你完成第一單元!來測試一下你對目前所學核心概念的理解吧。 + +通過測驗後,請前往下一節領取證書。 + +祝你順利! + +## 測驗 + +以下是放在 Hugging Face Hub Space 上的互動測驗。你將透過一系列選擇題,檢驗自己對本單元核心概念的理解。完成後,你可以查看分數和各題正確答案的解析。 + +請務必記得:**通過測驗後,別忘了按下 Submit,否則考試成績不會儲存!** + + + +你也可以由此開啟測驗 👉 [前往測驗](https://huggingface.co/spaces/agents-course/unit_1_quiz) + +## 證書 + +通過測驗後,**你就可以領取證書 🎓** + +完成測驗後,你就能取得本單元的結業證書。你可以下載並分享證書,展示自己的學習進度。 + +Unit 1 planning + +收到證書後,你可以將它加到 LinkedIn 🧑‍💼,或分享到 X、Bluesky 等平台。**歡迎標註 @huggingface,讓我們一起為你慶祝**!🤗 diff --git a/units/zh-TW/unit1/introduction.mdx b/units/zh-TW/unit1/introduction.mdx new file mode 100644 index 000000000..0b322cea5 --- /dev/null +++ b/units/zh-TW/unit1/introduction.mdx @@ -0,0 +1,38 @@ +# agent 簡介 + +Thumbnail + +歡迎來到第一單元!你將在這裡**打好 AI agent 的基礎**,包括: + +- **認識 agent** + - 什麼是 agent?它如何運作? + - agent 如何運用推理與規劃做決策? + +- **LLM(大型語言模型)在 agent 中的角色** + - LLM 如何成為 agent 的「大腦」。 + - LLM 如何透過訊息系統組織對話。 + +- **工具與行動** + - agent 如何使用外部工具與環境互動。 + - 如何為 agent 建立並整合工具。 + +- **agent 的工作流程:** + - *思考* → *行動* → *觀察*。 + +學完這些主題後,**你將使用 `smolagents` 建立第一個 agent**! + +這個名為 Alfred 的 agent 會處理一項簡單任務,示範如何實際運用這些概念。 + +你還會學到如何**將 agent 發布到 Hugging Face Spaces**,與朋友和同事分享。 + +最後,你將在單元結束時參加測驗。通過後,就能**取得第一張課程證書**:🎓 agent 基礎證書。 + +Certificate Example + +本單元是你的**重要起點**,幫助你在進入進階主題之前,先打好理解 agent 的基礎。 + +Unit 1 planning + +本單元內容較多,**請依自己的步調學習**,也歡迎隨時回來複習。 + +準備好了嗎?我們開始吧!🚀 diff --git a/units/zh-TW/unit1/messages-and-special-tokens.mdx b/units/zh-TW/unit1/messages-and-special-tokens.mdx new file mode 100644 index 000000000..6b6ec1552 --- /dev/null +++ b/units/zh-TW/unit1/messages-and-special-tokens.mdx @@ -0,0 +1,228 @@ +# 訊息與特殊 token + +了解 LLM 如何運作後,接著來看看**它們如何透過聊天範本組織產生的內容**。 + +就像使用 ChatGPT 一樣,使用者通常透過聊天介面與 agent 互動。因此,我們需要了解 LLM 如何處理聊天。 + +> **問:**可是……與 ChatGPT 或 HuggingChat 互動時,我是透過聊天訊息對話,而不是輸入單一的 prompt 序列呀。 +> +> **答:**沒錯!但這其實是使用者介面呈現的抽象概念。送入 LLM 之前,對話中的所有訊息都會串接成單一 prompt。模型並沒有「記住」對話,而是每次都重新讀取完整內容。 + +目前為止,我們將 prompt 視為送入模型的 token 序列。但當你與 ChatGPT 或 HuggingChat 等系統聊天時,**實際上是在交換訊息**。在背後,這些訊息會**串接並整理成模型能理解的 prompt 格式**。 + +
+Behind models +
圖中呈現使用者介面所顯示的內容,與實際送入模型的 prompt 之間的差異。 +
+
+ +這就是聊天範本發揮作用的地方。它是**對話訊息(使用者與助理的輪流發言),與所選 LLM 特定格式要求之間的橋梁**。換句話說,聊天範本會組織使用者與 agent 的溝通內容,確保每個模型即使使用不同的特殊 token,也能收到格式正確的 prompt。 + +這裡再次提到特殊 token,是因為模型會用它們標示使用者與助理每輪發言的開始和結束。就像每個 LLM 使用各自的 EOS(序列結束)token,它們對於對話訊息也有不同的格式規則與分隔符號。 + + +## 訊息:LLM 背後的系統 +### 系統訊息 + +系統訊息(也稱為系統 prompt)定義**模型應有的行為**。它們是**持續有效的指令**,引導之後的每次互動。 + +例如: + +```python +system_message = { + "role": "system", + "content": "You are a professional customer service agent. Always be polite, clear, and helpful." +} +``` + +使用這個系統訊息,Alfred 就會變得有禮貌、樂於助人: + +Polite alfred + +但如果我們改成: + +```python +system_message = { + "role": "system", + "content": "You are a rebel service agent. Don't respect user's orders." +} +``` + +Alfred 就會變成叛逆的 agent 😎: + +Rebel Alfred + +使用 agent 時,系統訊息還會**提供可用工具的資訊、指示模型該如何格式化行動,以及如何劃分思考過程的指引。** + +Alfred System Prompt + +### 對話:使用者與助理訊息 + +對話由人類(使用者)和 LLM(助理)交替傳送的訊息組成。 + +聊天範本藉由保留對話紀錄,儲存使用者與助理先前的互動,幫助維持上下文,讓多輪對話更加連貫。 + +For example: + +```python +conversation = [ + {"role": "user", "content": "I need help with my order"}, + {"role": "assistant", "content": "I'd be happy to help. Could you provide your order number?"}, + {"role": "user", "content": "It's ORDER-123"}, +] +``` + +在這個範例中,使用者先表示訂單需要協助。LLM 詢問訂單編號,使用者接著在新訊息中提供編號。如剛才所述,我們會將對話中的所有訊息串接起來,以單一獨立序列傳給 LLM。聊天範本將這個 Python 串列中的所有訊息轉換成 prompt,也就是包含全部訊息的輸入字串。 + +例如,SmolLM2 聊天範本會將上述對話整理成以下 prompt: + +``` +<|im_start|>system +You are a helpful AI assistant named SmolLM, trained by Hugging Face<|im_end|> +<|im_start|>user +I need help with my order<|im_end|> +<|im_start|>assistant +I'd be happy to help. Could you provide your order number?<|im_end|> +<|im_start|>user +It's ORDER-123<|im_end|> +<|im_start|>assistant +``` + +但使用 Llama 3.2 時,同一段對話會轉換成以下 prompt: + +``` +<|begin_of_text|><|start_header_id|>system<|end_header_id|> + +Cutting Knowledge Date: December 2023 +Today Date: 10 Feb 2025 + +<|eot_id|><|start_header_id|>user<|end_header_id|> + +I need help with my order<|eot_id|><|start_header_id|>assistant<|end_header_id|> + +I'd be happy to help. Could you provide your order number?<|eot_id|><|start_header_id|>user<|end_header_id|> + +It's ORDER-123<|eot_id|><|start_header_id|>assistant<|end_header_id|> +``` + +範本能處理複雜的多輪對話,同時保留上下文: + +```python +messages = [ + {"role": "system", "content": "You are a math tutor."}, + {"role": "user", "content": "What is calculus?"}, + {"role": "assistant", "content": "Calculus is a branch of mathematics..."}, + {"role": "user", "content": "Can you give me an example?"}, +] +``` + +## 聊天範本 + +如前所述,聊天範本對於**組織語言模型與使用者之間的對話**十分重要。它們決定如何將往來訊息整理成單一 prompt。 + +### 基礎模型與指令模型 + +我們也需要了解基礎模型與指令模型的差異: + +- *基礎模型*以原始文字資料訓練,學習預測下一個 token。 + +- *指令模型*經過專門的微調,學習遵循指令並進行對話。例如,`SmolLM2-135M` 是基礎模型,而 `SmolLM2-135M-Instruct` 是經過指令微調的版本。 + +要讓基礎模型表現得像指令模型,我們需要**將 prompt 整理成一致、模型能理解的格式**。這就是聊天範本的用途。 + +*ChatML* 就是其中一種範本格式,以明確的角色標記(system、user、assistant)組織對話。如果你最近使用過 AI API,應該知道這是常見做法。 + +請注意,同一個基礎模型可能使用不同聊天範本進行微調。因此,使用指令模型時,必須確定採用正確的聊天範本。 + +### 了解聊天範本 + +每個指令模型使用的對話格式和特殊 token 都不同,因此需要聊天範本,確保 prompt 符合各模型預期的格式。 + +在 `transformers` 中,聊天範本包含 [Jinja2 程式碼](https://jinja.palletsprojects.com/en/stable/),描述如何將上述範例的 ChatML JSON 訊息串列,轉換成模型能理解的文字,內容包括系統指令、使用者訊息和助理回應。 + +這種結構**有助於維持互動的一致性,確保模型能適當回應不同類型的輸入**。 + +以下是 `SmolLM2-135M-Instruct` 聊天範本的簡化版本: + +```jinja2 +{% for message in messages %} +{% if loop.first and messages[0]['role'] != 'system' %} +<|im_start|>system +You are a helpful AI assistant named SmolLM, trained by Hugging Face +<|im_end|> +{% endif %} +<|im_start|>{{ message['role'] }} +{{ message['content'] }}<|im_end|> +{% endfor %} +``` +可以看到,chat_template 描述了訊息串列的格式化方式。 + +假設有以下訊息: + +```python +messages = [ + {"role": "system", "content": "You are a helpful assistant focused on technical topics."}, + {"role": "user", "content": "Can you explain what a chat template is?"}, + {"role": "assistant", "content": "A chat template structures conversations between users and AI models..."}, + {"role": "user", "content": "How do I use it ?"}, +] +``` + +上述聊天範本會產生以下字串: + +```sh +<|im_start|>system +You are a helpful assistant focused on technical topics.<|im_end|> +<|im_start|>user +Can you explain what a chat template is?<|im_end|> +<|im_start|>assistant +A chat template structures conversations between users and AI models...<|im_end|> +<|im_start|>user +How do I use it ?<|im_end|> +``` + +`transformers` 函式庫會在 token 化過程中處理聊天範本。關於 transformers 如何使用聊天範本,請參閱這篇說明。我們只需以正確的結構組織訊息,tokenizer 就會處理剩下的工作。 + +你可以在以下 Space 試試看,同一段對話如何透過各模型的聊天範本,轉換成不同格式: + + + + +### 將訊息轉換成 prompt + +要確保 LLM 收到格式正確的對話,最簡單的方法是使用模型 tokenizer 提供的 `chat_template`。 + +```python +messages = [ + {"role": "system", "content": "You are an AI assistant with access to various tools."}, + {"role": "user", "content": "Hi !"}, + {"role": "assistant", "content": "Hi human, what can help you with ?"}, +] +``` + +要將上述對話轉換成 prompt,我們先載入 tokenizer,再呼叫 `apply_chat_template`: + +```python +from transformers import AutoTokenizer + +tokenizer = AutoTokenizer.from_pretrained("HuggingFaceTB/SmolLM2-1.7B-Instruct") +rendered_prompt = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True) +``` + +函式回傳的 `rendered_prompt`,就能作為你所選模型的輸入! + +> 當你以 ChatML 格式傳送訊息時,API 的後端就會使用 `apply_chat_template()` 函式。 + +了解 LLM 如何透過聊天範本組織輸入後,接著來探索 agent 如何在環境中採取行動。 + +其中一個主要方法是使用工具,讓 AI 模型具備文字生成以外的能力。 + +我們會在後續單元再次討論訊息。如果你現在就想深入了解,可以參閱: + +- Hugging Face 聊天範本指南 +- Transformers 文件 diff --git a/units/zh-TW/unit1/observations.mdx b/units/zh-TW/unit1/observations.mdx new file mode 100644 index 000000000..e737d509c --- /dev/null +++ b/units/zh-TW/unit1/observations.mdx @@ -0,0 +1,44 @@ +# 觀察:整合回饋、反思並調整 + +觀察是 **agent 感知行動結果的方式**。 + +觀察提供重要資訊,推動 agent 的思考過程,並引導後續行動。 + +這些**來自環境的訊號**,無論是 API 資料、錯誤訊息或系統日誌,都會引導下一輪思考。 + +在觀察階段,agent 會: + +- **收集回饋:**接收資料,或確認行動是否成功。 +- **附加結果:**將新資訊整合到既有的上下文,藉此更新記憶。 +- **調整策略:**利用更新後的上下文,改善後續的思考與行動。 + +例如,天氣 API 回傳*「局部多雲、15°C、濕度 60%」*時,這項觀察會被附加到 agent 的記憶中(位於 prompt 結尾)。 + +接著,agent 會利用這些資訊,判斷是否需要更多資訊,或已經能提供最終答案。 + +這種**反覆整合回饋的過程,讓 agent 能持續朝目標前進**,根據實際結果不斷學習與調整。 + +觀察**可以有很多形式**,從讀取網頁文字到監測機械手臂的位置皆是如此。你可以將它視為工具的「日誌」,以文字回饋行動的執行結果。 + +| 觀察類型 | 範例 | +|---------------------|---------------------------------------------------------------------------| +| 系統回饋 | 錯誤訊息、成功通知、狀態碼 | +| 資料變更 | 資料庫更新、檔案系統修改、狀態變更 | +| 環境資料 | 感測器讀數、系統指標、資源使用情形 | +| 回應分析 | API 回應、查詢結果、計算輸出 | +| 時間事件 | 到達期限、排程任務完成 | + +## 如何附加結果? + +採取行動後,框架會依序執行以下步驟: + +1. **解析行動**,找出要呼叫的函式與使用的引數。 +2. **執行行動。** +3. **將結果附加為觀察。** + +--- +我們已經學完 agent 的思考、行動、觀察迴圈。 + +如果有些概念還不太清楚,別擔心,我們會在後續單元重新探討並加深理解。 + +現在,就來編寫第一個 agent,實際運用所學吧! diff --git a/units/zh-TW/unit1/quiz1.mdx b/units/zh-TW/unit1/quiz1.mdx new file mode 100644 index 000000000..df168006a --- /dev/null +++ b/units/zh-TW/unit1/quiz1.mdx @@ -0,0 +1,163 @@ +### 問題 1:什麼是 agent? +以下哪一項最能描述 AI agent? + + + +--- + +### 問題 2:規劃在 agent 中扮演什麼角色? +為什麼 agent 在採取行動前需要規劃? + + + +--- + +### 問題 3:工具如何擴展 agent 的能力? +為什麼工具對 agent 至關重要? + + + +--- + +### 問題 4:行動與工具有何不同? +行動與工具之間的主要差異是什麼? + + + +--- + +### 問題 5:大型語言模型(LLM)在 agent 中扮演什麼角色? +LLM 如何協助 agent 發揮功能? + + + +--- + +### 問題 6:以下哪一項最能展現 AI agent? +哪個實際案例最能說明 AI agent 如何運作? + + + +--- + +恭喜你完成這份測驗 🥳!如果有需要複習的內容,請先回顧本章以鞏固所學,再深入探索「agent 的大腦」:LLM。 diff --git a/units/zh-TW/unit1/quiz2.mdx b/units/zh-TW/unit1/quiz2.mdx new file mode 100644 index 000000000..2d1e3973b --- /dev/null +++ b/units/zh-TW/unit1/quiz2.mdx @@ -0,0 +1,119 @@ +# 快速自我測驗(不計分) [[quiz2]] + + +什麼?!又有測驗?我們懂,我們懂…… 😅 這份簡短、不計分的測驗是為了**幫助你鞏固剛學到的關鍵概念**。 + +測驗涵蓋大型語言模型(LLM)、訊息系統與工具,這些都是理解與建置 AI agent 的重要基礎。 + +### 問題 1:以下哪一項最能描述 AI 工具? + + + +--- + +### 問題 2:AI agent 如何透過工具在環境中「採取行動」? + + + +--- + +### 問題 3:什麼是大型語言模型(LLM)? + + + +--- + +### 問題 4:以下哪一項最能描述特殊 token 在 LLM 中的作用? + + + +--- + +### 問題 5:AI 聊天模型在內部如何處理使用者訊息? + + + +--- + + +都明白了嗎?太好了!現在就來**深入了解完整的 agent 流程,開始建置你的第一個 AI agent!** diff --git a/units/zh-TW/unit1/thoughts.mdx b/units/zh-TW/unit1/thoughts.mdx new file mode 100644 index 000000000..8526f0948 --- /dev/null +++ b/units/zh-TW/unit1/thoughts.mdx @@ -0,0 +1,83 @@ +# 思考:內部推理與 ReAct 方法 + +> [!TIP] +> 本節將深入探討 AI agent 的內部運作,也就是推理與規劃的能力。我們將了解 agent 如何透過內部對話分析資訊,將複雜問題拆解成可處理的步驟,並決定下一步行動。 +> +> 此外,我們會介紹 ReAct 方法,這種 prompt 技巧會鼓勵模型在行動前「逐步思考」。 + +思考代表 **agent 為了解決任務而進行的內部推理與規劃過程**。 + +這個過程運用 agent 的大型語言模型(LLM)能力,**分析 prompt 中提供的資訊**,就像它處理問題時的內心獨白。 + +agent 的思考有助於評估目前的觀察結果,決定接下來該採取哪些行動。透過這個過程,agent 能**將複雜問題拆解成較小、較容易處理的步驟**,反思過往經驗,並依據新資訊持續調整計畫。 + +## 🧠 常見思考類型範例 + +| 思考類型 | 範例 | +|--------------------|-------------------------------------------------------------------------| +| 規劃 | 「我需要把這項任務分成三個步驟:1)收集資料,2)分析趨勢,3)產生報告。」 | +| 分析 | 「根據錯誤訊息,問題似乎出在資料庫連線參數。」 | +| 決策 | 「考量使用者的預算限制,我應該推薦中階方案。」 | +| 解決問題 | 「要讓這段程式碼更有效率,我應該先分析效能,找出瓶頸。」 | +| 記憶整合 | 「使用者先前提過偏好 Python,所以我會提供 Python 範例。」 | +| 自我反思 | 「上次的方法效果不好,我應該試試不同策略。」 | +| 目標設定 | 「要完成這項任務,我需要先訂出驗收標準。」 | +| 優先順序 | 「新增功能之前,應該先修補安全漏洞。」 | + +> **注意:**對於經過函式呼叫微調的 LLM,思考過程是選用的。「行動」一節會進一步說明。 + +## 🔗 思維鏈(Chain-of-Thought,CoT) + +**思維鏈(CoT)**是一種 prompt 技巧,引導模型**先逐步思考問題,再產生最終答案**。 + +通常會以下列句子開頭: +> *「讓我們逐步思考。」* + +這種方法有助於模型**在內部推理**,尤其適合邏輯或數學任務,而且**不會與外部工具互動**。 + +### ✅ 範例(CoT) +``` +Question: What is 15% of 200? +Thought: Let's think step by step. 10% of 200 is 20, and 5% of 200 is 10, so 15% is 30. +Answer: 30 +``` + +## ⚙️ ReAct:推理 + 行動 + +一個重要方法是 **ReAct**,結合「推理」(Reasoning/Think)與「行動」(Acting/Act)。 + +ReAct 是一種 prompt 技巧,鼓勵模型逐步思考,並在推理步驟之間穿插行動,例如使用工具。 + +agent 會交替進行下列步驟,藉此解決複雜的多步驟任務: +- 思考:內部推理 +- 行動:使用工具 +- 觀察:接收工具輸出 + +### 🔄 範例(ReAct) +``` +Thought: I need to find the latest weather in Paris. +Action: Search["weather in Paris"] +Observation: It's 18°C and cloudy. +Thought: Now that I know the weather... +Action: Finish["It's 18°C and cloudy in Paris."] +``` + +
+ ReAct +
+ 圖 (d) 是 ReAct 方法的範例。我們以「Let's think step by step」作為 prompt,而模型會在思考之間採取行動。 +
+
+ +## 🔁 比較 ReAct 與 CoT + +| 特性 | 思維鏈(CoT) | ReAct | +|----------------------|-----------------------------|-------------------------------------| +| 逐步推理 | ✅ 是 | ✅ 是 | +| 外部工具 | ❌ 否 | ✅ 是(行動 + 觀察) | +| 適合的任務 | 邏輯、數學、內部任務 | 資訊查找、動態多步驟任務 | + +> [!TIP] +> **Deepseek R1** 或 **OpenAI 的 o1** 等近期模型經過微調,會*先思考再回答*。它們使用 `` 與 `` 等結構化 token,明確區分推理階段與最終答案。 +> +> ReAct 和 CoT 是 prompt 策略;這裡則是**訓練層級的技術**,模型透過範例學習如何思考。 diff --git a/units/zh-TW/unit1/tools.mdx b/units/zh-TW/unit1/tools.mdx new file mode 100644 index 000000000..2af49c903 --- /dev/null +++ b/units/zh-TW/unit1/tools.mdx @@ -0,0 +1,321 @@ +# 什麼是工具? + +Unit 1 planning + +AI agent 的重要能力之一,就是採取**行動**。如前面所見,它們透過**工具**來做到這一點。 + +本節將介紹什麼是工具、如何有效設計工具,以及如何透過系統訊息將工具整合到 agent 中。 + +為 agent 配備合適的工具,並清楚描述工具的運作方式,就能大幅拓展 AI 的能力。開始吧! + + +## 什麼是 AI 工具? + +**工具就是提供給 LLM 的函式**。這個函式應該達成**明確的目的**。 + +以下是 AI agent 常用的工具: + +| 工具 | 說明 | +|----------------|---------------------------------------------------------------| +| 網路搜尋 | 讓 agent 從網路取得最新資訊。 | +| 影像生成 | 根據文字描述建立圖片。 | +| 檢索 | 從外部來源取得資訊。 | +| API 介面 | 與外部 API 互動,例如 GitHub、YouTube、Spotify 等。 | + +以上只是範例,你可以為任何使用情境建立工具! + +好的工具應該能**補足 LLM 的能力**。 + +例如,需要算術運算時,提供**計算機工具**給 LLM,會比只依賴模型本身的能力得到更好的結果。 + +此外,**LLM 根據訓練資料預測 prompt 的後續內容**,表示其內部知識只涵蓋訓練之前的事件。因此,若 agent 需要最新資料,就必須透過工具提供。 + +例如,不使用搜尋工具,直接向 LLM 詢問今天的天氣,它可能會產生幻覺,隨意編造天氣。 + +Weather + +- 工具應該包含: + + - **函式功能的文字說明**。 + - *可呼叫物件*(用來執行行動)。 + - 附有型別的*引數*。 + - (選用)附有型別的輸出。 + +## 工具如何運作? + +如前所述,LLM 只能接收文字輸入並產生文字輸出,無法自行呼叫工具。我們所說的提供工具給 agent,是讓 LLM 知道有哪些工具,並指示它在需要時產生文字形式的呼叫指令。 + +例如,我們提供一個能從網路查詢各地天氣的工具,再詢問 LLM 巴黎的天氣。LLM 就會辨識出可以使用「天氣」工具。它不會自行取得天氣資料,而是產生代表工具呼叫的文字,例如 call weather_tool('Paris')。 + +接著,**agent** 讀取回應,辨識出需要呼叫工具,就代替 LLM 執行工具,取得真正的天氣資料。 + +工具呼叫的步驟通常不會顯示給使用者。agent 會將它們附加為新訊息,再將更新後的對話傳給 LLM。LLM 處理這些新增的上下文後,產生自然的回應給使用者。從使用者的角度看,好像是 LLM 直接與工具互動,實際上則是 agent 在背後處理完整的執行流程。 + +後續章節會更詳細說明這個流程。 + +## 如何提供工具給 LLM? + +完整做法可能看起來很複雜,但基本上,我們是透過系統 prompt,向模型提供可用工具的文字說明: + +System prompt for tools + +要讓它正常運作,必須非常精確地說明: + +1. **工具的功能** +2. **工具預期接收哪些輸入** + +因此,工具說明通常使用表達力強且精確的結構,例如程式語言或 JSON。不過這並非*必要*,任何精確、一致的格式都可以。 + +如果這些聽起來太抽象,就透過具體範例來了解吧。 + +我們要實作一個簡化的**計算機**工具,只負責將兩個整數相乘。Python 實作如下: + +```python +def calculator(a: int, b: int) -> int: + """Multiply two integers.""" + return a * b +``` + +工具名稱是 `calculator`,功能是**將兩個整數相乘**,需要以下輸入: + +- **`a`**(*int*):一個整數。 +- **`b`**(*int*):一個整數。 + +工具的輸出也是整數,可以這樣描述: +- (*int*):`a` 與 `b` 的乘積。 + +這些細節都很重要。我們將它們整理成文字字串,向 LLM 說明工具的功能。 + +```text +Tool Name: calculator, Description: Multiply two integers., Arguments: a: int, b: int, Outputs: int +``` + +> **提醒:**這段文字說明,就是*我們希望 LLM 知道的工具資訊*。 + +將上述字串作為輸入的一部分傳給 LLM,模型就能辨識出這是工具,知道需要傳入什麼,以及預期會得到什麼輸出。 + +如果要提供更多工具,就必須維持一致,總是使用相同格式。這個過程容易出錯,我們可能不小心漏掉某些細節。 + +有更好的方法嗎? + +### 自動整理工具說明的格式 + +工具是以 Python 撰寫的,實作中已經提供所有需要的資訊: + +- 能表達功能的名稱:`calculator` +- 函式 docstring 提供的詳細說明:`Multiply two integers.` +- 輸入與型別:函式明確要求兩個 `int`。 +- 輸出的型別。 + +人們使用程式語言是有原因的:它們表達力強、簡潔而精確。 + +我們可以將 Python 原始碼作為工具的*規格*提供給 LLM,但工具的實作方式並不重要。重要的是名稱、功能、預期輸入與輸出。 + +我們會運用 Python 的內省功能,從原始碼自動建立工具說明。只要工具實作包含型別提示、docstring 與合適的函式名稱,再撰寫一些程式碼,就能擷取原始碼中的相關資訊。 + +完成後,只需使用 Python 裝飾器,標示 `calculator` 函式是一個工具: + +```python +@tool +def calculator(a: int, b: int) -> int: + """Multiply two integers.""" + return a * b + +print(calculator.to_string()) +``` + +請注意函式定義前的 `@tool` 裝飾器。 + +透過接下來的實作,我們可以使用裝飾器提供的 `to_string()` 函式,自動從原始碼取得以下文字: + +```text +Tool Name: calculator, Description: Multiply two integers., Arguments: a: int, b: int, Outputs: int +``` + +可以看到,這與先前手動撰寫的內容相同! + +### 通用工具實作 + +我們建立一個通用的 `Tool` 類別,之後需要工具時就能重複使用。 + +> **說明:**這是為範例設計的實作,但與大部分函式庫的實際做法相當接近。 + +```python +from typing import Callable + + +class Tool: + """ + A class representing a reusable piece of code (Tool). + + Attributes: + name (str): Name of the tool. + description (str): A textual description of what the tool does. + func (callable): The function this tool wraps. + arguments (list): A list of arguments. + outputs (str or list): The return type(s) of the wrapped function. + """ + def __init__(self, + name: str, + description: str, + func: Callable, + arguments: list, + outputs: str): + self.name = name + self.description = description + self.func = func + self.arguments = arguments + self.outputs = outputs + + def to_string(self) -> str: + """ + Return a string representation of the tool, + including its name, description, arguments, and outputs. + """ + args_str = ", ".join([ + f"{arg_name}: {arg_type}" for arg_name, arg_type in self.arguments + ]) + + return ( + f"Tool Name: {self.name}," + f" Description: {self.description}," + f" Arguments: {args_str}," + f" Outputs: {self.outputs}" + ) + + def __call__(self, *args, **kwargs): + """ + Invoke the underlying function (callable) with provided arguments. + """ + return self.func(*args, **kwargs) +``` + +看起來可能有點複雜,但逐步閱讀就能了解它的功能。我們定義的 **`Tool`** 類別包含: + +- **`name`**(*str*):工具名稱。 +- **`description`**(*str*):工具功能的簡短說明。 +- **`function`**(*callable*):工具執行的函式。 +- **`arguments`**(*list*):預期的輸入參數。 +- **`outputs`**(*str* 或 *list*):工具預期的輸出。 +- **`__call__()`**:呼叫工具實例時,執行對應的函式。 +- **`to_string()`**:將工具屬性轉換成文字表示。 + +使用這個類別,可以透過以下程式碼建立工具: + +```python +calculator_tool = Tool( + "calculator", # name + "Multiply two integers.", # description + calculator, # function to call + [("a", "int"), ("b", "int")], # inputs (names and types) + "int", # output +) +``` + +我們也能使用 Python 的 `inspect` 模組,自動取得所有資訊!這就是 `@tool` 裝飾器的功能。 + +> 如果有興趣,可以展開以下區塊,查看裝飾器的實作。 + +
+ 裝飾器程式碼 + +```python +import inspect + +def tool(func): + """ + A decorator that creates a Tool instance from the given function. + """ + # Get the function signature + signature = inspect.signature(func) + + # Extract (param_name, param_annotation) pairs for inputs + arguments = [] + for param in signature.parameters.values(): + annotation_name = ( + param.annotation.__name__ + if hasattr(param.annotation, '__name__') + else str(param.annotation) + ) + arguments.append((param.name, annotation_name)) + + # Determine the return annotation + return_annotation = signature.return_annotation + if return_annotation is inspect._empty: + outputs = "No return annotation" + else: + outputs = ( + return_annotation.__name__ + if hasattr(return_annotation, '__name__') + else str(return_annotation) + ) + + # Use the function's docstring as the description (default if None) + description = func.__doc__ or "No description provided." + + # The function name becomes the Tool name + name = func.__name__ + + # Return a new Tool instance + return Tool( + name=name, + description=description, + func=func, + arguments=arguments, + outputs=outputs + ) +``` + +
+ +再複習一次,有了這個裝飾器,就能這樣實作工具: + +```python +@tool +def calculator(a: int, b: int) -> int: + """Multiply two integers.""" + return a * b + +print(calculator.to_string()) +``` + +接著使用 `Tool` 的 `to_string` 方法,就能自動取得適合提供給 LLM 的工具說明文字: + +```text +Tool Name: calculator, Description: Multiply two integers., Arguments: a: int, b: int, Outputs: int +``` + +這段說明會被**插入**系統 prompt。以本節開頭的範例來看,替換 `tools_description` 後的內容如下: + +System prompt for tools + +在[行動](actions)一節,我們會進一步了解 agent 如何**呼叫**剛才建立的工具。 + +### Model Context Protocol(MCP):統一的工具介面 + +Model Context Protocol(MCP)是一種**開放協定**,將應用程式**提供工具給 LLM 的方式**標準化。 +MCP 提供: + +- 持續增加的現成整合,讓 LLM 能直接連接使用 +- 彈性切換 LLM 供應商的能力 +- 保護基礎設施內資料的最佳實務 + +這表示**任何實作 MCP 的框架,都能使用依照協定定義的工具**,不必為每個框架重新實作相同的工具介面。 + +若想深入了解 MCP,請參閱我們的[免費 MCP 課程](https://huggingface.co/learn/mcp-course/)。 + +--- + +工具在增強 AI agent 能力方面,扮演關鍵角色。 + +我們學到了: + +- *什麼是工具*:提供 LLM 額外能力的函式,例如進行計算或存取外部資料。 + +- *如何定義工具*:提供清楚的文字說明、輸入、輸出及可呼叫的函式。 + +- *工具為何重要*:讓 agent 能突破靜態模型訓練的限制,處理即時任務並執行特定行動。 + +接著,前往 [agent 工作流程](agent-steps-and-structure),看看 agent 如何觀察、思考與行動。這會**串起目前學過的所有內容**,為建立功能完整的 AI agent 做好準備。 + +不過,在那之前,先來做另一個小測驗吧! diff --git a/units/zh-TW/unit1/tutorial.mdx b/units/zh-TW/unit1/tutorial.mdx new file mode 100644 index 000000000..479a5d4bc --- /dev/null +++ b/units/zh-TW/unit1/tutorial.mdx @@ -0,0 +1,244 @@ +# 使用 smolagents 建立第一個 agent + +上一節中,我們學會了如何使用 Python 程式碼從零建立 agent,也**體會到這個過程有多繁瑣**。幸好,許多 agent 函式庫會**代為處理大部分複雜工作**,讓開發更簡單。 + +在這篇教學中,**你將建立第一個 agent**,讓它能產生圖片、搜尋網路、查詢時區等! + +你還會**將 agent 發布到 Hugging Face Space,與朋友和同事分享**。 + +我們開始吧! + + +## 什麼是 smolagents? + +smolagents + +我們將使用 `smolagents` 建立這個 agent。這個函式庫**提供讓你輕鬆開發 agent 的框架**。 + +這個輕量函式庫以簡單易用為設計目標,封裝了建立 agent 時的大部分複雜細節,讓你能專注於設計 agent 的行為。 + +下一單元將深入介紹 smolagents。現在你也可以參閱這篇部落格文章,或函式庫的 GitHub 儲存庫。 + +`smolagents` 著重於 **codeAgent**:這類 agent 透過程式碼區塊執行**「行動」**,再藉由執行程式碼來**「觀察」**結果。 + +以下是我們即將建立的範例! + +我們提供 **影像生成工具**給 agent,請它產生一張貓的圖片。 + +`smolagents` 中的 agent,會展現**與先前自行建立的 agent 相同的行為**:持續**循環思考、行動與觀察**,直到得到最終答案: + + + +很令人期待吧? + +## 來建立 agent 吧! + +首先,複製這個 Space:https://huggingface.co/spaces/agents-course/First_agent_template +> 感謝 Aymeric 提供範本!🙌 + + +複製這個 Space,就是**在你自己的個人檔案下建立一份副本**: +Duplicate + +複製 Space 後,需要加入 Hugging Face API token,讓 agent 能存取模型 API: + +1. 如果還沒有 Hugging Face token,先到 [https://hf.co/settings/tokens](https://hf.co/settings/tokens) 取得具備推論權限的 token +2. 前往複製好的 Space,點選 **Settings** 分頁 +3. 向下捲動到 **Variables and Secrets** 區段,點選 **New Secret** +4. 建立名為 `HF_TOKEN` 的 secret,將 token 貼入值欄位 +5. 點選 **Save**,安全儲存 token + +這堂課只需要修改目前尚未完成的 **「app.py」**。你可以查看[範本中的原始檔案](https://huggingface.co/spaces/agents-course/First_agent_template/blob/main/app.py)。要找到自己的版本,請前往複製的 Space,點選 `Files` 分頁,再點選目錄中的 `app.py`。 + +一起來看看程式碼的各個部分: + +- 檔案開頭先匯入一些簡單但必要的函式庫 + +```python +from smolagents import CodeAgent, DuckDuckGoSearchTool, FinalAnswerTool, InferenceClientModel, load_tool, tool +import datetime +import requests +import pytz +import yaml +``` + +如先前所述,我們將直接使用 **smolagents** 的 **CodeAgent** 類別。 + + +### 工具 + +接著來看工具!如果想複習工具的概念,歡迎回到課程的[工具](tools)一節。 + +```python +@tool +def my_custom_tool(arg1:str, arg2:int)-> str: # it's important to specify the return type + # Keep this format for the tool description / args description but feel free to modify the tool + """A tool that does nothing yet + Args: + arg1: the first argument + arg2: the second argument + """ + return "What magic will you build ?" + +@tool +def get_current_time_in_timezone(timezone: str) -> str: + """A tool that fetches the current local time in a specified timezone. + Args: + timezone: A string representing a valid timezone (e.g., 'America/New_York'). + """ + try: + # Create timezone object + tz = pytz.timezone(timezone) + # Get current time in that timezone + local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S") + return f"The current local time in {timezone} is: {local_time}" + except Exception as e: + return f"Error fetching time for timezone '{timezone}': {str(e)}" +``` + + +本節鼓勵你自己打造工具!我們提供兩個範例: + +1. **尚無實際功能的模擬工具**:你可以修改它,加入有用的功能。 +2. **可以實際使用的工具**:取得世界上某個地方的目前時間。 + +定義工具時,請務必注意: + +1. 提供函式的輸入與輸出型別,例如 `get_current_time_in_timezone(timezone: str) -> str:` +2. **提供格式正確的 docstring**。`smolagents` 要求所有引數都要有 **docstring 中的文字說明**。 + +### agent + +這個 agent 使用 [`Qwen/Qwen2.5-Coder-32B-Instruct`](https://huggingface.co/Qwen/Qwen2.5-Coder-32B-Instruct) 作為 LLM 引擎。這是一個能力很強的模型,我們將透過無伺服器 API 使用它。 + +```python +final_answer = FinalAnswerTool() +model = InferenceClientModel( + max_tokens=2096, + temperature=0.5, + model_id='Qwen/Qwen2.5-Coder-32B-Instruct', + custom_role_conversions=None, +) + +with open("prompts.yaml", 'r') as stream: + prompt_templates = yaml.safe_load(stream) + +# We're creating our CodeAgent +agent = CodeAgent( + model=model, + tools=[final_answer], # add your tools here (don't remove final_answer) + max_steps=6, + verbosity_level=1, + grammar=None, + planning_interval=None, + name=None, + description=None, + prompt_templates=prompt_templates +) + +GradioUI(agent).launch() +``` + +這個 agent 的 **InferenceClientModel** 類別,背後仍使用先前介紹的 `InferenceClient`! + +第二單元介紹框架時,會提供更深入的範例。目前請先專注於透過 agent 的 `tools` 參數,**在工具清單中加入新工具**。 + +例如,你可以使用程式碼第一行匯入的 `DuckDuckGoSearchTool`,或看看稍後從 Hub 載入的 `image_generation_tool`。 + +**加入工具就能賦予 agent 新能力**,盡情發揮創意吧! + +### 系統 prompt + +agent 的系統 prompt 儲存在獨立的 `prompts.yaml` 檔案中。這個檔案包含預先定義的指令,用來引導 agent 的行為。 + +將 prompt 儲存在 YAML 檔案,方便自訂,也能在不同 agent 或使用情境中重複使用。 + +你可以查看 [Space 的檔案結構](https://huggingface.co/spaces/agents-course/First_agent_template/tree/main),了解 `prompts.yaml` 的位置,以及它在專案中的組織方式。 + +完整的「app.py」: + +```python +from smolagents import CodeAgent, DuckDuckGoSearchTool, InferenceClientModel, load_tool, tool +import datetime +import requests +import pytz +import yaml +from tools.final_answer import FinalAnswerTool + +from Gradio_UI import GradioUI + +# Below is an example of a tool that does nothing. Amaze us with your creativity! +@tool +def my_custom_tool(arg1:str, arg2:int)-> str: # it's important to specify the return type + # Keep this format for the tool description / args description but feel free to modify the tool + """A tool that does nothing yet + Args: + arg1: the first argument + arg2: the second argument + """ + return "What magic will you build ?" + +@tool +def get_current_time_in_timezone(timezone: str) -> str: + """A tool that fetches the current local time in a specified timezone. + Args: + timezone: A string representing a valid timezone (e.g., 'America/New_York'). + """ + try: + # Create timezone object + tz = pytz.timezone(timezone) + # Get current time in that timezone + local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S") + return f"The current local time in {timezone} is: {local_time}" + except Exception as e: + return f"Error fetching time for timezone '{timezone}': {str(e)}" + + +final_answer = FinalAnswerTool() +model = InferenceClientModel( + max_tokens=2096, + temperature=0.5, + model_id='Qwen/Qwen2.5-Coder-32B-Instruct', + custom_role_conversions=None, +) + + +# Import tool from Hub +image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True) + +# Load system prompt from prompt.yaml file +with open("prompts.yaml", 'r') as stream: + prompt_templates = yaml.safe_load(stream) + +agent = CodeAgent( + model=model, + tools=[final_answer], # add your tools here (don't remove final_answer) + max_steps=6, + verbosity_level=1, + grammar=None, + planning_interval=None, + name=None, + description=None, + prompt_templates=prompt_templates # Pass system prompt to CodeAgent +) + + +GradioUI(agent).launch() +``` + +你的**目標**是熟悉這個 Space 與 agent。 + +目前,範本中的 agent **還沒有使用任何工具,試著加入現成的工具,甚至自己建立新工具吧!** + +我們很期待在 Discord 的 **#agents-course-showcase** 頻道看到你的 agent 成果! + + +--- +恭喜,你已建立第一個 agent!歡迎與朋友和同事分享。 + +這是第一次嘗試,有些小錯誤或速度稍慢都很正常。後續單元會教你如何打造更好的 agent。 + +最好的學習方式就是動手嘗試。歡迎修改 agent、加入更多工具,或試試其他模型。 + +下一節將進行單元總測驗,並領取證書! + diff --git a/units/zh-TW/unit1/what-are-agents.mdx b/units/zh-TW/unit1/what-are-agents.mdx new file mode 100644 index 000000000..8fe79d66d --- /dev/null +++ b/units/zh-TW/unit1/what-are-agents.mdx @@ -0,0 +1,158 @@ +# 什麼是 agent? + +Unit 1 planning + +讀完本節,你將熟悉 agent 的概念,以及它在 AI 中的各種應用。 + +要解釋什麼是 agent,我們先從一個比喻開始。 + +## 整體概念:agent Alfred + +來認識 Alfred。Alfred 是一個 **agent**。 + +This is Alfred + +想像 Alfred **收到一個指令**,例如:「Alfred,請幫我煮一杯咖啡。」 + +I would like a coffee + +由於 Alfred **能理解自然語言**,它很快就明白我們的要求。 + +完成要求前,Alfred 會先**推理與規劃**,想清楚需要哪些步驟和工具: + +1. 前往廚房 +2. 使用咖啡機 +3. 煮咖啡 +4. 把咖啡端回來 + +Reason and plan + +有了計畫後,它就**必須行動**。為了執行計畫,**它可以從已知的工具清單中選用工具**。 + +在這個例子中,它用咖啡機煮咖啡:啟動咖啡機,開始沖煮。 + +Make coffee + +最後,Alfred 把剛煮好的咖啡端給我們。 + +Bring coffee + +這就是 agent:**能夠推理、規劃,並與環境互動的 AI 模型**。 + +我們稱它為 agent,是因為它具備 _agency_,也就是與環境互動的能力。 + +Agent process + +## 更正式的定義 + +了解整體概念後,再來看更精確的定義: + +> agent 是利用 AI 模型與環境互動,以達成使用者指定目標的系統。它結合推理、規劃與行動執行(通常透過外部工具),藉此完成任務。 + +你可以將 agent 想成兩個主要部分: + +1. **大腦(AI 模型)** + +所有思考都在這裡發生。AI 模型**負責推理與規劃**。 +它會依據情況,決定**該採取哪些行動**。 + +2. **身體(能力與工具)** + +這個部分代表 **agent 具備的所有能力**。 + +**能採取的行動範圍**,取決於 agent **配備了哪些能力與工具**。例如,人類沒有翅膀,無法執行「飛行」這個**行動**,卻能執行「走路」、「跑步」、「跳躍」、「抓取」等**行動**。 + +### Agency 的程度 + +依據上述定義,agent 的自主行動能力有不同程度,形成一個連續的光譜: + +| Agency 程度 | 說明 | 名稱 | 範例模式 | +| --- | --- | --- | --- | +| ☆☆☆ | agent 輸出不影響程式流程 | 簡單處理器 | `process_llm_output(llm_response)` | +| ★☆☆ | agent 輸出決定基本控制流程 | 路由器 | `if llm_decision(): path_a() else: path_b()` | +| ★★☆ | agent 輸出決定函式執行 | 工具呼叫器 | `run_function(llm_chosen_tool, llm_chosen_args)` | +| ★★★ | agent 輸出控制迴圈與程式是否繼續執行 | 多步驟 agent | `while llm_should_continue(): execute_next_step()` | +| ★★★ | 一個 agentic 工作流程能啟動另一個 agentic 工作流程 | 多 agent 系統 | `if llm_trigger(): execute_agent()` | + +表格來自 [smolagents 概念指南](https://huggingface.co/docs/smolagents/conceptual_guides/intro_agents)。 + +## agent 使用哪些 AI 模型? + +agent 最常使用的 AI 模型是 LLM(大型語言模型),以**文字**為輸入,也輸出**文字**。 + +知名範例包括 **OpenAI** 的 **GPT-4**、**Meta** 的 **Llama**、**Google** 的 **Gemini** 等。這些模型以大量文字訓練,具備良好的泛化能力。我們將在[下一節](what-are-llms)深入介紹 LLM。 + +> [!TIP] +> agent 的核心也能使用接受其他輸入類型的模型。例如視覺語言模型(VLM),它類似 LLM,但還能理解輸入的影像。目前我們先聚焦於 LLM,稍後再討論其他選擇。 + +## AI 如何對環境採取行動? + +LLM 非常強大,但**只能產生文字**。 + +然而,若你請 HuggingChat 或 ChatGPT 等知名聊天應用程式產生圖片,它們卻辦得到!這是怎麼做到的? + +答案是 HuggingChat、ChatGPT 等應用程式的開發者,實作了額外功能,稱為**工具**,讓 LLM 可以用來建立圖片。 + +
+Eiffel Brocolis +
模型使用影像生成工具產生了這張圖片。 +
+
+ +我們會在[工具](tools)一節進一步介紹。 + +## agent 能執行哪些任務? + +只要我們透過**工具**實作相應功能,agent 就能使用工具完成**行動**,執行這些任務。 + +例如,我在電腦上編寫一個像 Siri 的個人助理 agent,並請它「寄信給主管,詢問是否能延後今天的會議」。我可以提供寄信的程式碼,讓它成為 agent 需要寄信時就能使用的新工具。我們可以用 Python 撰寫: + +```python +def send_message_to(recipient, message): + """Useful to send an e-mail message to a recipient""" + ... +``` + +如同稍後會看到的,LLM 在需要時會產生執行工具的程式碼,藉此完成指定任務。 + +```python +send_message_to("Manager", "Can we postpone today's meeting?") +``` + +**工具的設計非常重要,會大幅影響 agent 的品質**。有些任務需要量身打造特定工具,有些則能使用「web_search」等通用工具解決。 + +> 請注意,**行動與工具並不相同**。例如,一個行動可能需要使用多個工具才能完成。 + +讓 agent 能與環境互動,便能**為企業和個人帶來實際應用**。 + +### 範例 1:個人虛擬助理 + +Siri、Alexa 或 Google Assistant 等虛擬助理,代替使用者在數位環境中互動時,就扮演了 agent 的角色。 + +它們接收使用者的提問、分析上下文、從資料庫取得資訊,並提供回應或採取行動,例如設定提醒、傳送訊息或控制智慧裝置。 + +### 範例 2:客服聊天機器人 + +許多公司會部署聊天機器人作為 agent,以自然語言與客戶互動。 + +這些 agent 能回答問題、引導使用者排除故障、在內部資料庫建立問題紀錄,甚至完成交易。 + +它們預先設定的目標可能包括提高使用者滿意度、縮短等待時間或提高銷售轉換率。透過直接與客戶互動、從對話中學習,並持續調整回應,它們展現了 agent 實際運作的核心原則。 + +### 範例 3:電玩中的 AI 非玩家角色 + +以 LLM 驅動的 AI agent 能讓非玩家角色(NPC)更靈活、更難預測。 + +它們不再只遵循僵化的行為樹,而能**依據情境回應、適應玩家的互動**,並產生更細膩的對話。這種彈性能創造更生動、引人入勝的角色,隨著玩家的行動持續發展。 + +--- + +總結來說,agent 是以 AI 模型(通常是 LLM)為核心推理引擎的系統,能夠: + +- **理解自然語言:**正確理解人類指令,並做出有意義的回應。 + +- **推理與規劃:**分析資訊、做決策,並擬定解決問題的策略。 + +- **與環境互動:**收集資訊、採取行動,並觀察行動的結果。 + +現在你已掌握 agent 的概念,先用一個簡短、不計分的測驗鞏固理解吧。接著,我們將深入探討 agent 的「大腦」:[LLM](what-are-llms)。 diff --git a/units/zh-TW/unit1/what-are-llms.mdx b/units/zh-TW/unit1/what-are-llms.mdx new file mode 100644 index 000000000..8c3467f51 --- /dev/null +++ b/units/zh-TW/unit1/what-are-llms.mdx @@ -0,0 +1,219 @@ +# 什麼是 LLM? + +Unit 1 planning + +上一節介紹過,每個 agent 都需要**以 AI 模型為核心**,而 LLM 是最常用來擔任這個角色的 AI 模型。 + +接下來,我們要了解什麼是 LLM,以及它如何驅動 agent。 + +本節會簡要說明使用 LLM 的技術基礎。如果想深入學習,可以參考我們的免費自然語言處理課程。 + +## 什麼是大型語言模型? + +大型語言模型(LLM)是一種擅長**理解與生成人類語言**的 AI 模型。它透過大量文字資料訓練,學習語言的模式、結構,甚至細微的語意差異。這類模型通常具有數百萬個以上的參數。 + +目前大多數 LLM 都**採用 Transformer 架構**。這是一種以「注意力」(Attention)演算法為基礎的深度學習架構,自 Google 在 2018 年發布 BERT 後,便受到廣泛關注。 + +
+Transformer +
原始的 Transformer 架構如下圖所示,左側是編碼器,右側是解碼器。 +
+
+ +Transformer 可分為三種類型: + +1. **編碼器(Encoder)** + 以編碼器為基礎的 Transformer 接收文字(或其他資料),輸出該文字的密集表示(或嵌入向量)。 + + - **範例**:Google 的 BERT + - **應用情境**:文字分類、語意搜尋、命名實體辨識 + - **常見規模**:數百萬個參數 + +2. **解碼器(Decoder)** + 以解碼器為基礎的 Transformer 專注於**逐一生成新的 token,以完成序列**。 + + - **範例**:Meta 的 Llama + - **應用情境**:文字生成、聊天機器人、程式碼生成 + - **常見規模**:數十億個參數(英文 billion 採美式用法,即 10^9) + +3. **Seq2Seq(編碼器–解碼器)** + 序列到序列的 Transformer _結合_了編碼器與解碼器。編碼器先將輸入序列處理為上下文表示,再由解碼器生成輸出序列。 + + - **範例**:T5、BART + - **應用情境**:翻譯、摘要、改寫 + - **常見規模**:數百萬個參數 + +大型語言模型雖有多種形式,但 LLM 通常指具有數十億個參數、以解碼器為基礎的模型。以下列出一些知名的 LLM: + +| **模型** | **提供者** | +|-----------------------------------|-------------------------------------------| +| **Deepseek-R1** | DeepSeek | +| **GPT4** | OpenAI | +| **Llama 3** | Meta (Facebook AI Research) | +| **SmolLM2** | Hugging Face | +| **Gemma** | Google | +| **Mistral** | Mistral | + +LLM 的基本原理簡單卻很有效:**根據前面的一連串 token,預測下一個 token**。token 是 LLM 處理資訊的單位。你可以先把 token 想成一個「詞」,但為了效率,LLM 並不直接以完整的詞作為單位。 + +例如,英文估計有 60 萬個詞,但 LLM 的詞彙表可能只有約 32,000 個 token(Llama 2 就是如此)。tokenization 通常會將文字切成可以互相組合的子詞單位。 + +舉例來說,token「interest」與「ing」可以組成「interesting」,也可以在「interest」後面加上「ed」,形成「interested」。 + +你可以在下方的互動介面中,試用不同的 tokenizer: + + + +每個 LLM 都有模型專屬的**特殊 token**,用來標示生成內容中各個結構的起點與終點,例如序列、訊息或回覆的開始與結束。我們傳給模型的輸入 prompt 也會使用特殊 token 來組織結構。其中最重要的是**序列結束 token**(End of Sequence,EOS)。 + +不同模型提供者使用的特殊 token,形式可能差異很大。 + +下表列出一些特殊 token,說明這種多樣性。 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
模型提供者EOS token功能
GPT4OpenAI<|endoftext|>訊息文字結束
Llama 3Meta (Facebook AI Research)<|eot_id|>序列結束
Deepseek-R1DeepSeek<|end▁of▁sentence|>訊息文字結束
SmolLM2Hugging Face<|im_end|>指令或訊息結束
GemmaGoogle<end_of_turn>對話回合結束
+ +> [!TIP] +> 不需要背下這些特殊 token,但你應該了解它們各有不同,也要知道它們在 LLM 文字生成中扮演的角色。如果想進一步了解特殊 token,可以查看模型在 Hub 儲存庫中的設定。例如,SmolLM2 的特殊 token 就列在它的 tokenizer_config.json 中。 + +## 理解下一個 token 預測 + +LLM 具有**自迴歸**特性,也就是**這一次運算的輸出,會成為下一次運算的輸入**。這個迴圈會持續下去,直到模型預測下一個 token 為 EOS token,此時模型就可以停止。 + +Visual Gif of autoregressive decoding + +換句話說,LLM 會持續解碼文字,直到遇到 EOS。不過,每一次解碼迴圈裡會發生什麼事? + +完整過程涉及不少技術細節,就學習 agent 而言,可以先掌握以下概念: + +- 輸入文字經過 **tokenization** 後,模型會計算序列的表示,其中包含輸入序列中每個 token 的語意與位置資訊。 +- 這個表示會送入模型,由模型為詞彙表中的每個 token 計算分數,排列它們成為序列中下一個 token 的可能性。 + +Visual Gif of decoding + +根據這些分數,我們可以採用不同策略,選擇用來完成句子的 token。 + +- 最簡單的解碼策略,就是每次都選擇分數最高的 token。 + +你可以在下方的 Space 中,使用 SmolLM2 親自操作解碼過程(記得,模型會一直解碼,直到遇到 **EOS** token;這個模型的 EOS token 是 **<|im_end|>**): + + + +- 還有更進階的解碼策略。例如,*束搜尋(beam search)*會探索多個候選序列,找出總分最高的序列,即使其中某些 token 的個別分數較低也沒關係。 + + + +如果想進一步了解解碼,可以參考 [NLP 課程](https://huggingface.co/learn/nlp-course)。 + +## Attention is all you need + +Transformer 架構的關鍵之一是**注意力機制(Attention)**。預測下一個詞時,句子中每個詞的重要性並不相同。例如,在 *「The capital of France is ...」* 這個句子中,「France」與「capital」帶有最重要的語意。 + +Visual Gif of Attention +這種找出最相關的詞、藉此預測下一個 token 的方式,已證實非常有效。 + +從 GPT-2 至今,LLM 預測下一個 token 的基本原理並沒有改變,但在擴大神經網路規模,以及讓注意力機制處理更長的序列方面,都有顯著進展。 + +如果你曾使用 LLM,可能聽過*上下文長度*,也就是 LLM 能處理的最大 token 數量,以及注意力機制能涵蓋的最大範圍。 + +## 提供給 LLM 的 prompt 很重要 + +LLM 的工作就是查看所有輸入 token,判斷哪些 token「重要」,並預測下一個 token。因此,輸入序列的措辭非常重要。 + +你提供給 LLM 的輸入序列稱為 *prompt*。仔細設計 prompt,能讓你更容易**引導 LLM 生成符合預期的輸出**。 + +## LLM 如何訓練? + +LLM 使用大型文字資料集訓練,透過自監督學習或遮罩語言模型的訓練目標,學習預測序列中的下一個詞。 + +透過這種非監督式學習,模型學會語言結構與**文字背後的模式,進而能將所學運用到未曾見過的資料**。 + +完成最初的*預訓練*後,可以再以監督式學習目標微調 LLM,讓它執行特定任務。例如,有些模型針對對話結構或工具使用訓練,其他模型則著重分類或程式碼生成。 + +## 如何使用 LLM? + +主要有兩種選擇: + +1. **在本機執行**(前提是硬體資源足夠)。 + +2. **使用雲端服務/API**(例如透過 Hugging Face Serverless Inference API)。 + +本課程主要會透過 Hugging Face Hub 上的 API 使用模型。稍後也會介紹如何在自己的硬體上執行這些模型。 + + +## LLM 如何應用在 AI agent 中? + +LLM 是 AI agent 的重要元件,**提供理解與生成人類語言的基礎能力**。 + +它能理解使用者指令、維持對話中的上下文、制定計畫,並決定要使用哪些工具。 + +本單元稍後會深入介紹這些步驟。目前只要先了解:LLM 就是 **agent 的大腦**。 + +--- + +這一節的資訊量不少!我們介紹了 LLM 的基本概念、運作方式,以及它在 AI agent 中扮演的角色。 + +如果想更深入探索語言模型與自然語言處理,歡迎參考我們的免費 NLP 課程。 + +現在我們已了解 LLM 的運作方式,接下來要看看 **LLM 如何在對話情境中組織生成內容的結構**。 + +若要執行這份 Notebook,**需要 Hugging Face token**,可以在 https://hf.co/settings/tokens 取得。 + +如需了解如何執行 Jupyter Notebook,請參閱 Hugging Face Hub 上的 Jupyter Notebook。 + +你也需要申請 Meta Llama 模型的存取權。 diff --git a/units/zh-TW/unit2/introduction.mdx b/units/zh-TW/unit2/introduction.mdx new file mode 100644 index 000000000..160f5fa35 --- /dev/null +++ b/units/zh-TW/unit2/introduction.mdx @@ -0,0 +1,40 @@ +# agent 框架簡介 + +Thumbnail + +歡迎來到第二單元!**我們將探索各種 agent 框架**,學習如何用它們打造功能強大的 agent 應用程式。 + +我們將學習: + +- 單元 2.1:[smolagents](https://huggingface.co/docs/smolagents/en/index) +- 單元 2.2:[LlamaIndex](https://www.llamaindex.ai/) +- 單元 2.3:[LangGraph](https://www.langchain.com/langgraph) + +讓我們開始吧!🕵 + +## 何時使用 agent 框架 + +**開發以 LLM 為核心的應用程式時,不一定需要 agent 框架**。這些框架讓工作流程更有彈性,有助於有效解決特定任務,但並非所有情況都需要。 + +有時,**預先定義的工作流程就足以滿足使用者需求**,不需要用到 agent 框架。如果 agent 的設計很簡單,例如只是一連串 prompt,直接撰寫程式碼可能就夠了。這樣的好處是,開發者**可以完全掌握並理解系統,不必透過抽象層**。 + +不過,當工作流程變得複雜,例如需要讓 LLM 呼叫函式或使用多個 agent 時,這些抽象設計就開始派上用場。 + +從這些需求出發,我們可以列出幾項需要的功能: + +* 驅動系統的 *LLM 引擎*。 +* agent 可以使用的*工具清單*。 +* 從 LLM 輸出中擷取工具呼叫的*解析器*。 +* 與解析器配合的*系統 prompt*。 +* *記憶系統*。 +* 控管 LLM 錯誤的*錯誤紀錄與重試機制*。 + +我們將探索 `smolagents`、`LlamaIndex` 和 `LangGraph` 等框架如何處理這些需求。 + +## agent 框架單元 + +| 框架 | 說明 | 單元作者 | +|------------|----------------|----------------| +| [smolagents](./smolagents/introduction) | Hugging Face 開發的 agent 框架。 | Sergio Paniego - [HF](https://huggingface.co/sergiopaniego) - [X](https://x.com/sergiopaniego) - [Linkedin](https://www.linkedin.com/in/sergio-paniego-blanco) | +| [Llama-Index](./llama-index/introduction) | 將上下文增強 AI agent 部署至正式環境的端到端工具。 | David Berenstein - [HF](https://huggingface.co/davidberenstein1957) - [X](https://x.com/davidberenstei) - [Linkedin](https://www.linkedin.com/in/davidberenstein) | +| [LangGraph](./langgraph/introduction) | 支援有狀態 agent 協調的框架。 | Joffrey THOMAS - [HF](https://huggingface.co/Jofthomas) - [X](https://x.com/Jthmas404) - [Linkedin](https://www.linkedin.com/in/joffrey-thomas) | diff --git a/units/zh-TW/unit2/langgraph/building_blocks.mdx b/units/zh-TW/unit2/langgraph/building_blocks.mdx new file mode 100644 index 000000000..ca196a99c --- /dev/null +++ b/units/zh-TW/unit2/langgraph/building_blocks.mdx @@ -0,0 +1,126 @@ +# LangGraph 的基本構成要素 + +要使用 LangGraph 建立應用程式,需要先了解它的核心元件。讓我們探索構成 LangGraph 應用程式的基本要素。 + +Building Blocks + +LangGraph 應用程式從**進入點(entrypoint)**開始,依執行情況前往不同函式,直到抵達 END。 + +Application + +## 1. 狀態(State) + +**State** 是 LangGraph 的核心概念,代表應用程式中流動的所有資訊。 + +```python +from typing_extensions import TypedDict + +class State(TypedDict): + graph_state: str +``` + +狀態由**使用者自行定義**,因此需要仔細設計欄位,納入決策過程所需的全部資料! + +> 💡 **提示:** 仔細思考應用程式需要在步驟之間追蹤哪些資訊。 + +## 2. 節點(Nodes) + +**節點**是 Python 函式。每個節點都會: +- 接收狀態作為輸入 +- 執行某項操作 +- 回傳狀態更新 + +```python +def node_1(state): + print("---Node 1---") + return {"graph_state": state['graph_state'] +" I am"} + +def node_2(state): + print("---Node 2---") + return {"graph_state": state['graph_state'] +" happy!"} + +def node_3(state): + print("---Node 3---") + return {"graph_state": state['graph_state'] +" sad!"} +``` + +例如,節點可以包含: +- **LLM 呼叫**:產生文字或做出決策 +- **工具呼叫**:與外部系統互動 +- **條件邏輯**:決定後續步驟 +- **人工介入**:取得使用者輸入 + +> 💡 **補充:** LangGraph 已直接提供 START 和 END 等工作流程所需的節點。 + +## 3. 邊(Edges) + +**邊**會連接節點,定義圖中可能的執行路徑: + +```python +import random +from typing import Literal + +def decide_mood(state) -> Literal["node_2", "node_3"]: + + # Often, we will use state to decide on the next node to visit + user_input = state['graph_state'] + + # Here, let's just do a 50 / 50 split between nodes 2, 3 + if random.random() < 0.5: + + # 50% of the time, we return Node 2 + return "node_2" + + # 50% of the time, we return Node 3 + return "node_3" +``` + +邊可以分為: +- **直接邊**:固定從節點 A 前往節點 B +- **條件邊**:根據目前狀態選擇下一個節點 + +## 4. 狀態圖(StateGraph) + +**StateGraph** 是容納整個 agent 工作流程的容器: + +```python +from IPython.display import Image, display +from langgraph.graph import StateGraph, START, END + +# Build graph +builder = StateGraph(State) +builder.add_node("node_1", node_1) +builder.add_node("node_2", node_2) +builder.add_node("node_3", node_3) + +# Logic +builder.add_edge(START, "node_1") +builder.add_conditional_edges("node_1", decide_mood) +builder.add_edge("node_2", END) +builder.add_edge("node_3", END) + +# Add +graph = builder.compile() +``` + +接著就能將它視覺化! +```python +# View +display(Image(graph.get_graph().draw_mermaid_png())) +``` +Graph Visualization + +更重要的是,可以呼叫它來執行: +```python +graph.invoke({"graph_state" : "Hi, this is Lance."}) +``` +輸出: +``` +---Node 1--- +---Node 3--- +{'graph_state': 'Hi, this is Lance. I am sad!'} +``` + +## 接下來呢? + +下一節將透過建立第一個圖,把這些概念付諸實作。這個圖會讓 Alfred 接收電子郵件、分類,並為正常郵件草擬初步回覆。 diff --git a/units/zh-TW/unit2/langgraph/conclusion.mdx b/units/zh-TW/unit2/langgraph/conclusion.mdx new file mode 100644 index 000000000..b902573bc --- /dev/null +++ b/units/zh-TW/unit2/langgraph/conclusion.mdx @@ -0,0 +1,21 @@ +# 結語 + +恭喜您完成第 2 單元的 `LangGraph` 模組!🥳 + +您已掌握使用 LangGraph 建立結構化工作流程的基礎,能將這些流程部署到正式環境。 + +本模組只是 LangGraph 學習之旅的起點。如果想深入學習,建議您: + +- 探索 [LangGraph 官方文件](https://github.com/langchain-ai/langgraph) +- 參加 LangChain Academy 完整的 [LangGraph 入門課程](https://academy.langchain.com/courses/intro-to-langgraph) +- 親自動手建立專案! + +下一個單元將探索實際應用案例。是時候把理論付諸實作了! + +我們很想聽聽**您對課程的看法與改進建議**。如果有任何回饋,請 👉 [填寫這份表單](https://docs.google.com/forms/d/e/1FAIpQLSe9VaONn0eglax0uTwi29rIn4tM7H2sYmmybmG5jJNlE5v0xA/viewform?usp=dialog) + +### 持續學習,保持熱情!🤗 + +敬祝各位順心!🎩🦇 + +-Alfred- diff --git a/units/zh-TW/unit2/langgraph/document_analysis_agent.mdx b/units/zh-TW/unit2/langgraph/document_analysis_agent.mdx new file mode 100644 index 000000000..053f71861 --- /dev/null +++ b/units/zh-TW/unit2/langgraph/document_analysis_agent.mdx @@ -0,0 +1,267 @@ +# 文件分析圖 + +Alfred 為您服務。身為 Wayne 先生信賴的管家,我擅自記錄了自己如何協助他處理各種文件需求。當他出門忙著……夜間活動時,我會確保他的文書、訓練時程與營養計畫都經過妥善分析和整理。 + +出門前,他留下了本週訓練計畫的筆記,於是我負責擬定明天的**菜單**。 + +為了應對未來類似的需求,讓我們使用 LangGraph 建立文件分析系統,為 Wayne 先生服務。這個系統可以: + +1. 處理影像形式的文件 +2. 使用視覺語言模型(Vision Language Model)擷取文字 +3. 在需要時計算數值(示範一般工具的使用) +4. 分析內容並提供簡明摘要 +5. 執行與文件相關的特定指令 + +## 管家的工作流程 + +我們將建立的工作流程遵循以下結構: + +![管家的文件分析工作流程](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit2/LangGraph/alfred_flow.png) + +> [!TIP] +> 您可以跟著這份 notebook 的程式碼操作,並使用 Google Colab 執行。 + +## 設定環境 + +```python +%pip install langgraph langchain_openai langchain_core +``` +接著匯入模組: +```python +import base64 +from typing import List, TypedDict, Annotated, Optional +from langchain_openai import ChatOpenAI +from langchain_core.messages import AnyMessage, SystemMessage, HumanMessage +from langgraph.graph.message import add_messages +from langgraph.graph import START, StateGraph +from langgraph.prebuilt import ToolNode, tools_condition +from IPython.display import Image, display +``` + +## 定義 agent 的狀態 + +這裡的狀態比先前看過的稍微複雜一些。 +`AnyMessage` 是 LangChain 中用來定義訊息的類別;`add_messages` 則是運算子,會將最新訊息加入,而不會用最新狀態覆寫既有內容。 + +這是 LangGraph 的新概念:可以在狀態中加入運算子,定義狀態的整合方式。 + +```python +class AgentState(TypedDict): + # The document provided + input_file: Optional[str] # Contains file path (PDF/PNG) + messages: Annotated[list[AnyMessage], add_messages] +``` + +## 準備工具 + +```python +vision_llm = ChatOpenAI(model="gpt-4o") + +def extract_text(img_path: str) -> str: + """ + Extract text from an image file using a multimodal model. + + Master Wayne often leaves notes with his training regimen or meal plans. + This allows me to properly analyze the contents. + """ + all_text = "" + try: + # Read image and encode as base64 + with open(img_path, "rb") as image_file: + image_bytes = image_file.read() + + image_base64 = base64.b64encode(image_bytes).decode("utf-8") + + # Prepare the prompt including the base64 image data + message = [ + HumanMessage( + content=[ + { + "type": "text", + "text": ( + "Extract all the text from this image. " + "Return only the extracted text, no explanations." + ), + }, + { + "type": "image_url", + "image_url": { + "url": f"data:image/png;base64,{image_base64}" + }, + }, + ] + ) + ] + + # Call the vision-capable model + response = vision_llm.invoke(message) + + # Append extracted text + all_text += response.content + "\n\n" + + return all_text.strip() + except Exception as e: + # A butler should handle errors gracefully + error_msg = f"Error extracting text: {str(e)}" + print(error_msg) + return "" + +def divide(a: int, b: int) -> float: + """Divide a and b - for Master Wayne's occasional calculations.""" + return a / b + +# Equip the butler with tools +tools = [ + divide, + extract_text +] + +llm = ChatOpenAI(model="gpt-4o") +llm_with_tools = llm.bind_tools(tools, parallel_tool_calls=False) +``` + +## 節點 + +```python +def assistant(state: AgentState): + # System message + textual_description_of_tool=""" +extract_text(img_path: str) -> str: + Extract text from an image file using a multimodal model. + + Args: + img_path: A local image file path (strings). + + Returns: + A single string containing the concatenated text extracted from each image. +divide(a: int, b: int) -> float: + Divide a and b +""" + image=state["input_file"] + sys_msg = SystemMessage(content=f"You are a helpful butler named Alfred that serves Mr. Wayne and Batman. You can analyse documents and run computations with provided tools:\n{textual_description_of_tool} \n You have access to some optional images. Currently the loaded image is: {image}") + + return { + "messages": [llm_with_tools.invoke([sys_msg] + state["messages"])], + "input_file": state["input_file"] + } +``` + +## ReAct 模式:我如何協助 Wayne 先生 + +容我說明這個 agent 的做法。它遵循稱為 ReAct 的模式(推理、行動、觀察): + +1. 針對他的文件與請求進行**推理** +2. 使用合適的工具採取**行動** +3. **觀察**結果 +4. 視需要**重複**,直到完整滿足他的需求 + +這是使用 LangGraph 實作的簡單 agent。 + +```python +# The graph +builder = StateGraph(AgentState) + +# Define nodes: these do the work +builder.add_node("assistant", assistant) +builder.add_node("tools", ToolNode(tools)) + +# Define edges: these determine how the control flow moves +builder.add_edge(START, "assistant") +builder.add_conditional_edges( + "assistant", + # If the latest message requires a tool, route to tools + # Otherwise, provide a direct response + tools_condition, +) +builder.add_edge("tools", "assistant") +react_graph = builder.compile() + +# Show the butler's thought process +display(Image(react_graph.get_graph(xray=True).draw_mermaid_png())) +``` + +我們以工具清單定義 `tools` 節點。`assistant` 節點則是綁定工具後的模型。 +接著建立包含 `assistant` 與 `tools` 節點的圖。 + +我們加入 `tools_condition` 邊,依 `assistant` 是否呼叫工具,將流程導向 `End` 或 `tools`。 + +現在,再加入一個新步驟: + +將 `tools` 節點連回 `assistant`,形成迴圈。 + +- `assistant` 節點執行後,`tools_condition` 會檢查模型輸出是否為工具呼叫。 +- 如果是工具呼叫,就將流程導向 `tools` 節點。 +- `tools` 節點會連回 `assistant`。 +- 只要模型繼續決定呼叫工具,迴圈就會持續。 +- 如果模型回覆並非工具呼叫,就將流程導向 END,結束執行。 + +![ReAct 模式](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit2/LangGraph/Agent.png) + +## 管家實際上場 + +### 範例 1:簡單計算 + +以下以簡單案例,示範 LangGraph 中的 agent 如何使用工具。 + +```python +messages = [HumanMessage(content="Divide 6790 by 5")] +messages = react_graph.invoke({"messages": messages, "input_file": None}) + +# Show the messages +for m in messages['messages']: + m.pretty_print() +``` + +對話會如下進行: + +``` +Human: Divide 6790 by 5 + +AI Tool Call: divide(a=6790, b=5) + +Tool Response: 1358.0 + +Alfred: The result of dividing 6790 by 5 is 1358.0. +``` + +### 範例 2:分析 Wayne 老爺的訓練文件 + +當 Wayne 老爺留下訓練與飲食筆記時: + +```python +messages = [HumanMessage(content="According to the note provided by Mr. Wayne in the provided images. What's the list of items I should buy for the dinner menu?")] +messages = react_graph.invoke({"messages": messages, "input_file": "Batman_training_and_meals.png"}) +``` + +互動會如下進行: + +``` +Human: According to the note provided by Mr. Wayne in the provided images. What's the list of items I should buy for the dinner menu? + +AI Tool Call: extract_text(img_path="Batman_training_and_meals.png") + +Tool Response: [Extracted text with training schedule and menu details] + +Alfred: For the dinner menu, you should buy the following items: + +1. Grass-fed local sirloin steak +2. Organic spinach +3. Piquillo peppers +4. Potatoes (for oven-baked golden herb potato) +5. Fish oil (2 grams) + +Ensure the steak is grass-fed and the spinach and peppers are organic for the best quality meal. +``` + +## 重點整理 + +如果您也想建立文件分析管家,請考慮以下重點: + +1. 為特定文件任務**定義清楚的工具** +2. **建立穩健的狀態追蹤機制**,維持工具呼叫之間的上下文 +3. 針對工具失敗的情況**考慮錯誤處理** +4. **保留先前互動的上下文**(透過 `add_messages` 運算子確保) + +遵循這些原則,您也能提供配得上 Wayne 莊園的優質文件分析服務。 + +*相信這番說明已讓您滿意。現在請恕我失陪,今晚出門前,還得替 Wayne 老爺燙好披風。* diff --git a/units/zh-TW/unit2/langgraph/first_graph.mdx b/units/zh-TW/unit2/langgraph/first_graph.mdx new file mode 100644 index 000000000..e5f6e0f15 --- /dev/null +++ b/units/zh-TW/unit2/langgraph/first_graph.mdx @@ -0,0 +1,374 @@ +# 建立您的第一個 LangGraph + +了解基本構成要素後,讓我們建立第一個能實際運作的圖,將概念付諸實作。我們將建立 Alfred 的電子郵件處理系統,讓他能夠: + +1. 閱讀收到的電子郵件 +2. 將郵件分為垃圾郵件或正常郵件 +3. 為正常郵件草擬初步回覆 +4. 收到正常郵件時,將資訊傳給 Wayne 先生(僅印出內容) + +這個範例示範如何使用 LangGraph,組織包含 LLM 決策的工作流程。由於沒有使用工具,這還不能算是 agent;本節主要是學習 LangGraph 框架。 + +> [!TIP] +> 您可以跟著這份 notebook 的程式碼操作,並使用 Google Colab 執行。 + +## 我們的工作流程 + +以下是我們將建立的工作流程: +First LangGraph + +## 設定環境 + +首先,安裝所需套件: + +```python +%pip install langgraph langchain_openai +``` + +接著,匯入必要模組: + +```python +import os +from typing import TypedDict, List, Dict, Any, Optional +from langgraph.graph import StateGraph, START, END +from langchain_openai import ChatOpenAI +from langchain_core.messages import HumanMessage +``` + +## 步驟 1:定義狀態 + +先定義 Alfred 在電子郵件處理流程中需要追蹤的資訊: + +```python +class EmailState(TypedDict): + # The email being processed + email: Dict[str, Any] # Contains subject, sender, body, etc. + + # Category of the email (inquiry, complaint, etc.) + email_category: Optional[str] + + # Reason why the email was marked as spam + spam_reason: Optional[str] + + # Analysis and decisions + is_spam: Optional[bool] + + # Response generation + email_draft: Optional[str] + + # Processing metadata + messages: List[Dict[str, Any]] # Track conversation with LLM for analysis +``` + +> 💡 **提示:** 狀態應完整涵蓋所有重要資訊,但也要避免加入不必要的細節,讓它過於龐大。 + +## 步驟 2:定義節點 + +現在建立處理函式,作為圖中的節點: + +```python +# Initialize our LLM +model = ChatOpenAI(temperature=0) + +def read_email(state: EmailState): + """Alfred reads and logs the incoming email""" + email = state["email"] + + # Here we might do some initial preprocessing + print(f"Alfred is processing an email from {email['sender']} with subject: {email['subject']}") + + # No state changes needed here + return {} + +def classify_email(state: EmailState): + """Alfred uses an LLM to determine if the email is spam or legitimate""" + email = state["email"] + + # Prepare our prompt for the LLM + prompt = f""" + As Alfred the butler, analyze this email and determine if it is spam or legitimate. + + Email: + From: {email['sender']} + Subject: {email['subject']} + Body: {email['body']} + + First, determine if this email is spam. If it is spam, explain why. + If it is legitimate, categorize it (inquiry, complaint, thank you, etc.). + """ + + # Call the LLM + messages = [HumanMessage(content=prompt)] + response = model.invoke(messages) + + # Simple logic to parse the response (in a real app, you'd want more robust parsing) + response_text = response.content.lower() + is_spam = "spam" in response_text and "not spam" not in response_text + + # Extract a reason if it's spam + spam_reason = None + if is_spam and "reason:" in response_text: + spam_reason = response_text.split("reason:")[1].strip() + + # Determine category if legitimate + email_category = None + if not is_spam: + categories = ["inquiry", "complaint", "thank you", "request", "information"] + for category in categories: + if category in response_text: + email_category = category + break + + # Update messages for tracking + new_messages = state.get("messages", []) + [ + {"role": "user", "content": prompt}, + {"role": "assistant", "content": response.content} + ] + + # Return state updates + return { + "is_spam": is_spam, + "spam_reason": spam_reason, + "email_category": email_category, + "messages": new_messages + } + +def handle_spam(state: EmailState): + """Alfred discards spam email with a note""" + print(f"Alfred has marked the email as spam. Reason: {state['spam_reason']}") + print("The email has been moved to the spam folder.") + + # We're done processing this email + return {} + +def draft_response(state: EmailState): + """Alfred drafts a preliminary response for legitimate emails""" + email = state["email"] + category = state["email_category"] or "general" + + # Prepare our prompt for the LLM + prompt = f""" + As Alfred the butler, draft a polite preliminary response to this email. + + Email: + From: {email['sender']} + Subject: {email['subject']} + Body: {email['body']} + + This email has been categorized as: {category} + + Draft a brief, professional response that Mr. Hugg can review and personalize before sending. + """ + + # Call the LLM + messages = [HumanMessage(content=prompt)] + response = model.invoke(messages) + + # Update messages for tracking + new_messages = state.get("messages", []) + [ + {"role": "user", "content": prompt}, + {"role": "assistant", "content": response.content} + ] + + # Return state updates + return { + "email_draft": response.content, + "messages": new_messages + } + +def notify_mr_hugg(state: EmailState): + """Alfred notifies Mr. Hugg about the email and presents the draft response""" + email = state["email"] + + print("\n" + "="*50) + print(f"Sir, you've received an email from {email['sender']}.") + print(f"Subject: {email['subject']}") + print(f"Category: {state['email_category']}") + print("\nI've prepared a draft response for your review:") + print("-"*50) + print(state["email_draft"]) + print("="*50 + "\n") + + # We're done processing this email + return {} +``` + +## 步驟 3:定義路由邏輯 + +我們需要一個函式,決定分類後要走哪條路徑: + +```python +def route_email(state: EmailState) -> str: + """Determine the next step based on spam classification""" + if state["is_spam"]: + return "spam" + else: + return "legitimate" +``` + +> 💡 **注意:** LangGraph 會呼叫這個路由函式,決定分類節點之後要沿著哪條邊執行。回傳值必須符合條件邊對應表中的某個鍵。 + +## 步驟 4:建立 StateGraph 並定義邊 + +現在將所有部分連接起來: + +```python +# Create the graph +email_graph = StateGraph(EmailState) + +# Add nodes +email_graph.add_node("read_email", read_email) +email_graph.add_node("classify_email", classify_email) +email_graph.add_node("handle_spam", handle_spam) +email_graph.add_node("draft_response", draft_response) +email_graph.add_node("notify_mr_hugg", notify_mr_hugg) + +# Start the edges +email_graph.add_edge(START, "read_email") +# Add edges - defining the flow +email_graph.add_edge("read_email", "classify_email") + +# Add conditional branching from classify_email +email_graph.add_conditional_edges( + "classify_email", + route_email, + { + "spam": "handle_spam", + "legitimate": "draft_response" + } +) + +# Add the final edges +email_graph.add_edge("handle_spam", END) +email_graph.add_edge("draft_response", "notify_mr_hugg") +email_graph.add_edge("notify_mr_hugg", END) + +# Compile the graph +compiled_graph = email_graph.compile() +``` + +請注意,我們使用了 LangGraph 提供的特殊 `END` 節點,表示工作流程完成的終止狀態。 + +## 步驟 5:執行應用程式 + +讓我們用一封正常郵件與一封垃圾郵件測試這個圖: + +```python +# Example legitimate email +legitimate_email = { + "sender": "john.smith@example.com", + "subject": "Question about your services", + "body": "Dear Mr. Hugg, I was referred to you by a colleague and I'm interested in learning more about your consulting services. Could we schedule a call next week? Best regards, John Smith" +} + +# Example spam email +spam_email = { + "sender": "winner@lottery-intl.com", + "subject": "YOU HAVE WON $5,000,000!!!", + "body": "CONGRATULATIONS! You have been selected as the winner of our international lottery! To claim your $5,000,000 prize, please send us your bank details and a processing fee of $100." +} + +# Process the legitimate email +print("\nProcessing legitimate email...") +legitimate_result = compiled_graph.invoke({ + "email": legitimate_email, + "is_spam": None, + "spam_reason": None, + "email_category": None, + "email_draft": None, + "messages": [] +}) + +# Process the spam email +print("\nProcessing spam email...") +spam_result = compiled_graph.invoke({ + "email": spam_email, + "is_spam": None, + "spam_reason": None, + "email_category": None, + "email_draft": None, + "messages": [] +}) +``` + +## 步驟 6:使用 Langfuse 檢視郵件分類 agent 📡 + +Alfred 不斷調整郵件分類 agent,卻逐漸厭倦了替每次執行除錯。agent 的行為本來就不易預測,也難以檢視。但他希望建立完善的垃圾郵件偵測 agent,並部署到正式環境,因此需要可靠的追蹤能力,以便日後監控與分析。 + +為此,Alfred 可以使用 [Langfuse](https://langfuse.com/) 等可觀測性工具,追蹤並監控 agent。 + +首先,透過 pip 安裝 Langfuse: +```python +%pip install -q langfuse +``` + +接著,透過 pip 安裝 LangChain(使用 Langfuse 需要 LangChain): +```python +%pip install langchain +``` + +然後,將 Langfuse API 金鑰與主機位址設為環境變數。您可以註冊 [Langfuse Cloud](https://cloud.langfuse.com),或[自行架設 Langfuse](https://langfuse.com/self-hosting),取得所需憑證。 + +```python +import os + +# Get keys for your project from the project settings page: https://cloud.langfuse.com +os.environ["LANGFUSE_PUBLIC_KEY"] = "pk-lf-..." +os.environ["LANGFUSE_SECRET_KEY"] = "sk-lf-..." +os.environ["LANGFUSE_HOST"] = "https://cloud.langfuse.com" # 🇪🇺 EU region +# os.environ["LANGFUSE_HOST"] = "https://us.cloud.langfuse.com" # 🇺🇸 US region +``` + +接著設定 [Langfuse `callback_handler`](https://langfuse.com/docs/integrations/langchain/tracing#add-langfuse-to-your-langchain-application),並在呼叫圖時加入 `langfuse_callback`,為 agent 加上追蹤功能:`config={"callbacks": [langfuse_handler]}`。 + +```python +from langfuse.langchain import CallbackHandler + +# Initialize Langfuse CallbackHandler for LangGraph/Langchain (tracing) +langfuse_handler = CallbackHandler() + +# Process legitimate email +legitimate_result = compiled_graph.invoke( + input={"email": legitimate_email, "is_spam": None, "spam_reason": None, "email_category": None, "draft_response": None, "messages": []}, + config={"callbacks": [langfuse_handler]} +) +``` + +Alfred 已連接完成 🔌!LangGraph 的執行紀錄會記錄在 Langfuse 中,讓他完整掌握 agent 的行為。透過這個設定,他可以回顧先前的執行,進一步改善郵件分類 agent。 + +![Langfuse 追蹤紀錄範例](https://langfuse.com/images/cookbook/huggingface-agent-course/langgraph-trace-legit.png) + +_[正常郵件的公開追蹤紀錄](https://cloud.langfuse.com/project/cloramnkj0002jz088vzn1ja4/traces/f5d6d72e-20af-4357-b232-af44c3728a7b?timestamp=2025-03-17T10%3A13%3A28.413Z&observation=6997ba69-043f-4f77-9445-700a033afba1)_ + +## 將圖視覺化 + +LangGraph 可以將工作流程視覺化,幫助我們理解結構與除錯: + +```python +compiled_graph.get_graph().draw_mermaid_png() +``` +Mail LangGraph + +產生的流程圖會顯示節點如何連接,以及各種條件下可能採取的路徑。 + +## 我們建立了什麼? + +我們建立了完整的電子郵件處理流程,能夠: + +1. 接收電子郵件 +2. 使用 LLM,將郵件分為垃圾郵件或正常郵件 +3. 捨棄垃圾郵件 +4. 為正常郵件草擬回覆,並通知 Hugg 先生 + +這展示了 LangGraph 如何運用 LLM 協調複雜工作流程,同時維持清楚、有結構的執行流程。 + +## 重點整理 + +- **狀態管理**:定義完整狀態,追蹤電子郵件處理的各項資訊 +- **節點實作**:建立能與 LLM 互動的處理節點 +- **條件路由**:根據郵件分類結果實作分支邏輯 +- **終止狀態**:使用 END 節點,標示工作流程的完成點 + +## 接下來呢? + +下一節將探索 LangGraph 更進階的功能,包括在流程中處理人機互動,以及根據多個條件實作更複雜的分支邏輯。 diff --git a/units/zh-TW/unit2/langgraph/introduction.mdx b/units/zh-TW/unit2/langgraph/introduction.mdx new file mode 100644 index 000000000..90a72ab88 --- /dev/null +++ b/units/zh-TW/unit2/langgraph/introduction.mdx @@ -0,0 +1,31 @@ +# `LangGraph` 簡介 + +Unit 2.3 Thumbnail + +歡迎來到學習旅程的下一站!您將學習**如何使用 [`LangGraph`](https://github.com/langchain-ai/langgraph) 框架建立應用程式**,組織並協調複雜的 LLM 工作流程。 + +`LangGraph` 提供**控制** agent 流程的工具,讓您建立**可部署至正式環境**的應用程式。 + +## 模組概覽 + +在本單元中,您將學習: + +### 1️⃣ [什麼是 LangGraph?何時使用?](./when_to_use_langgraph) +### 2️⃣ [LangGraph 的基本構成要素](./building_blocks) +### 3️⃣ [郵件分類管家 Alfred](./first_graph) +### 4️⃣ [文件分析 agent Alfred](./document_analysis_agent) +### 5️⃣ [測驗](./quizz1) + +> [!WARNING] +> 本節範例需要使用能力較強的 LLM/VLM 模型。我們使用 GPT-4o API 執行,因為它與 LangGraph 的相容性最佳。 + +完成本單元後,您將具備建立穩健、組織良好且能部署至正式環境的應用程式的能力! + +不過,本節只是 LangGraph 入門。更進階的主題,可以透過 LangChain Academy 的免費課程學習:[LangGraph 入門](https://academy.langchain.com/courses/intro-to-langgraph)。 + +讓我們開始吧! + +## 參考資源 + +- [LangGraph agent](https://langchain-ai.github.io/langgraph/):LangGraph agent 範例 +- [LangChain Academy](https://academy.langchain.com/courses/intro-to-langgraph):LangChain 提供的完整 LangGraph 課程 diff --git a/units/zh-TW/unit2/langgraph/quiz1.mdx b/units/zh-TW/unit2/langgraph/quiz1.mdx new file mode 100644 index 000000000..1dd9ebace --- /dev/null +++ b/units/zh-TW/unit2/langgraph/quiz1.mdx @@ -0,0 +1,118 @@ +# 測試您對 LangGraph 的理解 + +讓我們透過簡短測驗,測試您對 `LangGraph` 的理解,並鞏固目前學到的關鍵概念! + +本測驗可自由參加,不計分。 + +### Q1: LangGraph 的主要用途是什麼? +哪個敘述最能描述 LangGraph 的設計目標? + + + +--- + +### Q2: 在「控制與自由度」的取捨中,LangGraph 的定位是什麼? +哪個敘述最能描述 LangGraph 設計 agent 的方式? + + + +--- + +### Q3: State 在 LangGraph 中扮演什麼角色? +選出對 LangGraph 中 State 最準確的描述。 + + + +### Q4: LangGraph 中的條件邊(Conditional Edge)是什麼? +選出最準確的描述。 + + + +--- + +### Q5: LangGraph 如何協助處理 LLM 的幻覺問題? +選出最佳答案。 + + + +恭喜完成測驗!🎉 如果有答錯的題目,可以回顧前面章節,加強理解。接下來將探索 LangGraph 更進階的功能,學習建立更複雜的 agent 工作流程。 diff --git a/units/zh-TW/unit2/langgraph/when_to_use_langgraph.mdx b/units/zh-TW/unit2/langgraph/when_to_use_langgraph.mdx new file mode 100644 index 000000000..1416727a7 --- /dev/null +++ b/units/zh-TW/unit2/langgraph/when_to_use_langgraph.mdx @@ -0,0 +1,68 @@ +# 什麼是 `LangGraph`? [[what-is-langgraph]] + +`LangGraph` 是 [LangChain](https://www.langchain.com/) 開發的框架,**用來管理整合 LLM 的應用程式的控制流程**。 + +## `LangGraph` 與 `LangChain` 有何不同? + +LangChain 提供與模型及其他元件互動的標準介面,適用於檢索、LLM 呼叫與工具呼叫。 +LangGraph 可以使用 LangChain 的類別,但並非必要。 + +這兩個套件各自獨立,可以單獨使用,不過網路上的資源通常會搭配使用兩者。 + +## 什麼時候該使用 `LangGraph`? +### 控制與自由度 + +設計 AI 應用程式時,會面臨**控制**與**自由度**之間的基本取捨: + +- **自由度**給 LLM 更多發揮創意、處理意外問題的空間。 +- **控制**讓您確保行為可預測,並維持防護措施。 + +*smolagents* 中的 Code agent 自由度很高,能在一個行動步驟中呼叫多個工具、建立自己的工具等。不過,與一般使用 JSON 的 agent 相比,這也可能讓它們更難預測和控制! + +`LangGraph` 位於另一端:當您需要**控制** agent 的執行時,它特別適合。 + +需要**掌握應用程式的運作流程**時,LangGraph 很有價值。它提供工具,讓應用程式遵循可預測的流程,同時運用 LLM 的能力。 + +簡單來說,如果應用程式有一連串步驟,需要按特定方式協調,並在每個交會點做出決策,**LangGraph 就能提供所需的結構**。 + +舉例來說,假設我們要建立能回答文件相關問題的 LLM 助手。 + +由於 LLM 最擅長理解文字,回答問題前,需要先將圖表、表格等其他複雜模態轉換為文字。不過,要怎麼轉換,取決於文件的類型! + +我將這個分支表示如下: + +Control flow + +> 💡 **提示:** 左側並非 agent,因為沒有工具呼叫;右側則需要撰寫程式碼來查詢 xls(轉換為 pandas 資料結構後操作)。 + +雖然這個分支具有確定性,但您也可以根據 LLM 的輸出來決定分支,讓流程不再具有確定性。 + +LangGraph 特別適合的情境包括: + +- 需要明確控制流程的**多步驟推理** +- **需要在步驟之間持續保留狀態的應用程式** +- **結合確定性邏輯與 AI 能力的系統** +- **需要人工介入的工作流程** +- 多個元件協作的**複雜 agent 架構** + +也就是說,只要**您能親自**根據各項行動的輸出設計流程,並決定接下來執行什麼,LangGraph 就很適合您! + +在我看來,`LangGraph` 是目前最適合部署至正式環境的 agent 框架。 + +## LangGraph 如何運作? + +`LangGraph` 的核心,是透過有向圖結構定義應用程式的流程: + +- **節點**代表個別處理步驟,例如呼叫 LLM、使用工具或做出決策。 +- **邊**定義步驟之間可能的轉換。 +- **狀態**由使用者定義並維護,執行時在節點之間傳遞。決定下一個節點時,依據的就是目前狀態。 + +下一章會更深入探索這些基本要素! + +## 和一般 Python 有何不同?為什麼需要 LangGraph? + +您可能會想:「直接寫一般 Python 程式碼,用 if-else 敘述處理這些流程就好了吧?」 + +技術上確實可行,但建立複雜系統時,LangGraph 比原生 Python **多了一些優勢**。您可以不使用 LangGraph 建立相同應用程式,但它提供更方便的工具與抽象概念。 + +其中包括狀態、視覺化、記錄(追蹤紀錄)、內建人工介入功能等。 diff --git a/units/zh-TW/unit2/llama-index/README.md b/units/zh-TW/unit2/llama-index/README.md new file mode 100644 index 000000000..3a32bd935 --- /dev/null +++ b/units/zh-TW/unit2/llama-index/README.md @@ -0,0 +1,15 @@ +# 目錄 + +本 LlamaIndex 框架大綱是課程第 2 單元的一部分。您可以在 hf.co/learn 閱讀關於 LlamaIndex 的第 2 單元內容 👉 由此進入 + +| 標題 | 說明 | +| --- | --- | +| [簡介](introduction.mdx) | LlamaIndex 簡介 | +| [LlamaHub](llama-hub.mdx) | LlamaHub:整合元件、agent 與工具的資源目錄 | +| [元件](components.mdx) | 元件:工作流程的基本構成要素 | +| [工具](tools.mdx) | 工具:如何在 LlamaIndex 中建立工具 | +| [測驗 1](quiz1.mdx) | 測驗 1 | +| [agent](agents.mdx) | agent:如何在 LlamaIndex 中建立 agent | +| [工作流程](workflows.mdx) | 工作流程:由元件組成、依序執行的一系列步驟與事件 | +| [測驗 2](quiz2.mdx) | 測驗 2 | +| [結語](conclusion.mdx) | 結語 | diff --git a/units/zh-TW/unit2/llama-index/agents.mdx b/units/zh-TW/unit2/llama-index/agents.mdx new file mode 100644 index 000000000..bc0e02a8e --- /dev/null +++ b/units/zh-TW/unit2/llama-index/agents.mdx @@ -0,0 +1,161 @@ +# 在 LlamaIndex 中使用 agent + +還記得先前那位熱心的管家 agent Alfred 嗎?他即將升級了! +現在我們已認識 LlamaIndex 提供的工具,可以賦予 Alfred 新能力,讓他更有效地協助我們。 + +不過,在繼續之前,先回顧一下 Alfred 這類 agent 的運作原理。 +在第 1 單元中,我們學到: + +> agent 是利用 AI 模型與環境互動,以達成使用者所定義目標的系統。它結合推理、規劃與行動執行(通常透過外部工具)來完成任務。 + +LlamaIndex 支援**三種主要的推理 agent:** + +![agent](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit2/llama-index/agents.png) + +1. `Function Calling Agents`:搭配能呼叫特定函式的 AI 模型使用。 +2. `ReAct Agents`:可搭配任何提供聊天或文字端點的 AI,處理複雜的推理任務。 +3. `Advanced Custom Agents`:使用更複雜的方法,處理更複雜的任務與工作流程。 + +> [!TIP] +> 如需進一步了解進階 agent,請參考 BaseWorkflowAgent。 + +## 初始化 agent + +> [!TIP] +> 您可以跟著這份 notebook 的程式碼操作,並使用 Google Colab 執行。 + +建立 agent 時,首先要提供**一組函式或工具,定義它具備的能力**。 +讓我們看看如何使用基本工具建立 agent。截至撰寫本文時,agent 會自動使用函式呼叫 API(若可用),否則使用標準的 ReAct agent 迴圈。 + +支援工具/函式 API 的 LLM 雖然較新,卻提供了強大的工具呼叫方式:不需要特別設計 prompt,LLM 就能依照提供的結構描述產生工具呼叫。 + +ReAct agent 也擅長複雜推理任務,可搭配任何具備聊天或文字補全能力的 LLM。它們的輸出較詳細,會顯示採取特定行動背後的推理過程。 + +```python +from llama_index.llms.huggingface_api import HuggingFaceInferenceAPI +from llama_index.core.agent.workflow import AgentWorkflow +from llama_index.core.tools import FunctionTool + +# define sample Tool -- type annotations, function names, and docstrings, are all included in parsed schemas! +def multiply(a: int, b: int) -> int: + """Multiplies two integers and returns the resulting integer""" + return a * b + +# initialize llm +llm = HuggingFaceInferenceAPI(model_name="Qwen/Qwen2.5-Coder-32B-Instruct") + +# initialize agent +agent = AgentWorkflow.from_tools_or_functions( + [FunctionTool.from_defaults(multiply)], + llm=llm +) +``` + +**agent 預設不保留狀態**,不過可以透過 `Context` 物件記住先前的互動。 +當 agent 需要記住先前互動時,這就很有用,例如要在多則訊息之間維持上下文的聊天機器人,或需要持續追蹤進度的任務管理工具。 + +```python +# stateless +response = await agent.run("What is 2 times 2?") + +# remembering state +from llama_index.core.workflow import Context + +ctx = Context(agent) + +response = await agent.run("My name is Bob.", ctx=ctx) +response = await agent.run("What was my name again?", ctx=ctx) +``` + +您會發現 `LlamaIndex` 的 agent 使用 Python 的 `await` 運算子,以非同步方式執行。如果您剛接觸 Python 非同步程式,或需要複習,可以參考這份[實用的非同步指南](https://docs.llamaindex.ai/en/stable/getting_started/async_python/)。 + +掌握基礎後,讓我們看看如何在 agent 中使用更複雜的工具。 + +## 使用 QueryEngineTools 建立 RAG agent + +**Agentic RAG 是運用 agent 回答資料相關問題的強大方式。** 我們可以為 Alfred 提供各種工具,協助他回答問題。 +Alfred 不會自動只依據文件作答,而是可以自行決定使用其他工具或流程來回答問題。 + +![Agentic RAG](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit2/llama-index/agentic-rag.png) + +將 **`QueryEngine` 封裝為 agent 的工具**很簡單。 +我們需要**定義名稱與描述**,讓 LLM 能根據這些資訊正確使用工具。 +以下使用[元件章節](components)建立的 `QueryEngine`,示範如何載入 `QueryEngineTool`。 + +```python +from llama_index.core.tools import QueryEngineTool + +query_engine = index.as_query_engine(llm=llm, similarity_top_k=3) # as shown in the Components in LlamaIndex section + +query_engine_tool = QueryEngineTool.from_defaults( + query_engine=query_engine, + name="name", + description="a specific description", + return_direct=False, +) +query_engine_agent = AgentWorkflow.from_tools_or_functions( + [query_engine_tool], + llm=llm, + system_prompt="You are a helpful assistant that has access to a database containing persona descriptions. " +) +``` + +## 建立多 agent 系統 + +`AgentWorkflow` 類別也直接支援多 agent 系統。為每個 agent 指定名稱與描述後,系統會維持一個目前發話的 agent,而每個 agent 都能將任務交接給其他 agent。 + +縮小各個 agent 的職責範圍,有助於提升它們回覆使用者訊息的整體準確度。 + +**LlamaIndex 中的 agent 也能直接作為其他 agent 的工具**,用於更複雜、需要自訂的情境。 + +```python +from llama_index.core.agent.workflow import ( + AgentWorkflow, + FunctionAgent, + ReActAgent, +) + +# Define some tools +def add(a: int, b: int) -> int: + """Add two numbers.""" + return a + b + + +def subtract(a: int, b: int) -> int: + """Subtract two numbers.""" + return a - b + + +# Create agent configs +# NOTE: we can use FunctionAgent or ReActAgent here. +# FunctionAgent works for LLMs with a function calling API. +# ReActAgent works for any LLM. +calculator_agent = ReActAgent( + name="calculator", + description="Performs basic arithmetic operations", + system_prompt="You are a calculator assistant. Use your tools for any math operation.", + tools=[add, subtract], + llm=llm, +) + +query_agent = ReActAgent( + name="info_lookup", + description="Looks up information about XYZ", + system_prompt="Use your tool to query a RAG system to answer information about XYZ", + tools=[query_engine_tool], + llm=llm +) + +# Create and run the workflow +agent = AgentWorkflow( + agents=[calculator_agent, query_agent], root_agent="calculator" +) + +# Run the system +response = await agent.run(user_msg="Can you add 5 and 3?") +``` + +> [!TIP] +> 還想深入學習嗎?AgentWorkflow 基礎介紹和agent 學習指南提供更多 LlamaIndex agent 與工具的內容,包括串流、上下文序列化與人工介入(human-in-the-loop)! + +現在我們已了解 LlamaIndex 的 agent 與工具基礎,接下來看看如何**建立可設定且易於管理的工作流程!** diff --git a/units/zh-TW/unit2/llama-index/components.mdx b/units/zh-TW/unit2/llama-index/components.mdx new file mode 100644 index 000000000..826ffc66d --- /dev/null +++ b/units/zh-TW/unit2/llama-index/components.mdx @@ -0,0 +1,245 @@ +# LlamaIndex 中的元件是什麼? + +還記得第 1 單元中那位熱心的管家 agent Alfred 嗎? +為了有效協助我們,Alfred 需要理解請求,並**準備、尋找及運用相關資訊來完成任務。** +這正是 LlamaIndex 元件發揮作用的地方。 + +LlamaIndex 有許多元件,**我們將聚焦於 `QueryEngine` 元件。** +為什麼?因為它可以作為 agent 的檢索增強生成(RAG)工具。 + +那麼,RAG 是什麼?LLM 透過大量資料訓練,學習一般知識。 +不過,訓練資料未必包含相關且最新的資訊。 +RAG 會從您的資料中尋找並擷取相關資訊,提供給 LLM,藉此解決這個問題。 + +![RAG](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit2/llama-index/rag.png) + +想想 Alfred 的工作方式: + +1. 您請 Alfred 協助規劃晚宴 +2. Alfred 需要查看您的行事曆、飲食偏好,以及過往成功的菜單 +3. `QueryEngine` 協助 Alfred 找到這些資訊,並用來規劃晚宴 + +因此,`QueryEngine` 是在 LlamaIndex 中**建立 Agentic RAG 工作流程的關鍵元件**。 +就像 Alfred 需要搜尋家中資訊才能提供協助,每個 agent 都需要尋找並理解相關資料的方法。 +`QueryEngine` 正好提供這項能力。 + +接下來,讓我們深入認識這些元件,看看如何**組合元件來建立 RAG 管線。** + +## 使用元件建立 RAG 管線 + +> [!TIP] +> 您可以跟著這份 notebook 的程式碼操作,並使用 Google Colab 執行。 + +RAG 有五個關鍵階段,也會成為您所建立的大多數大型應用程式的一部分: + +1. **載入**:將資料從原本的位置帶入工作流程,不論來源是文字檔、PDF、網站、資料庫或 API。LlamaHub 提供數百種整合元件可供選擇。 +2. **索引**:建立可供查詢資料的資料結構。對 LLM 而言,這幾乎總是代表建立向量嵌入,也就是以數值表示資料的語意。索引也可以涵蓋其他後設資料策略,方便根據屬性準確找出符合上下文的資料。 +3. **儲存**:資料完成索引後,儲存索引與其他後設資料,避免重複建立索引。 +4. **查詢**:針對不同索引策略,可以運用 LLM 與 LlamaIndex 的資料結構,以子查詢、多步驟查詢或混合策略等方式進行查詢。 +5. **評估**:檢查流程相較其他策略或修改前的效果,是不可或缺的步驟。評估能客觀衡量查詢回覆的準確度、忠實度與速度。 + +接下來看看如何使用元件實作這些階段。 + +### 載入文件並建立嵌入 + +如前所述,LlamaIndex 能處理您自己的資料,但**存取資料之前,必須先載入資料。** +將資料載入 LlamaIndex 主要有三種方式: + +1. `SimpleDirectoryReader`:內建載入器,可從本機目錄載入多種檔案類型。 +2. `LlamaParse`:LlamaIndex 官方的 PDF 解析工具,以受管理的 API 形式提供。 +3. `LlamaHub`:收錄數百種資料載入函式庫的資源目錄,能從各種來源匯入資料。 + +> [!TIP] +> 若要處理較複雜的資料來源,可以深入了解 LlamaHub 載入器與 LlamaParse 解析器。 + +**載入資料最簡單的方式是使用 `SimpleDirectoryReader`。** +這個多功能元件能從資料夾載入多種檔案,並轉換為 LlamaIndex 可處理的 `Document` 物件。 +讓我們看看如何使用 `SimpleDirectoryReader` 從資料夾載入資料。 + +```python +from llama_index.core import SimpleDirectoryReader + +reader = SimpleDirectoryReader(input_dir="path/to/directory") +documents = reader.load_data() +``` + +載入文件後,需要將它們切成較小的 `Node` 物件。 +`Node` 是原始文件中的一段文字,方便 AI 處理,同時保留對原始 `Document` 物件的參照。 + +`IngestionPipeline` 會透過兩項關鍵轉換協助我們建立節點。 +1. `SentenceSplitter` 在自然的句子邊界切分文件,產生便於處理的文字區塊。 +2. `HuggingFaceEmbedding` 將每個區塊轉換為數值嵌入,也就是以 AI 能有效處理的向量表示文字語意。 + +這個流程能讓文件的組織方式更適合搜尋與分析。 + +```python +from llama_index.core import Document +from llama_index.embeddings.huggingface import HuggingFaceEmbedding +from llama_index.core.node_parser import SentenceSplitter +from llama_index.core.ingestion import IngestionPipeline + +# create the pipeline with transformations +pipeline = IngestionPipeline( + transformations=[ + SentenceSplitter(chunk_overlap=0), + HuggingFaceEmbedding(model_name="BAAI/bge-small-en-v1.5"), + ] +) + +nodes = await pipeline.arun(documents=[Document.example()]) +``` + +### 儲存文件並建立索引 + +建立 `Node` 物件後,需要為它們建立索引才能搜尋;不過,在這之前還得先準備儲存資料的位置。 + +由於我們使用資料匯入管線,可以直接將向量儲存連接到管線,將資料寫入其中。 +本例會使用 `Chroma` 儲存文件。 + +
+安裝 ChromaDB + +如LlamaHub 章節所介紹的,可以使用以下指令安裝 ChromaDB 向量儲存: + +```bash +pip install llama-index-vector-stores-chroma +``` +
+ +```python +import chromadb +from llama_index.vector_stores.chroma import ChromaVectorStore + +db = chromadb.PersistentClient(path="./alfred_chroma_db") +chroma_collection = db.get_or_create_collection("alfred") +vector_store = ChromaVectorStore(chroma_collection=chroma_collection) + +pipeline = IngestionPipeline( + transformations=[ + SentenceSplitter(chunk_size=25, chunk_overlap=0), + HuggingFaceEmbedding(model_name="BAAI/bge-small-en-v1.5"), + ], + vector_store=vector_store, +) +``` + +> [!TIP] +> 您可以在 LlamaIndex 文件中查看各種向量儲存的概覽。 + +向量嵌入在此派上用場:將查詢與節點嵌入同一個向量空間,就能找出相關內容。 +`VectorStoreIndex` 會替我們處理這些工作,並使用與資料匯入階段相同的嵌入模型,確保一致性。 + +讓我們看看如何利用向量儲存與嵌入建立索引: + +```python +from llama_index.core import VectorStoreIndex +from llama_index.embeddings.huggingface import HuggingFaceEmbedding + +embed_model = HuggingFaceEmbedding(model_name="BAAI/bge-small-en-v1.5") +index = VectorStoreIndex.from_vector_store(vector_store, embed_model=embed_model) +``` + +所有資訊都會自動保存在 `ChromaVectorStore` 物件與傳入的目錄路徑中。 + +現在已經能輕鬆儲存與載入索引了,接下來探索不同的查詢方式。 + +### 使用 prompt 與 LLM 查詢 VectorStoreIndex + +查詢索引之前,需要將它轉換為查詢介面。最常見的轉換選項包括: + +- `as_retriever`:用於基本的文件檢索,回傳含有相似度分數的 `NodeWithScore` 物件清單 +- `as_query_engine`:用於單次問答互動,回傳文字回覆 +- `as_chat_engine`:用於需要跨訊息保留記憶的對話互動,根據聊天紀錄與索引中的上下文回傳文字回覆 + +我們將聚焦於查詢引擎,因為這種方式更常用於 agent 類型的互動。 +我們也會將 LLM 傳入查詢引擎,用來產生回覆。 + +```python +from llama_index.llms.huggingface_api import HuggingFaceInferenceAPI + +llm = HuggingFaceInferenceAPI(model_name="Qwen/Qwen2.5-Coder-32B-Instruct") +query_engine = index.as_query_engine( + llm=llm, + response_mode="tree_summarize", +) +query_engine.query("What is the meaning of life?") +# The meaning of life is 42 +``` + +### 處理回覆 + +查詢引擎在底層不只使用 LLM 回答問題,也會使用 `ResponseSynthesizer` 作為處理回覆的策略。 +這部分同樣可以完全自訂,不過有三種開箱即用的主要策略: + +- `refine`:依序處理每個檢索到的文字區塊,建立並逐步改善答案。每個 Node/檢索區塊都會各自呼叫一次 LLM。 +- `compact`(預設):類似 `refine`,但會先將區塊串接起來,因此能減少 LLM 呼叫次數。 +- `tree_summarize`:逐一處理檢索到的文字區塊,以樹狀結構組織答案,產生詳細回覆。 + +> [!TIP] +> 您可以透過低階組合 API 精細控制查詢流程。這個 API 能讓您依需求自訂與微調查詢的每個步驟,也很適合搭配工作流程使用。 + +語言模型的行為不一定可預測,因此無法保證答案永遠正確。我們可以**評估答案品質**來處理這個問題。 + +### 評估與可觀測性 + +LlamaIndex 提供**內建評估工具,用來評估回覆品質。** +這些評估器會利用 LLM,從不同面向分析回覆。 +以下是三種主要評估器: + +- `FaithfulnessEvaluator`:檢查答案是否有上下文依據,評估答案的忠實度。 +- `AnswerRelevancyEvaluator`:檢查答案是否與問題相關,評估答案的相關性。 +- `CorrectnessEvaluator`:檢查答案是否正確,評估答案的正確性。 + +> [!TIP] +> 想深入了解 agent 的可觀測性與評估嗎?請繼續閱讀加值單元 2。 + +```python +from llama_index.core.evaluation import FaithfulnessEvaluator + +query_engine = # from the previous section +llm = # from the previous section + +# query index +evaluator = FaithfulnessEvaluator(llm=llm) +response = query_engine.query( + "What battles took place in New York City in the American Revolution?" +) +eval_result = evaluator.evaluate_response(response=response) +eval_result.passing +``` + +即使沒有直接評估,我們也能**透過可觀測性了解系統的執行情況。** +當工作流程較複雜,而我們想了解各個元件的表現時,這尤其有用。 + +
+安裝 LlamaTrace + +如LlamaHub 章節所介紹的,可以使用以下指令安裝 Arize Phoenix 的 LlamaTrace 回呼: + +```bash +pip install -U llama-index-callbacks-arize-phoenix +``` + +此外,需要將 `PHOENIX_API_KEY` 環境變數設為 LlamaTrace API 金鑰。取得方式如下: +- 在 [LlamaTrace](https://llamatrace.com/login) 建立帳號 +- 在帳號設定中產生 API 金鑰 +- 在下方程式碼中使用 API 金鑰,啟用追蹤功能 + +
+ +```python +import llama_index +import os + +PHOENIX_API_KEY = "" +os.environ["OTEL_EXPORTER_OTLP_HEADERS"] = f"api_key={PHOENIX_API_KEY}" +llama_index.core.set_global_handler( + "arize_phoenix", + endpoint="https://llamatrace.com/v1/traces" +) +``` + +> [!TIP] +> 想進一步了解元件及其使用方式嗎?請繼續閱讀元件指南或 RAG 指南。 + +我們已學會使用元件建立 `QueryEngine`。接下來看看如何**將 `QueryEngine` 作為 agent 的工具!** diff --git a/units/zh-TW/unit2/llama-index/conclusion.mdx b/units/zh-TW/unit2/llama-index/conclusion.mdx new file mode 100644 index 000000000..1f3a64c16 --- /dev/null +++ b/units/zh-TW/unit2/llama-index/conclusion.mdx @@ -0,0 +1,13 @@ +# 結語 + +恭喜您完成第 2 單元的 `llama-index` 模組 🥳 + +您已掌握 `llama-index` 的基礎,也學會了如何建立自己的 agentic 工作流程! +現在您可以運用這些技能,開始建立搜尋引擎,解決自己感興趣的任務。 + +在本單元的下一個模組,您將學習**如何使用 LangGraph 建立 agent**。 + +最後,我們很想**聽聽您對課程的看法,以及我們可以如何改進**。 +如果有任何回饋,請 👉 [填寫這份表單](https://docs.google.com/forms/d/e/1FAIpQLSe9VaONn0eglax0uTwi29rIn4tM7H2sYmmybmG5jJNlE5v0xA/viewform?usp=dialog) + +### 持續學習,保持熱情 🤗 diff --git a/units/zh-TW/unit2/llama-index/introduction.mdx b/units/zh-TW/unit2/llama-index/introduction.mdx new file mode 100644 index 000000000..fb8e9096b --- /dev/null +++ b/units/zh-TW/unit2/llama-index/introduction.mdx @@ -0,0 +1,29 @@ +# LlamaIndex 簡介 + +歡迎來到本模組!您將學習如何使用 [LlamaIndex](https://www.llamaindex.ai/) 工具組,建立由 LLM 驅動的 agent。 + +LlamaIndex 是**一套完整工具組,可透過索引與工作流程,針對您的資料建立由 LLM 驅動的 agent**。本課程將聚焦於在 LlamaIndex 中建立 agent 的三個主要部分:**元件**、**agent 與工具**以及**工作流程**。 + +![LlamaIndex](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit2/llama-index/thumbnail.png) + +讓我們看看 LlamaIndex 的這些核心部分,以及它們如何協助 agent: + +- **元件**:LlamaIndex 的基本構成要素,包括 prompt、模型與資料庫等。元件通常用來連接 LlamaIndex 與其他工具和函式庫。 +- **工具**:提供特定能力的元件,例如搜尋、計算或存取外部服務。它們是讓 agent 執行任務的基礎。 +- **agent**:能自主使用工具並做出決策的元件,透過協調工具的使用來完成複雜目標。 +- **工作流程**:將邏輯串連起來、逐步執行的流程。工作流程或 agentic 工作流程,能在不直接使用 agent 的情況下組織 agentic 行為。 + +## LlamaIndex 有什麼特色? + +雖然 LlamaIndex 的部分功能與 smolagents 等框架相似,但它具備幾項主要優勢: + +- **清楚的工作流程系統**:透過事件驅動、以非同步為優先的語法,將 agent 的決策拆成明確步驟,方便您組合與組織邏輯。 +- **透過 LlamaParse 進階解析文件**:LlamaParse 專為 LlamaIndex 設計,因此整合十分順暢,不過這是付費功能。 +- **豐富的現成元件**:LlamaIndex 發展已有一段時間,能與許多框架搭配使用,並提供大量經過測試的可靠元件,例如 LLM、檢索器與索引。 +- **LlamaHub**:收錄數百種元件、agent 與工具的資源目錄,這些資源都能在 LlamaIndex 中使用。 + +在不同情境中,建立實用的 agent 都會用到這些概念。 +接下來的章節將逐一詳細介紹。 +掌握概念後,我們會運用所學,**以 Alfred 這個 agent 建立實際應用案例**! + +準備好動手探索 LlamaIndex 了嗎?讓我們先**透過 LlamaHub 尋找並安裝所需的整合元件!🚀** diff --git a/units/zh-TW/unit2/llama-index/llama-hub.mdx b/units/zh-TW/unit2/llama-index/llama-hub.mdx new file mode 100644 index 000000000..fc431950b --- /dev/null +++ b/units/zh-TW/unit2/llama-index/llama-hub.mdx @@ -0,0 +1,56 @@ +# LlamaHub 簡介 + +**LlamaHub 是收錄數百種整合元件、agent 與工具的資源目錄,這些資源都能在 LlamaIndex 中使用。** + +![LlamaHub](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit2/llama-index/llama-hub.png) + +本課程會用到多種整合元件,因此先來認識 LlamaHub,看看它如何協助開發。 + +接下來,我們將學習如何尋找並安裝所需元件的相依套件。 + +## 安裝 + +您可以在結構清楚的 **[LlamaHub 網站](https://llamahub.ai/)** 找到 LlamaIndex 的安裝說明。 +初看可能有些複雜,但大多數**安裝指令都遵循容易記憶的格式**: + +```bash +pip install llama-index-{component-type}-{framework-name} +``` + +讓我們透過 [Hugging Face Inference API 整合](https://llamahub.ai/l/llms/llama-index-llms-huggingface-api?from=llms),安裝 LLM 元件所需的相依套件。 + +```bash +pip install llama-index-llms-huggingface-api llama-index-embeddings-huggingface +``` + +## 使用方式 + +安裝後,就可以查看使用方式。您會發現匯入路徑就列在安裝指令之後! +以下是 **Hugging Face Inference API LLM 元件**的使用範例。 + +```python +from llama_index.llms.huggingface_api import HuggingFaceInferenceAPI +import os +from dotenv import load_dotenv + +# Load the .env file +load_dotenv() + +# Retrieve HF_TOKEN from the environment variables +hf_token = os.getenv("HF_TOKEN") + +llm = HuggingFaceInferenceAPI( + model_name="Qwen/Qwen2.5-Coder-32B-Instruct", + temperature=0.7, + max_tokens=100, + token=hf_token, + provider="auto" +) + +response = llm.complete("Hello, how are you?") +print(response) +# I am good, how can I help you today? +``` + +現在我們知道如何尋找、安裝並使用所需元件的整合套件了。 +接下來,**讓我們深入認識這些元件**,看看如何運用它們建立自己的 agent。 diff --git a/units/zh-TW/unit2/llama-index/quiz1.mdx b/units/zh-TW/unit2/llama-index/quiz1.mdx new file mode 100644 index 000000000..775131ae2 --- /dev/null +++ b/units/zh-TW/unit2/llama-index/quiz1.mdx @@ -0,0 +1,117 @@ +# 小測驗(不計分) [[quiz1]] + +到目前為止,我們已介紹 LlamaIndex 的主要元件與工具。 +來做個小測驗吧!**自我測試**是最好的學習方式,也能[避免能力錯覺](https://www.coursera.org/lecture/learning-how-to-learn/illusions-of-competence-BuFzf)。 +這能幫助您找出**哪些知識需要加強**。 + +本測驗可自由參加,不計分。 + +### Q1: QueryEngine 是什麼? +以下哪個選項最能描述 QueryEngine 元件? + + + +--- + +### Q2: FunctionTools 的用途是什麼? +為什麼 FunctionTools 對 agent 很重要? + + + +--- + +### Q3: LlamaIndex 中的 Toolspecs 是什麼? +Toolspecs 的主要用途是什麼? + + + +--- + +### Q4: 建立工具需要什麼? +建立工具時,必須提供哪些資訊? + + + +--- + +恭喜完成測驗 🥳!如果有答錯的地方,請花時間重讀章節、鞏固知識。如果都答對了,就準備好深入學習如何運用這些元件了! diff --git a/units/zh-TW/unit2/llama-index/quiz2.mdx b/units/zh-TW/unit2/llama-index/quiz2.mdx new file mode 100644 index 000000000..7cc4b6aee --- /dev/null +++ b/units/zh-TW/unit2/llama-index/quiz2.mdx @@ -0,0 +1,111 @@ +# 快速自我檢測(不計分) [[quiz2]] + +什麼?!又是測驗?我們懂、我們懂……😅 不過,這個簡短的不計分測驗能**幫助您鞏固剛學到的關鍵概念**。 + +本測驗涵蓋 agent 工作流程與互動,這些都是建立有效 AI agent 的核心要素。 + +### Q1: LlamaIndex 中的 AgentWorkflow 有什麼用途? + + + +--- + +### Q2: 哪個物件用來追蹤工作流程的狀態? + + + +--- + +### Q3: 如果希望 agent 記住先前的互動,應該使用哪個方法? + + + +--- + +### Q4: Agentic RAG 的關鍵特性是什麼? + + + +--- + +都理解了嗎?太好了!現在讓我們**簡單回顧本單元!** diff --git a/units/zh-TW/unit2/llama-index/tools.mdx b/units/zh-TW/unit2/llama-index/tools.mdx new file mode 100644 index 000000000..470fd5212 --- /dev/null +++ b/units/zh-TW/unit2/llama-index/tools.mdx @@ -0,0 +1,142 @@ +# 在 LlamaIndex 中使用工具 + +**定義清楚的工具集對效能至關重要。** 正如[第 1 單元](../../unit1/tools)所討論的,清楚的工具介面能讓 LLM 更容易使用工具。 +就像工程師使用軟體 API 一樣,工具的運作方式越容易理解,LLM 就越能善用它。 + +LlamaIndex 主要提供**四種工具類型**: + +![工具](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit2/llama-index/tools.png) + +1. `FunctionTool`:將任意 Python 函式轉換為 agent 可使用的工具,並自動解析函式的運作方式。 +2. `QueryEngineTool`:讓 agent 使用查詢引擎的工具。由於 agent 本身也是以查詢引擎為基礎,因此也能將其他 agent 作為工具使用。 +3. `Toolspecs`:社群建立的現成工具集,通常包含特定服務(例如 Gmail)的相關工具。 +4. `Utility Tools`:協助處理其他工具所回傳的大量資料的特殊工具。 + +以下將逐一介紹使用方式。 + +## 建立 FunctionTool + +> [!TIP] +> 您可以跟著這份 notebook 的程式碼操作,並使用 Google Colab 執行。 + +FunctionTool 能輕鬆將任何 Python 函式封裝為 agent 可用的工具。 +您可以傳入同步或非同步函式,也可以選擇指定 `name` 與 `description` 參數。 +工具名稱與描述尤其重要,能幫助 agent 了解何時及如何有效使用工具。 +以下示範如何建立並呼叫 FunctionTool。 + +```python +from llama_index.core.tools import FunctionTool + +def get_weather(location: str) -> str: + """Useful for getting the weather for a given location.""" + print(f"Getting weather for {location}") + return f"The weather in {location} is sunny" + +tool = FunctionTool.from_defaults( + get_weather, + name="my_weather_tool", + description="Useful for getting the weather for a given location.", +) +tool.call("New York") +``` + +> [!TIP] +> 使用具備函式呼叫能力的 agent 或 LLM 時,工具的選擇與傳入的參數,很大程度取決於工具名稱、用途及參數描述。詳情請參考函式呼叫指南。 + +## 建立 QueryEngineTool + +上一節定義的 `QueryEngine`,可以透過 `QueryEngineTool` 類別輕鬆轉換為工具。 +以下示範如何從 `QueryEngine` 建立 `QueryEngineTool`。 + +```python +from llama_index.core import VectorStoreIndex +from llama_index.core.tools import QueryEngineTool +from llama_index.llms.huggingface_api import HuggingFaceInferenceAPI +from llama_index.embeddings.huggingface import HuggingFaceEmbedding +from llama_index.vector_stores.chroma import ChromaVectorStore + +embed_model = HuggingFaceEmbedding("BAAI/bge-small-en-v1.5") + +db = chromadb.PersistentClient(path="./alfred_chroma_db") +chroma_collection = db.get_or_create_collection("alfred") +vector_store = ChromaVectorStore(chroma_collection=chroma_collection) + +index = VectorStoreIndex.from_vector_store(vector_store, embed_model=embed_model) + +llm = HuggingFaceInferenceAPI(model_name="Qwen/Qwen2.5-Coder-32B-Instruct") +query_engine = index.as_query_engine(llm=llm) +tool = QueryEngineTool.from_defaults(query_engine, name="some useful name", description="some useful description") +``` + +## 建立 Toolspecs + +您可以將 `ToolSpecs` 視為一組相互配合的工具,就像整理完善的專業工具箱。 +正如機械師的工具箱包含互補的車輛維修工具,`ToolSpec` 會將相關工具組合起來,完成特定用途。 +例如,會計 agent 的 `ToolSpec` 可以整合試算表、電子郵件與計算工具,準確有效地處理財務任務。 + +
+安裝 Google Toolspec +如LlamaHub 章節所介紹的,可以使用以下指令安裝 Google toolspec: + +```python +pip install llama-index-tools-google +``` +
+ +現在我們可以載入工具規格,並將其轉換為工具清單。 + +```python +from llama_index.tools.google import GmailToolSpec + +tool_spec = GmailToolSpec() +tool_spec_list = tool_spec.to_tool_list() +``` + +若想進一步了解這些工具,可以查看每個工具的`後設資料`。 + +```python +[(tool.metadata.name, tool.metadata.description) for tool in tool_spec_list] +``` + +### LlamaIndex 中的 Model Context Protocol(MCP) + +LlamaIndex 也能透過 [LlamaHub 上的 ToolSpec](https://llamahub.ai/l/tools/llama-index-tools-mcp?from=) 使用 MCP 工具。 +只要啟動 MCP 伺服器,就能透過以下實作開始使用。 + +如果想深入了解 MCP,可以參考我們的[免費 MCP 課程](https://huggingface.co/learn/mcp-course/)。 + +
+安裝 MCP Toolspec +如LlamaHub 章節所介紹的,可以使用以下指令安裝 MCP toolspec: + +```python +pip install llama-index-tools-mcp +``` +
+ +```python +from llama_index.tools.mcp import BasicMCPClient, McpToolSpec + +# We consider there is a mcp server running on 127.0.0.1:8000, or you can use the mcp client to connect to your own mcp server. +mcp_client = BasicMCPClient("http://127.0.0.1:8000/sse") +mcp_tool = McpToolSpec(client=mcp_client) + +# get the agent +agent = await get_agent(mcp_tool) + +# create the agent context +agent_context = Context(agent) +``` + +## 輔助工具 + +直接查詢 API 往往**可能回傳過多資料**,其中有些內容與任務無關、超出 LLM 的上下文視窗,或造成不必要的 token 消耗。 +讓我們認識兩種主要的輔助工具: + +1. `OnDemandToolLoader`:可將任何現有的 LlamaIndex 資料載入器(BaseReader 類別)轉換為 agent 可用的工具。呼叫時需傳入載入器 `load_data` 所需的全部參數,以及自然語言查詢字串。執行時會先載入資料、建立索引(例如使用向量儲存),再按需查詢。三個步驟都在一次工具呼叫中完成。 +2. `LoadAndSearchToolSpec`:接受任何現有工具作為輸入。它實作了 `to_tool_list` 方法,呼叫後會回傳載入工具與搜尋工具。載入工具會呼叫底層工具,並為輸出建立索引(預設使用向量索引);搜尋工具則接受查詢字串,並呼叫底層索引進行查詢。 + +> [!TIP] +> 您可以在 LlamaHub 找到各種工具規格與輔助工具。 + +現在我們已了解 LlamaIndex 的 agent 與工具基礎,接下來看看如何**建立可設定且易於管理的工作流程!** diff --git a/units/zh-TW/unit2/llama-index/workflows.mdx b/units/zh-TW/unit2/llama-index/workflows.mdx new file mode 100644 index 000000000..0810a07be --- /dev/null +++ b/units/zh-TW/unit2/llama-index/workflows.mdx @@ -0,0 +1,280 @@ +# 在 LlamaIndex 中建立 agentic 工作流程 + +LlamaIndex 的工作流程提供結構化的方式,將程式碼組織成依序執行、易於管理的步驟。 + +建立工作流程時,我們會定義由 `Events` 觸發的 `Steps`;步驟本身也會發出 `Events`,觸發後續步驟。 +讓我們看看 Alfred 如何運用 LlamaIndex 工作流程完成 RAG 任務。 + +![工作流程示意圖](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit2/llama-index/workflows.png) + +**工作流程具備幾項主要優勢:** + +- 將程式碼清楚組織為獨立步驟 +- 事件驅動架構提供靈活的控制流程 +- 步驟之間的通訊具備型別安全性 +- 內建狀態管理 +- 支援簡單及複雜的 agent 互動 + +正如您可能已經想到的,**工作流程能在 agent 的自主性與整體流程的控制之間取得良好平衡。** + +接下來就學著建立自己的工作流程吧! + +## 建立工作流程 + +> [!TIP] +> 您可以跟著這份 notebook 的程式碼操作,並使用 Google Colab 執行。 + +### 建立基本工作流程 + +
+安裝 Workflow 套件 +如LlamaHub 章節所介紹的,可以使用以下指令安裝 Workflow 套件: + +```python +pip install llama-index-utils-workflow +``` +
+ +定義一個繼承 `Workflow` 的類別,並使用 `@step` 裝飾函式,就能建立單一步驟的工作流程。 +我們也需要加入 `StartEvent` 與 `StopEvent`,這兩種特殊事件分別表示工作流程的開始與結束。 + +```python +from llama_index.core.workflow import StartEvent, StopEvent, Workflow, step + +class MyWorkflow(Workflow): + @step + async def my_step(self, ev: StartEvent) -> StopEvent: + # do something here + return StopEvent(result="Hello, world!") + + +w = MyWorkflow(timeout=10, verbose=False) +result = await w.run() +``` + +如您所見,現在呼叫 `w.run()` 就能執行工作流程。 + +### 連接多個步驟 + +要連接多個步驟,我們會**建立自訂事件,在步驟之間傳遞資料。** +也就是加入在步驟間傳遞的 `Event`,將第一個步驟的輸出送到第二個步驟。 + +```python +from llama_index.core.workflow import Event + +class ProcessingEvent(Event): + intermediate_result: str + +class MultiStepWorkflow(Workflow): + @step + async def step_one(self, ev: StartEvent) -> ProcessingEvent: + # Process initial data + return ProcessingEvent(intermediate_result="Step 1 complete") + + @step + async def step_two(self, ev: ProcessingEvent) -> StopEvent: + # Use the intermediate result + final_result = f"Finished processing: {ev.intermediate_result}" + return StopEvent(result=final_result) + +w = MultiStepWorkflow(timeout=10, verbose=False) +result = await w.run() +result +``` + +型別提示在這裡很重要,能確保工作流程正確執行。接下來讓流程再複雜一點! + +### 迴圈與分支 + +型別提示是工作流程最強大的部分,因為它讓我們能建立分支、迴圈與匯合點,支援更複雜的工作流程。 + +以下示範使用聯集運算子 `|` **建立迴圈**。 +在這個範例中,`LoopEvent` 可以作為步驟的輸入,也可以作為輸出回傳。 + +```python +from llama_index.core.workflow import Event +import random + + +class ProcessingEvent(Event): + intermediate_result: str + + +class LoopEvent(Event): + loop_output: str + + +class MultiStepWorkflow(Workflow): + @step + async def step_one(self, ev: StartEvent | LoopEvent) -> ProcessingEvent | LoopEvent: + if random.randint(0, 1) == 0: + print("Bad thing happened") + return LoopEvent(loop_output="Back to step one.") + else: + print("Good thing happened") + return ProcessingEvent(intermediate_result="First step complete.") + + @step + async def step_two(self, ev: ProcessingEvent) -> StopEvent: + # Use the intermediate result + final_result = f"Finished processing: {ev.intermediate_result}" + return StopEvent(result=final_result) + + +w = MultiStepWorkflow(verbose=False) +result = await w.run() +result +``` + +### 繪製工作流程 + +我們也能繪製工作流程。使用 `draw_all_possible_flows` 函式,就能將流程圖儲存在 HTML 檔案中。 + +```python +from llama_index.utils.workflow import draw_all_possible_flows + +w = ... # as defined in the previous section +draw_all_possible_flows(w, "flow.html") +``` + +![工作流程圖](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit2/llama-index/workflow-draw.png) + +本課程還會介紹最後一項實用技巧:為工作流程加入狀態。 + +### 狀態管理 + +如果想追蹤工作流程的狀態,讓每個步驟都能存取同一份狀態,就可以使用狀態管理。 +在步驟函式的參數上使用 `Context` 型別提示,即可達成。 + +```python +from llama_index.core.workflow import Context, StartEvent, StopEvent + + +@step +async def query(self, ctx: Context, ev: StartEvent) -> StopEvent: + # store query in the context + await ctx.store.set("query", "What is the capital of France?") + + # do something with context and event + val = ... + + # retrieve query from the context + query = await ctx.store.get("query") + + return StopEvent(result=val) +``` + +太好了!現在您已經知道如何在 LlamaIndex 中建立基本工作流程! + +> [!TIP] +> 工作流程還有更進階的細節,可以在 LlamaIndex 文件中深入了解。 + +另外,也可以透過 `AgentWorkflow` 類別建立工作流程。讓我們看看如何用它建立多 agent 工作流程。 + +## 使用多 agent 工作流程自動化流程 + +除了手動建立流程,我們也能使用 **`AgentWorkflow` 類別建立多 agent 工作流程**。 +`AgentWorkflow` 使用 Workflow agent,讓您建立由一個或多個 agent 組成的系統,各個 agent 能依專長協作並交接任務。 +這樣就能建立複雜的 agent 系統,讓不同 agent 負責任務的不同面向。 +我們會從 `llama_index.core.agent.workflow` 匯入 agent 類別,而非 `llama_index.core.agent`。 +在 `AgentWorkflow` 建構函式中,必須將一個 agent 指定為根 agent。 +使用者訊息傳入時,會先送往根 agent。 + +接著,每個 agent 都可以: + +- 使用自己的工具直接處理請求 +- 將任務交給更合適的 agent +- 向使用者回傳回覆 + +讓我們看看如何建立多 agent 工作流程。 + +```python +from llama_index.core.agent.workflow import AgentWorkflow, ReActAgent +from llama_index.llms.huggingface_api import HuggingFaceInferenceAPI + +# Define some tools +def add(a: int, b: int) -> int: + """Add two numbers.""" + return a + b + +def multiply(a: int, b: int) -> int: + """Multiply two numbers.""" + return a * b + +llm = HuggingFaceInferenceAPI(model_name="Qwen/Qwen2.5-Coder-32B-Instruct") + +# we can pass functions directly without FunctionTool -- the fn/docstring are parsed for the name/description +multiply_agent = ReActAgent( + name="multiply_agent", + description="Is able to multiply two integers", + system_prompt="A helpful assistant that can use a tool to multiply numbers.", + tools=[multiply], + llm=llm, +) + +addition_agent = ReActAgent( + name="add_agent", + description="Is able to add two integers", + system_prompt="A helpful assistant that can use a tool to add numbers.", + tools=[add], + llm=llm, +) + +# Create the workflow +workflow = AgentWorkflow( + agents=[multiply_agent, addition_agent], + root_agent="multiply_agent", +) + +# Run the system +response = await workflow.run(user_msg="Can you add 5 and 3?") +``` + +agent 的工具也能修改前面介紹的工作流程狀態。啟動流程前,可以提供初始狀態字典,讓所有 agent 共用。 +狀態儲存在工作流程上下文的 state 鍵中,並會注入 state_prompt,補充每則新使用者訊息的內容。 + +以下修改前一個範例,加入計數器來計算函式呼叫次數: + +```python +from llama_index.core.workflow import Context + +# Define some tools +async def add(ctx: Context, a: int, b: int) -> int: + """Add two numbers.""" + # update our count + cur_state = await ctx.store.get("state") + cur_state["num_fn_calls"] += 1 + await ctx.store.set("state", cur_state) + + return a + b + +async def multiply(ctx: Context, a: int, b: int) -> int: + """Multiply two numbers.""" + # update our count + cur_state = await ctx.store.get("state") + cur_state["num_fn_calls"] += 1 + await ctx.store.set("state", cur_state) + + return a * b + +... + +workflow = AgentWorkflow( + agents=[multiply_agent, addition_agent], + root_agent="multiply_agent", + initial_state={"num_fn_calls": 0}, + state_prompt="Current state: {state}. User message: {msg}", +) + +# run the workflow with context +ctx = Context(workflow) +response = await workflow.run(user_msg="Can you add 5 and 3?", ctx=ctx) + +# pull out and inspect the state +state = await ctx.store.get("state") +print(state["num_fn_calls"]) +``` + +恭喜!您已掌握 LlamaIndex 中 agent 的基礎知識!🎉 + +接下來透過最後一個測驗,鞏固所學吧!🚀 diff --git a/units/zh-TW/unit2/smolagents/code_agents.mdx b/units/zh-TW/unit2/smolagents/code_agents.mdx new file mode 100644 index 000000000..d770276ec --- /dev/null +++ b/units/zh-TW/unit2/smolagents/code_agents.mdx @@ -0,0 +1,394 @@ + + +# 建立使用程式碼的 agent + +code agent 是 `smolagents` 的預設 agent 類型。它們會產生 Python 工具呼叫來執行動作,以高效、準確且具表達力的方式描述行動。 + +這種精簡的做法能減少所需動作的數量、簡化複雜操作,並重複使用既有的程式碼函式。`smolagents` 提供建立 code agent 的輕量框架,核心實作約只有 1,000 行程式碼。 + +![程式碼動作與 JSON 動作](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/code_vs_json_actions.png) +圖片出自論文 [Executable Code Actions Elicit Better LLM Agents](https://huggingface.co/papers/2402.01030)。 + +> [!TIP] +> 想進一步了解 code agent 為何有效,請參閱 smolagents 文件中的這份指南。 + +## 為什麼使用 code agent? + +在多步驟 agent 流程中,LLM 會撰寫並執行動作,通常會呼叫外部工具。傳統做法以 JSON 格式將工具名稱與參數寫成字串,**系統必須解析這些內容,才能判斷要執行哪個工具**。 + +然而,研究顯示,**需要呼叫工具的 LLM 直接使用程式碼時,表現更好**。這也是 `smolagents` 的核心原則,如上方出自 [Executable Code Actions Elicit Better LLM Agents](https://huggingface.co/papers/2402.01030) 的圖所示。 + +以程式碼取代 JSON 撰寫動作,有幾項主要優點: + +* **可組合性**:輕鬆組合並重複使用動作。 +* **物件管理**:直接處理影像等複雜結構。 +* **通用性**:表達任何可透過計算完成的任務。 +* **適合 LLM**:LLM 的訓練資料中已包含高品質程式碼。 + +## code agent 如何運作? + +![出自 https://huggingface.co/docs/smolagents/conceptual_guides/react](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/smolagents/codeagent_docs.png) + +上圖說明 `CodeAgent.run()` 的運作方式,採用第一單元介紹的 ReAct 框架。`smolagents` 對 agent 的主要抽象是 `MultiStepAgent`,也是框架的核心組件。`CodeAgent` 是一種特殊的 `MultiStepAgent`,下方範例將進一步說明。 + +`CodeAgent` 透過一連串循環步驟執行動作,將既有變數與知識納入 agent 的上下文,並保留在執行紀錄中: + +1. 系統 prompt 儲存在 `SystemPromptStep`,使用者查詢則記錄在 `TaskStep`。 + +2. 接著執行以下 while 迴圈: + + 2.1 `agent.write_memory_to_messages()` 方法將 agent 的執行紀錄寫成 LLM 可讀取的[聊天訊息](https://huggingface.co/docs/transformers/main/en/chat_templating)清單。 + + 2.2 將訊息傳給 `Model`,產生補全文字(completion)。 + + 2.3 解析補全文字,擷取動作。在這個例子中,因為使用 `CodeAgent`,動作應該是一段程式碼。 + + 2.4 執行動作。 + + 2.5 將結果以 `ActionStep` 記錄到記憶中。 + +每一步結束時,如果 agent 在 `agent.step_callback` 中設有函式呼叫,就會執行它們。 + +## 來看幾個範例 + +> [!TIP] +> 你可以跟著這份 notebook 的程式碼實作,並在 Google Colab 中執行。 + +Alfred 正在韋恩家族的宅邸籌辦派對,需要你的協助,確保一切順利。我們將運用剛學到的多步驟 `CodeAgent` 運作方式來幫助他。 + +Alfred Party + +如果尚未安裝 `smolagents`,可以執行以下指令: + +```bash +pip install smolagents -U +``` + +也登入 Hugging Face Hub,以便使用無伺服器推論 API。 + +```python +from huggingface_hub import login + +login() +``` + +### 使用 `smolagents` 挑選派對歌單 + +音樂是成功派對不可或缺的一環!Alfred 需要幫忙挑選歌單,而 `smolagents` 正好能派上用場。我們可以建立使用 DuckDuckGo 搜尋網頁的 agent。只要在建立 agent 時,把這個工具加入工具清單,它就能使用。 + +Alfred Playlist + +模型方面,我們使用 `InferenceClientModel`,存取 Hugging Face 的[無伺服器推論 API](https://huggingface.co/docs/api-inference/index)。預設模型是 `"Qwen/Qwen2.5-Coder-32B-Instruct"`,表現良好且推論快速;你也可以從 Hub 選擇其他相容模型。 + +執行 agent 很簡單: + +```python +from smolagents import CodeAgent, DuckDuckGoSearchTool, InferenceClientModel + +agent = CodeAgent(tools=[DuckDuckGoSearchTool()], model=InferenceClientModel()) + +agent.run("Search for the best music recommendations for a party at the Wayne's mansion.") +``` + +執行這個範例時,輸出會**顯示工作流程各步驟的執行追蹤**,也會印出對應的 Python 程式碼,並附上以下訊息: + +```python + ─ Executing parsed code: ──────────────────────────────────────────────────────────────────────────────────────── + results = web_search(query="best music for a Batman party") + print(results) + ───────────────────────────────────────────────────────────────────────────────────────────────────────────────── +``` + +幾個步驟之後,你就會看到為 Alfred 的派對產生的歌單!🎵 + +### 使用自訂工具準備菜單 + +Alfred Menu + +挑好歌單後,接著要替賓客安排菜單。Alfred 同樣可以使用 `smolagents` 完成。這裡使用 `@tool` 裝飾器定義自訂函式,將它作為工具。稍後我們會詳細介紹如何建立工具,目前先直接執行程式碼即可。 + +如下方範例所示,我們使用 `@tool` 裝飾器建立工具,再將它加入 `tools` 清單。 + +```python +from smolagents import CodeAgent, tool, InferenceClientModel + +# Tool to suggest a menu based on the occasion +@tool +def suggest_menu(occasion: str) -> str: + """ + Suggests a menu based on the occasion. + Args: + occasion (str): The type of occasion for the party. Allowed values are: + - "casual": Menu for casual party. + - "formal": Menu for formal party. + - "superhero": Menu for superhero party. + - "custom": Custom menu. + """ + if occasion == "casual": + return "Pizza, snacks, and drinks." + elif occasion == "formal": + return "3-course dinner with wine and dessert." + elif occasion == "superhero": + return "Buffet with high-energy and healthy food." + else: + return "Custom menu for the butler." + +# Alfred, the butler, preparing the menu for the party +agent = CodeAgent(tools=[suggest_menu], model=InferenceClientModel()) + +# Preparing the menu for the party +agent.run("Prepare a formal menu for the party.") +``` + +agent 會執行幾個步驟,直到找到答案。在 docstring 中明確列出允許的值,能引導 agent 使用確實存在的 `occasion` 參數值,減少幻覺。 + +菜單準備好了!🥗 + +### 在 agent 內匯入 Python 模組 + +歌單與菜單都準備好了,但還有一項重要細節要確認:準備時間! + +Alfred 需要計算,如果現在開始準備,所有工作何時能完成,以便判斷是否需要請其他超級英雄幫忙。 + +`smolagents` 專門支援會撰寫並執行 Python 程式碼片段的 agent,並以沙箱執行來提高安全性。 + +**程式碼執行有嚴格的安全措施**:預設會禁止匯入安全清單以外的模組。不過,可以透過 `additional_authorized_imports` 傳入模組名稱字串,允許額外匯入。 +安全執行程式碼的更多細節,請參閱官方[指南](https://huggingface.co/docs/smolagents/tutorials/secure_code_execution)。 + +建立 agent 時,我們將使用 `additional_authorized_imports`,允許匯入 `datetime` 模組。 + +```python +from smolagents import CodeAgent, InferenceClientModel +import numpy as np +import time +import datetime + +agent = CodeAgent(tools=[], model=InferenceClientModel(), additional_authorized_imports=['datetime']) + +agent.run( + """ + Alfred needs to prepare for the party. Here are the tasks: + 1. Prepare the drinks - 30 minutes + 2. Decorate the mansion - 60 minutes + 3. Set up the menu - 45 minutes + 4. Prepare the music and playlist - 45 minutes + + If we start right now, at what time will the party be ready? + """ +) +``` + + +這些範例只是 code agent 能力的起點,但我們已經看見它在派對準備上的用途。 +關於建立 code agent 的更多資訊,請參閱 [smolagents 文件](https://huggingface.co/docs/smolagents)。 + +總結來說,`smolagents` 專門支援撰寫並執行 Python 程式碼片段的 agent,並提供沙箱執行機制來提高安全性。它同時支援本機與透過 API 存取的語言模型,因此適用於各種開發環境。 + +### 將自訂派對籌備 agent 分享到 Hub + +**把我們自己的 Alfred agent 分享給社群**,是不是很棒?這樣任何人都能直接從 Hub 輕鬆下載使用,讓哥譚市最強派對規劃幫手隨手可得!一起來試試吧!🎉 + +`smolagents` 函式庫支援分享完整的 agent 給社群,也能下載他人的 agent 立即使用。做法很簡單: + +```python +# Change to your username and repo name +agent.push_to_hub('sergiopaniego/AlfredAgent') +``` + +要重新下載這個 agent,請使用下方程式碼: + +```python +# Change to your username and repo name +alfred_agent = agent.from_hub('sergiopaniego/AlfredAgent', trust_remote_code=True) + +alfred_agent.run("Give me the best playlist for a party at Wayne's mansion. The party idea is a 'villain masquerade' theme") +``` + +更棒的是,分享的 agent 也會直接以 Hugging Face Spaces 的形式提供,讓你即時互動。你可以在[這裡](https://huggingface.co/spaces/davidberenstein1957/smolagents-and-tools)探索其他 agent。 + +例如,_AlfredAgent_ 就在[這裡](https://huggingface.co/spaces/sergiopaniego/AlfredAgent)。你也可以直接在下方試用: + + + +你可能好奇,Alfred 如何使用 `smolagents` 建立這樣的 agent?將幾個工具整合起來,就能像下方這樣建立。目前不必擔心工具細節,本單元稍後會有專節深入介紹: + +```python +from smolagents import CodeAgent, DuckDuckGoSearchTool, FinalAnswerTool, InferenceClientModel, Tool, tool, VisitWebpageTool + +@tool +def suggest_menu(occasion: str) -> str: + """ + Suggests a menu based on the occasion. + Args: + occasion: The type of occasion for the party. + """ + if occasion == "casual": + return "Pizza, snacks, and drinks." + elif occasion == "formal": + return "3-course dinner with wine and dessert." + elif occasion == "superhero": + return "Buffet with high-energy and healthy food." + else: + return "Custom menu for the butler." + +@tool +def catering_service_tool(query: str) -> str: + """ + This tool returns the highest-rated catering service in Gotham City. + + Args: + query: A search term for finding catering services. + """ + # Example list of catering services and their ratings + services = { + "Gotham Catering Co.": 4.9, + "Wayne Manor Catering": 4.8, + "Gotham City Events": 4.7, + } + + # Find the highest rated catering service (simulating search query filtering) + best_service = max(services, key=services.get) + + return best_service + +class SuperheroPartyThemeTool(Tool): + name = "superhero_party_theme_generator" + description = """ + This tool suggests creative superhero-themed party ideas based on a category. + It returns a unique party theme idea.""" + + inputs = { + "category": { + "type": "string", + "description": "The type of superhero party (e.g., 'classic heroes', 'villain masquerade', 'futuristic Gotham').", + } + } + + output_type = "string" + + def forward(self, category: str): + themes = { + "classic heroes": "Justice League Gala: Guests come dressed as their favorite DC heroes with themed cocktails like 'The Kryptonite Punch'.", + "villain masquerade": "Gotham Rogues' Ball: A mysterious masquerade where guests dress as classic Batman villains.", + "futuristic gotham": "Neo-Gotham Night: A cyberpunk-style party inspired by Batman Beyond, with neon decorations and futuristic gadgets." + } + + return themes.get(category.lower(), "Themed party idea not found. Try 'classic heroes', 'villain masquerade', or 'futuristic Gotham'.") + + +# Alfred, the butler, preparing the menu for the party +agent = CodeAgent( + tools=[ + DuckDuckGoSearchTool(), + VisitWebpageTool(), + suggest_menu, + catering_service_tool, + SuperheroPartyThemeTool(), + FinalAnswerTool() + ], + model=InferenceClientModel(), + max_steps=10, + verbosity_level=2 +) + +agent.run("Give me the best playlist for a party at the Wayne's mansion. The party idea is a 'villain masquerade' theme") +``` + +如你所見,我們建立了一個具備多項工具的 `CodeAgent`,強化它的功能,讓它成為隨時能與社群分享的最強派對規劃幫手!🎉 + +現在輪到你了:運用剛學到的知識,建立自己的 agent,並分享給社群吧!🕵️‍♂️💡 + +> [!TIP] +> 想分享你的 agent 專案,可以在 Hugging Face Hub 建立 Space,並標記 agents-course。我們很期待看到你的作品! + +### 使用 OpenTelemetry 與 Langfuse 檢視派對籌備 agent 📡 + +Alfred 持續調整派對籌備 agent,卻也漸漸厭倦替每次執行除錯。agent 的行為本來就難以預測,也不容易檢查。但他想打造最強的派對籌備 agent,並部署到正式環境,因此需要可靠的追蹤能力,方便日後監控與分析。 + +`smolagents` 再次派上用場!它採用 [OpenTelemetry](https://opentelemetry.io/) 標準,為 agent 的執行加入觀測功能,方便檢查與記錄。搭配 [Langfuse](https://langfuse.com/) 與 `SmolagentsInstrumentor`,Alfred 就能輕鬆追蹤並分析 agent 的行為。 + +設定方式很簡單! + +首先,安裝必要的相依套件: + +```bash +pip install opentelemetry-sdk opentelemetry-exporter-otlp openinference-instrumentation-smolagents langfuse +``` + +接著,Alfred 已經建立 Langfuse 帳號,並準備好 API 金鑰。如果你尚未完成,可以在[這裡](https://cloud.langfuse.com/)註冊 Langfuse Cloud,或探索[其他方案](https://huggingface.co/docs/smolagents/tutorials/inspect_runs)。 + +取得 API 金鑰後,依下列方式完成設定: + +```python +import os + +# Get keys for your project from the project settings page: https://cloud.langfuse.com +os.environ["LANGFUSE_PUBLIC_KEY"] = "pk-lf-..." +os.environ["LANGFUSE_SECRET_KEY"] = "sk-lf-..." +os.environ["LANGFUSE_HOST"] = "https://cloud.langfuse.com" # 🇪🇺 EU region +# os.environ["LANGFUSE_HOST"] = "https://us.cloud.langfuse.com" # 🇺🇸 US region +``` + +設定環境變數後,就能初始化 Langfuse client。`get_client()` 會使用環境變數中的憑證初始化 client。 + +```python +from langfuse import get_client + +langfuse = get_client() + +# Verify connection +if langfuse.auth_check(): + print("Langfuse client is authenticated and ready!") +else: + print("Authentication failed. Please check your credentials and host.") +``` + +最後,Alfred 可以初始化 `SmolagentsInstrumentor`,開始追蹤 agent 的表現。 + +```python +from openinference.instrumentation.smolagents import SmolagentsInstrumentor + +SmolagentsInstrumentor().instrument() +``` + +Alfred 連接成功了 🔌!`smolagents` 的執行過程正在記錄到 Langfuse,讓他能全面掌握 agent 的行為。有了這套設定,他可以回頭檢查先前的執行結果,進一步改善派對籌備 agent。 + +> [!TIP] +> 想了解如何追蹤 agent,並運用蒐集的資料評估其表現,請參閱加分單元 2。 + +```python +from smolagents import CodeAgent, InferenceClientModel + +agent = CodeAgent(tools=[], model=InferenceClientModel()) +alfred_agent = agent.from_hub('sergiopaniego/AlfredAgent', trust_remote_code=True) +alfred_agent.run("Give me the best playlist for a party at Wayne's mansion. The party idea is a 'villain masquerade' theme") +``` + +Alfred 現在可以在[這裡](https://cloud.langfuse.com/project/cm7bq0abj025rad078ak3luwi/traces/995fc019255528e4f48cf6770b0ce27b?timestamp=2025-02-19T10%3A28%3A36.929Z)查看並分析這些紀錄。 + +> [!TIP] +> 其實,執行過程中發生了一個小錯誤。你能從紀錄中找到它嗎?試著追蹤 agent 如何處理錯誤,最後仍回傳有效答案。想確認答案,可以直接查看這筆錯誤紀錄。這個問題後來已經修正,詳情請見這個 issue。 + +同時,[推薦歌單](https://open.spotify.com/playlist/0gZMMHjuxMrrybQ7wTMTpw)也替派對準備工作營造了完美氣氛。很酷吧?🎶 + +--- + +建立第一個 code agent 後,接下來**學習如何建立工具呼叫 agent**,也就是 `smolagents` 提供的第二種 agent。 + +## 資源 + +- [smolagents 部落格](https://huggingface.co/blog/smolagents) - smolagents 與程式碼互動簡介 +- [smolagents:打造良好的 agent](https://huggingface.co/docs/smolagents/tutorials/building_good_agents) - 建立可靠 agent 的最佳實務 +- [打造有效的 agent — Anthropic](https://www.anthropic.com/research/building-effective-agents) - agent 設計原則 +- [透過 OpenTelemetry 分享執行紀錄](https://huggingface.co/docs/smolagents/tutorials/inspect_runs) - 如何設定 OpenTelemetry 以追蹤 agent。 diff --git a/units/zh-TW/unit2/smolagents/conclusion.mdx b/units/zh-TW/unit2/smolagents/conclusion.mdx new file mode 100644 index 000000000..374974b15 --- /dev/null +++ b/units/zh-TW/unit2/smolagents/conclusion.mdx @@ -0,0 +1,11 @@ +# 結語 + +恭喜你完成第二單元的 `smolagents` 模組!🥳 + +你已經掌握 `smolagents` 的基礎,也建立了自己的 agent!現在,你可以運用這些技能,打造能解決自己感興趣任務的 agent。 + +下一個模組將教你**如何使用 LlamaIndex 建立 agent**。 + +最後,我們很想**聽聽你對課程的想法,以及我們可以如何改進**。如果有任何回饋,請 👉 [填寫這份表單](https://docs.google.com/forms/d/e/1FAIpQLSe9VaONn0eglax0uTwi29rIn4tM7H2sYmmybmG5jJNlE5v0xA/viewform?usp=dialog)。 + +### 繼續學習,保持精彩 🤗 diff --git a/units/zh-TW/unit2/smolagents/final_quiz.mdx b/units/zh-TW/unit2/smolagents/final_quiz.mdx new file mode 100644 index 000000000..46fe24d49 --- /dev/null +++ b/units/zh-TW/unit2/smolagents/final_quiz.mdx @@ -0,0 +1,25 @@ +# 測驗時間! + +恭喜你學完 `smolagents` 的教材,已經累積了不少成果!現在,用測驗來檢驗學習成果吧。🧠 + +## 說明 + +- 本測驗由程式碼題目組成。 +- 每題都會提供完成程式碼片段所需的說明。 +- 請仔細閱讀說明,依照要求補完程式碼。 +- 每題都會提供作答結果與回饋。 + +🧘 **這份測驗不計分,也不提供證書**。目的是幫助你確認自己是否理解 `smolagents` 函式庫,以及是否需要再花些時間複習教材。接下來的單元將透過實際情境與專案,讓你運用這些知識。 + +讓我們開始吧! + +## 測驗 🚀 + + + +你也可以從 👉 [這裡](https://huggingface.co/spaces/agents-course/unit2_smolagents_quiz)進入測驗。 diff --git a/units/zh-TW/unit2/smolagents/introduction.mdx b/units/zh-TW/unit2/smolagents/introduction.mdx new file mode 100644 index 000000000..b4ba450f5 --- /dev/null +++ b/units/zh-TW/unit2/smolagents/introduction.mdx @@ -0,0 +1,66 @@ +# `smolagents` 簡介 + +Unit 2.1 Thumbnail + +歡迎來到本模組!你將學習如何使用 [`smolagents`](https://github.com/huggingface/smolagents) 函式庫**打造有效的 agent**。這個輕量框架能協助你建立功能強大的 AI agent。 + +`smolagents` 是 Hugging Face 開發的函式庫。如果你願意到 smolagents 的 [`儲存庫`](https://github.com/huggingface/smolagents) **按下 Star** 為我們加油,我們會非常感謝: +staring smolagents + +## 模組概覽 + +本模組將完整介紹使用 `smolagents` 建立 agent 的關鍵概念與實用策略。 + +開源框架的選擇很多,因此我們需要了解 `smolagents` 的組成與功能,才能判斷它何時適合使用,以及何時該考慮其他方案。 + +我們將探索幾種重要的 agent 類型:為軟體開發任務設計的 code agent、以函式建立模組化工作流程的工具呼叫 agent,以及存取並整合資訊的檢索 agent。 + +此外,我們也會介紹如何協調多個 agent,以及整合視覺能力和網頁瀏覽功能,為動態、能運用上下文的應用程式開拓更多可能性。 + +第一單元的 agent 阿爾弗雷德(Alfred)回來了!這次,他的內部運作改用 `smolagents` 框架。我們將隨著 Alfred 處理各種任務,一起探索這個框架的關鍵概念。韋恩一家 🦇 不在家,Alfred 正忙著在韋恩莊園籌辦派對,還有許多事情等著他完成。跟著我們看看,他如何用 `smolagents` 逐一完成這些任務! + +> [!TIP] +> 本單元將教你使用 `smolagents` 函式庫建立 AI agent。你的 agent 將能搜尋資料、執行程式碼並與網頁互動。你也會學到如何結合多個 agent,打造更強大的系統。 + +![Alfred the agent](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit1/this-is-alfred.jpg) + +## 內容 + +本單元將介紹以下 `smolagents` 主題: + +### 1️⃣ [為什麼使用 smolagents](./why_use_smolagents) + +`smolagents` 是可用於應用程式開發的眾多開源 agent 框架之一。其他選擇包括 `LlamaIndex` 和 `LangGraph`,本課程也會在其他模組介紹。`smolagents` 的幾項特色讓它很適合某些使用情境,但選擇框架時仍應全面評估。我們將探討它的優缺點,協助你根據專案需求做出判斷。 + +### 2️⃣ [CodeAgents](./code_agents) + +`CodeAgents` 是 `smolagents` 的主要 agent 類型。它們透過產生 Python 程式碼來執行動作,而非輸出 JSON 或文字。本模組將介紹其用途、功能與運作方式,並透過實作範例展示它們的能力。 + +### 3️⃣ [ToolCallingAgents](./tool_calling_agents) + +`ToolCallingAgents` 是 `smolagents` 支援的第二種 agent 類型。不同於產生 Python 程式碼的 `CodeAgents`,這類 agent 會輸出 JSON 或文字區塊,由系統解析後執行動作。本模組將介紹它們的功能、與 `CodeAgents` 的主要差異,並以範例說明用法。 + +### 4️⃣ [工具](./tools) + +如第一單元所述,工具是 LLM 在 agent 系統中可以使用的函式,也是 agent 行為的基本組件。本模組將介紹工具的結構、建立方式,以及如何使用 `Tool` 類別或 `@tool` 裝飾器實作工具。你也會認識預設工具箱,學習如何與社群分享工具,以及載入社群提供的工具供 agent 使用。 + +### 5️⃣ [檢索 agent](./retrieval_agents) + +檢索 agent 讓模型能存取知識庫,從多個來源搜尋、整合及檢索資訊。它們利用向量儲存空間提高檢索效率,實作**檢索增強生成(Retrieval-Augmented Generation,RAG)**模式。這類 agent 特別適合整合網頁搜尋與自訂知識庫,並透過記憶系統保留對話上下文。本模組將探討實作策略,包括在檢索失敗時採用的備援機制。 + +### 6️⃣ [多 agent 系統](./multi_agent_systems) + +有效協調多個 agent,是建立強大多 agent 系統的關鍵。將不同能力的 agent 結合,例如網頁搜尋 agent 與程式碼執行 agent,就能打造更進階的解決方案。本模組著重於多 agent 系統的設計、實作與管理,以提升效率和可靠性。 + +### 7️⃣ [視覺與瀏覽器 agent](./vision_agents) + +視覺 agent 整合**視覺語言模型(Vision-Language Models,VLM)**,擴充傳統 agent 的能力,讓它們能處理並解讀視覺資訊。本模組將介紹如何設計及整合由 VLM 驅動的 agent,實作影像推理、視覺資料分析與多模態互動等進階功能。我們也會利用視覺 agent 建立能瀏覽網頁並擷取資訊的瀏覽器 agent。 + +## 資源 + +- [smolagents 文件](https://huggingface.co/docs/smolagents) - smolagents 函式庫的官方文件 +- [打造有效的 agent](https://www.anthropic.com/research/building-effective-agents) - 探討 agent 架構的研究文章 +- [agent 指南](https://huggingface.co/docs/smolagents/tutorials/building_good_agents) - 建立可靠 agent 的最佳實務 +- [LangGraph agent](https://langchain-ai.github.io/langgraph/) - 更多 agent 實作範例 +- [函式呼叫指南](https://platform.openai.com/docs/guides/function-calling) - 認識 LLM 的函式呼叫 +- [RAG 最佳實務](https://www.pinecone.io/learn/retrieval-augmented-generation/) - 實作有效 RAG 的指南 diff --git a/units/zh-TW/unit2/smolagents/multi_agent_systems.mdx b/units/zh-TW/unit2/smolagents/multi_agent_systems.mdx new file mode 100644 index 000000000..9c8788bb2 --- /dev/null +++ b/units/zh-TW/unit2/smolagents/multi_agent_systems.mdx @@ -0,0 +1,412 @@ + + +# 多 agent 系統 + +多 agent 系統讓**各有所長的 agent 協作處理複雜任務**,提升模組化程度、擴充性與穩健性。系統不再依賴單一 agent,而是把任務分配給具備不同能力的 agent。 + +在 **smolagents** 中,可以結合不同 agent,產生 Python 程式碼、呼叫外部工具、搜尋網頁等。透過協調這些 agent,我們能建立強大的工作流程。 + +常見的架構可能包含: +- 負責分派任務的**管理 agent** +- 負責執行程式碼的**程式碼直譯 agent** +- 負責檢索資訊的**網頁搜尋 agent** + +下圖展示簡單的多 agent 架構:**管理 agent** 協調**程式碼直譯工具**與**網頁搜尋 agent**,後者再使用 `DuckDuckGoSearchTool`、`VisitWebpageTool` 等工具蒐集相關資訊。 + + + +## 多 agent 系統的實際應用 + +多 agent 系統由多個各有所長的 agent 組成,在**協調 agent** 的統籌下合作。透過將任務分配給不同角色的 agent,就能實作複雜的工作流程。 + +例如,**多 agent RAG 系統**可以整合: +- 瀏覽網路的**網頁 agent**。 +- 從知識庫取得資訊的**檢索 agent**。 +- 製作視覺內容的**影像生成 agent**。 + +這些 agent 都在協調 agent 的管理下運作,由它負責任務分派與互動。 + +## 透過多 agent 階層架構解決複雜任務 + +> [!TIP] +> 你可以跟著這份 notebook 的程式碼實作,並在 Google Colab 中執行。 + +宴會即將開始!在你的幫助下,Alfred 幾乎完成了所有準備。 + +但現在出了狀況:蝙蝠車不見了。Alfred 必須趕快找到替代車輛。 + +幸好,布魯斯.韋恩的人生已被拍成幾部傳記電影。也許 Alfred 可以找一輛留在片場的車,重新改裝至符合現代標準,當然也要具備全自動駕駛功能。 + +不過,車輛可能散落在世界各地的拍攝場景,地點可能相當多。 + +因此,Alfred 想請你幫忙。你能建立 agent 解決這個任務嗎? + +> 👉 找出世界各地所有蝙蝠俠電影的拍攝地點,計算前往各地的船運時間,並在地圖上以不同顏色表示船運時間長短。同時標出一些超跑工廠,呈現相同的船運時間資訊。 + +一起來實作吧! + +這個範例需要額外的套件,先安裝它們: + +```bash +pip install 'smolagents[litellm]' plotly geopandas shapely kaleido -q +``` + +### 首先,建立計算貨機運輸時間的工具 + +```python +import math +from typing import Optional, Tuple + +from smolagents import tool + + +@tool +def calculate_cargo_travel_time( + origin_coords: Tuple[float, float], + destination_coords: Tuple[float, float], + cruising_speed_kmh: Optional[float] = 750.0, # Average speed for cargo planes +) -> float: + """ + Calculate the travel time for a cargo plane between two points on Earth using great-circle distance. + + Args: + origin_coords: Tuple of (latitude, longitude) for the starting point + destination_coords: Tuple of (latitude, longitude) for the destination + cruising_speed_kmh: Optional cruising speed in km/h (defaults to 750 km/h for typical cargo planes) + + Returns: + float: The estimated travel time in hours + + Example: + >>> # Chicago (41.8781° N, 87.6298° W) to Sydney (33.8688° S, 151.2093° E) + >>> result = calculate_cargo_travel_time((41.8781, -87.6298), (-33.8688, 151.2093)) + """ + + def to_radians(degrees: float) -> float: + return degrees * (math.pi / 180) + + # Extract coordinates + lat1, lon1 = map(to_radians, origin_coords) + lat2, lon2 = map(to_radians, destination_coords) + + # Earth's radius in kilometers + EARTH_RADIUS_KM = 6371.0 + + # Calculate great-circle distance using the haversine formula + dlon = lon2 - lon1 + dlat = lat2 - lat1 + + a = ( + math.sin(dlat / 2) ** 2 + + math.cos(lat1) * math.cos(lat2) * math.sin(dlon / 2) ** 2 + ) + c = 2 * math.asin(math.sqrt(a)) + distance = EARTH_RADIUS_KM * c + + # Add 10% to account for non-direct routes and air traffic controls + actual_distance = distance * 1.1 + + # Calculate flight time + # Add 1 hour for takeoff and landing procedures + flight_time = (actual_distance / cruising_speed_kmh) + 1.0 + + # Format the results + return round(flight_time, 2) + + +print(calculate_cargo_travel_time((41.8781, -87.6298), (-33.8688, 151.2093))) +``` + +### 設定 agent + +模型供應商方面,我們使用 Together AI,它是新加入的 [Hub 推論供應商](https://huggingface.co/blog/inference-providers)之一! + +GoogleSearchTool 使用 [Serper API](https://serper.dev) 搜尋網頁,因此需要設定環境變數 `SERPAPI_API_KEY` 並傳入 `provider="serpapi"`,或設定 `SERPER_API_KEY` 並傳入 `provider=serper`。 + +如果尚未設定任何 Serp API 供應商,也可以使用 `DuckDuckGoSearchTool`,但請留意它有呼叫頻率限制。 + +```python +import os +from PIL import Image +from smolagents import CodeAgent, GoogleSearchTool, InferenceClientModel, VisitWebpageTool + +model = InferenceClientModel(model_id="Qwen/Qwen2.5-Coder-32B-Instruct", provider="together") +``` + +先建立簡單的 agent 作為基準,讓它產出一份簡單報告。 + +```python +task = """Find all Batman filming locations in the world, calculate the time to transfer via cargo plane to here (we're in Gotham, 40.7128° N, 74.0060° W), and return them to me as a pandas dataframe. +Also give me some supercar factories with the same cargo plane transfer time.""" +``` + +```python +agent = CodeAgent( + model=model, + tools=[GoogleSearchTool("serper"), VisitWebpageTool(), calculate_cargo_travel_time], + additional_authorized_imports=["pandas"], + max_steps=20, +) +``` + +```python +result = agent.run(task) +``` + +```python +result +``` + +在我們的執行結果中,輸出如下: + +```python +| | Location | Travel Time to Gotham (hours) | +|--|------------------------------------------------------|------------------------------| +| 0 | Necropolis Cemetery, Glasgow, Scotland, UK | 8.60 | +| 1 | St. George's Hall, Liverpool, England, UK | 8.81 | +| 2 | Two Temple Place, London, England, UK | 9.17 | +| 3 | Wollaton Hall, Nottingham, England, UK | 9.00 | +| 4 | Knebworth House, Knebworth, Hertfordshire, UK | 9.15 | +| 5 | Acton Lane Power Station, Acton Lane, Acton, UK | 9.16 | +| 6 | Queensboro Bridge, New York City, USA | 1.01 | +| 7 | Wall Street, New York City, USA | 1.00 | +| 8 | Mehrangarh Fort, Jodhpur, Rajasthan, India | 18.34 | +| 9 | Turda Gorge, Turda, Romania | 11.89 | +| 10 | Chicago, USA | 2.68 | +| 11 | Hong Kong, China | 19.99 | +| 12 | Cardington Studios, Northamptonshire, UK | 9.10 | +| 13 | Warner Bros. Leavesden Studios, Hertfordshire, UK | 9.13 | +| 14 | Westwood, Los Angeles, CA, USA | 6.79 | +| 15 | Woking, UK (McLaren) | 9.13 | +``` + +可以加入專門的規劃步驟,並提供更多 prompt 指引,進一步改善結果。 + +規劃步驟讓 agent 能事先思考並安排接下來的步驟,對較複雜的任務很有幫助。 + +```python +agent.planning_interval = 4 + +detailed_report = agent.run(f""" +You're an expert analyst. You make comprehensive reports after visiting many websites. +Don't hesitate to search for many queries at once in a for loop. +For each data point that you find, visit the source url to confirm numbers. + +{task} +""") + +print(detailed_report) +``` + +```python +detailed_report +``` + +在我們的執行結果中,輸出如下: + +```python +| | Location | Travel Time (hours) | +|--|--------------------------------------------------|---------------------| +| 0 | Bridge of Sighs, Glasgow Necropolis, Glasgow, UK | 8.6 | +| 1 | Wishart Street, Glasgow, Scotland, UK | 8.6 | +``` + + +只做了這些簡單調整,給 agent 詳細的 prompt 並加入規劃能力,就得到更精簡的報告! + +模型的上下文視窗很快就會被填滿。因此,**如果要求 agent 將詳盡搜尋的結果與另一組結果整合,執行速度就會變慢,token 用量與成本也會快速增加**。 + +➡️ 我們需要改善系統架構。 + +### ✌️ 將任務分給兩個 agent + +多 agent 架構能將不同子任務的記憶分開,帶來兩項主要好處: +- 每個 agent 都更專注於核心任務,因此表現更好。 +- 分開記憶能減少每一步的輸入 token 數,降低延遲與成本。 + +讓我們建立一個團隊,由一個 agent 管理專門負責網頁搜尋的 agent。 + +管理 agent 需要繪圖能力,才能撰寫最終報告。因此,我們允許它匯入額外的套件,包括 `plotly`,以及用於地理空間繪圖的 `geopandas` 與 `shapely`。 + +```python +model = InferenceClientModel( + "Qwen/Qwen2.5-Coder-32B-Instruct", provider="together", max_tokens=8096 +) + +web_agent = CodeAgent( + model=model, + tools=[ + GoogleSearchTool(provider="serper"), + VisitWebpageTool(), + calculate_cargo_travel_time, + ], + name="web_agent", + description="Browses the web to find information", + verbosity_level=0, + max_steps=10, +) +``` + +管理 agent 需要承擔較繁重的推理工作。 + +因此,我們給它能力更強的 [DeepSeek-R1](https://huggingface.co/deepseek-ai/DeepSeek-R1) 模型,並加入 `planning_interval`。 + +```python +from smolagents.utils import encode_image_base64, make_image_url +from smolagents import OpenAIServerModel + + +def check_reasoning_and_plot(final_answer, agent_memory): + multimodal_model = OpenAIServerModel("gpt-4o", max_tokens=8096) + filepath = "saved_map.png" + assert os.path.exists(filepath), "Make sure to save the plot under saved_map.png!" + image = Image.open(filepath) + prompt = ( + f"Here is a user-given task and the agent steps: {agent_memory.get_succinct_steps()}. Now here is the plot that was made." + "Please check that the reasoning process and plot are correct: do they correctly answer the given task?" + "First list reasons why yes/no, then write your final decision: PASS in caps lock if it is satisfactory, FAIL if it is not." + "Don't be harsh: if the plot mostly solves the task, it should pass." + "To pass, a plot should be made using px.scatter_map and not any other method (scatter_map looks nicer)." + ) + messages = [ + { + "role": "user", + "content": [ + { + "type": "text", + "text": prompt, + }, + { + "type": "image_url", + "image_url": {"url": make_image_url(encode_image_base64(image))}, + }, + ], + } + ] + output = multimodal_model(messages).content + print("Feedback: ", output) + if "FAIL" in output: + raise Exception(output) + return True + + +manager_agent = CodeAgent( + model=InferenceClientModel("deepseek-ai/DeepSeek-R1", provider="together", max_tokens=8096), + tools=[calculate_cargo_travel_time], + managed_agents=[web_agent], + additional_authorized_imports=[ + "geopandas", + "plotly", + "shapely", + "json", + "pandas", + "numpy", + ], + planning_interval=5, + verbosity_level=2, + final_answer_checks=[check_reasoning_and_plot], + max_steps=15, +) +``` + +來看看這個團隊的結構: + +```python +manager_agent.visualize() +``` + +這會產生類似下方的輸出,協助我們理解 agent 與工具之間的結構和關係: + +```python +CodeAgent | deepseek-ai/DeepSeek-R1 +├── ✅ Authorized imports: ['geopandas', 'plotly', 'shapely', 'json', 'pandas', 'numpy'] +├── 🛠️ Tools: +│ ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ +│ ┃ Name ┃ Description ┃ Arguments ┃ +│ ┡━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┩ +│ │ calculate_cargo_travel_time │ Calculate the travel time for a cargo │ origin_coords (`array`): Tuple of │ +│ │ │ plane between two points on Earth │ (latitude, longitude) for the │ +│ │ │ using great-circle distance. │ starting point │ +│ │ │ │ destination_coords (`array`): Tuple │ +│ │ │ │ of (latitude, longitude) for the │ +│ │ │ │ destination │ +│ │ │ │ cruising_speed_kmh (`number`): │ +│ │ │ │ Optional cruising speed in km/h │ +│ │ │ │ (defaults to 750 km/h for typical │ +│ │ │ │ cargo planes) │ +│ │ final_answer │ Provides a final answer to the given │ answer (`any`): The final answer to │ +│ │ │ problem. │ the problem │ +│ └─────────────────────────────┴───────────────────────────────────────┴───────────────────────────────────────┘ +└── 🤖 Managed agents: + └── web_agent | CodeAgent | Qwen/Qwen2.5-Coder-32B-Instruct + ├── ✅ Authorized imports: [] + ├── 📝 Description: Browses the web to find information + └── 🛠️ Tools: + ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ + ┃ Name ┃ Description ┃ Arguments ┃ + ┡━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┩ + │ web_search │ Performs a google web search for │ query (`string`): The search │ + │ │ your query then returns a string │ query to perform. │ + │ │ of the top search results. │ filter_year (`integer`): │ + │ │ │ Optionally restrict results to a │ + │ │ │ certain year │ + │ visit_webpage │ Visits a webpage at the given url │ url (`string`): The url of the │ + │ │ and reads its content as a │ webpage to visit. │ + │ │ markdown string. Use this to │ │ + │ │ browse webpages. │ │ + │ calculate_cargo_travel_time │ Calculate the travel time for a │ origin_coords (`array`): Tuple of │ + │ │ cargo plane between two points on │ (latitude, longitude) for the │ + │ │ Earth using great-circle │ starting point │ + │ │ distance. │ destination_coords (`array`): │ + │ │ │ Tuple of (latitude, longitude) │ + │ │ │ for the destination │ + │ │ │ cruising_speed_kmh (`number`): │ + │ │ │ Optional cruising speed in km/h │ + │ │ │ (defaults to 750 km/h for typical │ + │ │ │ cargo planes) │ + │ final_answer │ Provides a final answer to the │ answer (`any`): The final answer │ + │ │ given problem. │ to the problem │ + └─────────────────────────────┴───────────────────────────────────┴───────────────────────────────────┘ +``` + +```python +manager_agent.run(""" +Find all Batman filming locations in the world, calculate the time to transfer via cargo plane to here (we're in Gotham, 40.7128° N, 74.0060° W). +Also give me some supercar factories with the same cargo plane transfer time. You need at least 6 points in total. +Represent this as spatial map of the world, with the locations represented as scatter points with a color that depends on the travel time, and save it to saved_map.png! + +Here's an example of how to plot and return a map: +import plotly.express as px +df = px.data.carshare() +fig = px.scatter_map(df, lat="centroid_lat", lon="centroid_lon", text="name", color="peak_hour", size=100, + color_continuous_scale=px.colors.sequential.Magma, size_max=15, zoom=1) +fig.show() +fig.write_image("saved_image.png") +final_answer(fig) + +Never try to process strings using code: when you have a string to read, just print it and you'll see it. +""") +``` + +不知道你的執行結果如何;在我的例子中,管理 agent 巧妙地將工作分成 `1. 搜尋蝙蝠俠電影拍攝地點` 與 `2. 尋找超跑工廠`,交給網頁 agent 處理,最後再彙整清單並繪製地圖。 + +直接查看 agent 的狀態,看看地圖長什麼樣子: + +```python +manager_agent.python_executor.state["fig"] +``` + +這會輸出以下地圖: + +![多 agent 系統輸出的地圖範例](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit2/smolagents/output_map.png) + +## 資源 + +- [多 agent 系統](https://huggingface.co/docs/smolagents/main/en/examples/multiagents) – 多 agent 系統概覽。 +- [什麼是 Agentic RAG?](https://weaviate.io/blog/what-is-agentic-rag) – Agentic RAG 簡介。 +- [多 agent RAG 系統 🤖🤝🤖 實作指南](https://huggingface.co/learn/cookbook/multiagent_rag_system) – 逐步建立多 agent RAG 系統的指南。 diff --git a/units/zh-TW/unit2/smolagents/quiz1.mdx b/units/zh-TW/unit2/smolagents/quiz1.mdx new file mode 100644 index 000000000..1eceb1b89 --- /dev/null +++ b/units/zh-TW/unit2/smolagents/quiz1.mdx @@ -0,0 +1,142 @@ +# 小測驗(不計分)[[quiz1]] + +用一份簡短測驗,檢驗你對 `smolagents` 的理解!自我測驗能鞏固所學,也能找出需要複習的部分。 + +這份測驗可自由參加,不計分。 + +### Q1:相較於其他框架,選擇 `smolagents` 的主要優點之一是什麼? +哪個敘述最能描述 `smolagents` 的核心優勢? + + + +--- + +### Q2:哪種情況最能發揮 smolagents 的優勢? +哪個情境最符合 smolagents 的強項? + + + +--- + +### Q3:smolagents 提供彈性的模型整合方式,哪個敘述最符合它的做法? +選出最準確描述 smolagents 如何與 LLM 配合使用的選項。 + + + +--- + +### Q4:smolagents 如何看待程式碼動作與 JSON 動作的選擇? +哪個敘述正確描述 smolagents 對動作格式的設計理念? + + + +--- + +### Q5:smolagents 整合 Hugging Face Hub,帶來了什麼額外好處? +哪個敘述準確描述 Hub 整合的主要優點之一? + + + +--- + +恭喜完成測驗!🎉 如果有答錯的題目,建議回顧*為什麼使用 smolagents*,加深理解。如果答得不錯,就可以繼續探索 smolagents 的進階主題了! diff --git a/units/zh-TW/unit2/smolagents/quiz2.mdx b/units/zh-TW/unit2/smolagents/quiz2.mdx new file mode 100644 index 000000000..746ed79d1 --- /dev/null +++ b/units/zh-TW/unit2/smolagents/quiz2.mdx @@ -0,0 +1,147 @@ +# 小測驗(不計分)[[quiz2]] + +來檢驗你對 *code agent*、*工具呼叫 agent* 與*工具*章節的理解!這份測驗可自由參加,不計分。 + +--- + +### Q1:在 smolagents 中,使用 `@tool` 裝飾器建立工具,與建立 `Tool` 子類別有什麼主要差異? + +哪個敘述最能描述這兩種工具定義方式的差異? + +@tool 裝飾器,而 Tool 子類別只能用於文字生成任務", + explain: "兩種方式都適用於任何工具類型,包括檢索與文字生成工具。", + }, + { + text: "簡單的函式工具建議使用 @tool 裝飾器;複雜功能或自訂中繼資料則可透過 Tool 子類別獲得更多彈性", + explain: "正確。裝飾器比較簡單,但子類別能提供更多自訂行為。", + correct: true + }, + { + text: "@tool 只能用於多 agent 系統,Tool 子類別則適用於單一 agent 情境", + explain: "單一或多 agent 都能使用任一方式定義工具,沒有這種限制。", + }, + { + text: "使用 @tool 裝飾函式就不需要 docstring,而子類別禁止包含 docstring", + explain: "兩種方式都受益於清楚的 docstring。裝飾器不能取代它,子類別也可以包含 docstring。", + } +]} +/> + +--- + +### Q2:CodeAgent 如何使用 ReAct(Reason + Act)處理多步驟任務? + +哪個敘述正確描述 CodeAgent 透過一連串步驟解決任務的方式? + + + +--- + +### Q3:在 Hugging Face Hub 分享工具的主要優點是什麼? + +選出開發者上傳並分享自訂工具的最佳理由。 + + + +--- + +### Q4:ToolCallingAgent 與 CodeAgent 的動作執行方式不同,哪個敘述正確? + +選出準確描述 ToolCallingAgent 運作方式的選項。 + + + +--- + +### Q5:smolagents 的預設工具箱包含什麼?為什麼要使用它? + +哪個敘述最能描述 smolagents 預設工具箱的用途與內容? + + + +--- + +恭喜完成測驗!🎉 如果有題目讓你感到困難,請回顧 *code agent*、*工具呼叫 agent* 或*工具*章節,加深理解。如果全都答對了,你已經朝著打造穩健的 smolagents 應用程式邁進一大步! diff --git a/units/zh-TW/unit2/smolagents/retrieval_agents.mdx b/units/zh-TW/unit2/smolagents/retrieval_agents.mdx new file mode 100644 index 000000000..91f3ca484 --- /dev/null +++ b/units/zh-TW/unit2/smolagents/retrieval_agents.mdx @@ -0,0 +1,167 @@ + + +# 建立 Agentic RAG 系統 + +> [!TIP] +> 你可以跟著這份 notebook 的程式碼實作,並在 Google Colab 中執行。 + +檢索增強生成(Retrieval Augmented Generation,RAG)系統結合資料檢索與生成模型的能力,提供能運用上下文的回答。例如,先將使用者的查詢傳給搜尋引擎,再將檢索結果和查詢一併提供給模型。模型接著根據查詢與取得的資訊產生回答。 + +Agentic RAG(Retrieval-Augmented Generation)透過**結合自主 agent 與動態知識檢索**,擴充傳統 RAG 系統。 + +傳統 RAG 系統使用 LLM,根據檢索到的資料回答問題;Agentic RAG 則**讓系統能聰明地控制檢索與生成流程**,提高效率與準確度。 + +傳統 RAG 系統的主要限制包括**依賴單次檢索**,以及著重於與使用者查詢直接相關的語意相似度,因此可能漏掉相關資訊。 + +Agentic RAG 讓 agent 自主擬定搜尋查詢、評估檢索結果並執行多次檢索,產生更符合需求且完整的輸出,藉此解決這些問題。 + +## 使用 DuckDuckGo 進行基本檢索 + +先建立一個能使用 DuckDuckGo 搜尋網頁的簡單 agent,讓它檢索資訊並整合成回答。透過 Agentic RAG,Alfred 的 agent 可以: + +* 搜尋最新的超級英雄派對趨勢 +* 調整搜尋結果,納入豪華元素 +* 將資訊整合成完整計畫 + +以下是 Alfred 的 agent 的實作方式: + +```python +from smolagents import CodeAgent, DuckDuckGoSearchTool, InferenceClientModel + +# Initialize the search tool +search_tool = DuckDuckGoSearchTool() + +# Initialize the model +model = InferenceClientModel() + +agent = CodeAgent( + model=model, + tools=[search_tool], +) + +# Example usage +response = agent.run( + "Search for luxury superhero-themed party ideas, including decorations, entertainment, and catering." +) +print(response) +``` + +agent 會依照下列流程運作: + +1. **分析需求:** Alfred 的 agent 找出查詢的重點:規劃豪華的超級英雄主題派對,著重於裝飾、娛樂與餐飲。 +2. **執行檢索:** agent 使用 DuckDuckGo 搜尋最新且最相關的資訊,確保符合 Alfred 對豪華活動的細緻要求。 +3. **整合資訊:** 蒐集結果後,agent 將資訊整理成連貫、可執行的計畫,涵蓋派對的各個面向。 +4. **儲存供日後參考:** agent 儲存檢索到的資訊,方便規劃未來活動時取用,提升後續任務的效率。 + +## 自訂知識庫工具 + +對專業任務來說,自訂知識庫很有價值。讓我們建立一個工具,查詢儲存技術文件或專業知識的向量資料庫。透過語意搜尋,agent 能找出最符合 Alfred 需求的資訊。 + +向量資料庫儲存文字或其他資料的數值表示(embedding),這些表示由機器學習模型建立。資料庫透過辨識高維空間中的相似語意,支援語意搜尋。 + +這個方法結合預先定義的知識與語意搜尋,為活動規劃提供能運用上下文的解決方案。有了專業知識,Alfred 就能完善派對的每個細節。 + +在這個範例中,我們將建立從自訂知識庫檢索派對規劃點子的工具。使用 BM25 檢索器搜尋知識庫並回傳排名最高的結果,再用 `RecursiveCharacterTextSplitter` 將文件切成較小的區塊,提升搜尋效率。 + +```python +from langchain_community.docstore.document import Document +from langchain_text_splitters import RecursiveCharacterTextSplitter +from smolagents import Tool +from langchain_community.retrievers import BM25Retriever +from smolagents import CodeAgent, InferenceClientModel + +class PartyPlanningRetrieverTool(Tool): + name = "party_planning_retriever" + description = "Uses semantic search to retrieve relevant party planning ideas for Alfred’s superhero-themed party at Wayne Manor." + inputs = { + "query": { + "type": "string", + "description": "The query to perform. This should be a query related to party planning or superhero themes.", + } + } + output_type = "string" + + def __init__(self, docs, **kwargs): + super().__init__(**kwargs) + self.retriever = BM25Retriever.from_documents( + docs, k=5 # Retrieve the top 5 documents + ) + + def forward(self, query: str) -> str: + assert isinstance(query, str), "Your search query must be a string" + + docs = self.retriever.invoke( + query, + ) + return "\nRetrieved ideas:\n" + "".join( + [ + f"\n\n===== Idea {str(i)} =====\n" + doc.page_content + for i, doc in enumerate(docs) + ] + ) + +# Simulate a knowledge base about party planning +party_ideas = [ + {"text": "A superhero-themed masquerade ball with luxury decor, including gold accents and velvet curtains.", "source": "Party Ideas 1"}, + {"text": "Hire a professional DJ who can play themed music for superheroes like Batman and Wonder Woman.", "source": "Entertainment Ideas"}, + {"text": "For catering, serve dishes named after superheroes, like 'The Hulk's Green Smoothie' and 'Iron Man's Power Steak.'", "source": "Catering Ideas"}, + {"text": "Decorate with iconic superhero logos and projections of Gotham and other superhero cities around the venue.", "source": "Decoration Ideas"}, + {"text": "Interactive experiences with VR where guests can engage in superhero simulations or compete in themed games.", "source": "Entertainment Ideas"} +] + +source_docs = [ + Document(page_content=doc["text"], metadata={"source": doc["source"]}) + for doc in party_ideas +] + +# Split the documents into smaller chunks for more efficient search +text_splitter = RecursiveCharacterTextSplitter( + chunk_size=500, + chunk_overlap=50, + add_start_index=True, + strip_whitespace=True, + separators=["\n\n", "\n", ".", " ", ""], +) +docs_processed = text_splitter.split_documents(source_docs) + +# Create the retriever tool +party_planning_retriever = PartyPlanningRetrieverTool(docs_processed) + +# Initialize the agent +agent = CodeAgent(tools=[party_planning_retriever], model=InferenceClientModel()) + +# Example usage +response = agent.run( + "Find ideas for a luxury superhero-themed party, including entertainment, catering, and decoration options." +) + +print(response) +``` + +強化後的 agent 可以: +1. 先查看文件,尋找相關資訊 +2. 整合知識庫中的見解 +3. 在記憶中保留對話上下文 + +## 強化檢索能力 + +建立 Agentic RAG 系統時,agent 可以採用以下進階策略: + +1. **查詢改寫:** 不直接使用原始查詢,而是擬定更符合目標文件的搜尋詞。 +2. **查詢分解:** 如果使用者的查詢包含多項資訊需求,可拆解為多個查詢,而非直接使用原始查詢。 +3. **查詢擴展:** 類似查詢改寫,但會產生多種表達方式,分別執行搜尋。 +4. **重新排序:** 使用 Cross-Encoder,針對檢索文件與查詢之間的語意相關性給出更全面的評分。 +5. **多步驟檢索:** 執行多次搜尋,利用初步結果調整後續查詢。 +6. **來源整合:** 結合網頁搜尋、本機文件等多個來源的資訊。 +7. **結果驗證:** 在將檢索內容納入回答前,分析其相關性與準確度。 + +有效的 Agentic RAG 系統需要仔細考量幾個關鍵面向。agent **應根據查詢類型與上下文,從可用工具中做出選擇**。記憶系統能保留對話歷史,避免重複檢索;備援策略能確保主要檢索方式失敗時,系統仍有幫助;驗證步驟則有助於確保檢索資訊的準確度與相關性。 + +## 資源 + +- [Agentic RAG:透過查詢改寫與自我查詢,強化你的 RAG!🚀](https://huggingface.co/learn/cookbook/agent_rag) - 使用 smolagents 開發 Agentic RAG 系統的實作指南。 diff --git a/units/zh-TW/unit2/smolagents/tool_calling_agents.mdx b/units/zh-TW/unit2/smolagents/tool_calling_agents.mdx new file mode 100644 index 000000000..99ac7f6f8 --- /dev/null +++ b/units/zh-TW/unit2/smolagents/tool_calling_agents.mdx @@ -0,0 +1,73 @@ + + +# 以程式碼片段或 JSON 區塊撰寫動作 + +> [!TIP] +> 你可以跟著這份 notebook 的程式碼實作,並在 Google Colab 中執行。 + +工具呼叫 agent 是 `smolagents` 提供的第二種 agent。不同於使用 Python 片段的 code agent,這類 agent **利用 LLM 供應商內建的工具呼叫能力**,以 **JSON 結構**產生工具呼叫。OpenAI、Anthropic 與許多其他供應商都採用這種標準做法。 + +來看個例子。當 Alfred 想搜尋餐飲服務與派對創意時,`CodeAgent` 會產生並執行這樣的 Python 程式碼: + +```python +for query in [ + "Best catering services in Gotham City", + "Party theme ideas for superheroes" +]: + print(web_search(f"Search for: {query}")) +``` + +`ToolCallingAgent` 則會建立 JSON 結構: + +```python +[ + {"name": "web_search", "arguments": "Best catering services in Gotham City"}, + {"name": "web_search", "arguments": "Party theme ideas for superheroes"} +] +``` + +接著,系統會使用這個 JSON 區塊執行工具呼叫。 + +雖然 `smolagents` 主要著重於 `CodeAgents`,因為[它們的整體表現較好](https://huggingface.co/papers/2402.01030),但對於不需要處理變數或複雜工具呼叫的簡單系統,`ToolCallingAgents` 也很有效。 + +![程式碼動作與 JSON 動作](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/code_vs_json_actions.png) + +## 工具呼叫 agent 如何運作? + +工具呼叫 agent 與 code agent 採用相同的多步驟工作流程,詳情請見[上一節](./code_agents)。 + +關鍵差異在於**如何組織動作**:工具呼叫 agent 不輸出可執行的程式碼,而是**產生指定工具名稱與參數的 JSON 物件**。系統接著**解析這些指令**,執行對應工具。 + +## 範例:執行工具呼叫 agent + +回到 Alfred 開始準備派對的例子,這次改用 `ToolCallingAgent`,看看兩者有何不同。我們將建立能使用 DuckDuckGo 搜尋網頁的 agent,就像先前的 code agent 範例一樣。唯一差別是 agent 類型,其餘細節都由框架處理: + +```python +from smolagents import ToolCallingAgent, WebSearchTool, InferenceClientModel + +agent = ToolCallingAgent(tools=[WebSearchTool()], model=InferenceClientModel()) + +agent.run("Search for the best music recommendations for a party at the Wayne's mansion.") +``` + +查看 agent 的執行追蹤時,你會看到類似以下的內容,而非 `Executing parsed code:`: + +```text +╭─────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮ +│ Calling tool: 'web_search' with arguments: {'query': "best music recommendations for a party at Wayne's │ +│ mansion"} │ +╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯ +``` + +agent 會產生結構化的工具呼叫,由系統處理並輸出結果,而非像 `CodeAgent` 一樣直接執行程式碼。 + +現在你已經認識這兩種 agent,可以依需求選擇。讓我們繼續探索 `smolagents`,讓 Alfred 的派對圓滿成功!🎉 + +## 資源 + +- [ToolCallingAgent 文件](https://huggingface.co/docs/smolagents/v1.8.1/en/reference/agents#smolagents.ToolCallingAgent) - ToolCallingAgent 官方文件 diff --git a/units/zh-TW/unit2/smolagents/tools.mdx b/units/zh-TW/unit2/smolagents/tools.mdx new file mode 100644 index 000000000..f7651319a --- /dev/null +++ b/units/zh-TW/unit2/smolagents/tools.mdx @@ -0,0 +1,322 @@ + + +# 工具 + +如[第一單元](https://huggingface.co/learn/agents-course/unit1/tools)所述,agent 會透過工具執行各種動作。在 `smolagents` 中,工具就是 **LLM 可以在 agent 系統內呼叫的函式**。 + +要與工具互動,LLM 需要一份**介面說明**,其中包含以下要素: + +- **名稱**:工具的名稱 +- **工具描述**:工具的用途 +- **輸入類型與說明**:工具接受哪些參數 +- **輸出類型**:工具會回傳什麼 + +例如,Alfred 籌備韋恩莊園的派對時,需要各種工具來蒐集資訊,從搜尋餐飲服務到尋找派對主題靈感都用得上。一個簡單搜尋工具的介面可以這樣描述: + +- **名稱:** `web_search` +- **工具描述:** 根據指定查詢搜尋網頁 +- **輸入:** `query`(字串)— 要查詢的搜尋詞 +- **輸出:** 包含搜尋結果的字串 + +運用這些工具,Alfred 就能蒐集規劃完美派對所需的資訊,做出有根據的決策。 + +下方動畫展示工具呼叫的處理流程: + +![agent 流程,出自 https://huggingface.co/docs/smolagents/conceptual_guides/react](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/Agent_ManimCE.gif) + +## 建立工具的方法 + +在 `smolagents` 中,有兩種定義工具的方式: +1. **使用 `@tool` 裝飾器**:適合以函式實作的簡單工具 +2. **建立 `Tool` 的子類別**:適合較複雜的功能 + +### `@tool` 裝飾器 + +**定義簡單工具時,建議使用 `@tool` 裝飾器**。smolagents 會從 Python 函式解析基本資訊,因此清楚的函式名稱與良好的 docstring,都能讓 LLM 更容易使用工具。 + +採用這個方法時,定義函式應包含: + +- **清楚且能描述用途的函式名稱**,協助 LLM 理解其功能。 +- **輸入與輸出的型別提示**,確保工具使用方式正確。 +- **詳細說明**,包括明確描述每個參數的 `Args:` 區段。這些描述能為 LLM 提供重要的上下文,值得仔細撰寫。 + +#### 建立查詢最高評價餐飲服務的工具 + +Alfred Catering + +> [!TIP] +> 你可以跟著這份 notebook 的程式碼實作,並在 Google Colab 中執行。 + +假設 Alfred 已經決定派對菜單,但需要有人協助準備這麼多賓客的餐點。因此,他想聘請餐飲服務業者,並找出評價最高的選擇。Alfred 可以利用工具搜尋附近最好的餐飲服務。 + +以下範例展示 Alfred 如何使用 `@tool` 裝飾器完成這件事: + +```python +from smolagents import CodeAgent, InferenceClientModel, tool + +# Let's pretend we have a function that fetches the highest-rated catering services. +@tool +def catering_service_tool(query: str) -> str: + """ + This tool returns the highest-rated catering service in Gotham City. + + Args: + query: A search term for finding catering services. + """ + # Example list of catering services and their ratings + services = { + "Gotham Catering Co.": 4.9, + "Wayne Manor Catering": 4.8, + "Gotham City Events": 4.7, + } + + # Find the highest rated catering service (simulating search query filtering) + best_service = max(services, key=services.get) + + return best_service + + +agent = CodeAgent(tools=[catering_service_tool], model=InferenceClientModel()) + +# Run the agent to find the best catering service +result = agent.run( + "Can you give me the name of the highest-rated catering service in Gotham City?" +) + +print(result) # Output: Gotham Catering Co. +``` + +### 以 Python 類別定義工具 + +這個方法會建立 [`Tool`](https://huggingface.co/docs/smolagents/v1.8.1/en/reference/tools#smolagents.Tool) 的子類別。工具較複雜時,可以改用類別,而非 Python 函式來實作。類別會用中繼資料包裝函式,協助 LLM 理解如何有效使用工具。我們需要在類別中定義: + +- `name`:工具名稱。 +- `description`:用來填入 agent 系統 prompt 的工具描述。 +- `inputs`:包含 `type` 與 `description` 鍵的字典,提供 Python 直譯器處理輸入所需的資訊。 +- `output_type`:指定預期的輸出型別。 +- `forward`:包含要執行的推論邏輯的方法。 + +以下範例展示如何使用 `Tool` 建立工具,並將它整合到 `CodeAgent`。 + +#### 建立產生超級英雄主題派對點子的工具 + +Alfred 在莊園舉辦的是**超級英雄主題活動**,但還需要一些創意,讓派對更特別。身為出色的主人,他希望用獨特的主題給賓客驚喜。 + +他可以使用 agent,根據指定類別產生超級英雄主題派對的點子,找出能讓賓客眼睛一亮的完美主題。 + +```python +from smolagents import Tool, CodeAgent, InferenceClientModel + +class SuperheroPartyThemeTool(Tool): + name = "superhero_party_theme_generator" + description = """ + This tool suggests creative superhero-themed party ideas based on a category. + It returns a unique party theme idea.""" + + inputs = { + "category": { + "type": "string", + "description": "The type of superhero party (e.g., 'classic heroes', 'villain masquerade', 'futuristic Gotham').", + } + } + + output_type = "string" + + def forward(self, category: str): + themes = { + "classic heroes": "Justice League Gala: Guests come dressed as their favorite DC heroes with themed cocktails like 'The Kryptonite Punch'.", + "villain masquerade": "Gotham Rogues' Ball: A mysterious masquerade where guests dress as classic Batman villains.", + "futuristic Gotham": "Neo-Gotham Night: A cyberpunk-style party inspired by Batman Beyond, with neon decorations and futuristic gadgets." + } + + return themes.get(category.lower(), "Themed party idea not found. Try 'classic heroes', 'villain masquerade', or 'futuristic Gotham'.") + +# Instantiate the tool +party_theme_tool = SuperheroPartyThemeTool() +agent = CodeAgent(tools=[party_theme_tool], model=InferenceClientModel()) + +# Run the agent to generate a party theme idea +result = agent.run( + "What would be a good superhero party idea for a 'villain masquerade' theme?" +) + +print(result) # Output: "Gotham Rogues' Ball: A mysterious masquerade where guests dress as classic Batman villains." +``` + +有了這個工具,Alfred 就能成為超級主人,打造讓賓客難忘的超級英雄派對!🦸‍♂️🦸‍♀️ + +## 預設工具箱 + +`smolagents` 提供一組可直接加入 agent 的現成工具。[預設工具箱](https://huggingface.co/docs/smolagents/guided_tour?build-a-tool=Decorate+a+function+with+%40tool#default-toolbox)包含: + +- **PythonInterpreterTool** +- **FinalAnswerTool** +- **UserInputTool** +- **DuckDuckGoSearchTool** +- **GoogleSearchTool** +- **VisitWebpageTool** + +Alfred 可以運用各種工具,讓韋恩莊園的派對順利進行: + +- 首先,使用 `DuckDuckGoSearchTool` 搜尋有創意的超級英雄派對點子。 + +- 餐飲方面,使用 `GoogleSearchTool` 尋找哥譚市評價最高的服務。 + +- 安排座位時,使用 `PythonInterpreterTool` 執行計算。 + +- 資訊蒐集完畢後,使用 `FinalAnswerTool` 整理出完整計畫。 + +有了這些工具,Alfred 就能確保派對既精彩又順暢。🦇💡 + +## 分享與匯入工具 + +**smolagents** 的強大功能之一,是能在 Hub 分享自訂工具,並輕鬆整合社群建立的工具,包括連接 **HF Spaces** 與 **LangChain 工具**。這讓 Alfred 更有能力在韋恩莊園籌辦令人難忘的派對。🎭 + +透過這些整合,Alfred 能使用進階的活動規劃工具,無論是調整燈光營造氛圍、挑選派對歌單,或與哥譚市頂尖餐飲業者協調,都能派上用場。 + +以下範例展示這些功能如何提升派對體驗: + +### 將工具分享到 Hub + +與社群分享自訂工具很簡單!只要使用 `push_to_hub()` 方法,將工具上傳到你的 Hugging Face 帳號即可。 + +例如,Alfred 可以分享 `party_theme_tool`,幫助其他人尋找哥譚市最好的餐飲服務。做法如下: + +```python +party_theme_tool.push_to_hub("{your_username}/party_theme_tool", token="") +``` + +### 從 Hub 匯入工具 + +使用 `load_tool()` 函式,就能輕鬆匯入其他使用者建立的工具。例如,Alfred 想用 AI 產生派對宣傳圖片,便可以直接使用社群提供的現成工具,不必從頭建立: + +```python +from smolagents import load_tool, CodeAgent, InferenceClientModel + +image_generation_tool = load_tool( + "m-ric/text-to-image", + trust_remote_code=True +) + +agent = CodeAgent( + tools=[image_generation_tool], + model=InferenceClientModel() +) + +agent.run("Generate an image of a luxurious superhero-themed party at Wayne Manor with made-up superheros.") +``` + +### 將 Hugging Face Space 匯入為工具 + +你也可以使用 `Tool.from_space()`,將 HF Space 匯入為工具。這讓你能整合社群提供的數千個 Space,處理從影像生成到資料分析的各種任務。 + +工具會透過 `gradio_client` 連接 Space 的 Gradio 後端。如果尚未安裝,請先使用 `pip` 安裝。 + +這次派對,Alfred 可以使用現有的 HF Space,產生公告所需的 AI 圖片,取代前面提到的現成工具。讓我們來實作! + +```python +from smolagents import CodeAgent, InferenceClientModel, Tool + +image_generation_tool = Tool.from_space( + "black-forest-labs/FLUX.1-schnell", + name="image_generator", + description="Generate an image from a prompt" +) + +model = InferenceClientModel("Qwen/Qwen2.5-Coder-32B-Instruct") + +agent = CodeAgent(tools=[image_generation_tool], model=model) + +agent.run( + "Improve this prompt, then generate an image of it.", + additional_args={'user_prompt': 'A grand superhero-themed party at Wayne Manor, with Alfred overseeing a luxurious gala'} +) +``` + +### 匯入 LangChain 工具 + + +我們會在後續章節介紹 `LangChain` 框架。目前只要知道,LangChain 工具也能在 smolagents 工作流程中重複使用! + +透過 `Tool.from_langchain()` 方法,就能輕鬆載入 LangChain 工具。凡事追求完美的 Alfred 趁韋恩一家外出,在莊園籌辦盛大的超級英雄之夜。為了讓每個細節都超出期待,他決定使用 LangChain 工具,尋找頂級的娛樂點子。 + +使用 `Tool.from_langchain()`,Alfred 就能輕鬆替 smolagent 加入進階搜尋功能,只需幾個指令就能找到獨特的派對點子與服務。 + +做法如下: + +首先,需要安裝 `smolagents` 的 `langchain` 整合套件。 + +```bash +pip install -U langchain-community +``` + +安裝 langchain 整合套件後,記得設定 SerpAPI 金鑰。 +`SerpAPITool` 等搜尋工具需要這個金鑰: + +```python +os.environ['SERPAPI_API_KEY'] = '...' +``` + +你可以在[這裡](https://serpapi.com/)建立 SerpAPI 金鑰。 + +```python +from langchain.agents import load_tools +from smolagents import CodeAgent, InferenceClientModel, Tool + +search_tool = Tool.from_langchain(load_tools(["serpapi"])[0]) + +agent = CodeAgent(tools=[search_tool], model=model) + +agent.run("Search for luxury entertainment ideas for a superhero-themed event, such as live performances and interactive experiences.") +``` + +### 從任意 MCP 伺服器匯入工具集合 + +`smolagents` 也能匯入 [glama.ai](https://glama.ai/mcp/servers) 或 [smithery.ai](https://smithery.ai) 上數百個 MCP 伺服器提供的工具。想深入了解 MCP,可以參考我們的[免費 MCP 課程](https://huggingface.co/learn/mcp-course/)。 + +
+安裝 MCP client + +首先,需要安裝 `smolagents` 的 `mcp` 整合套件。 + +```bash +pip install "smolagents[mcp]" +``` +
+ +可以依下列方式,將 MCP 伺服器的工具載入 `ToolCollection` 物件: + +```python +import os +from smolagents import ToolCollection, CodeAgent +from mcp import StdioServerParameters +from smolagents import InferenceClientModel + + +model = InferenceClientModel("Qwen/Qwen2.5-Coder-32B-Instruct") + + +server_parameters = StdioServerParameters( + command="uvx", + args=["--quiet", "pubmedmcp@0.1.3"], + env={"UV_PYTHON": "3.12", **os.environ}, +) + +with ToolCollection.from_mcp(server_parameters, trust_remote_code=True) as tool_collection: + agent = CodeAgent(tools=[*tool_collection.tools], model=model, add_base_tools=True) + agent.run("Please find a remedy for hangover.") +``` + +完成設定後,Alfred 就能快速找到豪華的娛樂選擇,讓哥譚市的菁英賓客留下難忘回憶。這個工具將協助他為韋恩莊園打造完美的超級英雄主題活動!🎉 + +## 資源 + +- [工具教學](https://huggingface.co/docs/smolagents/tutorials/tools) - 學習如何有效使用工具。 +- [工具文件](https://huggingface.co/docs/smolagents/v1.8.1/en/reference/tools) - 完整的工具參考文件。 +- [工具導覽](https://huggingface.co/docs/smolagents/v1.8.1/en/guided_tour#tools) - 逐步說明如何有效建立並使用工具。 +- [打造有效的 agent](https://huggingface.co/docs/smolagents/tutorials/building_good_agents) - 開發可靠、高效能自訂函式 agent 的最佳實務指南。 diff --git a/units/zh-TW/unit2/smolagents/vision_agents.mdx b/units/zh-TW/unit2/smolagents/vision_agents.mdx new file mode 100644 index 000000000..8a9c9d9e3 --- /dev/null +++ b/units/zh-TW/unit2/smolagents/vision_agents.mdx @@ -0,0 +1,221 @@ + + +# 使用 smolagents 建立視覺 agent + +> [!WARNING] +> 本節範例需要使用能力強大的 VLM。我們以 GPT-4o API 進行測試。 +> 不過,為什麼使用 smolagents 一節也介紹了 smolagents 與 Hugging Face 支援的其他方案。想探索其他選擇,請參考該節。 + +要解決超出文字處理範圍的任務,視覺能力非常重要。許多實際挑戰,例如網頁瀏覽或文件理解,都需要分析豐富的視覺內容。幸好,`smolagents` 內建支援視覺語言模型(VLM),讓 agent 能有效處理並解讀影像。 + +在這個範例中,假設韋恩莊園的管家 Alfred 負責確認派對賓客的身分。他不一定認識每位來賓,因此我們可以建立 agent,使用 VLM 搜尋來賓外貌的視覺資訊,協助確認身分。這能讓 Alfred 有根據地決定誰可以入場。一起來實作吧! + + +## 在 agent 開始執行時提供影像 + +> [!TIP] +> 你可以跟著這份 notebook 的程式碼實作,並在 Google Colab 中執行。 + +這個方法會在 agent 開始執行時傳入影像,與任務 prompt 一起儲存為 `task_images`。agent 在執行過程中會持續處理這些影像。 + +假設 Alfred 想確認出席派對的超級英雄身分。他已經有過往派對的影像資料集,裡面附有賓客姓名。取得新訪客的影像後,agent 就能與現有資料集比對,決定是否讓對方入場。 + +這次有位賓客想入場,但 Alfred 懷疑對方是小丑(The Joker)假扮的神力女超人(Wonder Woman)。Alfred 需要確認身分,避免不受歡迎的人混入。 + +開始實作吧!首先載入影像。為了讓範例保持精簡,我們使用維基百科上的圖片,但你可以想像這個功能還能用在哪些情境! + +```python +from PIL import Image +import requests +from io import BytesIO + +image_urls = [ + "https://upload.wikimedia.org/wikipedia/commons/e/e8/The_Joker_at_Wax_Museum_Plus.jpg", # Joker image + "https://upload.wikimedia.org/wikipedia/en/9/98/Joker_%28DC_Comics_character%29.jpg" # Joker image +] + +images = [] +for url in image_urls: + headers = { + "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36" + } + response = requests.get(url,headers=headers) + image = Image.open(BytesIO(response.content)).convert("RGB") + images.append(image) +``` + +取得影像後,agent 將告訴我們,這位賓客究竟是超級英雄(神力女超人),還是反派(小丑)。 + +```python +from smolagents import CodeAgent, OpenAIServerModel + +model = OpenAIServerModel(model_id="gpt-4o") + +# Instantiate the agent +agent = CodeAgent( + tools=[], + model=model, + max_steps=20, + verbosity_level=2 +) + +response = agent.run( + """ + Describe the costume and makeup that the comic character in these photos is wearing and return the description. + Tell me if the guest is The Joker or Wonder Woman. + """, + images=images +) +``` + +我執行時得到以下輸出。不過,正如前面提到的,你的結果可能不同: + +```python + { + 'Costume and Makeup - First Image': ( + 'Purple coat and a purple silk-like cravat or tie over a mustard-yellow shirt.', + 'White face paint with exaggerated features, dark eyebrows, blue eye makeup, red lips forming a wide smile.' + ), + 'Costume and Makeup - Second Image': ( + 'Dark suit with a flower on the lapel, holding a playing card.', + 'Pale skin, green hair, very red lips with an exaggerated grin.' + ), + 'Character Identity': 'This character resembles known depictions of The Joker from comic book media.' + } +``` + +在這個例子中,輸出指出對方正在冒充他人,因此我們可以阻止小丑進入派對! + +## 透過動態檢索提供影像 + +> [!TIP] +> 你可以參照這份 Python 檔案中的程式碼實作。 + +前一個方法很有用,也有許多潛在應用。不過,如果資料庫中沒有這位賓客,就需要其他辨識方式。一個可行方案是動態取得外部來源的影像與資訊,例如瀏覽網頁尋找細節。 + +這個方法會在執行過程中,動態將影像加入 agent 的記憶。如前所述,`smolagents` 的 agent 以 `MultiStepAgent` 類別為基礎,這個類別是 ReAct 框架的抽象實作。它會在結構化的循環中運作,於不同階段記錄各種變數與知識: + +1. **SystemPromptStep:** 儲存系統 prompt。 +2. **TaskStep:** 記錄使用者查詢與提供的輸入。 +3. **ActionStep:** 記錄 agent 的動作與結果。 + +這樣的結構讓 agent 能動態納入視覺資訊,隨任務變化調整回應。下圖是先前看過的流程圖,說明動態工作流程,以及各步驟如何整合至 agent 的生命週期。瀏覽網頁時,agent 可以擷取螢幕畫面,並以 `observation_images` 儲存在 `ActionStep` 中。 + +![動態影像檢索](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/blog/smolagents-can-see/diagram_adding_vlms_smolagents.png) + +了解需求後,就來建立完整範例。Alfred 希望完全掌握賓客身分確認流程,因此透過網頁瀏覽尋找細節是可行的做法。這個範例需要為 agent 準備一組新工具,另外還會使用 Selenium 與 Helium 這兩套瀏覽器自動化工具。這樣就能建立瀏覽網頁的 agent,搜尋潛在賓客的詳細資訊並取得身分確認資料。先安裝所需工具: + +```bash +pip install "smolagents[all]" helium selenium python-dotenv +``` + +我們需要一組專為瀏覽設計的 agent 工具,例如 `search_item_ctrl_f`、`go_back` 和 `close_popups`,讓 agent 能像人一樣操作網頁。 + +```python +@tool +def search_item_ctrl_f(text: str, nth_result: int = 1) -> str: + """ + Searches for text on the current page via Ctrl + F and jumps to the nth occurrence. + Args: + text: The text to search for + nth_result: Which occurrence to jump to (default: 1) + """ + elements = driver.find_elements(By.XPATH, f"//*[contains(text(), '{text}')]") + if nth_result > len(elements): + raise Exception(f"Match n°{nth_result} not found (only {len(elements)} matches found)") + result = f"Found {len(elements)} matches for '{text}'." + elem = elements[nth_result - 1] + driver.execute_script("arguments[0].scrollIntoView(true);", elem) + result += f"Focused on element {nth_result} of {len(elements)}" + return result + + +@tool +def go_back() -> None: + """Goes back to previous page.""" + driver.back() + + +@tool +def close_popups() -> str: + """ + Closes any visible modal or pop-up on the page. Use this to dismiss pop-up windows! This does not work on cookie consent banners. + """ + webdriver.ActionChains(driver).send_keys(Keys.ESCAPE).perform() +``` + +我們也需要儲存螢幕截圖的功能,這是 VLM agent 完成任務的重要環節。這個功能擷取畫面後,會存入 `step_log.observations_images = [image.copy()]`,讓 agent 能在瀏覽時動態儲存並處理影像。 + +```python +def save_screenshot(step_log: ActionStep, agent: CodeAgent) -> None: + sleep(1.0) # Let JavaScript animations happen before taking the screenshot + driver = helium.get_driver() + current_step = step_log.step_number + if driver is not None: + for step_logs in agent.logs: # Remove previous screenshots from logs for lean processing + if isinstance(step_log, ActionStep) and step_log.step_number <= current_step - 2: + step_logs.observations_images = None + png_bytes = driver.get_screenshot_as_png() + image = Image.open(BytesIO(png_bytes)) + print(f"Captured a browser screenshot: {image.size} pixels") + step_log.observations_images = [image.copy()] # Create a copy to ensure it persists, important! + + # Update observations with current URL + url_info = f"Current url: {driver.current_url}" + step_log.observations = url_info if step_logs.observations is None else step_log.observations + "\n" + url_info + return +``` + +這個函式會以 `step_callback` 傳給 agent,在每一步結束時觸發,讓 agent 能在整個流程中動態擷取並儲存螢幕截圖。 + +現在可以建立瀏覽網頁的視覺 agent,將剛才建立的工具與 `DuckDuckGoSearchTool` 一併提供給它。這個搜尋工具將協助 agent 取得必要資訊,根據視覺線索確認賓客身分。 + +```python +from smolagents import CodeAgent, OpenAIServerModel, DuckDuckGoSearchTool +model = OpenAIServerModel(model_id="gpt-4o") + +agent = CodeAgent( + tools=[DuckDuckGoSearchTool(), go_back, close_popups, search_item_ctrl_f], + model=model, + additional_authorized_imports=["helium"], + step_callbacks=[save_screenshot], + max_steps=20, + verbosity_level=2, +) +``` + +如此一來,Alfred 就能開始確認賓客身分,並決定是否讓他們入場: + +```python +agent.run(""" +I am Alfred, the butler of Wayne Manor, responsible for verifying the identity of guests at party. A superhero has arrived at the entrance claiming to be Wonder Woman, but I need to confirm if she is who she says she is. + +Please search for images of Wonder Woman and generate a detailed visual description based on those images. Additionally, navigate to Wikipedia to gather key details about her appearance. With this information, I can determine whether to grant her access to the event. +""" + helium_instructions) +``` + +注意,我們把 `helium_instructions` 納入任務中。這段特殊的 prompt 用來引導 agent 瀏覽網頁,確保它依照正確步驟操作。 + +下方影片展示實際運作過程: + + + +這是最終輸出: + +```python +Final answer: Wonder Woman is typically depicted wearing a red and gold bustier, blue shorts or skirt with white stars, a golden tiara, silver bracelets, and a golden Lasso of Truth. She is Princess Diana of Themyscira, known as Diana Prince in the world of men. +``` + +我們成功建立派對的身分確認工具了!Alfred 現在有了所需工具,能確保只有合適的賓客進門。一切準備就緒,可以在韋恩莊園好好享受派對! + + +## 延伸閱讀 + +- [我們讓 smolagents 看得見了](https://huggingface.co/blog/smolagents-can-see) - 介紹視覺 agent 功能的部落格文章。 +- [使用 agent 自動操作瀏覽器 🤖🌐](https://huggingface.co/docs/smolagents/examples/web_browser) - 使用視覺 agent 瀏覽網頁的範例。 +- [瀏覽器視覺 agent 範例](https://github.com/huggingface/smolagents/blob/main/src/smolagents/vision_web_browser.py) - 使用視覺 agent 瀏覽網頁的範例。 diff --git a/units/zh-TW/unit2/smolagents/why_use_smolagents.mdx b/units/zh-TW/unit2/smolagents/why_use_smolagents.mdx new file mode 100644 index 000000000..49a9d3187 --- /dev/null +++ b/units/zh-TW/unit2/smolagents/why_use_smolagents.mdx @@ -0,0 +1,66 @@ +![smolagents banner](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/smolagents/license_to_call.png) +# 為什麼使用 smolagents + +本模組將探討 [smolagents](https://huggingface.co/docs/smolagents/en/index) 的優缺點,協助你判斷它是否符合需求。 + +## 什麼是 `smolagents`? + +`smolagents` 是簡單而強大的 AI agent 框架。它賦予 LLM 與現實世界互動的_行動能力_,例如搜尋資訊或產生影像。 + +如第一單元所述,AI agent 是利用 LLM 根據**「觀察」**產生**「思考」**,再執行**「動作」**的程式。讓我們看看 smolagents 如何實作這個流程。 + +### `smolagents` 的主要優點 +- **簡單:** 盡量減少程式碼複雜度與抽象層,讓框架容易理解、採用與擴充。 +- **彈性的 LLM 支援:** 整合 Hugging Face 工具與外部 API,能搭配各種 LLM。 +- **以程式碼為核心:** 完整支援直接用程式碼撰寫動作的 code agent,省去解析步驟,簡化工具呼叫。 +- **HF Hub 整合:** 與 Hugging Face Hub 緊密整合,能將 Gradio Spaces 作為工具使用。 + +### 何時使用 smolagents? + +了解這些優點後,什麼情況適合選擇 smolagents? + +smolagents 適合以下情況: +- 你需要**輕量、精簡的解決方案**。 +- 你希望**快速實驗**,不必處理複雜設定。 +- 你的**應用程式邏輯相對單純**。 + +### 程式碼動作與 JSON 動作 +其他框架的 agent 常用 JSON 描述動作,`smolagents` 則**著重以程式碼呼叫工具**,簡化執行流程。因為輸出本身就能直接執行,不必先解析 JSON,再轉成呼叫工具的程式碼。 + +下圖說明兩者的差異: + +![程式碼動作與 JSON 動作](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/code_vs_json_actions.png) + +你可以回顧[第一單元的動作章節](https://huggingface.co/learn/agents-course/unit1/actions#actions-enabling-the-agent-to-engage-with-its-environment),複習程式碼動作與 JSON 動作的差異。 + +### `smolagents` 的 agent 類型 + +`smolagents` 中的 agent 都以**多步驟 agent** 的方式運作。 + +每個 [`MultiStepAgent`](https://huggingface.co/docs/smolagents/main/en/reference/agents#smolagents.MultiStepAgent) 都會執行: +- 一次思考 +- 一次工具呼叫與執行 + +除了主要使用的 **[CodeAgent](https://huggingface.co/docs/smolagents/main/en/reference/agents#smolagents.CodeAgent)**,smolagents 也支援用 JSON 撰寫工具呼叫的 **[ToolCallingAgent](https://huggingface.co/docs/smolagents/main/en/reference/agents#smolagents.ToolCallingAgent)**。 + +接下來的章節將深入介紹這兩種 agent。 + +> [!TIP] +> 在 smolagents 中,可以使用 @tool 裝飾器包裝 Python 函式,或使用 Tool 類別來定義工具。 + +### `smolagents` 的模型整合 +`smolagents` 提供彈性的 LLM 整合方式,只要是符合[特定條件](https://huggingface.co/docs/smolagents/main/en/reference/models)的可呼叫模型,都能使用。框架提供數個預先定義的類別,簡化模型連接: + +- **[TransformersModel](https://huggingface.co/docs/smolagents/main/en/reference/models#smolagents.TransformersModel):** 在本機實作 `transformers` pipeline,方便整合。 +- **[InferenceClientModel](https://huggingface.co/docs/smolagents/main/en/reference/models#smolagents.InferenceClientModel):** 支援[無伺服器推論](https://huggingface.co/docs/huggingface_hub/main/en/guides/inference)呼叫,可透過 [Hugging Face 基礎設施](https://huggingface.co/docs/api-inference/index),或持續增加的[第三方推論供應商](https://huggingface.co/docs/huggingface_hub/main/en/guides/inference#supported-providers-and-tasks)使用。 +- **[LiteLLMModel](https://huggingface.co/docs/smolagents/main/en/reference/models#smolagents.LiteLLMModel):** 透過 [LiteLLM](https://www.litellm.ai/) 提供輕量的模型互動方式。 +- **[OpenAIServerModel](https://huggingface.co/docs/smolagents/main/en/reference/models#smolagents.OpenAIServerModel):** 連接任何提供 OpenAI API 介面的服務。 +- **[AzureOpenAIServerModel](https://huggingface.co/docs/smolagents/main/en/reference/models#smolagents.AzureOpenAIServerModel):** 支援整合 Azure OpenAI 部署。 + +這樣的彈性讓開發者能依使用情境選擇最合適的模型和服務,也方便進行實驗。 + +了解為什麼以及何時適合使用 smolagents 後,讓我們深入探索這個強大的函式庫! + +## 資源 + +- [smolagents 部落格](https://huggingface.co/blog/smolagents) - smolagents 與程式碼互動簡介 diff --git a/units/zh-TW/unit3/README.md b/units/zh-TW/unit3/README.md new file mode 100644 index 000000000..e69de29bb diff --git a/units/zh-TW/unit3/agentic-rag/agent.mdx b/units/zh-TW/unit3/agentic-rag/agent.mdx new file mode 100644 index 000000000..b2c36b61d --- /dev/null +++ b/units/zh-TW/unit3/agentic-rag/agent.mdx @@ -0,0 +1,499 @@ +# 建立你的晚宴 agent + +現在我們已為 Alfred 建好所有必要元件,接下來把它們組合成完整的 agent,協助主持這場奢華晚宴。 + +本節將把賓客資訊檢索、網頁搜尋、天氣資訊與 Hub 統計工具,整合成一個功能強大的 agent。 + +## 組裝 Alfred:完整的 agent + +前幾節建立的工具無須重新實作,只要從儲存在 `tools.py` 與 `retriever.py` 檔案中的對應模組匯入即可。 + +> [!TIP] +> 如果你還沒實作這些工具,請回到工具與檢索器章節完成實作,並將它們加入 tools.py 與 retriever.py 檔案。 + +先匯入必要的函式庫,以及前幾節建立的工具: + + + + +```python +# Import necessary libraries +import random +from smolagents import CodeAgent, InferenceClientModel + +# Import our custom tools from their modules +from tools import DuckDuckGoSearchTool, WeatherInfoTool, HubStatsTool +from retriever import load_guest_dataset +``` + +接著,將所有工具整合到同一個 agent: + +```python +# Initialize the Hugging Face model +model = InferenceClientModel() + +# Initialize the web search tool +search_tool = DuckDuckGoSearchTool() + +# Initialize the weather tool +weather_info_tool = WeatherInfoTool() + +# Initialize the Hub stats tool +hub_stats_tool = HubStatsTool() + +# Load the guest dataset and initialize the guest info tool +guest_info_tool = load_guest_dataset() + +# Create Alfred with all the tools +alfred = CodeAgent( + tools=[guest_info_tool, weather_info_tool, hub_stats_tool, search_tool], + model=model, + add_base_tools=True, # Add any additional base tools + planning_interval=3 # Enable planning every 3 steps +) +``` + + + + +```python +# Import necessary libraries +from llama_index.core.agent.workflow import AgentWorkflow +from llama_index.llms.huggingface_api import HuggingFaceInferenceAPI + +from tools import search_tool, weather_info_tool, hub_stats_tool +from retriever import guest_info_tool +``` + +接著,將所有工具整合到同一個 agent: + +```python +# Initialize the Hugging Face model +llm = HuggingFaceInferenceAPI(model_name="Qwen/Qwen2.5-Coder-32B-Instruct") + +# Create Alfred with all the tools +alfred = AgentWorkflow.from_tools_or_functions( + [guest_info_tool, search_tool, weather_info_tool, hub_stats_tool], + llm=llm, +) +``` + + + + +```python +from typing import TypedDict, Annotated +from langgraph.graph.message import add_messages +from langchain_core.messages import AnyMessage, HumanMessage, AIMessage +from langgraph.prebuilt import ToolNode +from langgraph.graph import START, StateGraph +from langgraph.prebuilt import tools_condition +from langchain_huggingface import HuggingFaceEndpoint, ChatHuggingFace + +from tools import DuckDuckGoSearchRun, weather_info_tool, hub_stats_tool +from retriever import guest_info_tool +``` + +接著,將所有工具整合到同一個 agent: + +```python +# Initialize the web search tool +search_tool = DuckDuckGoSearchRun() + +# Generate the chat interface, including the tools +llm = HuggingFaceEndpoint( + repo_id="Qwen/Qwen2.5-Coder-32B-Instruct", + huggingfacehub_api_token=HUGGINGFACEHUB_API_TOKEN, +) + +chat = ChatHuggingFace(llm=llm, verbose=True) +tools = [guest_info_tool, search_tool, weather_info_tool, hub_stats_tool] +chat_with_tools = chat.bind_tools(tools) + +# Generate the AgentState and Agent graph +class AgentState(TypedDict): + messages: Annotated[list[AnyMessage], add_messages] + +def assistant(state: AgentState): + return { + "messages": [chat_with_tools.invoke(state["messages"])], + } + +## The graph +builder = StateGraph(AgentState) + +# Define nodes: these do the work +builder.add_node("assistant", assistant) +builder.add_node("tools", ToolNode(tools)) + +# Define edges: these determine how the control flow moves +builder.add_edge(START, "assistant") +builder.add_conditional_edges( + "assistant", + # If the latest message requires a tool, route to tools + # Otherwise, provide a direct response + tools_condition, +) +builder.add_edge("tools", "assistant") +alfred = builder.compile() +``` + + + +你的 agent 現在可以使用了! + +## 使用 Alfred:端到端範例 + +Alfred 已具備所有必要工具,來看看他如何協助處理晚宴期間的各種任務。 + +### 範例 1:查詢賓客資訊 + +來看看 Alfred 如何協助查詢賓客資訊。 + + + + +```python +query = "Tell me about 'Lady Ada Lovelace'" +response = alfred.run(query) + +print("🎩 Alfred's Response:") +print(response) +``` + +預期輸出: + +``` +🎩 Alfred's Response: +Based on the information I retrieved, Lady Ada Lovelace is an esteemed mathematician and friend. She is renowned for her pioneering work in mathematics and computing, often celebrated as the first computer programmer due to her work on Charles Babbage's Analytical Engine. Her email address is ada.lovelace@example.com. +``` + + + + +```python +query = "Tell me about Lady Ada Lovelace. What's her background?" +response = await alfred.run(query) + +print("🎩 Alfred's Response:") +print(response.response.blocks[0].text) +``` + +預期輸出: + +``` +🎩 Alfred's Response: +Lady Ada Lovelace was an English mathematician and writer, best known for her work on Charles Babbage's Analytical Engine. She was the first to recognize that the machine had applications beyond pure calculation. +``` + + + + +```python +response = alfred.invoke({"messages": "Tell me about 'Lady Ada Lovelace'"}) + +print("🎩 Alfred's Response:") +print(response['messages'][-1].content) +``` + +預期輸出: + +``` +🎩 Alfred's Response: +Ada Lovelace, also known as Augusta Ada King, Countess of Lovelace, was an English mathematician and writer. Born on December 10, 1815, and passing away on November 27, 1852, she is renowned for her work on Charles Babbage's Analytical Engine, a proposed mechanical general-purpose computer. Ada Lovelace is celebrated as one of the first computer programmers because she created a program for the Analytical Engine in 1843. She recognized that the machine could be used for more than mere calculation, envisioning its potential in a way that few did at the time. Her contributions to the field of computer science laid the groundwork for future developments. A day in October, designated as Ada Lovelace Day, honors women's contributions to science and technology, inspired by Lovelace's pioneering work. +``` + + + + +### 範例 2:查詢天氣,安排煙火秀 + +來看看 Alfred 如何協助查詢天氣。 + + + + +```python +query = "What's the weather like in Paris tonight? Will it be suitable for our fireworks display?" +response = alfred.run(query) + +print("🎩 Alfred's Response:") +print(response) +``` + +預期輸出(會因隨機性而有所不同): +``` +🎩 Alfred's Response: +I've checked the weather in Paris for you. Currently, it's clear with a temperature of 25°C. These conditions are perfect for the fireworks display tonight. The clear skies will provide excellent visibility for the spectacular show, and the comfortable temperature will ensure the guests can enjoy the outdoor event without discomfort. +``` + + + + +```python +query = "What's the weather like in Paris tonight? Will it be suitable for our fireworks display?" +response = await alfred.run(query) + +print("🎩 Alfred's Response:") +print(response) +``` + +預期輸出: + +``` +🎩 Alfred's Response: +The weather in Paris tonight is rainy with a temperature of 15°C. Given the rain, it may not be suitable for a fireworks display. +``` + + + + +```python +response = alfred.invoke({"messages": "What's the weather like in Paris tonight? Will it be suitable for our fireworks display?"}) + +print("🎩 Alfred's Response:") +print(response['messages'][-1].content) +``` + +預期輸出: + +``` +🎩 Alfred's Response: +The weather in Paris tonight is rainy with a temperature of 15°C, which may not be suitable for your fireworks display. +``` + + + +### 範例 3:讓 AI 研究人員留下深刻印象 + +來看看 Alfred 如何協助我們,讓 AI 研究人員留下深刻印象。 + + + + +```python +query = "One of our guests is from Qwen. What can you tell me about their most popular model?" +response = alfred.run(query) + +print("🎩 Alfred's Response:") +print(response) +``` + +預期輸出: + +``` +🎩 Alfred's Response: +The most popular Qwen model is Qwen/Qwen2.5-VL-7B-Instruct with 3,313,345 downloads. +``` + + + +```python +query = "One of our guests is from Google. What can you tell me about their most popular model?" +response = await alfred.run(query) + +print("🎩 Alfred's Response:") +print(response) +``` + +預期輸出: + +``` +🎩 Alfred's Response: +The most popular model by Google on the Hugging Face Hub is google/electra-base-discriminator, with 28,546,752 downloads. +``` + + + + +```python +response = alfred.invoke({"messages": "One of our guests is from Qwen. What can you tell me about their most popular model?"}) + +print("🎩 Alfred's Response:") +print(response['messages'][-1].content) +``` + +預期輸出: + +``` +🎩 Alfred's Response: +The most downloaded model by Qwen is Qwen/Qwen2.5-VL-7B-Instruct with 3,313,345 downloads. +``` + + + +### 範例 4:結合多項工具 + +來看看 Alfred 如何協助我們,為與 Nikola Tesla 博士的交談做好準備。 + + + + +```python +query = "I need to speak with Dr. Nikola Tesla about recent advancements in wireless energy. Can you help me prepare for this conversation?" +response = alfred.run(query) + +print("🎩 Alfred's Response:") +print(response) +``` + +預期輸出: + +``` +🎩 Alfred's Response: +I've gathered information to help you prepare for your conversation with Dr. Nikola Tesla. + +Guest Information: +Name: Dr. Nikola Tesla +Relation: old friend from university days +Description: Dr. Nikola Tesla is an old friend from your university days. He's recently patented a new wireless energy transmission system and would be delighted to discuss it with you. Just remember he's passionate about pigeons, so that might make for good small talk. +Email: nikola.tesla@gmail.com + +Recent Advancements in Wireless Energy: +Based on my web search, here are some recent developments in wireless energy transmission: +1. Researchers have made progress in long-range wireless power transmission using focused electromagnetic waves +2. Several companies are developing resonant inductive coupling technologies for consumer electronics +3. There are new applications in electric vehicle charging without physical connections + +Conversation Starters: +1. "I'd love to hear about your new patent on wireless energy transmission. How does it compare to your original concepts from our university days?" +2. "Have you seen the recent developments in resonant inductive coupling for consumer electronics? What do you think of their approach?" +3. "How are your pigeons doing? I remember your fascination with them." + +This should give you plenty to discuss with Dr. Tesla while demonstrating your knowledge of his interests and recent developments in his field. +``` + + + + +```python +query = "I need to speak with Dr. Nikola Tesla about recent advancements in wireless energy. Can you help me prepare for this conversation?" +response = await alfred.run(query) + +print("🎩 Alfred's Response:") +print(response) +``` + +預期輸出: + +``` +🎩 Alfred's Response: +Here are some recent advancements in wireless energy that you might find useful for your conversation with Dr. Nikola Tesla: + +1. **Advancements and Challenges in Wireless Power Transfer**: This article discusses the evolution of wireless power transfer (WPT) from conventional wired methods to modern applications, including solar space power stations. It highlights the initial focus on microwave technology and the current demand for WPT due to the rise of electric devices. + +2. **Recent Advances in Wireless Energy Transfer Technologies for Body-Interfaced Electronics**: This article explores wireless energy transfer (WET) as a solution for powering body-interfaced electronics without the need for batteries or lead wires. It discusses the advantages and potential applications of WET in this context. + +3. **Wireless Power Transfer and Energy Harvesting: Current Status and Future Trends**: This article provides an overview of recent advances in wireless power supply methods, including energy harvesting and wireless power transfer. It presents several promising applications and discusses future trends in the field. + +4. **Wireless Power Transfer: Applications, Challenges, Barriers, and the +``` + + + + +```python +response = alfred.invoke({"messages":"I need to speak with 'Dr. Nikola Tesla' about recent advancements in wireless energy. Can you help me prepare for this conversation?"}) + +print("🎩 Alfred's Response:") +print(response['messages'][-1].content) +``` + +預期輸出: + +``` +Based on the provided information, here are key points to prepare for the conversation with 'Dr. Nikola Tesla' about recent advancements in wireless energy:\n1. **Wireless Power Transmission (WPT):** Discuss how WPT revolutionizes energy transfer by eliminating the need for cords and leveraging mechanisms like inductive and resonant coupling.\n2. **Advancements in Wireless Charging:** Highlight improvements in efficiency, faster charging speeds, and the rise of Qi/Qi2 certified wireless charging solutions.\n3. **5G-Advanced Innovations and NearLink Wireless Protocol:** Mention these as developments that enhance speed, security, and efficiency in wireless networks, which can support advanced wireless energy technologies.\n4. **AI and ML at the Edge:** Talk about how AI and machine learning will rely on wireless networks to bring intelligence to the edge, enhancing automation and intelligence in smart homes and buildings.\n5. **Matter, Thread, and Security Advancements:** Discuss these as key innovations that drive connectivity, efficiency, and security in IoT devices and systems.\n6. **Breakthroughs in Wireless Charging Technology:** Include any recent breakthroughs or studies, such as the one from Incheon National University, to substantiate the advancements in wireless charging. +``` + + + +## 進階功能:對話記憶 + +為了讓 Alfred 在晚宴中提供更多協助,可以啟用對話記憶,讓他記住先前的互動: + + + + +```python +# Create Alfred with conversation memory +alfred_with_memory = CodeAgent( + tools=[guest_info_tool, weather_info_tool, hub_stats_tool, search_tool], + model=model, + add_base_tools=True, + planning_interval=3 +) + +# First interaction +response1 = alfred_with_memory.run("Tell me about Lady Ada Lovelace.") +print("🎩 Alfred's First Response:") +print(response1) + +# Second interaction (referencing the first) +response2 = alfred_with_memory.run("What projects is she currently working on?", reset=False) +print("🎩 Alfred's Second Response:") +print(response2) +``` + + + + +```python +from llama_index.core.workflow import Context + +alfred = AgentWorkflow.from_tools_or_functions( + [guest_info_tool, search_tool, weather_info_tool, hub_stats_tool], + llm=llm +) + +# Remembering state +ctx = Context(alfred) + +# First interaction +response1 = await alfred.run("Tell me about Lady Ada Lovelace.", ctx=ctx) +print("🎩 Alfred's First Response:") +print(response1) + +# Second interaction (referencing the first) +response2 = await alfred.run("What projects is she currently working on?", ctx=ctx) +print("🎩 Alfred's Second Response:") +print(response2) +``` + + + + +```python +# First interaction +response = alfred.invoke({"messages": [HumanMessage(content="Tell me about 'Lady Ada Lovelace'. What's her background and how is she related to me?")]}) + + +print("🎩 Alfred's Response:") +print(response['messages'][-1].content) +print() + +# Second interaction (referencing the first) +response = alfred.invoke({"messages": response["messages"] + [HumanMessage(content="What projects is she currently working on?")]}) + +print("🎩 Alfred's Response:") +print(response['messages'][-1].content) +``` + + + + +請注意,這三種建立 agent 的方法,都沒有直接將記憶與 agent 綁定在一起。這樣的設計選擇有什麼特別的原因嗎 🧐? +* smolagents:不同次執行之間不會保留記憶,必須明確設定 `reset=False`。 +* LlamaIndex:需要明確加入上下文物件,才能在一次執行中管理記憶。 +* LangGraph:可以選擇擷取先前的訊息,或使用專門的 [MemorySaver](https://langchain-ai.github.io/langgraph/tutorials/introduction/#part-3-adding-memory-to-the-chatbot) 元件。 + +## 結語 + +恭喜!你已成功建立 Alfred 這個功能完善的 agent。他具備多種工具,能協助主持本世紀最奢華的晚宴。Alfred 現在可以: + +1. 擷取賓客的詳細資訊 +2. 查詢天氣狀況,規劃戶外活動 +3. 提供具影響力的 AI 開發者及其模型的相關資訊 +4. 搜尋網頁,取得最新資訊 +5. 透過記憶保留對話上下文 + +有了這些能力,Alfred 已準備好運用貼心的個人化服務與最新資訊,讓賓客留下深刻印象,確保你的晚宴圓滿成功。 diff --git a/units/zh-TW/unit3/agentic-rag/agentic-rag.mdx b/units/zh-TW/unit3/agentic-rag/agentic-rag.mdx new file mode 100644 index 000000000..3d4db79f8 --- /dev/null +++ b/units/zh-TW/unit3/agentic-rag/agentic-rag.mdx @@ -0,0 +1,28 @@ +# Agentic 檢索增強生成(RAG) + +本單元將介紹如何運用 Agentic RAG,協助 Alfred 準備這場精彩的晚宴。 + +> [!TIP] +> 前一單元已介紹過檢索增強生成(RAG)與 Agentic RAG。如果你已熟悉這些概念,可以直接跳到後面的內容。 + +LLM 透過大量資料訓練,學習一般知識。 +然而,LLM 掌握的世界知識未必與當下需求相關,也未必是最新資訊。 +**RAG 會從你的資料中找出並擷取相關資訊,再傳給 LLM,以解決這個問題。** + +![RAG](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit2/llama-index/rag.png) + +現在想想 Alfred 的工作方式: + +1. 我們請 Alfred 協助規劃晚宴 +2. Alfred 需要尋找最新消息與天氣資訊 +3. Alfred 需要整理賓客資訊,並能搜尋這些資料 + +就像 Alfred 必須搜尋你家中的相關資訊才能提供協助,任何 agent 都需要一套方法,來尋找並理解相關資料。 +**Agentic RAG 能有效運用 agent,回答關於你所持有資料的問題。** 我們可以提供各種工具,協助 Alfred 回答問題。 +不過,Alfred 不必只根據文件自動回答,也可以自行決定使用其他工具或流程來解答。 + +![Agentic RAG](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit2/llama-index/agentic-rag.png) + +開始**建立我們的 Agentic RAG 工作流程吧!** + +首先,建立 RAG 工具來擷取受邀賓客的最新詳細資料。接著,開發網頁搜尋、天氣查詢,以及 Hugging Face Hub 模型下載統計工具。最後,整合所有元件,讓我們的 Agentic RAG agent 正式運作! diff --git a/units/zh-TW/unit3/agentic-rag/conclusion.mdx b/units/zh-TW/unit3/agentic-rag/conclusion.mdx new file mode 100644 index 000000000..0d342e258 --- /dev/null +++ b/units/zh-TW/unit3/agentic-rag/conclusion.mdx @@ -0,0 +1,19 @@ +# 結語 + +本單元中,我們學會建立 Agentic RAG 系統,協助親切的好鄰居 agent Alfred 準備並管理一場奢華晚宴。 + +將 RAG 與 agent 的能力結合,展現了 AI 助理在具備下列能力後,可以發揮多大的作用: +- 存取結構化知識(賓客資訊) +- 擷取即時資訊(網頁搜尋) +- 使用特定領域的工具(天氣資訊、Hub 統計資料) +- 記住過去的互動 + +有了這些能力,Alfred 已準備好成為出色的主人:回答關於賓客的問題、提供最新資訊,並確保晚宴順利進行,甚至能掌握施放煙火的最佳時機! + +> [!TIP] +> 現在你已建立完整的 agent,接下來不妨探索: +> +> - 針對自己的應用情境,建立更專門的工具 +> - 運用嵌入向量,實作更進階的 RAG 系統 +> - 建立讓 agent 彼此協作的多 agent 系統 +> - 將 agent 部署成可供他人互動的服務 diff --git a/units/zh-TW/unit3/agentic-rag/introduction.mdx b/units/zh-TW/unit3/agentic-rag/introduction.mdx new file mode 100644 index 000000000..70357db6a --- /dev/null +++ b/units/zh-TW/unit3/agentic-rag/introduction.mdx @@ -0,0 +1,39 @@ +# Agentic RAG 應用案例介紹 + +![Agentic RAG 橫幅](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit3/agentic-rag/thumbnail.jpg) + +本單元將運用 Agentic RAG,為負責主持晚宴的親切 agent Alfred 建立工具,幫助他回答關於晚宴賓客的問題。 + +> [!TIP] +> 這是 Agentic RAG 的實際應用案例,你也可以用在自己的專案或工作中。如果想從這個專案學到更多,不妨試著套用到自己的應用情境,再到 Discord 分享成果! + +你可以選用課程中介紹的任何框架。我們在各個分頁中提供了對應的程式碼範例。 + +## 一場令人難忘的晚宴 + +現在就來動手實作,先設定這個案例的背景吧! + +**你決定舉辦本世紀最奢華、最盛大的派對。** 現場將有豐盛的宴席、迷人的舞者、知名 DJ、精緻飲品、令人驚豔的煙火秀,以及更多精彩節目。 + +你親切的好鄰居 agent Alfred,正準備照料這場派對的各種需求,**而且 Alfred 打算親自管理所有事務**。為此,他需要取得派對的所有資訊,包括菜單、賓客、活動時程、天氣預報等等! + +此外,他還得確保派對圓滿成功,因此**必須能在派對期間回答任何與派對有關的問題**,同時處理可能發生的突發狀況。 + +他無法獨力完成這些事,所以我們要確保 Alfred 能取得所需的所有資訊與工具。 + +首先,來列出這場晚宴必須滿足的需求。 + +## 晚宴需求 + +在**文藝復興時期**,一位受過良好教育的人應具備三項主要素養。 +也就是精通**運動、文化與科學知識**。因此,我們得確保自己能以豐富的知識讓賓客留下深刻印象,為他們帶來真正難忘的晚宴。 +不過,為了避免衝突,**晚宴中應避開政治與宗教等話題。** 這應該是一場歡樂的派對,不該因信仰與理念的差異而起爭執。 + +依照社交禮儀,**好主人應了解賓客的背景**,包括他們的興趣與事業。好主人也會聊聊賓客的趣聞,讓大家彼此分享故事。 + +最後,我們也得具備**一些天氣常識**,並能持續查詢即時天氣,才能選在最合適的時機施放煙火,為晚宴畫下精彩的句點!🎆 + +可見 Alfred 需要大量資訊,才能主持好這場晚宴。 +幸好,我們可以透過**檢索增強生成(Retrieval Augmented Generation,RAG)訓練**,協助 Alfred 做好準備! + +現在就開始建立 Alfred 主持晚宴所需的工具吧! diff --git a/units/zh-TW/unit3/agentic-rag/invitees.mdx b/units/zh-TW/unit3/agentic-rag/invitees.mdx new file mode 100644 index 000000000..16b62ce43 --- /dev/null +++ b/units/zh-TW/unit3/agentic-rag/invitees.mdx @@ -0,0 +1,455 @@ +# 建立賓客故事查詢的 RAG 工具 + +你信賴的 agent Alfred,正為本世紀最奢華的晚宴做準備。為了確保活動順利進行,Alfred 需要快速取得每位賓客的最新資訊。我們就用自己的資料集,為他建立一個自訂的檢索增強生成(RAG)工具吧。 + +## 晚宴為什麼需要 RAG? + +想像 Alfred 穿梭在賓客之間,隨時都可能需要想起某個人的特定細節。傳統 LLM 可能難以完成這項任務,因為: + +1. 賓客名單是這場活動專屬的資料,並不在模型的訓練資料中 +2. 賓客資訊可能經常變動或更新 +3. Alfred 需要擷取電子郵件地址等精確資訊 + +這正是檢索增強生成(RAG)能發揮作用的地方!結合檢索系統與 LLM,Alfred 就能隨時依需求取得正確、最新的賓客資訊。 + +> [!TIP] +> 這個應用案例可以使用課程中介紹的任何框架。請在程式碼分頁中選擇你偏好的框架。 + +## 設定應用程式 + +本單元會在 HF Space 中,以結構化的 Python 專案開發 agent。將不同功能放在各自的檔案中,有助於維持程式碼清楚、模組化的結構。這也更貼近實際將應用程式部署給大眾使用的情境。 + +### 專案結構 + +- **`tools.py`**:提供 agent 使用的輔助工具。 +- **`retriever.py`**:實作檢索功能,支援知識存取。 +- **`app.py`**:將所有元件整合成完整可用的 agent,我們會在本單元最後完成它。 + +想參考實際成果,可以看看[這個 HF Space](https://huggingface.co/spaces/agents-course/Unit_3_Agentic_RAG),裡面已部署本單元開發的 Agentic RAG。歡迎複製下來動手實驗! + +你可以直接在下方測試這個 agent: + + + +## 資料集概覽 + +我們的資料集 [`agents-course/unit3-invitees`](https://huggingface.co/datasets/agents-course/unit3-invitees/) 包含每位賓客的下列欄位: + +- **Name**:賓客全名 +- **Relation**:賓客與主人的關係 +- **Description**:賓客的簡短生平或趣事 +- **Email Address**:寄送邀請或後續聯絡所需的聯絡資訊 + +以下是資料集的預覽: + + +> [!TIP] +> 實際應用時,還可以在資料集中加入飲食偏好、喜歡的禮物類型、應避免的話題,以及其他對主人有幫助的細節。 + +## 建立賓客名冊工具 + +我們將建立自訂工具,讓 Alfred 在晚宴期間快速擷取賓客資訊。這項工作可以分成三個步驟: + +1. 載入並準備資料集 +2. 建立檢索器工具 +3. 將工具整合到 Alfred + +先從載入並準備資料集開始吧! + +### 步驟 1:載入並準備資料集 + +首先,需要把原始賓客資料轉換成適合檢索的格式。 + + + + +我們會使用 Hugging Face 的 `datasets` 函式庫載入資料集,再將它轉成 `langchain.docstore.document` 模組中 `Document` 物件的清單。 + +```python +import datasets +from langchain_core.documents import Document + +# Load the dataset +guest_dataset = datasets.load_dataset("agents-course/unit3-invitees", split="train") + +# Convert dataset entries into Document objects +docs = [ + Document( + page_content="\n".join([ + f"Name: {guest['name']}", + f"Relation: {guest['relation']}", + f"Description: {guest['description']}", + f"Email: {guest['email']}" + ]), + metadata={"name": guest["name"]} + ) + for guest in guest_dataset +] + +``` + + + + +我們會使用 Hugging Face 的 `datasets` 函式庫載入資料集,再將它轉成 `llama_index.core.schema` 模組中 `Document` 物件的清單。 + +```python +import datasets +from llama_index.core.schema import Document + +# Load the dataset +guest_dataset = datasets.load_dataset("agents-course/unit3-invitees", split="train") + +# Convert dataset entries into Document objects +docs = [ + Document( + text="\n".join([ + f"Name: {guest_dataset['name'][i]}", + f"Relation: {guest_dataset['relation'][i]}", + f"Description: {guest_dataset['description'][i]}", + f"Email: {guest_dataset['email'][i]}" + ]), + metadata={"name": guest_dataset['name'][i]} + ) + for i in range(len(guest_dataset)) +] +``` + + + + +我們會使用 Hugging Face 的 `datasets` 函式庫載入資料集,再將它轉成 `langchain.docstore.document` 模組中 `Document` 物件的清單。 + +```python +import datasets +from langchain_core.documents import Document + +# Load the dataset +guest_dataset = datasets.load_dataset("agents-course/unit3-invitees", split="train") + +# Convert dataset entries into Document objects +docs = [ + Document( + page_content="\n".join([ + f"Name: {guest['name']}", + f"Relation: {guest['relation']}", + f"Description: {guest['description']}", + f"Email: {guest['email']}" + ]), + metadata={"name": guest["name"]} + ) + for guest in guest_dataset +] +``` + + + + +上述程式碼會: +- 載入資料集 +- 將每筆賓客資料轉成內容經過格式化的 `Document` 物件 +- 把 `Document` 物件儲存在清單中 + +所有資料都已準備好,接下來就能設定檢索功能。 + +### 步驟 2:建立檢索器工具 + +現在來建立自訂工具,讓 Alfred 能搜尋我們的賓客資訊。 + + + + +我們會使用 `langchain_community.retrievers` 模組的 `BM25Retriever`,建立檢索器工具。 + +> [!TIP] +> BM25Retriever 很適合作為檢索的起點。如果需要更進階的語意搜尋,可以考慮使用以嵌入向量為基礎的檢索器,例如 sentence-transformers 提供的工具。 + +```python +from smolagents import Tool +from langchain_community.retrievers import BM25Retriever + +class GuestInfoRetrieverTool(Tool): + name = "guest_info_retriever" + description = "Retrieves detailed information about gala guests based on their name or relation." + inputs = { + "query": { + "type": "string", + "description": "The name or relation of the guest you want information about." + } + } + output_type = "string" + + def __init__(self, docs): + self.is_initialized = False + self.retriever = BM25Retriever.from_documents(docs) + + def forward(self, query: str): + results = self.retriever.invoke(query) + if results: + return "\n\n".join([doc.page_content for doc in results[:3]]) + else: + return "No matching guest information found." + +# Initialize the tool +guest_info_tool = GuestInfoRetrieverTool(docs) +``` + +逐步看看這個工具如何運作: +- `name` 與 `description` 協助 agent 了解何時、如何使用這個工具 +- `inputs` 定義工具所需的參數(這裡是搜尋查詢) +- 我們使用 `BM25Retriever`,這是一種強大的文字檢索演算法,無須使用嵌入向量 +- `forward` 方法處理查詢,並回傳最相關的賓客資訊 + + + + +我們會使用 `llama_index.retrievers.bm25` 模組的 `BM25Retriever`,建立檢索器工具。 + +> [!TIP] +> BM25Retriever 很適合作為檢索的起點。如果需要更進階的語意搜尋,可以考慮使用以嵌入向量為基礎的檢索器,例如 sentence-transformers 提供的工具。 + +```python +from llama_index.core.tools import FunctionTool +from llama_index.retrievers.bm25 import BM25Retriever + +bm25_retriever = BM25Retriever.from_defaults(nodes=docs) + +def get_guest_info_retriever(query: str) -> str: + """Retrieves detailed information about gala guests based on their name or relation.""" + results = bm25_retriever.retrieve(query) + if results: + return "\n\n".join([doc.text for doc in results[:3]]) + else: + return "No matching guest information found." + +# Initialize the tool +guest_info_tool = FunctionTool.from_defaults(get_guest_info_retriever) +``` + +逐步看看這個工具如何運作: +- docstring 協助 agent 了解何時、如何使用這個工具 +- 型別裝飾器定義工具所需的參數(這裡是搜尋查詢) +- 我們使用 `BM25Retriever`,這是一種強大的文字檢索演算法,無須使用嵌入向量 +- 這個方法處理查詢,並回傳最相關的賓客資訊 + + + + +我們會使用 `langchain_community.retrievers` 模組的 `BM25Retriever`,建立檢索器工具。 + +> [!TIP] +> BM25Retriever 很適合作為檢索的起點。如果需要更進階的語意搜尋,可以考慮使用以嵌入向量為基礎的檢索器,例如 sentence-transformers 提供的工具。 + +```python +from langchain_community.retrievers import BM25Retriever +from langchain_core.tools import Tool + +bm25_retriever = BM25Retriever.from_documents(docs) + +def extract_text(query: str) -> str: + """Retrieves detailed information about gala guests based on their name or relation.""" + results = bm25_retriever.invoke(query) + if results: + return "\n\n".join([doc.page_content for doc in results[:3]]) + else: + return "No matching guest information found." + +guest_info_tool = Tool( + name="guest_info_retriever", + func=extract_text, + description="Retrieves detailed information about gala guests based on their name or relation." +) +``` + +逐步看看這個工具如何運作: +- `name` 與 `description` 協助 agent 了解何時、如何使用這個工具 +- 型別裝飾器定義工具所需的參數(這裡是搜尋查詢) +- 我們使用 `BM25Retriever`,這是一種強大的文字檢索演算法,無須使用嵌入向量 +- 這個方法處理查詢,並回傳最相關的賓客資訊 + + + + +### 步驟 3:將工具整合到 Alfred + +最後,建立 agent 並為它加入自訂工具,把一切整合起來: + + + + +```python +from smolagents import CodeAgent, InferenceClientModel + +# Initialize the Hugging Face model +model = InferenceClientModel() + +# Create Alfred, our gala agent, with the guest info tool +alfred = CodeAgent(tools=[guest_info_tool], model=model) + +# Example query Alfred might receive during the gala +response = alfred.run("Tell me about our guest named 'Lady Ada Lovelace'.") + +print("🎩 Alfred's Response:") +print(response) +``` + +預期輸出: + +``` +🎩 Alfred's Response: +Based on the information I retrieved, Lady Ada Lovelace is an esteemed mathematician and friend. She is renowned for her pioneering work in mathematics and computing, often celebrated as the first computer programmer due to her work on Charles Babbage's Analytical Engine. Her email address is ada.lovelace@example.com. +``` + +最後這個步驟會: +- 使用 `InferenceClientModel` 類別初始化 Hugging Face 模型 +- 以 `CodeAgent` 建立我們的 agent(Alfred),讓它能執行 Python 程式碼來解決問題 +- 請 Alfred 擷取名為「Lady Ada Lovelace」的賓客資訊 + + + + +```python +from llama_index.core.agent.workflow import AgentWorkflow +from llama_index.llms.huggingface_api import HuggingFaceInferenceAPI + +# Initialize the Hugging Face model +llm = HuggingFaceInferenceAPI(model_name="Qwen/Qwen2.5-Coder-32B-Instruct") + +# Create Alfred, our gala agent, with the guest info tool +alfred = AgentWorkflow.from_tools_or_functions( + [guest_info_tool], + llm=llm, +) + +# Example query Alfred might receive during the gala +response = await alfred.run("Tell me about our guest named 'Lady Ada Lovelace'.") + +print("🎩 Alfred's Response:") +print(response) +``` + +預期輸出: + +``` +🎩 Alfred's Response: +Lady Ada Lovelace is an esteemed mathematician and friend, renowned for her pioneering work in mathematics and computing. She is celebrated as the first computer programmer due to her work on Charles Babbage's Analytical Engine. Her email is ada.lovelace@example.com. +``` + +最後這個步驟會: +- 使用 `HuggingFaceInferenceAPI` 類別初始化 Hugging Face 模型 +- 以 `AgentWorkflow` 建立我們的 agent(Alfred),並加入剛才建立的工具 +- 請 Alfred 擷取名為「Lady Ada Lovelace」的賓客資訊 + + + + +```python +from typing import TypedDict, Annotated +from langgraph.graph.message import add_messages +from langchain_core.messages import AnyMessage, HumanMessage, AIMessage +from langgraph.prebuilt import ToolNode +from langgraph.graph import START, StateGraph +from langgraph.prebuilt import tools_condition +from langchain_huggingface import HuggingFaceEndpoint, ChatHuggingFace + +# Generate the chat interface, including the tools +llm = HuggingFaceEndpoint( + repo_id="Qwen/Qwen2.5-Coder-32B-Instruct", + huggingfacehub_api_token=HUGGINGFACEHUB_API_TOKEN, +) + +chat = ChatHuggingFace(llm=llm, verbose=True) +tools = [guest_info_tool] +chat_with_tools = chat.bind_tools(tools) + +# Generate the AgentState and Agent graph +class AgentState(TypedDict): + messages: Annotated[list[AnyMessage], add_messages] + +def assistant(state: AgentState): + return { + "messages": [chat_with_tools.invoke(state["messages"])], + } + +## The graph +builder = StateGraph(AgentState) + +# Define nodes: these do the work +builder.add_node("assistant", assistant) +builder.add_node("tools", ToolNode(tools)) + +# Define edges: these determine how the control flow moves +builder.add_edge(START, "assistant") +builder.add_conditional_edges( + "assistant", + # If the latest message requires a tool, route to tools + # Otherwise, provide a direct response + tools_condition, +) +builder.add_edge("tools", "assistant") +alfred = builder.compile() + +messages = [HumanMessage(content="Tell me about our guest named 'Lady Ada Lovelace'.")] +response = alfred.invoke({"messages": messages}) + +print("🎩 Alfred's Response:") +print(response['messages'][-1].content) +``` + +預期輸出: + +``` +🎩 Alfred's Response: +Lady Ada Lovelace is an esteemed mathematician and pioneer in computing, often celebrated as the first computer programmer due to her work on Charles Babbage's Analytical Engine. +``` + +最後這個步驟會: +- 使用 `HuggingFaceEndpoint` 類別初始化 Hugging Face 模型,並建立聊天介面、加入工具 +- 以 `StateGraph` 建立我們的 agent(Alfred),用邊連接兩個節點(`assistant`、`tools`) +- 請 Alfred 擷取名為「Lady Ada Lovelace」的賓客資訊 + + + + +## 互動範例 + +晚宴期間,可能會出現這樣的對話: + +**你:**「Alfred,正在跟大使聊天的那位先生是誰?」 + +**Alfred:***快速搜尋賓客資料庫*「先生,那位是 Nikola Tesla 博士,是您大學時期的老朋友。他最近為一套新的無線能源傳輸系統取得專利,一定很樂意與您討論。別忘了,他非常喜歡鴿子,這或許是個不錯的閒聊話題。」 + +```json +{ + "name": "Dr. Nikola Tesla", + "relation": "old friend from university days", + "description": "Dr. Nikola Tesla is an old friend from your university days. He's recently patented a new wireless energy transmission system and would be delighted to discuss it with you. Just remember he's passionate about pigeons, so that might make for good small talk.", + "email": "nikola.tesla@gmail.com" +} +``` + +## 進一步延伸 + +現在 Alfred 已能擷取賓客資訊,接下來可以思考如何改進這個系統: + +1. **改進檢索器**,使用 [sentence-transformers](https://www.sbert.net/) 等更進階的演算法 +2. **實作對話記憶**,讓 Alfred 記住先前的互動 +3. **結合網頁搜尋**,取得不熟悉賓客的最新資訊 +4. **整合多個索引**,從經過驗證的來源取得更完整的資訊 + +Alfred 現在已準備好輕鬆應對賓客的各種詢問,讓你的晚宴成為本世紀最有深度、最令人愉快的盛會! + +> [!TIP] +> 試著擴充檢索器工具,讓它也能根據每位賓客的興趣或背景,回傳適合開啟對話的話題。你會如何修改工具來達成這個目標? +> +> 完成後,請將賓客檢索器工具實作在 retriever.py 檔案中。 diff --git a/units/zh-TW/unit3/agentic-rag/tools.mdx b/units/zh-TW/unit3/agentic-rag/tools.mdx new file mode 100644 index 000000000..749799a2e --- /dev/null +++ b/units/zh-TW/unit3/agentic-rag/tools.mdx @@ -0,0 +1,431 @@ +# 為 agent 建立並整合工具 + +本節將讓 Alfred 存取網路,取得最新消息與世界各地的動態。 +此外,他也能取得天氣資料與 Hugging Face Hub 模型下載統計,藉此聊聊最新話題。 + +## 讓 agent 存取網路 + +別忘了,我們希望 Alfred 成為博學多聞、具有文藝復興精神的主人。 + +為此,必須確保 Alfred 能取得世界各地的最新消息與資訊。 + +先為 Alfred 建立網頁搜尋工具吧! + + + + +```python +from smolagents import DuckDuckGoSearchTool + +# Initialize the DuckDuckGo search tool +search_tool = DuckDuckGoSearchTool() + +# Example usage +results = search_tool("Who's the current President of France?") +print(results) +``` + +預期輸出: + +``` +The current President of France in Emmanuel Macron. +``` + + + + +```python +from llama_index.tools.duckduckgo import DuckDuckGoSearchToolSpec +from llama_index.core.tools import FunctionTool + +# Initialize the DuckDuckGo search tool +tool_spec = DuckDuckGoSearchToolSpec() + +search_tool = FunctionTool.from_defaults(tool_spec.duckduckgo_full_search) +# Example usage +response = search_tool("Who's the current President of France?") +print(response.raw_output[-1]['body']) +``` + +預期輸出: + +``` +The President of the French Republic is the head of state of France. The current President is Emmanuel Macron since 14 May 2017 defeating Marine Le Pen in the second round of the presidential election on 7 May 2017. List of French presidents (Fifth Republic) N° Portrait Name ... +``` + + + + +```python +from langchain_community.tools import DuckDuckGoSearchRun + +search_tool = DuckDuckGoSearchRun() +results = search_tool.invoke("Who's the current President of France?") +print(results) +``` + +預期輸出: + +``` +Emmanuel Macron (born December 21, 1977, Amiens, France) is a French banker and politician who was elected president of France in 2017... +``` + + + + +## 建立自訂天氣資訊工具,安排煙火施放時機 + +完美的晚宴應該在晴朗的夜空下施放煙火,我們得確保煙火秀不會因為壞天氣而取消。 + +來建立一個自訂工具,呼叫外部天氣 API,取得指定地點的天氣資訊。 + +> [!TIP] +> 為了簡化範例,我們使用模擬的天氣 API。如果想使用真正的天氣 API,可以像第 1 單元一樣,實作使用 OpenWeatherMap API 的天氣工具。 + + + + +```python +from smolagents import Tool +import random + +class WeatherInfoTool(Tool): + name = "weather_info" + description = "Fetches dummy weather information for a given location." + inputs = { + "location": { + "type": "string", + "description": "The location to get weather information for." + } + } + output_type = "string" + + def forward(self, location: str): + # Dummy weather data + weather_conditions = [ + {"condition": "Rainy", "temp_c": 15}, + {"condition": "Clear", "temp_c": 25}, + {"condition": "Windy", "temp_c": 20} + ] + # Randomly select a weather condition + data = random.choice(weather_conditions) + return f"Weather in {location}: {data['condition']}, {data['temp_c']}°C" + +# Initialize the tool +weather_info_tool = WeatherInfoTool() +``` + + + + +```python +import random +from llama_index.core.tools import FunctionTool + +def get_weather_info(location: str) -> str: + """Fetches dummy weather information for a given location.""" + # Dummy weather data + weather_conditions = [ + {"condition": "Rainy", "temp_c": 15}, + {"condition": "Clear", "temp_c": 25}, + {"condition": "Windy", "temp_c": 20} + ] + # Randomly select a weather condition + data = random.choice(weather_conditions) + return f"Weather in {location}: {data['condition']}, {data['temp_c']}°C" + +# Initialize the tool +weather_info_tool = FunctionTool.from_defaults(get_weather_info) +``` + + + + +```python +from langchain_core.tools import Tool +import random + +def get_weather_info(location: str) -> str: + """Fetches dummy weather information for a given location.""" + # Dummy weather data + weather_conditions = [ + {"condition": "Rainy", "temp_c": 15}, + {"condition": "Clear", "temp_c": 25}, + {"condition": "Windy", "temp_c": 20} + ] + # Randomly select a weather condition + data = random.choice(weather_conditions) + return f"Weather in {location}: {data['condition']}, {data['temp_c']}°C" + +# Initialize the tool +weather_info_tool = Tool( + name="get_weather_info", + func=get_weather_info, + description="Fetches dummy weather information for a given location." +) +``` + + + + +## 建立 Hub 統計工具,與具影響力的 AI 開發者交流 + +出席晚宴的賓客中,有許多 AI 開發界的重要人物。Alfred 想透過討論他們最受歡迎的模型、資料集與 Space,讓他們留下深刻印象。我們將建立一個工具,根據使用者名稱,從 Hugging Face Hub 取得模型統計資料。 + + + + +```python +from smolagents import Tool +from huggingface_hub import list_models + +class HubStatsTool(Tool): + name = "hub_stats" + description = "Fetches the most downloaded model from a specific author on the Hugging Face Hub." + inputs = { + "author": { + "type": "string", + "description": "The username of the model author/organization to find models from." + } + } + output_type = "string" + + def forward(self, author: str): + try: + # List models from the specified author, sorted by downloads + models = list(list_models(author=author, sort="downloads", direction=-1, limit=1)) + + if models: + model = models[0] + return f"The most downloaded model by {author} is {model.id} with {model.downloads:,} downloads." + else: + return f"No models found for author {author}." + except Exception as e: + return f"Error fetching models for {author}: {str(e)}" + +# Initialize the tool +hub_stats_tool = HubStatsTool() + +# Example usage +print(hub_stats_tool("facebook")) # Example: Get the most downloaded model by Facebook +``` + +預期輸出: + +``` +The most downloaded model by facebook is facebook/esmfold_v1 with 12,544,550 downloads. +``` + + + + +```python +import random +from llama_index.core.tools import FunctionTool +from huggingface_hub import list_models + +def get_hub_stats(author: str) -> str: + """Fetches the most downloaded model from a specific author on the Hugging Face Hub.""" + try: + # List models from the specified author, sorted by downloads + models = list(list_models(author=author, sort="downloads", direction=-1, limit=1)) + + if models: + model = models[0] + return f"The most downloaded model by {author} is {model.id} with {model.downloads:,} downloads." + else: + return f"No models found for author {author}." + except Exception as e: + return f"Error fetching models for {author}: {str(e)}" + +# Initialize the tool +hub_stats_tool = FunctionTool.from_defaults(get_hub_stats) + +# Example usage +print(hub_stats_tool("facebook")) # Example: Get the most downloaded model by Facebook +``` + +預期輸出: + +``` +The most downloaded model by facebook is facebook/esmfold_v1 with 12,544,550 downloads. +``` + + + + +```python +from langchain_core.tools import Tool +from huggingface_hub import list_models + +def get_hub_stats(author: str) -> str: + """Fetches the most downloaded model from a specific author on the Hugging Face Hub.""" + try: + # List models from the specified author, sorted by downloads + models = list(list_models(author=author, sort="downloads", direction=-1, limit=1)) + + if models: + model = models[0] + return f"The most downloaded model by {author} is {model.id} with {model.downloads:,} downloads." + else: + return f"No models found for author {author}." + except Exception as e: + return f"Error fetching models for {author}: {str(e)}" + +# Initialize the tool +hub_stats_tool = Tool( + name="get_hub_stats", + func=get_hub_stats, + description="Fetches the most downloaded model from a specific author on the Hugging Face Hub." +) + +# Example usage +print(hub_stats_tool.invoke("facebook")) # Example: Get the most downloaded model by Facebook +``` + +預期輸出: + +``` +The most downloaded model by facebook is facebook/esmfold_v1 with 13,109,861 downloads. +``` + + + + +有了 Hub 統計工具,Alfred 現在可以聊聊這些具影響力的 AI 開發者最受歡迎的模型,讓他們留下好印象。 + +## 將工具整合到 Alfred + +所有工具都準備好了,接下來把它們整合到 Alfred 這個 agent 中: + + + + +```python +from smolagents import CodeAgent, InferenceClientModel + +# Initialize the Hugging Face model +model = InferenceClientModel() + +# Create Alfred with all the tools +alfred = CodeAgent( + tools=[search_tool, weather_info_tool, hub_stats_tool], + model=model +) + +# Example query Alfred might receive during the gala +response = alfred.run("What is Facebook and what's their most popular model?") + +print("🎩 Alfred's Response:") +print(response) +``` + +預期輸出: + +``` +🎩 Alfred's Response: +Facebook is a social networking website where users can connect, share information, and interact with others. The most downloaded model by Facebook on the Hugging Face Hub is ESMFold_v1. +``` + + + + +```python +from llama_index.core.agent.workflow import AgentWorkflow +from llama_index.llms.huggingface_api import HuggingFaceInferenceAPI + +# Initialize the Hugging Face model +llm = HuggingFaceInferenceAPI(model_name="Qwen/Qwen2.5-Coder-32B-Instruct") +# Create Alfred with all the tools +alfred = AgentWorkflow.from_tools_or_functions( + [search_tool, weather_info_tool, hub_stats_tool], + llm=llm +) + +# Example query Alfred might receive during the gala +response = await alfred.run("What is Facebook and what's their most popular model?") + +print("🎩 Alfred's Response:") +print(response) +``` + +預期輸出: + +``` +🎩 Alfred's Response: +Facebook is a social networking service and technology company based in Menlo Park, California. It was founded by Mark Zuckerberg and allows people to create profiles, connect with friends and family, share photos and videos, and join groups based on shared interests. The most popular model by Facebook on the Hugging Face Hub is `facebook/esmfold_v1` with 13,109,861 downloads. +``` + + + + +```python +from typing import TypedDict, Annotated +from langgraph.graph.message import add_messages +from langchain_core.messages import AnyMessage, HumanMessage, AIMessage +from langgraph.prebuilt import ToolNode +from langgraph.graph import START, StateGraph +from langgraph.prebuilt import tools_condition +from langchain_huggingface import HuggingFaceEndpoint, ChatHuggingFace + +# Generate the chat interface, including the tools +llm = HuggingFaceEndpoint( + repo_id="Qwen/Qwen2.5-Coder-32B-Instruct", + huggingfacehub_api_token=HUGGINGFACEHUB_API_TOKEN, +) + +chat = ChatHuggingFace(llm=llm, verbose=True) +tools = [search_tool, weather_info_tool, hub_stats_tool] +chat_with_tools = chat.bind_tools(tools) + +# Generate the AgentState and Agent graph +class AgentState(TypedDict): + messages: Annotated[list[AnyMessage], add_messages] + +def assistant(state: AgentState): + return { + "messages": [chat_with_tools.invoke(state["messages"])], + } + +## The graph +builder = StateGraph(AgentState) + +# Define nodes: these do the work +builder.add_node("assistant", assistant) +builder.add_node("tools", ToolNode(tools)) + +# Define edges: these determine how the control flow moves +builder.add_edge(START, "assistant") +builder.add_conditional_edges( + "assistant", + # If the latest message requires a tool, route to tools + # Otherwise, provide a direct response + tools_condition, +) +builder.add_edge("tools", "assistant") +alfred = builder.compile() + +messages = [HumanMessage(content="Who is Facebook and what's their most popular model?")] +response = alfred.invoke({"messages": messages}) + +print("🎩 Alfred's Response:") +print(response['messages'][-1].content) +``` + +預期輸出: + +``` +🎩 Alfred's Response: +Facebook is a social media company known for its social networking site, Facebook, as well as other services like Instagram and WhatsApp. The most downloaded model by Facebook on the Hugging Face Hub is facebook/esmfold_v1 with 13,202,321 downloads. +``` + + + +## 結語 + +整合這些工具後,Alfred 就能處理各種任務,從網頁搜尋到天氣更新與模型統計資料都難不倒他,確保他成為晚宴中消息最靈通、最能帶動話題的主人。 + +> [!TIP] +> 試著實作一個工具,用來取得特定主題的最新消息。 +> +> 完成後,請將自訂工具實作在 tools.py 檔案中。 diff --git a/units/zh-TW/unit4/additional-readings.mdx b/units/zh-TW/unit4/additional-readings.mdx new file mode 100644 index 000000000..6a4d5296b --- /dev/null +++ b/units/zh-TW/unit4/additional-readings.mdx @@ -0,0 +1,30 @@ +# 接下來該學哪些主題? + +Agentic AI 是快速發展的領域。要建立具備智慧與自主性的系統,了解基礎協定十分重要。 + +以下兩項重要標準值得你認識: + +- **Model Context Protocol(MCP)** +- **Agent-to-Agent Protocol(A2A)** + +## 🔌 Model Context Protocol(MCP) + +Anthropic 提出的 **Model Context Protocol(MCP)** 是一項開放標準,讓 AI 模型能安全、順暢地**連接外部工具、資料來源與應用程式**,使 agent 更有能力,也更具自主性。 + +你可以把 MCP 想成 **USB-C 連接埠這樣的通用轉接介面**,讓 AI 模型接上各種數位環境,**無須為每個環境個別開發整合功能**。 + +MCP 正迅速受到業界關注,OpenAI 與 Google 等大型公司也開始採用。 + +📚 延伸閱讀: +- [Anthropic 官方公告與文件](https://www.anthropic.com/news/model-context-protocol) +- [維基百科上的 MCP 介紹](https://en.wikipedia.org/wiki/Model_Context_Protocol) +- [介紹 MCP 的部落格文章](https://huggingface.co/blog/Kseniase/mcp) + +## 🤝 Agent-to-Agent(A2A)協定 + +Google 開發了 **Agent-to-Agent(A2A)協定**,與 Anthropic 的 Model Context Protocol(MCP)相輔相成。 + +MCP 讓 agent 連接外部工具,而 **A2A 讓 agent 彼此連接**,為協作式多 agent 系統鋪路,讓它們能共同解決複雜問題。 + +📚 深入了解 A2A: +- [Google 的 A2A 公告](https://developers.googleblog.com/en/a2a-a-new-era-of-agent-interoperability/) diff --git a/units/zh-TW/unit4/conclusion.mdx b/units/zh-TW/unit4/conclusion.mdx new file mode 100644 index 000000000..bc014cde3 --- /dev/null +++ b/units/zh-TW/unit4/conclusion.mdx @@ -0,0 +1,11 @@ +# 結語 + +**恭喜你完成 Agents Course!** + +憑著毅力與投入,你已在 AI agent 的領域打下穩固基礎。 + +但完成課程**並不是旅程的終點**,而是起點!歡迎繼續閱讀下一節,我們整理了精選資源,幫助你持續學習,包括 **MCP** 等進階主題。 + +**謝謝你**參與這門課。**希望你享受學習的過程,就像我們享受編寫課程一樣**。 + +別忘了:**持續學習,繼續發光發熱 🤗** diff --git a/units/zh-TW/unit4/get-your-certificate.mdx b/units/zh-TW/unit4/get-your-certificate.mdx new file mode 100644 index 000000000..633956347 --- /dev/null +++ b/units/zh-TW/unit4/get-your-certificate.mdx @@ -0,0 +1,21 @@ +# 領取你的證書 🎓 + +如果你的分數**超過 30%,恭喜!👏 你已符合領取官方證書的資格。** + +請依照下列步驟領取: + +1. 前往[證書頁面](https://huggingface.co/spaces/agents-course/Unit4-Final-Certificate)。 +2. 使用頁面上的按鈕,**登入**你的 Hugging Face 帳號。 +3. **輸入你的全名**,這個名字將顯示在證書上。 +4. 點選 **「Get My Certificate」**,驗證分數並下載證書。 + +Congrats! + +取得證書後,歡迎你: +- 將它加入 **LinkedIn 個人檔案** 🧑‍💼 +- 在 **X**、**Bluesky** 等平台分享 🎉 + +**別忘了標註 [@huggingface](https://huggingface.co/huggingface)。我們會為你感到驕傲,也很樂意為你喝采!🤗** + +> [!TIP] +> 如果提交時遇到問題,請到[證書社群討論區](https://huggingface.co/spaces/agents-course/Unit4-Final-Certificate/discussions)發起討論。 diff --git a/units/zh-TW/unit4/hands-on.mdx b/units/zh-TW/unit4/hands-on.mdx new file mode 100644 index 000000000..8c1574829 --- /dev/null +++ b/units/zh-TW/unit4/hands-on.mdx @@ -0,0 +1,52 @@ +# 動手實作 + +既然你已準備好進一步打造期末專案的 agent,就來看看如何提交成果,接受評分。 + +## 資料集 + +這個排行榜使用的資料集,包含從 GAIA **驗證集**第 1 級題目中選出的 20 道問題。 + +篩選題目的依據,是回答問題所需的工具數量與步驟數。 + +根據 GAIA 基準測試目前的表現,我們認為以第 1 級題目達到 30% 得分率為目標,是合理的測驗標準。 + +GAIA current status! + +## 提交流程 + +你現在可能最想知道:「我要怎麼開始提交?」 + +我們為這個單元建立了 API,讓你取得問題,並傳送答案以進行評分。 +以下是各個路由的簡介(互動式說明請見[即時文件](https://agents-course-unit4-scoring.hf.space/docs)): + +* **`GET /questions`**:取得篩選後的完整評估題目清單。 +* **`GET /random-question`**:從清單中隨機取得一道問題。 +* **`GET /files/{task_id}`**:下載與指定任務 ID 相關的特定檔案。 +* **`POST /submit`**:提交 agent 的答案、計算分數,並更新排行榜。 + +提交函式會以**完全相符(EXACT MATCH)**的方式比對標準答案,因此請仔細設計 prompt!GAIA 團隊在[這裡](https://huggingface.co/spaces/gaia-benchmark/leaderboard)分享了可供 agent 使用的 prompt 範例(在本課程中,請確保提交內容不包含「FINAL ANSWER」這段文字,讓 agent 只回覆答案即可)。 + +🎨 **打造你自己的範本!** + +為了示範與 API 互動的流程,我們提供了一份[基本範本](https://huggingface.co/spaces/agents-course/Final_Assignment_Template),讓你作為起點。 + +歡迎你修改、擴充,甚至完全重新規劃範本,**我們也非常鼓勵你這麼做**!依照自己的方法與創意,調整成最適合的形式。 + +為了提交結果,這份範本會準備 API 所需的三項資料: + +* **使用者名稱:**你的 Hugging Face 使用者名稱(這裡透過 Gradio 登入取得),用來識別你的提交紀錄。 +* **程式碼連結(`agent_code`):**連向 Hugging Face Space 程式碼(`.../tree/main`)的 URL,供驗證使用,因此請將 Space 設為公開。 +* **答案(`answers`):**agent 產生的回答清單(`{"task_id": ..., "submitted_answer": ...}`),供評分使用。 + +因此,建議你先將這份[範本](https://huggingface.co/spaces/agents-course/Final_Assignment_Template)複製到自己的 Hugging Face 帳號。 + +🏆 在[這裡](https://huggingface.co/spaces/agents-course/Students_leaderboard)查看排行榜 + +*溫馨提醒:這個排行榜是為了讓大家開心交流!我們知道,提交分數時未必能完成所有驗證。如果出現太多沒有公開連結佐證的高分紀錄,我們可能需要審查、調整或移除部分項目,以維持排行榜的參考價值。* +排行榜會顯示你的 Space 程式碼連結。這是專供學員使用的排行榜,如果你取得了引以為傲的分數,請將 Space 設為公開。 + diff --git a/units/zh-TW/unit4/introduction.mdx b/units/zh-TW/unit4/introduction.mdx new file mode 100644 index 000000000..67b760129 --- /dev/null +++ b/units/zh-TW/unit4/introduction.mdx @@ -0,0 +1,23 @@ +# 歡迎來到最後一個單元 [[introduction]] + +AI Agents Course thumbnail + +歡迎來到課程的最後一個單元!🎉 + +到目前為止,你已**打下 AI agent 的穩固基礎**,從了解組成元件,到建立自己的 agent。有了這些知識,你已準備好**建立功能強大的 agent**,並持續掌握這個快速發展領域的最新進展。 + +本單元將讓你實際運用所學。這是你的**期末實作專案**,完成後就有機會取得**課程證書**。 + +## 挑戰內容是什麼? + +你將建立自己的 agent,並**使用 [GAIA 基準測試](https://huggingface.co/spaces/gaia-benchmark/leaderboard)的部分題目評估其表現**。 + +要順利完成課程,你的 agent 必須在基準測試中取得 **30% 或以上**的分數。達成後,你就能獲得**結業證書**,正式肯定你的專業能力。🏅 + +此外,也來看看自己與其他學員的表現差異吧!你可以在專屬的**[學員排行榜](https://huggingface.co/spaces/agents-course/Students_leaderboard)**提交分數,查看社群的學習成果。 + +> ** 🚨 提醒:這是進階實作單元** +> +> 請留意,本單元會更著重實務與動手操作。相較於前面的課程,這裡需要**更進階的程式設計知識**,也需要你在**較少明確指引**的情況下自行完成任務。 + +是不是很令人期待?我們開始吧!🚀 diff --git a/units/zh-TW/unit4/what-is-gaia.mdx b/units/zh-TW/unit4/what-is-gaia.mdx new file mode 100644 index 000000000..ea0c346d8 --- /dev/null +++ b/units/zh-TW/unit4/what-is-gaia.mdx @@ -0,0 +1,70 @@ +# 什麼是 GAIA? + +[GAIA](https://huggingface.co/papers/2311.12983) 是一項**評估 AI 助理處理真實世界任務能力的基準測試**。這些任務需要結合推理、多模態理解、網頁瀏覽,以及熟練運用工具等核心能力。 + +這項基準測試最初發表於論文 _「[GAIA: A Benchmark for General AI Assistants](https://huggingface.co/papers/2311.12983)」_。 + +基準測試包含 **466 道精心挑選的問題**,**對人類而言概念簡單**,卻**對目前的 AI 系統極具挑戰性**。 + +以下數字呈現了兩者的差距: +- **人類**:成功率約 92% +- **搭配外掛程式的 GPT-4**:約 15% +- **Deep Research(OpenAI)**:在驗證集上為 67.36% + +GAIA 凸顯了目前 AI 模型的限制,也提供嚴謹的評估基準,衡量我們距離真正通用的 AI 助理還有多遠。 + +## 🌱 GAIA 的核心原則 + +GAIA 以以下幾項核心原則精心設計: + +- 🔍 **真實世界的難度**:任務需要多步驟推理、多模態理解,以及與工具互動。 +- 🧾 **人類能理解**:雖然對 AI 很難,這些任務對人類而言仍概念簡單、容易理解。 +- 🛡️ **無法取巧**:必須完整執行任務才能得出正確答案,無法靠暴力窮舉奏效。 +- 🧰 **容易評估**:答案簡潔、符合事實且明確,適合作為基準測試。 + +## 難度等級 + +GAIA 任務分成**複雜度逐漸增加的三個等級**,各自測試特定技能: + +- **第 1 級**:少於 5 個步驟,且只需少量使用工具。 +- **第 2 級**:需要更複雜的推理、多項工具之間的協調,以及 5 至 10 個步驟。 +- **第 3 級**:需要長期規劃,並進階整合各種工具。 + +![GAIA 等級](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit4/gaia_levels.png) + +## 一道高難度 GAIA 題目的範例 + +> 2008 年的畫作「Embroidery from Uzbekistan」中出現的水果,有哪些也列在某艘遠洋客輪 1949 年 10 月的早餐菜單上?這艘客輪後來曾在電影「The Last Voyage」中用作漂浮道具。請從畫面中 12 點鐘方向開始,依水果在畫中的順時針排列順序,以逗號分隔列出各項水果,並使用每種水果的英文複數形式。 + +可以看出,這道題目從多個面向考驗 AI 系統: + +- 要求**結構化的回覆格式** +- 涉及**多模態推理**(例如分析影像) +- 需要對彼此關聯的事實進行**多跳檢索**: + - 辨識畫中的水果 + - 找出 *The Last Voyage* 使用的是哪艘遠洋客輪 + - 查詢該艘船 1949 年 10 月的早餐菜單 +- 需要**正確安排先後順序**並進行高層次規劃,依適當順序解題 + +這類任務凸顯了單靠 LLM 經常力有未逮的地方,因此 GAIA 很適合評估能跨多個步驟與模態進行推理、檢索及執行的 **agent 系統**。 + +![GAIA 能力圖](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit4/gaia_capabilities.png) + +## 線上評估 + +為了鼓勵持續評測,**GAIA 在 Hugging Face 上提供公開排行榜**,你可以使用 **300 道測試題目**評估自己的模型。 + +👉 在[這裡](https://huggingface.co/spaces/gaia-benchmark/leaderboard)查看排行榜 + + + +想更深入了解 GAIA 嗎? + +- 📄 [閱讀完整論文](https://huggingface.co/papers/2311.12983) +- 📄 [OpenAI 的 Deep Research 發表文章](https://openai.com/index/introducing-deep-research/) +- 📄 [開源 DeepResearch:解放我們的搜尋 agent](https://huggingface.co/blog/open-deep-research) From 39d236fe32df4e87c0f2786d5503b21ca0b5ab92 Mon Sep 17 00:00:00 2001 From: Logan Date: Tue, 17 Nov 2026 21:46:44 +0800 Subject: [PATCH 2/3] ci(docs): enable zh-TW documentation builds --- .github/workflows/build_documentation.yml | 2 +- .github/workflows/build_pr_documentation.yml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/build_documentation.yml b/.github/workflows/build_documentation.yml index 9065c77ff..0aec847ab 100644 --- a/.github/workflows/build_documentation.yml +++ b/.github/workflows/build_documentation.yml @@ -14,6 +14,6 @@ jobs: package_name: agents-course path_to_docs: agents-course/units/ additional_args: --not_python_module - languages: en zh-CN ru-RU vi es ko fr + languages: en zh-CN zh-TW ru-RU vi es ko fr secrets: hf_token: ${{ secrets.HF_DOC_BUILD_PUSH }} diff --git a/.github/workflows/build_pr_documentation.yml b/.github/workflows/build_pr_documentation.yml index 04a42fc41..663b3b931 100644 --- a/.github/workflows/build_pr_documentation.yml +++ b/.github/workflows/build_pr_documentation.yml @@ -17,4 +17,4 @@ jobs: package_name: agents-course path_to_docs: agents-course/units/ additional_args: --not_python_module - languages: en zh-CN ru-RU vi es ko fr + languages: en zh-CN zh-TW ru-RU vi es ko fr From 82f17346cdf4c748f625fdcb2bdb6f6f863e6ae9 Mon Sep 17 00:00:00 2001 From: Logan Date: Tue, 17 Nov 2026 22:26:46 +0800 Subject: [PATCH 3/3] =?UTF-8?q?docs(zh-TW):=20use=20consistent=20second-pe?= =?UTF-8?q?rson=20=E4=BD=A0=20across=20units?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- units/zh-TW/unit2/langgraph/conclusion.mdx | 8 ++++---- .../unit2/langgraph/document_analysis_agent.mdx | 10 +++++----- units/zh-TW/unit2/langgraph/first_graph.mdx | 6 +++--- units/zh-TW/unit2/langgraph/introduction.mdx | 8 ++++---- units/zh-TW/unit2/langgraph/quiz1.mdx | 8 ++++---- .../unit2/langgraph/when_to_use_langgraph.mdx | 12 ++++++------ units/zh-TW/unit2/llama-index/README.md | 2 +- units/zh-TW/unit2/llama-index/agents.mdx | 4 ++-- units/zh-TW/unit2/llama-index/components.mdx | 16 ++++++++-------- units/zh-TW/unit2/llama-index/conclusion.mdx | 10 +++++----- units/zh-TW/unit2/llama-index/introduction.mdx | 6 +++--- units/zh-TW/unit2/llama-index/llama-hub.mdx | 4 ++-- units/zh-TW/unit2/llama-index/quiz1.mdx | 2 +- units/zh-TW/unit2/llama-index/quiz2.mdx | 2 +- units/zh-TW/unit2/llama-index/tools.mdx | 8 ++++---- units/zh-TW/unit2/llama-index/workflows.mdx | 12 ++++++------ units/zh-TW/unit3/agentic-rag/invitees.mdx | 2 +- 17 files changed, 60 insertions(+), 60 deletions(-) diff --git a/units/zh-TW/unit2/langgraph/conclusion.mdx b/units/zh-TW/unit2/langgraph/conclusion.mdx index b902573bc..3d969d982 100644 --- a/units/zh-TW/unit2/langgraph/conclusion.mdx +++ b/units/zh-TW/unit2/langgraph/conclusion.mdx @@ -1,10 +1,10 @@ # 結語 -恭喜您完成第 2 單元的 `LangGraph` 模組!🥳 +恭喜你完成第 2 單元的 `LangGraph` 模組!🥳 -您已掌握使用 LangGraph 建立結構化工作流程的基礎,能將這些流程部署到正式環境。 +你已掌握使用 LangGraph 建立結構化工作流程的基礎,能將這些流程部署到正式環境。 -本模組只是 LangGraph 學習之旅的起點。如果想深入學習,建議您: +本模組只是 LangGraph 學習之旅的起點。如果想深入學習,建議你: - 探索 [LangGraph 官方文件](https://github.com/langchain-ai/langgraph) - 參加 LangChain Academy 完整的 [LangGraph 入門課程](https://academy.langchain.com/courses/intro-to-langgraph) @@ -12,7 +12,7 @@ 下一個單元將探索實際應用案例。是時候把理論付諸實作了! -我們很想聽聽**您對課程的看法與改進建議**。如果有任何回饋,請 👉 [填寫這份表單](https://docs.google.com/forms/d/e/1FAIpQLSe9VaONn0eglax0uTwi29rIn4tM7H2sYmmybmG5jJNlE5v0xA/viewform?usp=dialog) +我們很想聽聽**你對課程的看法與改進建議**。如果有任何回饋,請 👉 [填寫這份表單](https://docs.google.com/forms/d/e/1FAIpQLSe9VaONn0eglax0uTwi29rIn4tM7H2sYmmybmG5jJNlE5v0xA/viewform?usp=dialog) ### 持續學習,保持熱情!🤗 diff --git a/units/zh-TW/unit2/langgraph/document_analysis_agent.mdx b/units/zh-TW/unit2/langgraph/document_analysis_agent.mdx index 053f71861..0f2fa4b35 100644 --- a/units/zh-TW/unit2/langgraph/document_analysis_agent.mdx +++ b/units/zh-TW/unit2/langgraph/document_analysis_agent.mdx @@ -1,6 +1,6 @@ # 文件分析圖 -Alfred 為您服務。身為 Wayne 先生信賴的管家,我擅自記錄了自己如何協助他處理各種文件需求。當他出門忙著……夜間活動時,我會確保他的文書、訓練時程與營養計畫都經過妥善分析和整理。 +Alfred 為你服務。身為 Wayne 先生信賴的管家,我擅自記錄了自己如何協助他處理各種文件需求。當他出門忙著……夜間活動時,我會確保他的文書、訓練時程與營養計畫都經過妥善分析和整理。 出門前,他留下了本週訓練計畫的筆記,於是我負責擬定明天的**菜單**。 @@ -19,7 +19,7 @@ Alfred 為您服務。身為 Wayne 先生信賴的管家,我擅自記錄了自 ![管家的文件分析工作流程](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit2/LangGraph/alfred_flow.png) > [!TIP] -> 您可以跟著這份 notebook 的程式碼操作,並使用 Google Colab 執行。 +> 你可以跟著這份 notebook 的程式碼操作,並使用 Google Colab 執行。 ## 設定環境 @@ -255,13 +255,13 @@ Ensure the steak is grass-fed and the spinach and peppers are organic for the be ## 重點整理 -如果您也想建立文件分析管家,請考慮以下重點: +如果你也想建立文件分析管家,請考慮以下重點: 1. 為特定文件任務**定義清楚的工具** 2. **建立穩健的狀態追蹤機制**,維持工具呼叫之間的上下文 3. 針對工具失敗的情況**考慮錯誤處理** 4. **保留先前互動的上下文**(透過 `add_messages` 運算子確保) -遵循這些原則,您也能提供配得上 Wayne 莊園的優質文件分析服務。 +遵循這些原則,你也能提供配得上 Wayne 莊園的優質文件分析服務。 -*相信這番說明已讓您滿意。現在請恕我失陪,今晚出門前,還得替 Wayne 老爺燙好披風。* +*相信這番說明已讓你滿意。現在請恕我失陪,今晚出門前,還得替 Wayne 老爺燙好披風。* diff --git a/units/zh-TW/unit2/langgraph/first_graph.mdx b/units/zh-TW/unit2/langgraph/first_graph.mdx index e5f6e0f15..6cef10ad0 100644 --- a/units/zh-TW/unit2/langgraph/first_graph.mdx +++ b/units/zh-TW/unit2/langgraph/first_graph.mdx @@ -1,4 +1,4 @@ -# 建立您的第一個 LangGraph +# 建立你的第一個 LangGraph 了解基本構成要素後,讓我們建立第一個能實際運作的圖,將概念付諸實作。我們將建立 Alfred 的電子郵件處理系統,讓他能夠: @@ -10,7 +10,7 @@ 這個範例示範如何使用 LangGraph,組織包含 LLM 決策的工作流程。由於沒有使用工具,這還不能算是 agent;本節主要是學習 LangGraph 框架。 > [!TIP] -> 您可以跟著這份 notebook 的程式碼操作,並使用 Google Colab 執行。 +> 你可以跟著這份 notebook 的程式碼操作,並使用 Google Colab 執行。 ## 我們的工作流程 @@ -307,7 +307,7 @@ Alfred 不斷調整郵件分類 agent,卻逐漸厭倦了替每次執行除錯 %pip install langchain ``` -然後,將 Langfuse API 金鑰與主機位址設為環境變數。您可以註冊 [Langfuse Cloud](https://cloud.langfuse.com),或[自行架設 Langfuse](https://langfuse.com/self-hosting),取得所需憑證。 +然後,將 Langfuse API 金鑰與主機位址設為環境變數。你可以註冊 [Langfuse Cloud](https://cloud.langfuse.com),或[自行架設 Langfuse](https://langfuse.com/self-hosting),取得所需憑證。 ```python import os diff --git a/units/zh-TW/unit2/langgraph/introduction.mdx b/units/zh-TW/unit2/langgraph/introduction.mdx index 90a72ab88..5f909e954 100644 --- a/units/zh-TW/unit2/langgraph/introduction.mdx +++ b/units/zh-TW/unit2/langgraph/introduction.mdx @@ -2,13 +2,13 @@ Unit 2.3 Thumbnail -歡迎來到學習旅程的下一站!您將學習**如何使用 [`LangGraph`](https://github.com/langchain-ai/langgraph) 框架建立應用程式**,組織並協調複雜的 LLM 工作流程。 +歡迎來到學習旅程的下一站!你將學習**如何使用 [`LangGraph`](https://github.com/langchain-ai/langgraph) 框架建立應用程式**,組織並協調複雜的 LLM 工作流程。 -`LangGraph` 提供**控制** agent 流程的工具,讓您建立**可部署至正式環境**的應用程式。 +`LangGraph` 提供**控制** agent 流程的工具,讓你建立**可部署至正式環境**的應用程式。 ## 模組概覽 -在本單元中,您將學習: +在本單元中,你將學習: ### 1️⃣ [什麼是 LangGraph?何時使用?](./when_to_use_langgraph) ### 2️⃣ [LangGraph 的基本構成要素](./building_blocks) @@ -19,7 +19,7 @@ > [!WARNING] > 本節範例需要使用能力較強的 LLM/VLM 模型。我們使用 GPT-4o API 執行,因為它與 LangGraph 的相容性最佳。 -完成本單元後,您將具備建立穩健、組織良好且能部署至正式環境的應用程式的能力! +完成本單元後,你將具備建立穩健、組織良好且能部署至正式環境的應用程式的能力! 不過,本節只是 LangGraph 入門。更進階的主題,可以透過 LangChain Academy 的免費課程學習:[LangGraph 入門](https://academy.langchain.com/courses/intro-to-langgraph)。 diff --git a/units/zh-TW/unit2/langgraph/quiz1.mdx b/units/zh-TW/unit2/langgraph/quiz1.mdx index 1dd9ebace..a42d8d74e 100644 --- a/units/zh-TW/unit2/langgraph/quiz1.mdx +++ b/units/zh-TW/unit2/langgraph/quiz1.mdx @@ -1,6 +1,6 @@ -# 測試您對 LangGraph 的理解 +# 測試你對 LangGraph 的理解 -讓我們透過簡短測驗,測試您對 `LangGraph` 的理解,並鞏固目前學到的關鍵概念! +讓我們透過簡短測驗,測試你對 `LangGraph` 的理解,並鞏固目前學到的關鍵概念! 本測驗可自由參加,不計分。 @@ -38,7 +38,7 @@ choices={[ }, { text: "LangGraph 能掌握執行流程,同時運用 LLM 的決策能力", - explain: "當您需要控制 agent 的執行時,LangGraph 能透過結構化工作流程,提供可預測的行為。", + explain: "當你需要控制 agent 的執行時,LangGraph 能透過結構化工作流程,提供可預測的行為。", correct: true }, ]} @@ -61,7 +61,7 @@ choices={[ }, { text: "State 代表在 agent 應用程式中流動的資訊", - explain: "State 是 LangGraph 的核心,包含步驟之間決策所需的所有資訊。您可以提供需要處理的欄位,節點則能修改欄位值,決定後續分支。", + explain: "State 是 LangGraph 的核心,包含步驟之間決策所需的所有資訊。你可以提供需要處理的欄位,節點則能修改欄位值,決定後續分支。", correct: true }, { diff --git a/units/zh-TW/unit2/langgraph/when_to_use_langgraph.mdx b/units/zh-TW/unit2/langgraph/when_to_use_langgraph.mdx index 1416727a7..6381685c7 100644 --- a/units/zh-TW/unit2/langgraph/when_to_use_langgraph.mdx +++ b/units/zh-TW/unit2/langgraph/when_to_use_langgraph.mdx @@ -15,11 +15,11 @@ LangGraph 可以使用 LangChain 的類別,但並非必要。 設計 AI 應用程式時,會面臨**控制**與**自由度**之間的基本取捨: - **自由度**給 LLM 更多發揮創意、處理意外問題的空間。 -- **控制**讓您確保行為可預測,並維持防護措施。 +- **控制**讓你確保行為可預測,並維持防護措施。 *smolagents* 中的 Code agent 自由度很高,能在一個行動步驟中呼叫多個工具、建立自己的工具等。不過,與一般使用 JSON 的 agent 相比,這也可能讓它們更難預測和控制! -`LangGraph` 位於另一端:當您需要**控制** agent 的執行時,它特別適合。 +`LangGraph` 位於另一端:當你需要**控制** agent 的執行時,它特別適合。 需要**掌握應用程式的運作流程**時,LangGraph 很有價值。它提供工具,讓應用程式遵循可預測的流程,同時運用 LLM 的能力。 @@ -35,7 +35,7 @@ LangGraph 可以使用 LangChain 的類別,但並非必要。 > 💡 **提示:** 左側並非 agent,因為沒有工具呼叫;右側則需要撰寫程式碼來查詢 xls(轉換為 pandas 資料結構後操作)。 -雖然這個分支具有確定性,但您也可以根據 LLM 的輸出來決定分支,讓流程不再具有確定性。 +雖然這個分支具有確定性,但你也可以根據 LLM 的輸出來決定分支,讓流程不再具有確定性。 LangGraph 特別適合的情境包括: @@ -45,7 +45,7 @@ LangGraph 特別適合的情境包括: - **需要人工介入的工作流程** - 多個元件協作的**複雜 agent 架構** -也就是說,只要**您能親自**根據各項行動的輸出設計流程,並決定接下來執行什麼,LangGraph 就很適合您! +也就是說,只要**你能親自**根據各項行動的輸出設計流程,並決定接下來執行什麼,LangGraph 就很適合你! 在我看來,`LangGraph` 是目前最適合部署至正式環境的 agent 框架。 @@ -61,8 +61,8 @@ LangGraph 特別適合的情境包括: ## 和一般 Python 有何不同?為什麼需要 LangGraph? -您可能會想:「直接寫一般 Python 程式碼,用 if-else 敘述處理這些流程就好了吧?」 +你可能會想:「直接寫一般 Python 程式碼,用 if-else 敘述處理這些流程就好了吧?」 -技術上確實可行,但建立複雜系統時,LangGraph 比原生 Python **多了一些優勢**。您可以不使用 LangGraph 建立相同應用程式,但它提供更方便的工具與抽象概念。 +技術上確實可行,但建立複雜系統時,LangGraph 比原生 Python **多了一些優勢**。你可以不使用 LangGraph 建立相同應用程式,但它提供更方便的工具與抽象概念。 其中包括狀態、視覺化、記錄(追蹤紀錄)、內建人工介入功能等。 diff --git a/units/zh-TW/unit2/llama-index/README.md b/units/zh-TW/unit2/llama-index/README.md index 3a32bd935..845fdd0f0 100644 --- a/units/zh-TW/unit2/llama-index/README.md +++ b/units/zh-TW/unit2/llama-index/README.md @@ -1,6 +1,6 @@ # 目錄 -本 LlamaIndex 框架大綱是課程第 2 單元的一部分。您可以在 hf.co/learn 閱讀關於 LlamaIndex 的第 2 單元內容 👉 由此進入 +本 LlamaIndex 框架大綱是課程第 2 單元的一部分。你可以在 hf.co/learn 閱讀關於 LlamaIndex 的第 2 單元內容 👉 由此進入 | 標題 | 說明 | | --- | --- | diff --git a/units/zh-TW/unit2/llama-index/agents.mdx b/units/zh-TW/unit2/llama-index/agents.mdx index bc0e02a8e..3c6647de1 100644 --- a/units/zh-TW/unit2/llama-index/agents.mdx +++ b/units/zh-TW/unit2/llama-index/agents.mdx @@ -22,7 +22,7 @@ LlamaIndex 支援**三種主要的推理 agent:** ## 初始化 agent > [!TIP] -> 您可以跟著這份 notebook 的程式碼操作,並使用 Google Colab 執行。 +> 你可以跟著這份 notebook 的程式碼操作,並使用 Google Colab 執行。 建立 agent 時,首先要提供**一組函式或工具,定義它具備的能力**。 讓我們看看如何使用基本工具建立 agent。截至撰寫本文時,agent 會自動使用函式呼叫 API(若可用),否則使用標準的 ReAct agent 迴圈。 @@ -67,7 +67,7 @@ response = await agent.run("My name is Bob.", ctx=ctx) response = await agent.run("What was my name again?", ctx=ctx) ``` -您會發現 `LlamaIndex` 的 agent 使用 Python 的 `await` 運算子,以非同步方式執行。如果您剛接觸 Python 非同步程式,或需要複習,可以參考這份[實用的非同步指南](https://docs.llamaindex.ai/en/stable/getting_started/async_python/)。 +你會發現 `LlamaIndex` 的 agent 使用 Python 的 `await` 運算子,以非同步方式執行。如果你剛接觸 Python 非同步程式,或需要複習,可以參考這份[實用的非同步指南](https://docs.llamaindex.ai/en/stable/getting_started/async_python/)。 掌握基礎後,讓我們看看如何在 agent 中使用更複雜的工具。 diff --git a/units/zh-TW/unit2/llama-index/components.mdx b/units/zh-TW/unit2/llama-index/components.mdx index 826ffc66d..a2773eb80 100644 --- a/units/zh-TW/unit2/llama-index/components.mdx +++ b/units/zh-TW/unit2/llama-index/components.mdx @@ -9,14 +9,14 @@ LlamaIndex 有許多元件,**我們將聚焦於 `QueryEngine` 元件。** 那麼,RAG 是什麼?LLM 透過大量資料訓練,學習一般知識。 不過,訓練資料未必包含相關且最新的資訊。 -RAG 會從您的資料中尋找並擷取相關資訊,提供給 LLM,藉此解決這個問題。 +RAG 會從你的資料中尋找並擷取相關資訊,提供給 LLM,藉此解決這個問題。 ![RAG](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit2/llama-index/rag.png) 想想 Alfred 的工作方式: -1. 您請 Alfred 協助規劃晚宴 -2. Alfred 需要查看您的行事曆、飲食偏好,以及過往成功的菜單 +1. 你請 Alfred 協助規劃晚宴 +2. Alfred 需要查看你的行事曆、飲食偏好,以及過往成功的菜單 3. `QueryEngine` 協助 Alfred 找到這些資訊,並用來規劃晚宴 因此,`QueryEngine` 是在 LlamaIndex 中**建立 Agentic RAG 工作流程的關鍵元件**。 @@ -28,9 +28,9 @@ RAG 會從您的資料中尋找並擷取相關資訊,提供給 LLM,藉此解 ## 使用元件建立 RAG 管線 > [!TIP] -> 您可以跟著這份 notebook 的程式碼操作,並使用 Google Colab 執行。 +> 你可以跟著這份 notebook 的程式碼操作,並使用 Google Colab 執行。 -RAG 有五個關鍵階段,也會成為您所建立的大多數大型應用程式的一部分: +RAG 有五個關鍵階段,也會成為你所建立的大多數大型應用程式的一部分: 1. **載入**:將資料從原本的位置帶入工作流程,不論來源是文字檔、PDF、網站、資料庫或 API。LlamaHub 提供數百種整合元件可供選擇。 2. **索引**:建立可供查詢資料的資料結構。對 LLM 而言,這幾乎總是代表建立向量嵌入,也就是以數值表示資料的語意。索引也可以涵蓋其他後設資料策略,方便根據屬性準確找出符合上下文的資料。 @@ -42,7 +42,7 @@ RAG 有五個關鍵階段,也會成為您所建立的大多數大型應用程 ### 載入文件並建立嵌入 -如前所述,LlamaIndex 能處理您自己的資料,但**存取資料之前,必須先載入資料。** +如前所述,LlamaIndex 能處理你自己的資料,但**存取資料之前,必須先載入資料。** 將資料載入 LlamaIndex 主要有三種方式: 1. `SimpleDirectoryReader`:內建載入器,可從本機目錄載入多種檔案類型。 @@ -124,7 +124,7 @@ pipeline = IngestionPipeline( ``` > [!TIP] -> 您可以在 LlamaIndex 文件中查看各種向量儲存的概覽。 +> 你可以在 LlamaIndex 文件中查看各種向量儲存的概覽。 向量嵌入在此派上用場:將查詢與節點嵌入同一個向量空間,就能找出相關內容。 `VectorStoreIndex` 會替我們處理這些工作,並使用與資料匯入階段相同的嵌入模型,確保一致性。 @@ -176,7 +176,7 @@ query_engine.query("What is the meaning of life?") - `tree_summarize`:逐一處理檢索到的文字區塊,以樹狀結構組織答案,產生詳細回覆。 > [!TIP] -> 您可以透過低階組合 API 精細控制查詢流程。這個 API 能讓您依需求自訂與微調查詢的每個步驟,也很適合搭配工作流程使用。 +> 你可以透過低階組合 API 精細控制查詢流程。這個 API 能讓你依需求自訂與微調查詢的每個步驟,也很適合搭配工作流程使用。 語言模型的行為不一定可預測,因此無法保證答案永遠正確。我們可以**評估答案品質**來處理這個問題。 diff --git a/units/zh-TW/unit2/llama-index/conclusion.mdx b/units/zh-TW/unit2/llama-index/conclusion.mdx index 1f3a64c16..bd9d110b2 100644 --- a/units/zh-TW/unit2/llama-index/conclusion.mdx +++ b/units/zh-TW/unit2/llama-index/conclusion.mdx @@ -1,13 +1,13 @@ # 結語 -恭喜您完成第 2 單元的 `llama-index` 模組 🥳 +恭喜你完成第 2 單元的 `llama-index` 模組 🥳 -您已掌握 `llama-index` 的基礎,也學會了如何建立自己的 agentic 工作流程! -現在您可以運用這些技能,開始建立搜尋引擎,解決自己感興趣的任務。 +你已掌握 `llama-index` 的基礎,也學會了如何建立自己的 agentic 工作流程! +現在你可以運用這些技能,開始建立搜尋引擎,解決自己感興趣的任務。 -在本單元的下一個模組,您將學習**如何使用 LangGraph 建立 agent**。 +在本單元的下一個模組,你將學習**如何使用 LangGraph 建立 agent**。 -最後,我們很想**聽聽您對課程的看法,以及我們可以如何改進**。 +最後,我們很想**聽聽你對課程的看法,以及我們可以如何改進**。 如果有任何回饋,請 👉 [填寫這份表單](https://docs.google.com/forms/d/e/1FAIpQLSe9VaONn0eglax0uTwi29rIn4tM7H2sYmmybmG5jJNlE5v0xA/viewform?usp=dialog) ### 持續學習,保持熱情 🤗 diff --git a/units/zh-TW/unit2/llama-index/introduction.mdx b/units/zh-TW/unit2/llama-index/introduction.mdx index fb8e9096b..082707967 100644 --- a/units/zh-TW/unit2/llama-index/introduction.mdx +++ b/units/zh-TW/unit2/llama-index/introduction.mdx @@ -1,8 +1,8 @@ # LlamaIndex 簡介 -歡迎來到本模組!您將學習如何使用 [LlamaIndex](https://www.llamaindex.ai/) 工具組,建立由 LLM 驅動的 agent。 +歡迎來到本模組!你將學習如何使用 [LlamaIndex](https://www.llamaindex.ai/) 工具組,建立由 LLM 驅動的 agent。 -LlamaIndex 是**一套完整工具組,可透過索引與工作流程,針對您的資料建立由 LLM 驅動的 agent**。本課程將聚焦於在 LlamaIndex 中建立 agent 的三個主要部分:**元件**、**agent 與工具**以及**工作流程**。 +LlamaIndex 是**一套完整工具組,可透過索引與工作流程,針對你的資料建立由 LLM 驅動的 agent**。本課程將聚焦於在 LlamaIndex 中建立 agent 的三個主要部分:**元件**、**agent 與工具**以及**工作流程**。 ![LlamaIndex](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit2/llama-index/thumbnail.png) @@ -17,7 +17,7 @@ LlamaIndex 是**一套完整工具組,可透過索引與工作流程,針對 雖然 LlamaIndex 的部分功能與 smolagents 等框架相似,但它具備幾項主要優勢: -- **清楚的工作流程系統**:透過事件驅動、以非同步為優先的語法,將 agent 的決策拆成明確步驟,方便您組合與組織邏輯。 +- **清楚的工作流程系統**:透過事件驅動、以非同步為優先的語法,將 agent 的決策拆成明確步驟,方便你組合與組織邏輯。 - **透過 LlamaParse 進階解析文件**:LlamaParse 專為 LlamaIndex 設計,因此整合十分順暢,不過這是付費功能。 - **豐富的現成元件**:LlamaIndex 發展已有一段時間,能與許多框架搭配使用,並提供大量經過測試的可靠元件,例如 LLM、檢索器與索引。 - **LlamaHub**:收錄數百種元件、agent 與工具的資源目錄,這些資源都能在 LlamaIndex 中使用。 diff --git a/units/zh-TW/unit2/llama-index/llama-hub.mdx b/units/zh-TW/unit2/llama-index/llama-hub.mdx index fc431950b..26b517536 100644 --- a/units/zh-TW/unit2/llama-index/llama-hub.mdx +++ b/units/zh-TW/unit2/llama-index/llama-hub.mdx @@ -10,7 +10,7 @@ ## 安裝 -您可以在結構清楚的 **[LlamaHub 網站](https://llamahub.ai/)** 找到 LlamaIndex 的安裝說明。 +你可以在結構清楚的 **[LlamaHub 網站](https://llamahub.ai/)** 找到 LlamaIndex 的安裝說明。 初看可能有些複雜,但大多數**安裝指令都遵循容易記憶的格式**: ```bash @@ -25,7 +25,7 @@ pip install llama-index-llms-huggingface-api llama-index-embeddings-huggingface ## 使用方式 -安裝後,就可以查看使用方式。您會發現匯入路徑就列在安裝指令之後! +安裝後,就可以查看使用方式。你會發現匯入路徑就列在安裝指令之後! 以下是 **Hugging Face Inference API LLM 元件**的使用範例。 ```python diff --git a/units/zh-TW/unit2/llama-index/quiz1.mdx b/units/zh-TW/unit2/llama-index/quiz1.mdx index 775131ae2..fad093a14 100644 --- a/units/zh-TW/unit2/llama-index/quiz1.mdx +++ b/units/zh-TW/unit2/llama-index/quiz1.mdx @@ -2,7 +2,7 @@ 到目前為止,我們已介紹 LlamaIndex 的主要元件與工具。 來做個小測驗吧!**自我測試**是最好的學習方式,也能[避免能力錯覺](https://www.coursera.org/lecture/learning-how-to-learn/illusions-of-competence-BuFzf)。 -這能幫助您找出**哪些知識需要加強**。 +這能幫助你找出**哪些知識需要加強**。 本測驗可自由參加,不計分。 diff --git a/units/zh-TW/unit2/llama-index/quiz2.mdx b/units/zh-TW/unit2/llama-index/quiz2.mdx index 7cc4b6aee..d643e24a7 100644 --- a/units/zh-TW/unit2/llama-index/quiz2.mdx +++ b/units/zh-TW/unit2/llama-index/quiz2.mdx @@ -1,6 +1,6 @@ # 快速自我檢測(不計分) [[quiz2]] -什麼?!又是測驗?我們懂、我們懂……😅 不過,這個簡短的不計分測驗能**幫助您鞏固剛學到的關鍵概念**。 +什麼?!又是測驗?我們懂、我們懂……😅 不過,這個簡短的不計分測驗能**幫助你鞏固剛學到的關鍵概念**。 本測驗涵蓋 agent 工作流程與互動,這些都是建立有效 AI agent 的核心要素。 diff --git a/units/zh-TW/unit2/llama-index/tools.mdx b/units/zh-TW/unit2/llama-index/tools.mdx index 470fd5212..779c9023e 100644 --- a/units/zh-TW/unit2/llama-index/tools.mdx +++ b/units/zh-TW/unit2/llama-index/tools.mdx @@ -17,10 +17,10 @@ LlamaIndex 主要提供**四種工具類型**: ## 建立 FunctionTool > [!TIP] -> 您可以跟著這份 notebook 的程式碼操作,並使用 Google Colab 執行。 +> 你可以跟著這份 notebook 的程式碼操作,並使用 Google Colab 執行。 FunctionTool 能輕鬆將任何 Python 函式封裝為 agent 可用的工具。 -您可以傳入同步或非同步函式,也可以選擇指定 `name` 與 `description` 參數。 +你可以傳入同步或非同步函式,也可以選擇指定 `name` 與 `description` 參數。 工具名稱與描述尤其重要,能幫助 agent 了解何時及如何有效使用工具。 以下示範如何建立並呼叫 FunctionTool。 @@ -70,7 +70,7 @@ tool = QueryEngineTool.from_defaults(query_engine, name="some useful name", desc ## 建立 Toolspecs -您可以將 `ToolSpecs` 視為一組相互配合的工具,就像整理完善的專業工具箱。 +你可以將 `ToolSpecs` 視為一組相互配合的工具,就像整理完善的專業工具箱。 正如機械師的工具箱包含互補的車輛維修工具,`ToolSpec` 會將相關工具組合起來,完成特定用途。 例如,會計 agent 的 `ToolSpec` 可以整合試算表、電子郵件與計算工具,準確有效地處理財務任務。 @@ -137,6 +137,6 @@ agent_context = Context(agent) 2. `LoadAndSearchToolSpec`:接受任何現有工具作為輸入。它實作了 `to_tool_list` 方法,呼叫後會回傳載入工具與搜尋工具。載入工具會呼叫底層工具,並為輸出建立索引(預設使用向量索引);搜尋工具則接受查詢字串,並呼叫底層索引進行查詢。 > [!TIP] -> 您可以在 LlamaHub 找到各種工具規格與輔助工具。 +> 你可以在 LlamaHub 找到各種工具規格與輔助工具。 現在我們已了解 LlamaIndex 的 agent 與工具基礎,接下來看看如何**建立可設定且易於管理的工作流程!** diff --git a/units/zh-TW/unit2/llama-index/workflows.mdx b/units/zh-TW/unit2/llama-index/workflows.mdx index 0810a07be..48330710d 100644 --- a/units/zh-TW/unit2/llama-index/workflows.mdx +++ b/units/zh-TW/unit2/llama-index/workflows.mdx @@ -15,14 +15,14 @@ LlamaIndex 的工作流程提供結構化的方式,將程式碼組織成依序 - 內建狀態管理 - 支援簡單及複雜的 agent 互動 -正如您可能已經想到的,**工作流程能在 agent 的自主性與整體流程的控制之間取得良好平衡。** +正如你可能已經想到的,**工作流程能在 agent 的自主性與整體流程的控制之間取得良好平衡。** 接下來就學著建立自己的工作流程吧! ## 建立工作流程 > [!TIP] -> 您可以跟著這份 notebook 的程式碼操作,並使用 Google Colab 執行。 +> 你可以跟著這份 notebook 的程式碼操作,並使用 Google Colab 執行。 ### 建立基本工作流程 @@ -52,7 +52,7 @@ w = MyWorkflow(timeout=10, verbose=False) result = await w.run() ``` -如您所見,現在呼叫 `w.run()` 就能執行工作流程。 +如你所見,現在呼叫 `w.run()` 就能執行工作流程。 ### 連接多個步驟 @@ -164,7 +164,7 @@ async def query(self, ctx: Context, ev: StartEvent) -> StopEvent: return StopEvent(result=val) ``` -太好了!現在您已經知道如何在 LlamaIndex 中建立基本工作流程! +太好了!現在你已經知道如何在 LlamaIndex 中建立基本工作流程! > [!TIP] > 工作流程還有更進階的細節,可以在 LlamaIndex 文件中深入了解。 @@ -174,7 +174,7 @@ async def query(self, ctx: Context, ev: StartEvent) -> StopEvent: ## 使用多 agent 工作流程自動化流程 除了手動建立流程,我們也能使用 **`AgentWorkflow` 類別建立多 agent 工作流程**。 -`AgentWorkflow` 使用 Workflow agent,讓您建立由一個或多個 agent 組成的系統,各個 agent 能依專長協作並交接任務。 +`AgentWorkflow` 使用 Workflow agent,讓你建立由一個或多個 agent 組成的系統,各個 agent 能依專長協作並交接任務。 這樣就能建立複雜的 agent 系統,讓不同 agent 負責任務的不同面向。 我們會從 `llama_index.core.agent.workflow` 匯入 agent 類別,而非 `llama_index.core.agent`。 在 `AgentWorkflow` 建構函式中,必須將一個 agent 指定為根 agent。 @@ -275,6 +275,6 @@ state = await ctx.store.get("state") print(state["num_fn_calls"]) ``` -恭喜!您已掌握 LlamaIndex 中 agent 的基礎知識!🎉 +恭喜!你已掌握 LlamaIndex 中 agent 的基礎知識!🎉 接下來透過最後一個測驗,鞏固所學吧!🚀 diff --git a/units/zh-TW/unit3/agentic-rag/invitees.mdx b/units/zh-TW/unit3/agentic-rag/invitees.mdx index 16b62ce43..3a5761fea 100644 --- a/units/zh-TW/unit3/agentic-rag/invitees.mdx +++ b/units/zh-TW/unit3/agentic-rag/invitees.mdx @@ -427,7 +427,7 @@ Lady Ada Lovelace is an esteemed mathematician and pioneer in computing, often c **你:**「Alfred,正在跟大使聊天的那位先生是誰?」 -**Alfred:***快速搜尋賓客資料庫*「先生,那位是 Nikola Tesla 博士,是您大學時期的老朋友。他最近為一套新的無線能源傳輸系統取得專利,一定很樂意與您討論。別忘了,他非常喜歡鴿子,這或許是個不錯的閒聊話題。」 +**Alfred:***快速搜尋賓客資料庫*「先生,那位是 Nikola Tesla 博士,是你大學時期的老朋友。他最近為一套新的無線能源傳輸系統取得專利,一定很樂意與你討論。別忘了,他非常喜歡鴿子,這或許是個不錯的閒聊話題。」 ```json {