动态绑定工具参数:在LangChain中使用运行时值的实用指南

199 阅读2分钟
# 动态绑定工具参数:在LangChain中使用运行时值的实用指南

## 引言

在开发AI应用程序时,我们常常需要将某些参数在运行时传递给工具,而这些参数在设计时是未知的。例如,处理用户请求时需要使用用户ID。这些值不应由LLM(语言模型)控制,因为这可能导致安全风险。本文将指导您如何在LangChain中防止模型生成特定工具参数,并在运行时注入这些参数。

## 主要内容

### 隐藏参数不被模型生成

在LangChain中,我们可以使用`InjectedToolArg`注解来标记某些工具参数(如`user_id`)为在运行时注入,而不由模型生成。

```python
from typing import List
from langchain_core.tools import InjectedToolArg, tool
from typing_extensions import Annotated

user_to_pets = {}

@tool(parse_docstring=True)
def update_favorite_pets(
    pets: List[str], user_id: Annotated[str, InjectedToolArg]
) -> None:
    """Add the list of favorite pets."""
    user_to_pets[user_id] = pets

如上所示,user_id被标记为InjectedToolArg,因此它在工具调用时不会被模型生成。

代码示例

# 设置用户ID
user_id = "123"

# 手动调用工具并传递user_id
update_favorite_pets.invoke({"pets": ["lizard", "dog"], "user_id": user_id})
print(user_to_pets)  # 输出:{'123': ['lizard', 'dog']}

在模型调用工具时,user_id不会被自动生成:

tools = [
    update_favorite_pets,
    delete_favorite_pets,
    list_favorite_pets,
]
llm_with_tools = llm.bind_tools(tools)
ai_msg = llm_with_tools.invoke("my favorite animals are cats and parrots")
# 模型不会生成user_id

在运行时注入参数

我们需要自行注入user_id,然后执行模型生成的工具调用:

from copy import deepcopy
from langchain_core.runnables import chain

@chain
def inject_user_id(ai_msg):
    tool_calls = []
    for tool_call in ai_msg.tool_calls:
        tool_call_copy = deepcopy(tool_call)
        tool_call_copy["args"]["user_id"] = user_id
        tool_calls.append(tool_call_copy)
    return tool_calls

# 执行注入并调用工具
inject_user_id.invoke(ai_msg)

常见问题和解决方案

  • 模型无法生成某些参数:确保正确使用InjectedToolArg进行注解。
  • 工具调用失败:确认在调用时所有必需参数都已提供。

总结和进一步学习资源

我们探讨了在LangChain中如何使用运行时值动态绑定工具参数。这种方法能有效提升应用的安全性和灵活性。对于进一步学习,您可以查看以下资源:

参考资料

如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!

---END---