返回首頁AI Agent

AI Agent 實作教學:從零開始打造你的第一個 AI 代理

24 min 分鐘閱讀

AI Agent 實作教學:從零開始打造你的第一個 AI 代理

AI Agent 實作教學:從零開始打造你的第一個 AI 代理

「看了一堆 AI Agent 的文章,但還是不知道怎麼動手做。」

這是我們最常聽到的回饋。理論很多,但實際能跑起來的教學太少。更糟的是,很多教學用的是過時的 API,照著做根本跑不起來。

這篇教學會帶你從零開始,一步一步建構一個真正能用的 AI Agent。我們會使用 Python 和 LangChain,這是目前最主流的組合。完成後,你會有一個能搜尋網路、查詢天氣、執行計算的 AI Agent,而且你會理解每一行程式碼在做什麼。

如果你對 AI Agent 的基本概念還不熟悉,建議先閱讀 AI Agent 是什麼?完整指南。如果你想了解有哪些工具可以選擇,可以參考 AI Agent 工具比較

開始之前:你需要準備什麼

技術要求

  • Python 3.9+:本教學使用 Python 3.11
  • 基本 Python 知識:了解函數、類別、套件安裝
  • 命令列操作:會使用終端機執行指令
  • 程式碼編輯器:VS Code、PyCharm 或任何你習慣的編輯器

帳號與 API Key

  • OpenAI API Key:用於呼叫 GPT 模型

    • 前往 platform.openai.com 註冊
    • 在 API Keys 頁面建立新的 Key
    • 需要綁定付款方式(有免費額度可用)
  • SerpAPI Key(選用):用於網路搜尋功能

    • 前往 serpapi.com 註冊
    • 免費方案每月 100 次查詢

預計時間

  • 環境設定:15 分鐘
  • 基礎 Agent 實作:30 分鐘
  • 進階功能:30 分鐘
  • 總計約 1.5 小時

第一步:環境設定

建立專案目錄

mkdir ai-agent-tutorial
cd ai-agent-tutorial

建立虛擬環境

使用虛擬環境是 Python 開發的最佳實踐,可以避免套件衝突。

# 建立虛擬環境
python -m venv venv

# 啟動虛擬環境(Mac/Linux)
source venv/bin/activate

# 啟動虛擬環境(Windows)
.\venv\Scripts\activate

安裝必要套件

pip install langchain langchain-openai langchain-community python-dotenv

套件說明:

  • langchain:核心框架
  • langchain-openai:OpenAI 整合
  • langchain-community:社群工具整合
  • python-dotenv:環境變數管理

設定環境變數

建立 .env 檔案儲存 API Key(不要將此檔案提交到版本控制):

# .env
OPENAI_API_KEY=your-openai-api-key-here
SERPAPI_API_KEY=your-serpapi-key-here

驗證安裝

建立 test_setup.py 驗證環境是否正確:

# test_setup.py
from dotenv import load_dotenv
import os

load_dotenv()

# 檢查環境變數
api_key = os.getenv("OPENAI_API_KEY")
if api_key:
    print("✅ OpenAI API Key 已設定")
else:
    print("❌ 找不到 OpenAI API Key")

# 測試 LangChain 匯入
try:
    from langchain_openai import ChatOpenAI
    print("✅ LangChain 安裝成功")
except ImportError as e:
    print(f"❌ LangChain 匯入失敗: {e}")

執行測試:

python test_setup.py

看到兩個綠色勾勾就代表環境設定完成。

插圖:AI Agent 開發環境架構圖

場景描述: 展示 AI Agent 開發環境的完整架構,包含本地開發環境、API 服務和工具整合

視覺重點:

  • 主要內容清晰呈現

必須出現的元素:

  • 依據描述中的關鍵元素

需要顯示的中文字:

顏色調性: 專業、清晰

避免元素: 抽象圖形、齒輪、發光特效

Slug: ai-agent-development-environment-architecture

第二步:建構最簡單的 Agent

從對話開始

在建構複雜的 Agent 之前,我們先確認能與 LLM 正常對話。

建立 01_simple_chat.py

# 01_simple_chat.py
from dotenv import load_dotenv
from langchain_openai import ChatOpenAI
from langchain_core.messages import HumanMessage

load_dotenv()

# 初始化 LLM
llm = ChatOpenAI(
    model="gpt-4o-mini",  # 使用較便宜的模型測試
    temperature=0.7
)

