langchain-learning/tools/tool_definition.py
2026-04-15 10:45:46 +08:00

57 lines
1.8 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import sys
from langchain_core.tools import tool, StructuredTool
from pydantic import BaseModel, Field
from sqlalchemy import True_
# 定义函数/tool
## 方式1使用注解
@tool
def get_weather1(city: str) -> str:
"""查询指定城市的最新天气信息"""
# 通过api调用天气网站的接口得到最新的天气信息
return f"{city}当前的温度为18°C"
class FieldInfo(BaseModel):
city: str = Field(description="要查询的城市名称")
## 注解中可以通过传参覆盖原有函数的描述等信息
@tool(
name_or_callable="get_weather1",
args_schema=FieldInfo,
description="查询某个城市的天气,并返回温度信息",
return_direct=True
)
def get_weather2(city: str) -> str:
"""查询指定城市的最新天气信息"""
# 通过api调用天气网站的接口得到最新的天气信息
return f"{city}当前的温度为18°C"
## 方式2
def get_weather3(city: str) -> str:
"""查询指定城市的最新天气信息"""
# 通过api调用天气网站的接口得到最新的天气信息
return f"{city}当前的温度为18°C"
get_weather3_tool = StructuredTool.from_function(
func=get_weather3,
name="get_weather3",
args_schema=FieldInfo,
description="第三个返回天气的函数"
)
if __name__ == '__main__':
# 调用函数,并打印返回结果
print(get_weather1("北京"))
print(get_weather1("巴黎"))
print(f"name={get_weather3_tool.name}")
print(f"args={get_weather3_tool.args}")
print(f"description={get_weather3_tool.description}")
print(f"return_direct={get_weather3_tool.return_direct}") # 直接返回如果为false就是会将返回值给到大模型让大模型进一步加工后再返回。如果是true则直接返回给用户。