HumanLayer与Flask框架:轻量级Web应用中集成人类审批的快速入门

HumanLayer与Flask框架:轻量级Web应用中集成人类审批的快速入门

【免费下载链接】humanlayer HumanLayer enables AI agents to communicate with humans in tool-based and async workflows. Guarantee human oversight of high-stakes function calls with approval workflows across slack, email and more. Bring your LLM and Framework of choice and start giving your AI agents safe access to the world. Agentic Workflows, human in the loop, tool calling 【免费下载链接】humanlayer 项目地址: https://gitcode.com/GitHub_Trending/hu/humanlayer

痛点:AI决策需要人类监督

在当今AI驱动的应用中,我们经常面临一个关键挑战:如何确保AI的重要决策得到适当的人类监督?特别是在金融、医疗、法律等高风险领域,完全自动化的AI决策可能带来严重后果。

你是否遇到过这些问题?

  • AI生成的财务报告需要人工审核
  • 客户服务AI需要人工确认敏感操作
  • 内容审核系统需要人工复审
  • 自动化流程需要人工审批节点

HumanLayer正是为解决这些问题而生,它提供了标准化的API和SDK,让开发者可以轻松地在AI应用中集成人类审批流程。

什么是HumanLayer?

HumanLayer是一个专门为AI代理设计的API和SDK,它使AI代理能够与人类进行通信,获取帮助、反馈和审批。通过HumanLayer,你可以:

  • ✅ 实现软件和人工驱动工作流的手动审批步骤
  • ✅ 对自主AI代理进行监督
  • ✅ 管理AI与人类之间的平稳过渡

Flask + HumanLayer:完美组合

Flask作为轻量级Python Web框架,以其简洁性和灵活性著称。结合HumanLayer,你可以快速构建需要人类审批的AI应用。

环境准备

首先,让我们设置开发环境:

# 创建虚拟环境
python -m venv venv
source venv/bin/activate  # Linux/Mac
# 或 venv\Scripts\activate  # Windows

# 安装依赖
pip install flask python-dotenv langchain langchain-openai humanlayer==0.7.9

项目结构

mermaid

核心代码实现

1. Flask主应用 (app.py)

from flask import Flask, jsonify, request
from typing import Dict, Union
from agent import run_agent

app = Flask(__name__)

@app.route("/")
def root() -> Dict[str, str]:
    return {"message": "欢迎使用HumanLayer Flask示例"}

@app.route("/run")
def run() -> Dict[str, str]:
    prompt = request.args.get("prompt")
    if not prompt:
        return {"status": "error", "message": "未提供提示词"}

    result = run_agent(prompt)
    return {"status": "success", "result": result}

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=8000)

2. Agent实现 (agent.py)

from dotenv import load_dotenv
from langchain_openai import ChatOpenAI
from langchain.agents import AgentType, initialize_agent
from langchain.tools import tool
from humanlayer.core.approval import HumanLayer

load_dotenv()

# 初始化HumanLayer
hl = HumanLayer(
    verbose=True,
    run_id="flask-langchain-math",
)

# 无需审批的工具函数
@tool
def add(x: int, y: int) -> int:
    """两个数字相加"""
    return x + y

# 需要审批的工具函数
@tool
@hl.require_approval()
def multiply(x: int, y: int) -> int:
    """两个数字相乘(需要审批)"""
    return x * y

def run_agent(prompt: str) -> str:
    """运行Agent并返回结果"""
    tools = [add.as_tool(), multiply.as_tool()]
    llm = ChatOpenAI(model="gpt-4", temperature=0)

    agent = initialize_agent(
        tools,
        llm,
        agent=AgentType.OPENAI_FUNCTIONS,
        verbose=True,
        handle_parsing_errors=True,
    )

    return agent.run(prompt)

3. 环境配置 (.env)

# HumanLayer API密钥
HUMANLAYER_API_KEY=your_api_key_here

