自訂工具的建立

Designing Agentic Systems with LangChain

Dilini K. Sumanapala, PhD

Founder & AI Engineer, Genverv, Ltd.

計算平方英呎

開放式套房的長方形平面圖

Designing Agentic Systems with LangChain

計算平方英呎

開放式套房的長方形平面圖,長與寬分別標示為「side a」與「side b」。

Designing Agentic Systems with LangChain

建立數學工具

LangChain 的內部查詢處理

"What is the area of a rectangle with 
sides 5 and 7?"

input = " 5, 7"

     

  • 自然語言輸入

         
  • 取出數值字串

Designing Agentic Systems with LangChain

建立數學工具

定義你的工具函式

@tool

def rectangle_area(input: str) -> float:
"""Calculates the area of a rectangle given the lengths of sides a and b."""
sides = input.split(',')
a = float(sides[0].strip()) b = float(sides[1].strip())
return a * b

 

  • 使用 @tool 裝飾器
  • 命名函式
  • 撰寫 docstring
  • .split() 分割輸入
  • .strip() 去除空白並轉為 float
  • ab 相乘並回傳結果
Designing Agentic Systems with LangChain

設定工具與查詢

# 定義代理可使用的工具
tools = [rectangle_area]

# 以自然語言建立查詢 query = "What is the area of a rectangle with sides 5 and 7?"
# 傳入工具並啟動代理 app = create_react_agent(model, tools)
Designing Agentic Systems with LangChain

設定工具與查詢

# 呼叫代理並印出回應
response = app.invoke({"messages": [("human", query)]})
print(response['messages'][-1].content)
The area of the rectangle with sides 5 and 7 is 35 square units.
Designing Agentic Systems with LangChain

預建與自訂工具

    工具圖示

 

Designing Agentic Systems with LangChain

一起來練習吧!

Designing Agentic Systems with LangChain

Preparing Video For Download...