Custom Tools - main.py

"""
LangChain 1.0 - 自定义工具 (@tool 装饰器)
=========================================

本模块重点讲解:
1. 使用 @tool 装饰器创建工具(LangChain 1.0 推荐方式)
2. 工具的参数和文档字符串(docstring)的重要性
3. 测试工具
"""

import os
import sys


from langchain_core.tools import tool
from init_model import get_chat_model

# 导入自定义工具
from tools import weather
from tools import web_search
from tools import calculator

# ============================================================================
# 示例 1:使用第一个工具
# ============================================================================


def example_1():
    """
    示例1:创建天气查询工具
    """
    # 创建天气查询工具
    weather_tool = weather.get_weather
    # 测试天气工具
    print(weather_tool.invoke({"city": "北京"}))
    print(weather_tool.invoke({"city": "上海"}))


def example_2():
    tests = [
        {"operation": "add", "a": 10, "b": 5},
        {"operation": "multiply", "a": 7, "b": 8},
        {"operation": "divide", "a": 20, "b": 4},
    ]

    # 创建计算器工具
    calc_tool = calculator.get_calculator

    for test in tests:
        result = calc_tool.invoke(test)
        print(f"  {result}")


def example_3():
    """
    工具绑定到模型
    """
    calc_tool = calculator.get_calculator
    model_with_tools = get_chat_model(tools=[calc_tool])
    response = model_with_tools.invoke("北京今天天气怎么样?")
    # 检查模型是否要求调用工具
    if response.tool_calls:
        print(f"\n✅ AI 决定使用工具!")
        print(f"工具调用: {response.tool_calls}")
    else:
        print(f"\nℹ️ AI 直接回答(未使用工具)")
        print(f"回复: {response.content}")
添加新评论