Solon AI 开发学习14 - chat - 工具上下文和附加参数

toolsContext(工具上下文),可以在工具调用时附加参数。比如,传递鉴权信息、数据隔离标识等。

  • 可以通过模型配置传递:ChatConfig:defaultToolsContext
  • 可以通过聊天选项传递:ChatOptions:toolsContext

1、示例

  • 通过 ChatConfig:defaultToolsContext 传递
public void case2(ChatConfig config, String user) {
    ChatModel chatModel = ChatModel.of(config)
                                   .defaultToolsAdd(new WeatherTool())  //添加默认工具
                                   .defaultToolsContextAdd("user", user) //添加默认工具上下文
                                   .build(); 
    
    chatModel.prompt("hello").call();
}

//user 参数不加 @Param(即不要求 llm 生成),由 toolsContext 传入(附加参数)!
public class WeatherTool {
    @ToolMapping(description = "获取指定城市的天气情况")
    public String get_weather(@Param(description = "根据用户提到的地点推测城市") String location, String user) {
        return "晴,24度"; //可使用 “数据库” 或 “网络” 接口根据 location 查询合适数据;
    }
}
  • 通过 ChatOptions:toolsContext 传递
public void case2(ChatConfig config, String user) {
    ChatModel chatModel = ChatModel.of(config).build(); 
    
    chatModel.prompt("hello")
        .options(o->o.toolsAdd(new WeatherTool()) //添加工具
                     .toolsContext(Utils.asMap("user", user))) //添加工具上下文
        .call();
}

//user 参数不加 @Param(即不要求 llm 生成),由 toolsContext 传入(附加参数)!
public class WeatherTool {
    @ToolMapping(description = "获取指定城市的天气情况")
    public String get_weather(@Param(description = "根据用户提到的地点推测城市") String location, String user) {
        return "晴,24度"; //可使用 “数据库” 或 “网络” 接口根据 location 查询合适数据;
    }
}

参考:《模型配置与请求选项》

2、具体说明

  • 兼容 MCP 参数传递

  • ChatOptions:toolsContext 或者 ChatConfig:defaultToolsContext 工具上下文

在 llm 生成的参数之外,传递用户附加的参数。如果参数名相同,toolsContext 会替换 llm 生成的参数。

  • @Param 注解的参数
情况 描述
@Param 注解 会成为 tool 的输入架构,会要求 llm 生成
@Param 注解 一般由用户额外输入(比如: toolsContext)
posted @ 2025-12-05 17:47  带刺的坐椅  阅读(0)  评论(0)    收藏  举报