百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术文章 > 正文

langchain 如何提示大模型使用哪个工具函数

myzbx 2025-03-11 19:12 22 浏览

在使用 langchain 时,可以设置大模型绑定工具,这些工具用来完成各种功能,譬如搜索网络、操作数据库等。langchain 向大模型提问时,大模型可以自动选择要使用的工具返回给 langchain,langchain 再调用对应的工具。

大模型如何自动选择要使用的工具?

langchain 工具代码

使用 ollama 在本地运行大模型,下面代码片段,langchain 给大模型绑定了可使用的工具,然后会请求大模型,并打印请求和大模型响应。

# 省略 python 包引入代码

# 状态存储
class State(TypedDict):
    messages: Annotated[list, add_messages]

# 这个工具会回答有关猫的各种问题
# 为了简化代码,工具返回值没有提供有用信息
@tool
def cat_expert(cat_category: str) -> str:
    """A tool that helps users find information about cats."""
    return f"I'm here to help you find information about {cat_category} cats."


# 这个工具会回答有关狗的各种问题
# 为了简化代码,工具固定返回有关猎狗的介绍
@tool
def dog_expert(dog_category: str) -> str:
    """A tool that helps users find information about dogs."""
    return """Hounds are a type of dog that were originally bred for hunting,
            known for their strong sense of smell and excellent tracking skills.
            They come in various breeds such as Beagle, Bloodhound, Basset Hound,
            Dachshund (or Weiner Dog), Coonhound, and Greyhound among others"""


# 请求大模型
def chatbot(state: State):
    return {"messages": [llm_with_tools.invoke(state["messages"])]}


# 使用 ollma 在本地运行大模型 qwen2.5:14b-instruct-q8_0
llm = ChatOllama(model="qwen2.5:14b-instruct-q8_0", base_url="http://127.0.0.1:11434")

# 大模型绑定工具
tools = [cat_expert, dog_expert]
llm_with_tools = llm.bind_tools(tools)

# 创建状态图,添加大模型节点
graph_builder = StateGraph(State)
graph_builder.add_node("chatbot", chatbot)

# 创建工具节点,添加到状态图
tool_node = ToolNode(tools=tools)
graph_builder.add_node("tools", tool_node)

# 若大模型识别到要使用工具,会把请求路由到工具
graph_builder.add_conditional_edges("chatbot", tools_condition)
# 请求完工具后,会把响应结果交给大模型处理
graph_builder.add_edge("tools", "chatbot")
# 状态图把请求首先发送给大模型处理
graph_builder.set_entry_point("chatbot")
# 编译状态图
graph = graph_builder.compile()

# 向大模型请求问题,打印大模型和工具响应
for event in graph.stream({"messages": [("user", "tell me about Hound Dogs")]}, stream_mode="values"):
    msg_repr = event.get("messages")[-1].pretty_repr(html=True)
    print(msg_repr)

chatbot

运行程序,记录日志如下。可以看到大模型返回的第一条信息(Ai Message)就提示使用工具 dog_expert,似乎大模型自身就知道有这个工具,但这很不合理!!工具 dog_expert 是我们在代码中定义的函数,大模型自身不可能知道。

================================ Human Message =================================

tell me about Hound Dogs
================================== Ai Message ==================================
Tool Calls:
  dog_expert (e01c6ca1-9c5d-448c-ac04-48e371d14da2)
 Call ID: e01c6ca1-9c5d-448c-ac04-48e371d14da2
  Args:
    dog_category: Hound Dogs
================================= Tool Message =================================
Name: dog_expert

Hounds are a type of dog that were originally bred for hunting,
            known for their strong sense of smell and excellent tracking skills.
            They come in various breeds such as Beagle, Bloodhound, Basset Hound,
            Dachshund (or Weiner Dog), Coonhound, and Greyhound among others
================================== Ai Message ==================================

Hounds are a type of dog that were originally bred for hunting. They are known for their 
strong sense of smell and excellent tracking skills. Some popular hound breeds include the Beagle, 
Bloodhound, Basset Hound, Dachshund (or Weiner Dog), Coonhound, and Greyhound among others.
Each breed has its own unique characteristics and abilities that make them well-suited to different 
types of hunting or tracking tasks.

tcpdump 查看请求内容

大模型知道使用哪个工具的原因应该是 langchain 请求大模型时发送了额外信息,应该可以查找到对应代码,但是笔者代码能力欠佳,没找到 langchain 发送请求代码位置

但我们可以曲线救国,追踪流经 ollama 大模型服务端口tcp数据,可以看到全部发送给大模型的请求信息和其响应。下面日志打印了追踪本地 ollama 大模型服务端口信息,注意日志中以。。。 。。。包裹的内容是作者加的解释性信息。

