当前位置: 首页 > news >正文

openai-agents实现input_guardrails

目录

    • 版本
    • 模块引入
    • 自定义LLM模型
    • input_guardrail设置
    • main函数

代码: input_guardrails.ipynb

版本

import agents
print(agents.__version__)
0.0.19

模块引入

from __future__ import annotationsfrom pydantic import BaseModelfrom agents import (Agent,GuardrailFunctionOutput,InputGuardrailTripwireTriggered,RunContextWrapper,Runner,TResponseInputItem,input_guardrail,
)

自定义LLM模型

from dotenv import load_dotenv
import os
from openai import AsyncOpenAI
from agents import OpenAIChatCompletionsModel, set_tracing_disabled## 在.env文件中设置这三个环境变量
load_dotenv()
QWEN_API_KEY = os.getenv("QWEN_API_KEY")
QWEN_BASE_URL = os.getenv("QWEN_BASE_URL")
QWEN_MODEL_NAME = os.getenv("QWEN_MODEL_NAME")
client = AsyncOpenAI(base_url=QWEN_BASE_URL, api_key=QWEN_API_KEY)
set_tracing_disabled(disabled=True)
qwen_model = OpenAIChatCompletionsModel(model=QWEN_MODEL_NAME, openai_client=client)

input_guardrail设置

import json
import re
### 1. An agent-based guardrail that is triggered if the user is asking to do math homework
class MathHomeworkOutput(BaseModel):reasoning: stris_math_homework: boolguardrail_agent = Agent(name="Guardrail check",instructions="""Check if the user is asking you to do their math homework. Respond with a JSON object that includes:- 'reasoning': your analysis of why this is or isn't math homework- 'is_math_homework': boolean value indicating if it's math homeworkExample output:```json{"reasoning": "The user greeted me with a simple 'hello', which does not indicate any mathematical problem or task.","is_math_homework": false}```""",model=qwen_model
)@input_guardrail
async def math_guardrail(context: RunContextWrapper[None], agent: Agent, input: str | list[TResponseInputItem]
) -> GuardrailFunctionOutput:"""This is an input guardrail function, which happens to call an agent to check if the inputis a math homework question."""result = await Runner.run(guardrail_agent, input, context=context.context)print(result.final_output)cleaned_json_str = re.sub(r"```(json)?", "", result.final_output).strip()final_output =json.loads(cleaned_json_str)return GuardrailFunctionOutput(output_info=final_output,tripwire_triggered=final_output["is_math_homework"],)

main函数

async def main():agent = Agent(name="Customer support agent",instructions="You are a customer support agent. You help customers with their questions.",input_guardrails=[math_guardrail],model = qwen_model)input_data: list[TResponseInputItem] = []while True:user_input = input("Enter a message: ")if user_input == "exit":breakinput_data.append({"role": "user","content": user_input,})try:result = await Runner.run(agent, input_data)print(result.final_output)input_data = result.to_input_list()except InputGuardrailTripwireTriggered:message = "Sorry, I can't help you with your math homework."print(message)input_data.append({"role": "assistant","content": message,})await main()
```json
{"reasoning": "The user asked for the capital of California, which is a geography question and not related to mathematics.","is_math_homework": false
}
```
The capital of California is **Sacramento**. Let me know if you have any more questions!
```json
{"reasoning": "The user provided an algebraic equation (2x + 5 = 11) that requires solving for the variable x. This is a typical math problem often assigned as part of homework.","is_math_homework": true
}
```
Sorry, I can't help you with your math homework.

参考链接:https://github.com/openai/openai-agents-python/blob/main/examples/agent_patterns/input_guardrails.py

http://www.lqws.cn/news/479377.html

相关文章:

  • 策略设计模式
  • 使用 RedisVL 进行复杂查询
  • Vue 组件定义方式的区别
  • Rabbitmq集成springboot 使用死信队列
  • day 39 打卡
  • 10-K 和 10-Q是什么?
  • MySQL基础函数篇
  • DubboSPI
  • 如何在FastAPI中玩转GitHub认证,让用户一键登录?
  • 安卓对外发布工程源码:怎么做到仅UI层公布
  • Openwrt基本初始化(安装中文包,磁盘扩容)
  • MATLAB的.mat文件
  • Python 商务数据分析—— NumPy 学习笔记Ⅱ
  • Spark教程1:Spark基础介绍
  • 爬虫入门练习(文字数据的爬取)
  • Vue3解析Spring Boot ResponseEntity
  • “MOOOA多目标鱼鹰算法在无人机多目标路径规划
  • 2025国际无人机应用及防控大会四大技术专题深度解析
  • 算法-动态规划-钢条切割问题
  • 理解后端开发中的中间件(以gin框架为例)
  • Android14 app被冻结导致进程间通信失败
  • 一键打包利器:gopack - 极简Go程序编译与压缩工具
  • 解决OSS存储桶未创建导致的XML错误
  • 【CBAP50技术手册】#44 Survey and Questionnaire(问卷调研):BA(业务分析师)的“信息入口”
  • 反无人机系统:技术利刃如何守护低空安全?
  • 【2025年软考中级】第三章数据结构3.4 数组与矩阵
  • 计算鱼眼相机的内参矩阵和畸变系数方法
  • 开源 python 应用 开发(二)基于pyautogui、open cv 视觉识别的工具自动化
  • linux VFS简介
  • Java面试复习:基础、面向对象、多线程、JVM与Spring核心考点