tools 工具类

calculator.py

"""
自定义工具:计算器
==================

演示带多个参数的工具
"""

from langchain.tools import tool


@tool
def calculator(operation: str, num1: float, num2: float) -> float:
    """
    执行基本的数学计算

    参数:
        operation: 运算类型,支持 "add"(加), "subtract"(减), "multiply"(乘), "divide"(除)
        a: 第一个数字
        b: 第二个数字

    返回:
        计算结果字符串
    """
    operations = {
        "add": lambda x, y: x + y,
        "subtract": lambda x, y: x - y,
        "multiply": lambda x, y: x * y,
        "divide": lambda x, y: x / y if y != 0 else "错误:除数不能为零",
    }

    if operation not in operations:
        return f"不支持的运算类型:{operation}。支持的类型:add, subtract, multiply, divide"

    try:
        result = operations[operation](num1, num2)
        return f"{num1} {operation} {num2} = {result}"
    except Exception as e:
        return f"计算错误:{e}"


# 测试工具
if __name__ == "__main__":
    print("测试计算器工具:")
    print(calculator.invoke({"operation": "add", "a": 10, "b": 5}))
    print(calculator.invoke({"operation": "multiply", "a": 7, "b": 8}))
    print(calculator.invoke({"operation": "divide", "a": 20, "b": 4}))

weather.py

"""
自定义工具:天气查询
====================

使用 @tool 装饰器创建工具(LangChain 1.0 推荐方式)
"""

from langchain.tools import tool


@tool
def get_weather(city: str) -> str:
    """
    获取指定城市的天气信息
    参数:
        city (str): 要查询天气的城市名称 例如 "北京"

    返回:
        str: 包含天气信息的字符串,格式为 "城市 天气描述 温度"

    """
    # 模拟天气数据
    weather_data = {
        "北京": "晴天,温度 15°C,空气质量良好",
        "上海": "多云,温度 18°C,有轻微雾霾",
        "深圳": "阴天,温度 22°C,可能有小雨",
        "成都": "小雨,温度 12°C,湿度较高",
    }
    # 检查城市是否在数据中

    if city not in weather_data:
        return f"城市 {city} 的天气信息未找到"

    # 返回天气信息
    return weather_data.get(city, f"抱歉,暂时没有{city}的天气数据")


# 测试工具
if __name__ == "__main__":
    print("测试天气工具:")
    print(f"北京天气: {get_weather.invoke({'city': '北京'})}")
    print(f"上海天气: {get_weather.invoke({'city': '上海'})}")

web_search.py

"""
自定义工具:网页搜索(模拟)
============================

演示可选参数的工具
"""

from langchain.tools import tool
from typing import Optional


@tool
def web_search(query: str, num_results: Optional[int] = 3) -> str:
    """
    模拟网页搜索工具

    参数:
        query: 搜索查询
        num_results: 返回的结果数量(可选,默认3)

    返回:
        搜索结果字符串
    """

    # 模拟搜索结果
    mock_results = {
        "Python": [
            "Python官方网站 - https://www.python.org",
            "Python教程 - 菜鸟教程",
            "Python最佳实践 - Real Python",
        ],
        "机器学习": [
            "机器学习入门 - Coursera",
            "Scikit-learn文档",
            "机器学习实战 - GitHub",
        ],
        "LangChain": [
            "LangChain官方文档",
            "LangChain GitHub仓库",
            "LangChain教程 - YouTube",
        ],
    }

    # 查找结果
    results = []
    for key in mock_results:
        if key.lower() in query.lower():
            results.extend(mock_results[key][:num_results])
            break

    if not results:
        return f"未找到关于'{query}'的结果"

        # 格式化输出
    output = f"搜索 '{query}' 找到 {len(results)} 条结果:\n"
    for i, result in enumerate(results, 1):
        output += f"{i}. {result}\n"

    return output.strip()


if __name__ == "__main__":
    print("测试搜索工具:")
    print(web_search.invoke({"query": "Python"}))
    print("\n" + web_search.invoke({"query": "LangChain", "num_results": 2}))
添加新评论