# OpenAI API密钥
OPENAI_API_KEY=your_openai_api_key

审批流程详解

mermaid

测试与应用

启动应用

python app.py

测试用例

# 测试简单加法(无需审批)
curl "http://localhost:8000/run?prompt=2+3等于多少"

# 测试乘法(需要审批)
curl "http://localhost:8000/run?prompt=计算2乘以3"

预期响应

无需审批的操作:

{
  "status": "success",
  "result": "2+3等于5"
}

需要审批的操作:

{
  "status": "success",
  "result": "2乘以3等于6"
}

高级功能:Webhook集成

对于更复杂的应用场景,HumanLayer支持Webhook模式实现异步审批:

# app-webhooks.py 示例
from flask import Flask, request, jsonify
from humanlayer.core.approval import HumanLayer

app = Flask(__name__)
hl = HumanLayer()

# Webhook接收端点
@app.route('/webhook/inbound', methods=['POST'])
def inbound_webhook():
    data = request.json
    # 处理审批结果
    return jsonify({"status": "received"})

审批配置选项

HumanLayer提供了丰富的配置选项:

配置项说明示例值
run_id运行标识符"flask-math-app"
verbose详细日志True
timeout审批超时时间3600 (秒)
allowed_repliers允许的审批人["user@example.com"]

实际应用场景

1. 财务审批系统

@tool
@hl.require_approval(timeout=7200)  # 2小时超时
def approve_payment(amount: float, recipient: str) -> bool:
    """审批付款(金额大于1000需要审批)"""
    return True if amount <= 1000 else None  # 需要人工审批

2. 内容审核

@tool
@hl.require_approval(allowed_repliers=["moderator@company.com"])
def moderate_content(content: str) -> str:
    """内容审核(需要人工审核)"""
    return "待审核"

3. 客户服务升级

@tool
@hl.require_approval()
def escalate_to_human(customer_issue: str) -> str:
    """升级到人工客服"""
    return "已转接人工客服"

最佳实践

1. 错误处理

@app.route("/run")
def run():
    try:
        result = run_agent(prompt)
        return {"status": "success", "result": result}
    except Exception as e:
        return {"status": "error", "message": str(e)}

2. 超时管理

hl = HumanLayer(
    timeout=3600,  # 1小时超时
    run_id="production-app"
)

3. 日志记录

import logging
logging.basicConfig(level=logging.INFO)

性能优化建议

  1. 连接池管理: 重用HumanLayer客户端实例
  2. 异步处理: 对于高并发场景使用异步Web框架
  3. 缓存策略: 缓存已审批的结果
  4. 监控告警: 设置审批超时告警

总结

通过Flask与HumanLayer的集成,你可以快速构建需要人类审批的AI应用。这种组合提供了:

  • 🚀 快速开发: Flask的简洁性 + HumanLayer的标准API
  • 🔒 安全保障: 重要决策始终有人类监督
  • 📊 可审计性: 完整的审批记录和追溯
  • 🌐 多渠道支持: Slack、Email等多种审批渠道
  • 高性能: 优化的异步处理能力

无论你是构建财务系统、内容审核平台还是客户服务应用,HumanLayer都能为你提供可靠的人类审批基础设施。

下一步行动:

  1. 注册HumanLayer获取API密钥
  2. 按照本文示例搭建你的第一个审批应用
  3. 根据业务需求定制审批流程
  4. 部署到生产环境并监控运行状态

开始你的AI+人类协作之旅吧!

【免费下载链接】humanlayer HumanLayer enables AI agents to communicate with humans in tool-based and async workflows. Guarantee human oversight of high-stakes function calls with approval workflows across slack, email and more. Bring your LLM and Framework of choice and start giving your AI agents safe access to the world. Agentic Workflows, human in the loop, tool calling 【免费下载链接】humanlayer 项目地址: https://gitcode.com/GitHub_Trending/hu/humanlayer

创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值