当前位置: 首页 > news >正文

[LangChain] 20. Tools配置

在实际开发中,经常还有如下的需求:

  1. 禁止模型调用某个工具
  2. 强制调用某个工具
  3. 注册多个函数工具

禁止模型调用工具

默认情况下,模型会自行决定是否使用 tool。但有时你希望它只能用自己的知识回答,怎么办?

你可以通过 tool_choice: "none" 禁用工具调用。

const result = await openai.chat.completions.create({model: "gpt-3.5-turbo-1106",messages: [{ role: "user", content: "北京天气如何?" }],tools, // 工具注册了,但不会被调用tool_choice: "none", // 显式禁止调用工具
});

强制调用工具

有时候你希望无论用户说什么,模型都必须调用某个函数

思考🤔什么场景有这样的需求?

  1. 系统内部函数(写日志、上报埋点):比如用户输入“哈哈哈”,你并不在乎他问了啥,但系统强制调用 logUserInteraction(),确保每次对话都会记录到数据库里。
  2. 必须走翻译函数:如果你做一个“统一英文客服”,无论用户输入中英文,都必须调用 translateToEnglish(),再交给后续处理。
  3. 结构化场景
    • 提取表单信息:无论用户说“我的名字是张三”还是“我来自北京”,你都强制调用 extractUserProfile(),把内容整理成 {name: "张三", city: "北京"}
    • 生成 SQL:即使用户说“hi”,也要求模型调用 toSQL(),这样就能保持统一的 SQL 输出。
