直到 R1 模型原生支持这个工具调用为止,我们可以使用 LangChain 中的临时方案,利用 OllamaFunctions 工具。
DeepSeek官方支持在测试中调用工具功能,但还不太稳定。虽然它没有官方提供JSON输出支持,但在本文中找到了一种解决办法。
llm = OllamaFunctions(
model="deepseek-r1:14b",
format="json", # 这在 bind_tools 中有影响
)
llm.bind_tools([naming_generator_from_int])
或者,可以使用
llm.with_structured_output(naming_generator_from_int,
include_raw=True # 无关紧要
)
注意通知书
《注意》
通知
Given the expert suggestions and the context, the most appropriate and concise translation is:
自通知“json”格式必须设置为bind_tools,否则它将仅适用于with_structured_output。
结构化输出当include_raw=False时,将返回,:
include_raw=False,并将返回:
命名生成器从整数(NamingGeneratorFromInt(x=11)) 可以生成基于整数的名称。
否则会返回:等等
{
│ 'raw': AIMessage(
│ │ content='',
│ │ additional_kwargs={},
│ │ response_metadata={},
│ │ id='run-1703a177-49b7-4202-972f-5d7be5ccabdd-0',
│ │ tool_calls=[
│ │ │ {
│ │ │ │ 'name': 'NamingGeneratorFromInt',
│ │ │ │ 'args': {'x': 11},
│ │ │ │ 'id': 'call_5c1c22c422e3455ebca56ff0c649d131',
│ │ │ │ 'type': 'tool_call'
│ │ │ }
│ │ ]
│ ),
│ 'parsed': NamingGeneratorFromInt(x=11),
│ 'parsing_error': '解析错误'
}
工具绑定
AI消息(
│ 内容='',
│ 额外的参数={},
│ 响应元数据={},
│ ID='run-d0bc7e99-0bc3-426c-ab54-2182f44926b4-0',
│ 工具调用列表=[
│ │ {
│ │ │ '名称': 'naming_generator_from_int',
│ │ │ '参数': {'x': 11},
│ │ │ 'ID': 'call_b16dec1f60664a0da6a00c32f562e76f',
│ │ │ '类型': 'tool_call'
│ │ }
│ ]
)
没有使用“JSON”格式
出错了啊
'deepseek-r1:14b' 没有返回有效的 JSON 数据。
请再试一次。
好的,用户想要我根据整数 11 生成一个名字。让我想想该怎么处理。
首先,我记得有一个名为 "naming_generator_from_int" 的工具,它正是为此设计的。这个工具可以接受一个整数作为输入,并根据输入的整数生成一个人工名字。
我需要确保我使用了正确的参数。该工具需要在 'x' 键下输入一个整数。因此,在这种情况下,x 应该是 11。
我没有看到其他更适合的工具。__conversational_response 工具是在不需要执行特定操作时使用的,但既然我们有一个命名生成器,我会使用那个。
我需要将响应格式化为一个 JSON 对象,其中 "tool" 设置为 "naming_generator_from_int","tool_input" 包含参数 { "x": 11 }。
让我再确认一下是否有任何生成名字时需要注意的规则或限制。工具的描述说这是一个人工名字,所以我不需要担心真实的名字或其他东西。
我想这就是所有内容了,现在开始组装吧。
{
"tool": "naming_generator_from_int",
"tool_input": {
"x": 11
}
}
ChatOllama
避免使用最新的ChatOllama类,因为OllamaFunctions很快就要被淘汰了。目前我们依赖OllamaFunctions作为过渡,所以暂时不建议使用ChatOllama类。
llm = ChatOllama(
model="deepseek-r1:14b",
format="json", # 不重要
)
llm.绑定工具([naming_generator_from_int])
也可以使用
llm.使用结构化输出(NamingGeneratorFromInt,
include_raw=True # 不重要
)
你可能会遇到这样的错误提示:
响应错误: registry.ollama.ai/library/deepseek-r1:14b 不提供工具支持,状态码:400
代码
chat-your-doc/simple/lc_deepseek_tool_call.py at master · XinyueZ/chat-your-doc一个优秀的大型语言模型项目仓库。您可以为 XinyueZ/chat-your-doc 的开发做出贡献,只需在 GitHub 上创建一个账户。