# 發送訊息
response = llm.invoke([
    HumanMessage(content="用一句話解釋什麼是 AI Agent")
])

print(response.content)

執行:

python 01_simple_chat.py

你應該會看到 GPT 對 AI Agent 的簡短解釋。這確認了 API 連線正常。

加入工具:讓 Agent 能「做事」

普通的 LLM 只能回答問題,Agent 的關鍵在於能使用工具。我們先建立一個簡單的計算工具。

建立 02_agent_with_tool.py

# 02_agent_with_tool.py
from dotenv import load_dotenv
from langchain_openai import ChatOpenAI
from langchain_core.tools import tool
from langchain.agents import create_tool_calling_agent, AgentExecutor
from langchain_core.prompts import ChatPromptTemplate

load_dotenv()

# 定義工具
@tool
def calculate(expression: str) -> str:
    """計算數學表達式。輸入應該是有效的 Python 數學表達式。"""
    try:
        result = eval(expression)
        return f"計算結果:{result}"
    except Exception as e:
        return f"計算錯誤:{str(e)}"

@tool
def get_current_time() -> str:
    """取得目前的日期和時間。"""
    from datetime import datetime
    now = datetime.now()
    return f"目前時間:{now.strftime('%Y-%m-%d %H:%M:%S')}"

# 初始化 LLM
llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)

# 定義工具列表
tools = [calculate, get_current_time]

# 建立 Prompt 模板
prompt = ChatPromptTemplate.from_messages([
    ("system", "你是一個有幫助的助手,可以使用工具來回答問題。"),
    ("human", "{input}"),
    ("placeholder", "{agent_scratchpad}"),
])

# 建立 Agent
agent = create_tool_calling_agent(llm, tools, prompt)

# 建立執行器
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)

# 測試
if __name__ == "__main__":
    # 測試計算功能
    result = agent_executor.invoke({
        "input": "請幫我計算 (123 + 456) * 2 是多少?"
    })
    print(f"\n結果:{result['output']}\n")

    # 測試時間功能
    result = agent_executor.invoke({
        "input": "現在幾點了?"
    })
    print(f"\n結果:{result['output']}\n")

執行後,你會看到 Agent 的思考過程(因為設定了 verbose=True):

> Entering new AgentExecutor chain...
Invoking: `calculate` with `{'expression': '(123 + 456) * 2'}`
計算結果:1158
計算結果是 1158。
> Finished chain.

結果:計算結果是 1158。

這就是 AI Agent 的基本運作:

  1. 接收用戶輸入
  2. 判斷需要使用哪個工具
  3. 呼叫工具並取得結果
  4. 根據結果生成回應

程式碼解析

讓我們拆解關鍵部分:

@tool 裝飾器

@tool
def calculate(expression: str) -> str:
    """計算數學表達式。輸入應該是有效的 Python 數學表達式。"""

@tool 裝飾器將普通函數轉換成 Agent 可以使用的工具。文檔字串(docstring)非常重要,因為 LLM 會根據這段描述來決定何時使用這個工具。

AgentExecutor

agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)

AgentExecutor 是 Agent 的運行環境,負責:

  • 管理 Agent 的執行循環
  • 處理工具呼叫
  • 追蹤執行狀態

第三步:建構實用的 AI Agent

現在我們來建構一個更實用的 Agent,整合多種工具。

加入網路搜尋能力

建立 03_practical_agent.py

# 03_practical_agent.py
from dotenv import load_dotenv
from langchain_openai import ChatOpenAI
from langchain_core.tools import tool
from langchain.agents import create_tool_calling_agent, AgentExecutor
from langchain_core.prompts import ChatPromptTemplate
import requests
import os

load_dotenv()

# 工具 1:計算器
@tool
def calculator(expression: str) -> str:
    """
    計算數學表達式。

    Args:
        expression: 有效的 Python 數學表達式,例如 "2 + 2" 或 "100 / 4"

    Returns:
        計算結果的字串
    """
    try:
        # 安全性檢查:只允許數學運算
        allowed_chars = set('0123456789+-*/.() ')
        if not all(c in allowed_chars for c in expression):
            return "錯誤:表達式包含不允許的字元"

        result = eval(expression)
        return f"{expression} = {result}"
    except Exception as e:
        return f"計算錯誤:{str(e)}"

