langchain的内容实在太多了,tools工具相关的拆出来。

tools执行机制(重)

1、定义工具(说明、执行内容) # @tool一步搞定
2、llm绑定[tools] # @tool定义的函数名可以直接填到tools里面
3、用户输入内容 | 大模型根据内容判断是否需要调用工具,需要则代理执行对应的tool,return_direct默认是false,所以一般不会直接返回,而是再次喂给大模型。

llm.bind_tools([tools])绑定工具支持几种形式

1、符合openAI格式的json字符串。
2、@tool注解的方法
3、Pydantic类形式

工具定义-1、符合openAI格式的json字符串

代码:

# 这是一个纯字典,完全符合 OpenAI Function Calling 的 JSON 格式
sentiment_analyzer = {
    "name": "analyze_sentiment",
    "description": "分析文本的情感倾向(正面、负面或中性)",
    "parameters": {
        "type": "object",
        "properties": {
            "text": {
                "type": "string",
                "description": "需要分析的用户评论或文本内容"
            }
        },
        "required": ["text"]
    }
}

# 直接传给 bind_tools 也是完全支持的
llm.bind_tools([sentiment_analyzer])
工具定义-2、@tool注解的方法(最推荐)

代码:

from langchain_core.tools import tool

@tool
def sentiment_analyzer(text: str):
    """分析文本情感"""
    return "positive"

llm.bind_tools([sentiment_analyzer])
工具定义3、Pydantic类形式

判断一个类是否是pydantic类只有一个标准,那就是必须「继承」BaseModel,这是唯一标准

实际上如果实体类只被一个函数调用,完全可以都写在@tool里,只有实体类被反复引用的时候,用这种解耦的方式反而好

代码:

from pydantic import BaseModel

# 这就是标准 Pydantic 类
class User(BaseModel):  # 关键:继承 BaseModel
    name: str          # 类型注解字段
    age: int

@tool

常用参数:
args_schema # 指定实体类,如 args_schema=自定义类名
return_direct # 默认false,设置为true会直接返回

tools和function calling哪个好?

tools完胜
function calling是早期的概念了,依赖于json格式定义,解json,拿到方法再执行,太麻烦了。
tools一站式全部齐活,用的是代理,自动对应方法。

@tool参数列表

从代码里面看:

@overload
def tool(
    *,
    description: str | None = None,
    return_direct: bool = False,
    args_schema: ArgsSchema | None = None,
    infer_schema: bool = True,
    response_format: Literal["content", "content_and_artifact"] = "content",
    parse_docstring: bool = False,
    error_on_invalid_docstring: bool = True,
    extras: dict[str, Any] | None = None,
) 

报错

报错 AttributeError: ‘HuggingFacePipeline’ object has no attribute 'bind_tools

是因为基础的pipeline不支持这个属性,改为具体的pipeline即可,如:

model_name = "Qwen/Qwen2.5-0.5B-Instruct"

print(f"正在加载 {model_name} ...")
try:
    hf_pipeline = HuggingFacePipeline.from_model_id(
        model_id=model_name,
        task="text-generation",
        device_map="auto",
        pipeline_kwargs={
            "max_new_tokens": 256,
            "do_sample": False,
            # 0.5B 需要极低的温度来减少幻觉
            "temperature": 0.0
        }
    )
except ImportError:
    print("❌ 缺少依赖库,请运行: pip install langchain-huggingface transformers accelerate")
    exit()

llm = ChatHuggingFace(llm=hf_pipeline)
Logo

汇聚全球AI编程工具,助力开发者即刻编程。

更多推荐