本地大模型编程实战(13)与外部工具交互(4)

在使用 LLM(大语言模型) 调用工具方法时,可能会在运行时才会将类似 用户ID 的数值传递给工具。
大多数情况下,此类值不应由 LLM 控制。允许 LLM 控制 用户ID 可能会导致安全风险
相反,LLM 应该只控制本应由 LLM 控制的工具参数,而其他参数(如用户ID)应由应用程序逻辑固定。

本文将向您展示:如何防止模型生成某些工具参数并在运行时直接注入它们。

本文使用 llama3.1MFDoom/deepseek-r1-tool-calling:7b 进行演练。 deepseek-r1 不支持 langchain 的 bind_tools 方法。

准备

在正式开始撸代码之前,需要准备一下编程环境。

  1. 计算机
    本文涉及的所有代码可以在没有显存的环境中执行。 我使用的机器配置为:

    • CPU: Intel i5-8400 2.80GHz
    • 内存: 16GB
  2. Visual Studio Code 和 venv
    这是很受欢迎的开发工具,相关文章的代码可以在 Visual Studio Code 中开发和调试。 我们用 pythonvenv 创建虚拟环境, 详见:
    在Visual Studio Code中配置venv

  3. Ollama
    Ollama 平台上部署本地大模型非常方便,基于此平台,我们可以让 langchain 使用 llama3.1qwen2.5deepseek 等各种本地大模型。详见:
    在langchian中使用本地部署的llama3.1大模型

定义工具方法

下面的工具方法将用于后面的测试:

user_to_pets = {
   }

@tool(parse_docstring=True)
def update_favorite_pets(
    pets: List[str], user_id: Annotated[str, InjectedToolArg]
) -> None:
    """添加喜爱的宠物列表。

    Args:
        pets: 喜爱的宠物列表。
        user_id: 用户 ID。
    """
    print(f'update_favorite_pets is called:{
     user_id}')
    user_to_pets[user_id] = pets


@tool(parse_docstring=True)
def delete_favorite_pets(user_id: Annotated[str, InjectedToolArg]) -> None:
    """删除喜爱的宠物列表。

    Args:
        user_id: 用户 ID。
    """
    print(f'delete_favorite_pets is called:{
     user_id}')
    if user_id in user_to_pets:
        del user_to_pets[user_id]


@tool(parse_docstring=True)
def list_favorite_pets(user_id: Annotated[str, InjectedToolArg]) -> None:
    """列出最喜欢的宠物(如果有)。

    Args:
        user_id: 用户 ID。
    """
    print(f'list_favorite_pets is called:{
     user_id}'
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值