# 工具 2:天氣查詢(使用免費 API)
@tool
def get_weather(city: str) -> str:
    """
    查詢指定城市的天氣。

    Args:
        city: 城市名稱,例如 "Taipei" 或 "Tokyo"

    Returns:
        天氣資訊的字串
    """
    try:
        # 使用 wttr.in 免費天氣 API
        url = f"https://wttr.in/{city}?format=%C+%t+%h"
        response = requests.get(url, timeout=10)

        if response.status_code == 200:
            return f"{city} 的天氣:{response.text.strip()}"
        else:
            return f"無法取得 {city} 的天氣資訊"
    except Exception as e:
        return f"查詢天氣時發生錯誤:{str(e)}"

# 工具 3:網路搜尋(使用 SerpAPI,需要 API Key)
@tool
def web_search(query: str) -> str:
    """
    搜尋網路上的資訊。

    Args:
        query: 搜尋關鍵字

    Returns:
        搜尋結果摘要
    """
    api_key = os.getenv("SERPAPI_API_KEY")

    if not api_key:
        return "搜尋功能未設定(需要 SERPAPI_API_KEY)"

    try:
        url = "https://serpapi.com/search"
        params = {
            "q": query,
            "api_key": api_key,
            "num": 3  # 只取前 3 筆結果
        }
        response = requests.get(url, params=params, timeout=15)
        data = response.json()

        if "organic_results" in data:
            results = []
            for item in data["organic_results"][:3]:
                title = item.get("title", "")
                snippet = item.get("snippet", "")
                results.append(f"- {title}: {snippet}")
            return "\n".join(results)
        else:
            return "找不到相關結果"
    except Exception as e:
        return f"搜尋時發生錯誤:{str(e)}"

# 工具 4:日期時間
@tool
def get_datetime() -> str:
    """取得目前的日期、時間和星期幾。"""
    from datetime import datetime
    now = datetime.now()
    weekday = ["週一", "週二", "週三", "週四", "週五", "週六", "週日"][now.weekday()]
    return f"現在是 {now.strftime('%Y年%m月%d日')} {weekday} {now.strftime('%H:%M:%S')}"

# 初始化 LLM
llm = ChatOpenAI(
    model="gpt-4o-mini",
    temperature=0  # Agent 建議使用較低的 temperature 以確保穩定性
)

# 定義工具列表
tools = [calculator, get_weather, web_search, get_datetime]

# 建立 Prompt 模板
prompt = ChatPromptTemplate.from_messages([
    ("system", """你是一個有幫助的 AI 助手,可以使用以下工具來回答問題:
    - calculator:進行數學計算
    - get_weather:查詢天氣
    - web_search:搜尋網路資訊
    - get_datetime:取得目前時間

    請根據用戶的問題,判斷是否需要使用工具,以及使用哪個工具。
    回答時請使用繁體中文。"""),
    ("human", "{input}"),
    ("placeholder", "{agent_scratchpad}"),
])

# 建立 Agent
agent = create_tool_calling_agent(llm, tools, prompt)

# 建立執行器
agent_executor = AgentExecutor(
    agent=agent,
    tools=tools,
    verbose=True,
    max_iterations=5,  # 限制最大迭代次數,避免無限循環
    handle_parsing_errors=True  # 處理解析錯誤
)

def chat(user_input: str) -> str:
    """與 Agent 對話的函數"""
    try:
        result = agent_executor.invoke({"input": user_input})
        return result["output"]
    except Exception as e:
        return f"發生錯誤:{str(e)}"

# 互動式對話
if __name__ == "__main__":
    print("=" * 50)
    print("AI Agent 已啟動!輸入 'quit' 離開")
    print("=" * 50)

    while True:
        user_input = input("\n你:").strip()

        if user_input.lower() in ['quit', 'exit', 'q']:
            print("再見!")
            break

        if not user_input:
            continue

        print("\nAgent 思考中...")
        response = chat(user_input)
        print(f"\nAgent:{response}")

執行這個 Agent:

python 03_practical_agent.py

現在你可以跟它進行對話:

你:台北現在天氣如何?
Agent:台北 的天氣:Partly cloudy +28°C 70%

你:幫我算一下如果我有 50000 元,年利率 3%,5 年後會變多少?
Agent:50000 * (1 + 0.03) ** 5 = 57963.70...

你:今天星期幾?
Agent:現在是 2025年01月15日 週三 14:30:25

插圖:AI Agent 工具呼叫流程圖

場景描述: 展示 AI Agent 處理用戶請求時的完整工具呼叫流程

