构建自定义工具

使用 LangChain 设计 Agentic 系统

Dilini K. Sumanapala, PhD

Founder & AI Engineer, Genverv, Ltd.

计算面积(平方英尺)

一居室公寓的矩形平面图

使用 LangChain 设计 Agentic 系统

计算面积(平方英尺)

一居室公寓的矩形平面图,长度与宽度分别标注为"side a"和"side b"。

使用 LangChain 设计 Agentic 系统

创建数学工具

LangChain 的内部查询处理

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

input = " 5, 7"

     

  • 自然语言输入

         
  • 提取数值字符串

使用 LangChain 设计 Agentic 系统

创建数学工具

定义工具函数

@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 装饰器
  • 命名函数
  • 编写文档字符串
  • .split() 分割输入
  • .strip() 去空格并转为 float
  • 计算 a×b 并返回
使用 LangChain 设计 Agentic 系统

工具与查询设置

# Define the tools that the agent can access
tools = [rectangle_area]

# Create a query using natural language query = "What is the area of a rectangle with sides 5 and 7?"
# Pass in the hypotenuse length tool and invoke the agent app = create_react_agent(model, tools)
使用 LangChain 设计 Agentic 系统

工具与查询设置

# Invoke the agent and print the response
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.
使用 LangChain 设计 Agentic 系统

预构建与自定义工具

    工具图标

 

使用 LangChain 设计 Agentic 系统

开始练习!

使用 LangChain 设计 Agentic 系统

Preparing Video For Download...