const res = await openai.chat.completions.create({model: "gpt-3.5-turbo-1106",messages,tools,tool_choice: {type: "function",function: {name: "getCurrentWeather", // 强制调用该函数},},
});

注册多个工具

很多实际场景中,我们的机器人不仅能查天气,还可能支持查时间、查汇率、订机票……

tools 支持同时注册多个函数。模型会根据用户提问智能选择对应函数,无需额外配置。

额外需注意字段

parallel_tool_calls

是否允许模型在一次回复里并行提出多个 tool 调用。默认是开启的。

注意,parallel_tool_calls 只决定“能不能一次要多个工具”;用哪个工具仍由 tool_choice(或模型自动选择)决定。还有就是,parallel_tool_calls: false 只是禁止并行提出多个调用,也就是模型通常会只给一个 tool_call。它不保证“一轮就结束”。模型仍可能在下一轮继续提别的工具。

description

tools.function 中,description 字段能显著影响模型选择工具的行为。如果你注册多个工具,要写清楚每个工具的用途和限制,否则模型可能误选。

import OpenAI from "openai";
import { tools, getCurrentWeather, getCurrentTime } from "./tools.js";
import dotenv from "dotenv";
dotenv.config();const openai = new OpenAI({apiKey: process.env.API_KEY,
});// 1. 用户提的问题
const messages = [{role: "user",content: "北京今天的天气怎么样?另外,现在几点了?",},
];// 2. 将问题 + 工具箱一起给模型,模型判断是否使用工具
const res = await openai.chat.completions.create({model: "gpt-3.5-turbo-1106",messages,tools,parallel_tool_calls: false,
});console.dir(res.choices[0], { depth: null });const assistanMsg = res.choices[0].message;// 不需要调用工具的情况
if (!assistanMsg.tool_calls?.length) {console.log("模型未调用任何工具,直接回复的内容:", assistanMsg.content);process.exit(0);
}// 下面是需要调用工具的流程
messages.push(assistanMsg);// 构建一个本地的工具箱
const funcs = {getCurrentWeather,getCurrentTime,
};for (const call of assistanMsg.tool_calls) {const {id: tool_call_id,function: { name, arguments: args },} = call;const fn = funcs[name];if (!fn) {messages.push({role: "tool",tool_call_id,name,content: JSON.stringify({error: `${name}的工具不存在`,}),});continue;}const toolResult = await fn(args);// 针对工具调用返回的结果做一个简单的日志const content =typeof toolResult === "string" ? toolResult : JSON.stringify(toolResult);console.log(`已执行 ${name}(${JSON.stringify(args)}), 返回: ${content}`);// 将工具调用结果和之前的会话组装起来,再给大模型messages.push({role: "tool",tool_call_id,name,content,});
}const finalRes = await openai.chat.completions.create({model: "gpt-3.5-turbo-1106",messages,tools,
});
// console.log("最终回答:", finalRes.choices[0].message.content);
console.log(finalRes.choices[0].message.tool_calls);
// 外部工具
export function getCurrentWeather({ location, unit = "celsius" }) {const weather_info = {location, // 查询的城市名称temperature: "22",unit, // 温度的单位("celsius" 或 "fahrenheit")forecast: ["晴朗 ☀️", "微风 🌬️"], // 天气简单的描述};return JSON.stringify(weather_info);
}// 工具:获取当前时间
export function getCurrentTime({ format = "locale" }) {switch (format) {case "iso":return new Date().toISOString(); // ISO 格式:2025-06-24T09:00:00.000Zcase "locale":return new Date().toLocaleString(); // 本地格式:2025/6/24 17:00:00case "string":return new Date().toString(); // 英文字符串格式:Tue Jun 24 2025 17:00:00 GMT+0800default:return "不支持的 format 类型,请传入 iso / locale / string";}
}// 工具箱
export const tools = [{type: "function",function: {name: "getCurrentWeather",description: "获取指定城市当前的天气情况",parameters: {type: "object",properties: {location: {type: "string",description: "城市名称,例如:北京、上海、成都",},unit: {type: "string",enum: ["celsius", "fahrenheit"],description: "温度单位,可选:摄氏度或者华氏度",},},required: ["location"],},},},{type: "function",function: {name: "getCurrentTime",description: "获取当前时间(可选格式)",parameters: {type: "object",properties: {format: {type: "string",enum: ["iso", "locale", "string"],},},required: ["format"],},},},
];

-EOF-

http://www.hn-smt.com/news/46919/

相关文章:

  • 网络分析模型十
  • 拼音词典的野路子
  • 题解:P14002 [eJOI 2025] Navigation
  • 团队管理与技术驱动
  • Mastercam2021软件界面
  • 用 Python 和 Tesseract OCR 识别复杂验证码
  • 2025.11.16 萌熊
  • 手撸大模型的分布式训练:深刻理解大模型训练的“起飞”原理
  • 第28天(简单题中等题 二分查找)
  • 20232410 2025-2026-1 《网络与系统攻防技术》实验六实验报告
  • FastAPI Test Project
  • GS4:首个泛化高斯溅射语义SLAM框架,十倍效率三维建图 - MKT
  • 连续段 DP
  • 【UE客户端/技术策划】- 工具链篇(一):通用有限分层状态机框架(浅耦合+内建+全模块化)
  • Who wants to be king:2
  • 使用 LLM + Atlassian MCP 1小时生成年终总结
  • javascript类型
  • 美国本科申请中介怎么选?2025口碑TOP5出炉,藤校资源/申请成功率双保障
  • 2025 最新推荐!保定篮球俱乐部培训中心实力榜单:揭秘行业顶尖机构服务与教学优势权威指南
  • 2025美国研究生申请认准这些机构!藤校offer收割机/背景提升全流程,实力中介测评
  • V8的垃圾回收器
  • 智慧建筑工地传感器参数一览表
  • curtime在MySQL触发器中的使用方法
  • 是时候从 MySQL 转到 PostgreSQL 18 了
  • 小学生兴趣班避坑指南:2025年实力机构TOP5,妙小程AI编程领衔推荐
  • OpenHarmony onDrag拖拽事件
  • 2025年四川硬芯线厂家排名前十权威评测及行业选择指南
  • 2025年江苏浙江上海地区留学服务商综合实力排行榜TOP10
  • 教育资源优质学习机品牌全面解析与实用指南:2025年11月最新版TOP5推荐榜单
  • PlantAssistant-管道数据文件PCF