視覺重點:

  • 主要內容清晰呈現

必須出現的元素:

  • 依據描述中的關鍵元素

需要顯示的中文字:

顏色調性: 專業、清晰

避免元素: 抽象圖形、齒輪、發光特效

Slug: ai-agent-tool-calling-flow

第四步:加入記憶功能

到目前為止,我們的 Agent 是「無記憶」的,每次對話都是獨立的。加入記憶功能讓 Agent 能記住之前的對話。

建立 04_agent_with_memory.py

# 04_agent_with_memory.py
from dotenv import load_dotenv
from langchain_openai import ChatOpenAI
from langchain_core.tools import tool
from langchain.agents import create_tool_calling_agent, AgentExecutor
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain_community.chat_message_histories import ChatMessageHistory
from langchain_core.runnables.history import RunnableWithMessageHistory

load_dotenv()

# 定義工具(簡化版)
@tool
def calculator(expression: str) -> str:
    """計算數學表達式。"""
    try:
        allowed_chars = set('0123456789+-*/.() ')
        if not all(c in allowed_chars for c in expression):
            return "錯誤:表達式包含不允許的字元"
        result = eval(expression)
        return f"{expression} = {result}"
    except Exception as e:
        return f"計算錯誤:{str(e)}"

@tool
def get_datetime() -> str:
    """取得目前的日期和時間。"""
    from datetime import datetime
    now = datetime.now()
    return f"現在是 {now.strftime('%Y年%m月%d日 %H:%M')}"

# 初始化 LLM
llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)

# 工具列表
tools = [calculator, get_datetime]

# 建立帶有記憶的 Prompt 模板
prompt = ChatPromptTemplate.from_messages([
    ("system", """你是一個有幫助的 AI 助手。
    你可以記住我們之前的對話。
    請使用繁體中文回答。"""),
    MessagesPlaceholder(variable_name="chat_history"),  # 對話歷史
    ("human", "{input}"),
    ("placeholder", "{agent_scratchpad}"),
])

# 建立 Agent
agent = create_tool_calling_agent(llm, tools, prompt)
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)

# 建立記憶儲存(使用 session_id 區分不同對話)
message_histories = {}

def get_session_history(session_id: str):
    if session_id not in message_histories:
        message_histories[session_id] = ChatMessageHistory()
    return message_histories[session_id]

# 包裝成帶記憶的 Agent
agent_with_memory = RunnableWithMessageHistory(
    agent_executor,
    get_session_history,
    input_messages_key="input",
    history_messages_key="chat_history",
)

def chat(user_input: str, session_id: str = "default") -> str:
    """與帶記憶的 Agent 對話"""
    try:
        result = agent_with_memory.invoke(
            {"input": user_input},
            config={"configurable": {"session_id": session_id}}
        )
        return result["output"]
    except Exception as e:
        return f"發生錯誤:{str(e)}"

# 測試記憶功能
if __name__ == "__main__":
    print("=" * 50)
    print("帶記憶的 AI Agent 已啟動!")
    print("=" * 50)

    # 測試記憶功能
    print("\n--- 測試記憶功能 ---")

    print("\n你:我叫小明")
    print(f"Agent:{chat('我叫小明')}")

    print("\n你:我最喜歡的數字是 7")
    print(f"Agent:{chat('我最喜歡的數字是 7')}")

    print("\n你:我叫什麼名字?我喜歡的數字是多少?")
    print(f"Agent:{chat('我叫什麼名字?我喜歡的數字是多少?')}")

    print("\n你:幫我用喜歡的數字計算 7 * 7")
    print(f"Agent:{chat('幫我用喜歡的數字計算 7 * 7')}")

執行後,你會發現 Agent 能記住之前對話的內容:

你:我叫小明
Agent:你好,小明!很高興認識你。有什麼我可以幫助你的嗎?

你:我叫什麼名字?
Agent:你叫小明。

[CTA-ai]

第五步:錯誤處理與最佳實踐

錯誤處理

建立 05_robust_agent.py,加入完整的錯誤處理:

# 05_robust_agent.py
from dotenv import load_dotenv
from langchain_openai import ChatOpenAI
from langchain_core.tools import tool
from langchain.agents import create_tool_calling_agent, AgentExecutor
from langchain_core.prompts import ChatPromptTemplate
from langchain.callbacks import StdOutCallbackHandler
import logging

load_dotenv()

