chat - 工具上下文和附加参数
2026年1月23日 下午11:09:56
toolContext(工具上下文),可以在工具调用时附加参数。比如,传递鉴权信息、数据隔离标识等。
- 可以通过模型配置传递:
ChatConfig:defaultToolContext - 可以通过聊天选项传递:
ChatOptions:toolContext
1、示例
- 通过
ChatConfig:defaultToolContext传递
public void case2(ChatConfig config, String user) {
ChatModel chatModel = ChatModel.of(config)
.defaultToolAdd(new WeatherTool()) //添加默认工具
.defaultToolContextPut("user", user) //添加默认工具上下文
.build();
chatModel.prompt("hello").call();
}
//user 参数不加 @Param(即不要求 llm 生成),由 toolContext 传入(附加参数)!
public class WeatherTool {
@ToolMapping(description = "获取指定城市的天气情况")
public String get_weather(@Param(description = "根据用户提到的地点推测城市") String location, String user) {
return "晴,24度"; //可使用 “数据库” 或 “网络” 接口根据 location 查询合适数据;
}
}
- 通过
ChatOptions:toolContext传递
public void case2(ChatConfig config, String user) {
ChatModel chatModel = ChatModel.of(config).build();
chatModel.prompt("hello")
.options(o->o.toolAdd(new WeatherTool()) //添加工具
.toolContextPut("user", user)) //添加工具上下文
.call();
}
//user 参数不加 @Param(即不要求 llm 生成),由 toolContext 传入(附加参数)!
public class WeatherTool {
@ToolMapping(description = "获取指定城市的天气情况")
public String get_weather(@Param(description = "根据用户提到的地点推测城市") String location, String user) {
return "晴,24度"; //可使用 “数据库” 或 “网络” 接口根据 location 查询合适数据;
}
}
参考:《模型配置与请求选项》
2、具体说明
-
兼容
MCP参数传递 -
ChatOptions:toolContext或者ChatConfig:defaultToolContext工具上下文
在 llm 生成的参数之外,传递用户附加的参数。如果参数名相同,toolContext 会替换 llm 生成的参数。
@Param注解的参数
| 情况 | 描述 |
|---|---|
有 @Param 注解 | 会成为 tool 的输入架构,会要求 llm 生成 |
无 @Param 注解 | 一般由用户额外输入(比如: toolContext) |