在使用 LLM(大语言模型)
调用工具方法时,可能会在运行时才会将类似 用户ID 的数值传递给工具。
大多数情况下,此类值不应由 LLM
控制。允许 LLM
控制 用户ID 可能会导致安全风险。
相反,LLM
应该只控制本应由 LLM
控制的工具参数,而其他参数(如用户ID)应由应用程序逻辑固定。
本文将向您展示:如何防止模型生成某些工具参数并在运行时直接注入它们。
本文使用
llama3.1
和MFDoom/deepseek-r1-tool-calling:7b
进行演练。deepseek-r1
不支持langchain
的 bind_tools 方法。
准备
在正式开始撸代码之前,需要准备一下编程环境。
-
计算机
本文涉及的所有代码可以在没有显存的环境中执行。 我使用的机器配置为:- CPU: Intel i5-8400 2.80GHz
- 内存: 16GB
-
Visual Studio Code 和 venv
这是很受欢迎的开发工具,相关文章的代码可以在Visual Studio Code
中开发和调试。 我们用python
的venv
创建虚拟环境, 详见:
在Visual Studio Code中配置venv。 -
Ollama
在Ollama
平台上部署本地大模型非常方便,基于此平台,我们可以让langchain
使用llama3.1
、qwen2.5
、deepseek
等各种本地大模型。详见:
在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}'