# 設定日誌
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# 工具定義加入錯誤處理
@tool
def safe_calculator(expression: str) -> str:
    """
    安全的數學計算器。只接受基本數學運算。

    Args:
        expression: 數學表達式,例如 "2 + 2"
    """
    logger.info(f"計算表達式: {expression}")

    # 輸入驗證
    if not expression or len(expression) > 100:
        return "錯誤:表達式無效或過長"

    allowed_chars = set('0123456789+-*/.() ')
    if not all(c in allowed_chars for c in expression):
        return "錯誤:表達式包含不允許的字元。只能使用數字和基本運算符 (+-*/)"

    try:
        result = eval(expression)

        # 結果驗證
        if isinstance(result, (int, float)):
            return f"計算結果:{result}"
        else:
            return "錯誤:計算結果類型異常"

    except ZeroDivisionError:
        return "錯誤:除數不能為零"
    except SyntaxError:
        return "錯誤:表達式語法錯誤"
    except Exception as e:
        logger.error(f"計算錯誤: {e}")
        return f"計算時發生未預期的錯誤"

# 建立具有重試機制的 Agent
def create_robust_agent():
    llm = ChatOpenAI(
        model="gpt-4o-mini",
        temperature=0,
        max_retries=3,  # API 呼叫重試次數
        request_timeout=30  # 請求超時時間
    )

    tools = [safe_calculator]

    prompt = ChatPromptTemplate.from_messages([
        ("system", """你是一個謹慎的 AI 助手。
        當工具返回錯誤時,請向用戶清楚解釋問題並提供建議。
        使用繁體中文回答。"""),
        ("human", "{input}"),
        ("placeholder", "{agent_scratchpad}"),
    ])

    agent = create_tool_calling_agent(llm, tools, prompt)

    agent_executor = AgentExecutor(
        agent=agent,
        tools=tools,
        verbose=True,
        max_iterations=3,  # 限制迭代次數
        max_execution_time=60,  # 最大執行時間(秒)
        handle_parsing_errors=True,  # 處理解析錯誤
        return_intermediate_steps=True,  # 返回中間步驟(除錯用)
    )

    return agent_executor

def safe_chat(agent_executor, user_input: str) -> dict:
    """安全的對話函數,包含完整錯誤處理"""

    # 輸入驗證
    if not user_input or len(user_input) > 1000:
        return {
            "success": False,
            "output": "輸入無效或過長",
            "error": None
        }

    try:
        result = agent_executor.invoke({"input": user_input})
        return {
            "success": True,
            "output": result["output"],
            "steps": result.get("intermediate_steps", [])
        }
    except TimeoutError:
        logger.error("請求超時")
        return {
            "success": False,
            "output": "請求超時,請稍後再試",
            "error": "timeout"
        }
    except Exception as e:
        logger.error(f"執行錯誤: {e}")
        return {
            "success": False,
            "output": "發生錯誤,請稍後再試",
            "error": str(e)
        }

if __name__ == "__main__":
    agent = create_robust_agent()

    # 測試各種情況
    test_cases = [
        "計算 10 + 20",
        "計算 100 / 0",  # 除以零
        "計算 abc + 123",  # 無效輸入
    ]

    for test in test_cases:
        print(f"\n測試:{test}")
        result = safe_chat(agent, test)
        print(f"結果:{result['output']}")

最佳實踐清單

1. 工具設計

  • 為每個工具寫清楚的 docstring
  • 加入輸入驗證,防止注入攻擊
  • 處理所有可能的錯誤情況

2. 效能優化

  • 使用較便宜的模型進行測試(如 gpt-4o-mini)
  • 設定合理的 timeout 和重試次數
  • 限制 Agent 的最大迭代次數

3. 安全性

  • 不要在程式碼中硬編碼 API Key
  • 使用環境變數或秘密管理服務
  • 限制工具的權限範圍

4. 監控與除錯

  • 啟用 verbose 模式觀察 Agent 行為
  • 記錄日誌以便事後分析
  • 使用 LangSmith 進行進階監控

插圖:AI Agent 錯誤處理流程圖

場景描述: 展示 AI Agent 完整的錯誤處理與重試機制

視覺重點:

  • 主要內容清晰呈現

必須出現的元素:

  • 依據描述中的關鍵元素

需要顯示的中文字:

顏色調性: 專業、清晰

避免元素: 抽象圖形、齒輪、發光特效

Slug: ai-agent-error-handling-flow