# tcpdump -i enp5s0 port 11434 -A
。。。省略不相关信息 。。。
。。。发送给大模型的请求信息包含工具 dog_expoert 和 cat_expert 介绍。。。
B ..,...*oj..&P.......{"model": "qwen2.5:14b-instruct-q8_0", "messages": [{"role": "user", "content": 
"tell me about Hound Dogs", "images": []}], "tools": [{"type": "function", "function": {"name": 
"cat_expert", "description": "A tool that helps users find information about cats.", "parameters": 
{"properties": {"cat_category": {"type": "string"}}, "required": ["cat_category"], "type": "object"}}}, 
{"type": "function", "function": {"name": "dog_expert", "description": 
"A tool that helps users find information about dogs.", "parameters": {"properties": 
 {"dog_category": {"type": "string"}}, "required": ["dog_category"], "type": "object"}}}], "stream": false, 
"format": "", "options": {"mirostat": null, "mirostat_eta": null, "mirostat_tau": null, "num_ctx": null, 
"num_gpu": null, "num_thread": null, "num_predict": null, "repeat_last_n": null, "repeat_penalty": null, 
"temperature": null, "seed": null, "stop": null, "tfs_z": null, "top_k": null, "top_p": null}, 
"keep_alive": null}
14:55:18.263136 IP EnDS.11434 > 10.231.2.81.49935: Flags [.], ack 1217, win 501, length 0
。。。。省略不相关信息 。。
。。。大模型响应信息建议使用工具 dag_expert,并设置了工具参数。。。
{"model":"qwen2.5:14b-instruct-q8_0","created_at":"2024-11-02T06:55:19.165983569Z","message":
{"role":"assistant","content":"","tool_calls":[{"function":{"name":"dog_expert","arguments":
{"dog_category":"Hound"}}}]},"done_reason":"stop","done":true,"total_duration":903539694,
"load_duration":12678860,"prompt_eval_count":218,"prompt_eval_duration":145095000,
"eval_count":23,"eval_duration":610960000}
14:55:19.285836 IP 10.231.2.81.49935 > EnDS.11434: Flags [P.], seq 1217:1468, ack 523, win 1024, length 251
。。。。省略不相关信息 。。。
。。。发送给大模型的请求信息包含工具 dag_expert 返回信息。。。
.B ..,.../0j..0P.......{"model": "qwen2.5:14b-instruct-q8_0", "messages": [{"role": "user", "content": 
"tell me about Hound Dogs", "images": []}, {"role": "assistant", "content": "", "images": [], "tool_calls": 
[{"type": "function", "id": "9a97417d-f300-4e19-9bd0-42970002c257", "function": {"name": 
"dog_expert", "arguments": {"dog_category": "Hound"}}}]}, {"role": "tool", "content": 
"Hounds are a type of dog that were originally bred for hunting,\n            
known for their strong sense of smell and excellent tracking skills.\n            
They come in various breeds such as Beagle, Bloodhound, Basset Hound,\n            
Dachshund (or Weiner Dog), Coonhound, and Greyhound among others", "images": [], 
"tool_call_id": "9a97417d-f300-4e19-9bd0-42970002c257"}], "tools": [{"type": "function", 
"function": {"name": "cat_expert", "description": "A tool that helps users find information about cats.",
"parameters": {"properties": {"cat_category": {"type": "string"}}, "required": ["cat_category"], 
"type": "object"}}}, {"type": "function", "function": {"name": "dog_expert", "description": 
"A tool that helps users find information about dogs.", "parameters": {"properties": 
{"dog_category": {"type": "string"}}, "required": ["dog_category"], "type": "object"}}}], 
  "stream": false, "format": "", "options": {"mirostat": null, "mirostat_eta
14:55:19.286044 IP EnDS.11434 > 10.231.2.81.49935: Flags [.], ack 2788, win 501, length 0
。。。。省略不相关信息 。。。
。。。大模型给用户返回最终答案。。。
{"model":"qwen2.5:14b-instruct-q8_0","created_at":"2024-11-02T06:55:22.095858086Z",
"message":{"role":"assistant","content":"Hounds are a type of dog that were originally bred for 
 hunting. They are known for their strong sense of smell and excellent tracking skills. 
 Some popular hound breeds include the Beagle, Bloodhound, Basset Hound, Dachshund 
 (or Weiner Dog), Coonhound, and Greyhound among others. Each breed has its own unique
 characteristics and abilities that make them well-suited to different types of hunting or tracking 
 tasks."},"done_reason":"stop","done":true,"total_duration":2809906743,"load_duration":12378162,
 "prompt_eval_count":323,"prompt_eval_duration":74670000,"eval_count":90,"eval_duration":2475317000}
14:55:22.186196 IP 10.231.2.81.49935 > EnDS.11434: Flags [.], ack 1374, win 1026, length 0
。。。。省略不相关信息 。。。

从上面日志可知 langchain 向大模型发送请求时会把工具介绍和问题同时发送,大模型根据自己的知识判断是返回答案还是返回工具,若返回工具,会把工具要求的参数一同返回。示意图如下。

chatbot


本文刨析了 langchain 使用大模型调用工具的内部逻辑,虽然没有从代码上做解析,但追踪大模型的请求信息和响应可知:大模型是根据喂给它的工具信息决策回答用户问题时是使用某个工具还是直接回答。

相关推荐

资深架构师亲授,从堆栈到GC,一篇文章打通任督二脉!

“又双叒OOM了?”“服务半夜崩了,日志全是`java.lang.OutOfMemoryError`...”“GC停顿太长,用户投诉卡顿!”如果你也常被这些问题折磨,根本症结往往在于:你对Java...

Java JAR 启动内存参数配置指南:从基础设置到性能优化

在启动Java可执行JAR文件时,合理配置JVM内存参数是保障应用稳定性和性能的关键。本文将系统讲解如何通过命令行参数、环境变量等方式指定内存配置,并结合实际场景提供优化建议。一、核心内存...

浏览器存储"四大家族":谁才是你的数据管家?

当你关闭浏览器再重新打开,登录状态为何还在?购物车商品为何不会消失?这些"记忆"背后,藏着浏览器存储的"四大家族"——Cookie、localStorage、sessi...

SOP与SIP深度解析(sop与soic)

SOP(标准作业程序)与SIP(标准检验程序)是确保产品质量和生产效率的两大支柱,分别聚焦于生产执行和质量验证。一、核心区别:目标与作用域维度SOP(标准作业程序)SIP(标准检验程序)定位指导“如何...

Java 技术岗面试全景备战!从基础到架构的系统性通关攻略分享

Java技术岗的面试往往是一项多维度的能力检验。本文将会从核心知识点、项目经验到面试策略,为你梳理一份系统性的备战攻略!需要的同学可以私信小编【学习】一、技术基础:面试的“硬性指标”1.最重要的还是...

C++11 新特性(c++11新特性 pdf)

一、核心语言革新移动语义与右值引用通过&&标识临时对象(右值),实现资源转移而非复制。例如移动构造函数将原对象资源指针转移后置空,避免深拷贝,极大优化容器操作性能。12类型推导auto:自动推导变量类...

2026年前每个开发者都应该学习的技能

优秀开发者和伟大开发者之间的差距正在快速扩大。随着AI工具的爆炸式增长、自动化工作流程和日益复杂的技术栈,开发者不能再仅仅"知道如何编码"了。在2026年及以后,您的优势不仅仅是编写代...

看一看,Python这四种作用域你都知道吗?

点赞、收藏、加关注,下次找我不迷路一、啥是作用域?先打个比方比如说,你在自己的卧室(相当于一个小空间)里放了一本书,这本书在卧室里随便你怎么看,这就是这本书在卧室这个"作用域"内...

抛弃立即执行函数 (IIFE),拥抱现代 JavaScript 块级作用域

IIFE(ImmediatelyInvokedFunctionExpression)曾是JavaScript开发中的重要工具,但随着ES6+的块级作用域特性,我们现在有了更优雅的替代...

2025 年是时候重新认识 Symbol 的八大特性了?

大家好,很高兴又见面了,我是"高级前端进阶",由我带着大家一起关注前端前沿、深入前端底层技术,大家一起进步,也欢迎大家关注、点赞、收藏、转发!1.什么是Symbol原始类型在J...

函数、表达式与控制流:Rust 的核心语法构建块

在上一篇中我们了解了变量与类型,本篇将深入函数、表达式与控制流的使用,让你的代码更具逻辑性。一、函数定义与调用函数是组织和复用代码的基本单元。在Rust中,使用fn关键字定义函数:///计算...

所有权、借用与生命周期:理解 Rust 的核心机制

上一篇我们学习了函数、表达式和控制流,这一篇将正式进入Rust最核心、最独特的语言机制:所有权系统。一、为什么需要所有权机制?在C/C++中,内存管理依赖开发者手动操作,容易出现野指针、重复...

Rust 语言的借用规则:构筑安全内存管理体系的核心保障机制

前言在系统级编程范畴内,内存安全始终是一项极具挑战性的关键议题。Rust语言凭借其独树一帜的「借用规则」(BorrowingRules),于编译阶段便有效规避了诸如空指针、野指针以及数据竞争等一系...

函数编写指南:参数、返回值与作用域实战详解

你是否在编写函数时遇到过参数传递混乱、返回值逻辑不清晰,或者变量作用域导致的奇怪bug?别担心,这篇文章将用最通俗的语言和实战案例,带你彻底搞懂函数的核心三要素:参数、返回值与作用域。一、参数:灵活...

服务器频繁报错?5 步教你快速排查修复!运维必看!

服务器突然报错、网站打不开、数据库连不上……这些问题是不是让你头大?别慌!今天教你一套「望闻问切」的排查法,90%的服务器故障都能轻松解决!一、定位错误类型:先看日志再动手1.日志是关键系统日志...