第六步:部署你的 Agent

建立 API 服務

使用 FastAPI 將 Agent 包裝成 API 服務:

# api_server.py
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from dotenv import load_dotenv
# 匯入你的 Agent(假設已經定義好)

load_dotenv()

app = FastAPI(title="AI Agent API")

class ChatRequest(BaseModel):
    message: str
    session_id: str = "default"

class ChatResponse(BaseModel):
    response: str
    success: bool

@app.post("/chat", response_model=ChatResponse)
async def chat_endpoint(request: ChatRequest):
    try:
        # 呼叫你的 Agent
        response = chat(request.message, request.session_id)
        return ChatResponse(response=response, success=True)
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@app.get("/health")
async def health_check():
    return {"status": "healthy"}

啟動服務:

pip install fastapi uvicorn
uvicorn api_server:app --reload --port 8000

Docker 部署

建立 Dockerfile

FROM python:3.11-slim

WORKDIR /app

COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

COPY . .

EXPOSE 8000

CMD ["uvicorn", "api_server:app", "--host", "0.0.0.0", "--port", "8000"]

建立 requirements.txt

langchain
langchain-openai
langchain-community
python-dotenv
fastapi
uvicorn
requests

想深入了解不同框架的技術細節,可以參考 AI Agent 框架深度解析

完整專案結構

最終的專案結構應該如下:

ai-agent-tutorial/
├── .env                    # 環境變數(不要提交到 git)
├── .gitignore
├── requirements.txt
├── Dockerfile
├── test_setup.py           # 環境測試
├── 01_simple_chat.py       # 基礎對話
├── 02_agent_with_tool.py   # 加入工具
├── 03_practical_agent.py   # 實用 Agent
├── 04_agent_with_memory.py # 帶記憶 Agent
├── 05_robust_agent.py      # 錯誤處理
└── api_server.py           # API 服務

插圖:AI Agent 專案架構圖

場景描述: 展示完整的 AI Agent 專案檔案結構和模組關係

視覺重點:

  • 主要內容清晰呈現

必須出現的元素:

  • 依據描述中的關鍵元素

需要顯示的中文字:

顏色調性: 專業、清晰

避免元素: 抽象圖形、齒輪、發光特效

Slug: ai-agent-project-structure

下一步學習建議

完成這個教學後,你已經具備建構基礎 AI Agent 的能力。以下是進階學習的方向:

1. 深入學習 LangChain

  • 了解 Chain 和 LCEL(LangChain Expression Language)
  • 學習 LangGraph 處理複雜的多步驟流程
  • 使用 LangSmith 進行監控和除錯

2. 探索其他框架

3. 無程式碼方案

4. 企業應用

恭喜你完成了第一個 AI Agent!持續實作是最好的學習方式,試著修改程式碼、加入新工具,打造屬於你的 AI 助手。

[CTA-ai]

常見問題 FAQ

為什麼我的 Agent 一直呼叫錯誤的工具?

這通常是因為工具的 docstring 描述不夠清楚。LLM 會根據描述來判斷使用哪個工具,所以要確保每個工具的功能描述明確、不會與其他工具混淆。也可以在 system prompt 中加入更多指引。

API 費用大概是多少?

使用 GPT-4o-mini 模型,一般的開發測試大約每天 1-5 美元。正式上線後取決於使用量。建議在開發階段使用較便宜的模型,確認功能正常後再切換到效能更好的模型。

如何處理 Agent 的幻覺問題?

幾個方法:(1) 在 prompt 中明確告訴 Agent 「如果不確定就說不知道」 (2) 要求 Agent 只根據工具返回的結果回答 (3) 加入事實查核的工具 (4) 降低 temperature 參數提高輸出穩定性。

可以使用其他 LLM 嗎?

可以。LangChain 支援多種 LLM,包括 Anthropic Claude、Google Gemini、開源模型(如 Llama)等。只需要更換對應的套件和初始化方式。不同模型的工具呼叫能力有差異,需要實測。

如何讓 Agent 存取本地檔案或資料庫?

建立對應的工具函數即可。例如,建立一個讀取 CSV 檔案的工具、一個查詢 SQLite 資料庫的工具。注意安全性,要限制可存取的路徑和權限,防止 Agent 存取敏感資料。

需要專業的雲端建議?

無論您正在評估雲平台、優化現有架構,或尋找節費方案,我們都能提供協助

預約免費諮詢

相關文章