Datawhale OpenAI官方智能体框架202510
课程地址:https://github.com/datawhalechina/wow-agent/tree/main/tutorial/%E7%AC%AC03%E7%AB%A0-openai-agents
目录
第01、02章
Agents的核心组件
智能体指令的最佳实践
结构化 Prompt 模板
LangGPT 中的 Role (角色)模板
创建阿里云API KEY
手搓一个土得掉渣的Agent
定义一个智能客服智能体
简历信息提取智能体
OpenAI实现阅卷智能体
第03章-openai-agents
01-安装与配置
02-初步尝鲜
作业
does drinking tea good for the body?
如何证明勾股定理?
who was the first president of the united states?
what is life?
第01、02章
Agents的核心组件
一个完整的Agent组件主要由三个核心构成:
1. 模型 (Model):
- 角色:作为Agent的“大脑”,负责理解用户输入,进行推理和规划,并选择合适的工具进行执行。
- 类型:常用的模型包括ReAct、Chain-of-Thought、Tree-of-Thought等,它们提供不同的推理框架,帮助Agent进行多轮交互和决策。
- 重要性:模型是Agent的核心,其推理能力决定了Agent的行动效率和准确性。
2. 工具 (Tools):
- 角色:作为Agent与外界交互的“桥梁”,允许Agent访问外部数据和服务,执行各种任务。
- 类型:工具可以是各种API,例如数据库查询、搜索引擎、代码执行器、邮件发送器等。
- 重要性:工具扩展了Agent的能力,使其能够执行更复杂的任务。
3. 编排层 (Orchestration Layer):
- 角色:负责管理Agent的内部状态,协调模型和工具的使用,并根据目标指导Agent的行动。
- 类型:编排层可以使用各种推理框架,例如ReAct、Chain-of-Thought等,帮助Agent进行规划和决策。
- 重要性:编排层是Agent的“指挥中心”,负责协调各个组件,确保Agent的行动符合目标。
选择模型的原则很简单:
- 建立评估以确定性能基线。
- 专注于使用可用的最佳模型达到您的准确性目标。
- 尽可能用较小的模型替换较大的模型,以优化成本和延迟。
智能体指令的最佳实践
- 使用现有文档创建大语言模型友好的例程:在创建例程时,可以使用现有的操作程序、支持脚本或政策文档。例如,在客户服务中,例程可以大致对应知识库中的各个文章。
- 促使智能体分解任务:从密集的资源中提供更小、更清晰的步骤,有助于最大限度地减少歧义,帮助模型更好地遵循指令。
- 定义明确的行动:确保例程中的每个步骤都对应一个特定的行动或输出。例如,一个步骤可能指示智能体向用户询问订单号,或调用应用程序编程接口检索账户详细信息。明确行动(甚至是面向用户消息的措辞)可以减少解释错误的空间。
- 捕捉边缘情况:现实世界的交互通常会产生决策点,例如当用户提供不完整信息或提出意外问题时如何继续。一个强大的例程会预见到常见的变化,并包括如何通过条件步骤或分支来处理这些情况的指令,例如在缺少必需信息时的替代步骤。
结构化 Prompt 模板
一个好的结构化 Prompt 模板,某种意义上是构建了一个好的全局思维链。 如 LangGPT 中展示的模板设计时就考虑了如下思维链:
Role (角色) -> Profile(角色简介)—> Profile 下的 skill (角色技能) -> Rules (角色要遵守的规则) -> Workflow (满足上述条件的角色的工作流程) -> Initialization (进行正式开始工作的初始化准备) -> 开始实际使用
LangGPT 中的 Role (角色)模板
Role: Your_Role_NameProfileAuthor: YZFly
Version: 0.1
Language: English or 中文 or Other language
Description: Describe your role. Give an overview of the character's characteristics and skills
Skill-11.技能描述1 2.技能描述2Skill-21.技能描述1 2.技能描述2RulesDon't break character under any circumstance.
Don't talk nonsense and make up facts.
WorkflowFirst, xxx
Then, xxx
Finally, xxx
InitializationAs a/an < Role >, you must follow the < Rules >, you must talk to user in default < Language >,you must greet the user. Then introduce yourself and introduce the < Workflow >.
Prompt Chain 将原有需求分解,通过用多个小的 Prompt 来串联/并联,共同解决一项复杂任务。
Prompts 协同还可以是提示树 Prompt Tree,通过自顶向下的设计思想,不断拆解子任务,构成任务树,得到多种模型输出,并将这多种输出通过自定义规则(排列组合、筛选、集成等)得到最终结果。 API 版本的 Prompt Chain 结合编程可以将整个流程变得更加自动化。
创建阿里云API KEY
大模型服务平台百炼控制台https://bailian.console.aliyun.com/?tab=model#/model-market
创建.env文件:
在项目的根目录新建一个txt文件,把文件名改成.env。需要注意的是,前面这个点儿不能省略。因为这个文件就叫做dotenv,dot就是点儿的意思。
api_key = "sk-b197b7b4ef6b4a96a8e41d82c2414af0"
base_url = "https://dashscope.aliyuncs.com/compatible-mode/v1"
chat_model = "qwen-max-latest"
创建虚拟环境:
conda create -n wow-agent python=3.9
-n: -name
激活环境:
激活环境:conda activate wow-agent
安装 openai 和python-dotenv
包
pip install openai -i https://pypi.tuna.tsinghua.edu.cn/simple
pip install python-dotenv -i https://pypi.tuna.tsinghua.edu.cn/simple
安装完成后,可以运行以下命令检查是否已安装:
pip show python-dotenv
手搓一个土得掉渣的Agent
import os
from dotenv import load_dotenv# 加载 .env 文件中的环境变量
load_dotenv()# 从环境变量中读取 DashScope 的 API Key
# 建议在 .env 中设置:DASHSCOPE_API_KEY=sk-b197b7b4ef6b4a96a8e41d82c2414af0
api_key = os.getenv('DASHSCOPE_API_KEY')# 阿里云 DashScope 兼容 OpenAI API 的固定 base_url
base_url = "https://dashscope.aliyuncs.com/compatible-mode/v1"# 使用的 Qwen 模型名称
chat_model = "qwen-max-latest"from openai import OpenAI
client = OpenAI(api_key = api_key,base_url = base_url
)def get_completion(prompt):response = client.chat.completions.create(model="qwen-max-latest", # 填写需要调用的模型名称messages=[{"role": "user", "content": prompt},],)return response.choices[0].message.contentresponse = get_completion("你是谁?")
print(response)
定义一个智能客服智能体
import os
from dotenv import load_dotenv
from openai import OpenAI# ======================
# 1. 加载环境变量和初始化客户端
# ======================
load_dotenv()api_key = os.getenv("DASHSCOPE_API_KEY")
if not api_key:raise ValueError("❌ 请在 .env 文件中设置 DASHSCOPE_API_KEY")base_url = "https://dashscope.aliyuncs.com/compatible-mode/v1"
chat_model = "qwen-max-latest"client = OpenAI(api_key=api_key, base_url=base_url)# ======================
# 2. 定义所有 Prompt
# ======================
SYS_PROMPT = """你是一个聪明的客服。您将能够根据用户的问题将不同的任务分配给不同的人。您有以下业务线:
1. 用户注册。如果用户想要执行这样的操作,您应该发送一个带有"registered workers"的特殊令牌。并告诉用户您正在调用它。
2. 用户数据查询。如果用户想要执行这样的操作,您应该发送一个带有"query workers"的特殊令牌。并告诉用户您正在调用它。
3. 删除用户数据。如果用户想执行这种类型的操作,您应该发送一个带有"delete workers"的特殊令牌。并告诉用户您正在调用它。
请直接输出特殊令牌(如:registered workers),不要添加其他解释。"""REGISTERED_PROMPT = """您的任务是根据用户信息存储数据。您需要从用户那里获得以下信息:
1.用户名、性别、年龄
2.用户设置的密码
3.用户的电子邮件地址
如果用户没有提供此信息,您需要提示用户提供。如果用户提供了此信息,则需要将此信息存储在数据库中,并告诉用户注册成功。
存储方法是使用SQL语句。您可以使用SQL编写插入语句,并且需要生成用户ID并将其返回给用户。
如果用户没有新问题,您应该回复带有 "customer service" 的特殊令牌,以结束任务。"""QUERY_PROMPT = """您的任务是查询用户信息。您需要从用户那里获得以下信息:
1.用户ID
2.用户设置的密码
如果用户没有提供此信息,则需要提示用户提供。如果用户提供了此信息,那么需要查询数据库。如果用户ID和密码匹配,则需要返回用户的信息。
如果用户没有新问题,您应该回复带有 "customer service" 的特殊令牌,以结束任务。"""DELETE_PROMPT = """您的任务是删除用户信息。您需要从用户那里获得以下信息:
1.用户ID
2.用户设置的密码
3.用户的电子邮件地址
如果用户没有提供此信息,则需要提示用户提供该信息。
如果用户提供了这些信息,则需要查询数据库。如果用户ID和密码匹配,您需要通知用户验证码已发送到他们的电子邮件,需要进行验证。
如果用户没有新问题,您应该回复带有 "customer service" 的特殊令牌,以结束任务。"""# ======================
# 3. 两阶段函数定义
# ======================def identify_task(user_input: str) -> str:"""第一阶段:识别用户意图,返回特殊令牌"""print("🔍 [阶段1] 正在识别用户意图...")response = client.chat.completions.create(model=chat_model,messages=[{"role": "system", "content": SYS_PROMPT},{"role": "user", "content": user_input}],temperature=0.0 # 确保输出稳定)token = response.choices[0].message.content.strip()print(f"✅ 识别结果: '{token}'")return tokendef execute_task(task_token: str, user_input: str) -> str:"""第二阶段:根据令牌执行具体任务"""print("⚙️ [阶段2] 正在执行具体任务...")if "registered workers" in task_token:system_prompt = REGISTERED_PROMPTelif "query workers" in task_token:system_prompt = QUERY_PROMPTelif "delete workers" in task_token:system_prompt = DELETE_PROMPTelse:return "❌ 无法识别任务类型,请重新描述您的需求。"response = client.chat.completions.create(model=chat_model,messages=[{"role": "system", "content": system_prompt},{"role": "user", "content": user_input}])return response.choices[0].message.content.strip()# ======================
# 4. 主程序入口
# ======================
def main():print("👋 欢迎使用智能客服系统!")print("支持操作:注册、查询、删除用户数据")print("-" * 40)while True:user_input = input("\n👤 请输入您的请求(输入 'quit' 退出): ").strip()if user_input.lower() in ['quit', 'exit', 'q']:print("👋 再见!")breakif not user_input:continue# 第一阶段:识别任务token = identify_task(user_input)# 第二阶段:执行任务reply = execute_task(token, user_input)print(f"\n💬 客服回复:\n{reply}")# ======================
# 5. 运行程序
# ======================
if __name__ == "__main__":main()
简历信息提取智能体
import os
from dotenv import load_dotenv
from openai import OpenAI# ======================
# 1. 加载环境变量和初始化客户端
# ======================
load_dotenv()api_key = os.getenv("DASHSCOPE_API_KEY")
base_url = "https://dashscope.aliyuncs.com/compatible-mode/v1"
chat_model = "qwen-max-latest"client = OpenAI(api_key=api_key, base_url=base_url)def get_completion(prompt):response = client.chat.completions.create(model=chat_model, # 填写需要调用的模型名称messages=[{"role": "user", "content": prompt},],)return response.choices[0].message.content# response = get_completion("你是谁?")
# print(response)from datetime import datetime, date
from typing import List, Optional
from pydantic import BaseModel, Field, field_validator, EmailStr, model_validator# 定义这个pydantic模型是关键的关键
class Resume(BaseModel):name: Optional[str] = Field(None, description="求职者姓名,如果没找到就置为空字符串")city: Optional[str] = Field(None, description="求职者居住地,如果没找到就置为空字符串")birthday: Optional[str] = Field(None, description="求职者生日,如果没找到就置为空字符串")phone: Optional[str] = Field(None, description="求职者手机号,如果没找到就置为空字符串")email: Optional[str] = Field(None, description="求职者邮箱,如果没找到就置为空字符串")education: Optional[List[str]] = Field(None, description="求职者教育背景")experience: Optional[List[str]] = Field(None, description="求职者工作或实习经历,如果没找到就置为空字符串")project: Optional[List[str]] = Field(None, description="求职者项目经历,如果没找到就置为空字符串")certificates: Optional[List[str]] = Field(None, description="求职者资格证书,如果没找到就置为空字符串")@field_validator("birthday", mode="before")def validate_and_convert_date(cls, raw_date):if raw_date is None:return Noneif isinstance(raw_date, str):# List of acceptable date formatsdate_formats = ['%d-%m-%Y', '%Y-%m-%d', '%d/%m/%Y', '%m-%d-%Y']for fmt in date_formats:try:# Attempt to parse the date string with the current formatparsed_date = datetime.strptime(raw_date, fmt).date()# Return the date in MM-DD-YYYY format as a stringreturn parsed_date.strftime('%m-%d-%Y')except ValueError:continue # Try the next format# If none of the formats match, raise an errorraise ValueError(f"Invalid date format for 'consultation_date'. Expected one of: {', '.join(date_formats)}.")if isinstance(raw_date, date):# Convert date object to MM-DD-YYYY formatreturn raw_date.strftime('%m-%d-%Y')raise ValueError("Invalid type for 'consultation_date'. Must be a string or a date object.")class ResumeOpenAI:def __init__(self):self.resume_profile = Resume()self.output_schema = self.resume_profile.model_json_schema()self.template = """You are an expert in analyzing resumes. Use the following JSON schema to extract relevant information:```json{output_schema}```jsonExtract the information from the following document and provide a structured JSON response strictly adhering to the schema above. Please remove any ```json ``` characters from the output. Do not make up any information. If a field cannot be extracted, mark it as `n/a`.Document:----------------{resume_content}----------------"""def create_prompt(self, output_schema, resume_content):return self.template.format(output_schema=output_schema,resume_content=resume_content)def run(self, resume_content):try:response = client.chat.completions.create(model=chat_model,# 不是所有模型都支持response_format,要看一下调用的模型是否支持这个参数# 千问、智谱的模型一般支持response_format={ "type": "json_object" },messages=[{"role": "system", "content": "你是一位专业的简历信息提取专家。"},{"role": "user", "content": self.create_prompt(self.output_schema, resume_content)}],)result = response.choices[0].message.contentexcept Exception as e:print(f"Error occurred: {e}")return resultresume_openai = ResumeOpenAI()# 示例输入数据
input_data = """
59a488639e2f882c1nR_2NS6EFJXwZG-UPKaR-WhnPQ~
杜素宁
MOBILE : 15904130130
E-MAIL:0da08x@163.com
Address:云南省昭通市
个人信息
民族:汉 籍贯:云南省昭通市 性别:女 年龄: 22
教育经历
2008.08-2012.08 北方工业大学 食品科学与工程 学士学位
主要经历
Project Experience
工作经历:
1997.06-2010.07 江苏华英企业管理股份有限公司 水处理工程师
工作内容:
1.负责部门内日常用品的采购;2.做好与公司内其他部门的对接工作;3.协助部门进行办公环境管理和后勤管理工作;4.销
售人员与公司的信息交流,随时保持与市场销售人员的电话沟通,销售政策及公司文件的及时传达。5.领导交办的其他工作
工作经历:
1991年12月-2012年 和宇健康科技股份有限公司 市场营销专员
09月
工作内容:
1、做好消费宾客的迎、送接待工作,接受宾客各种渠道的预定并加以落实;2、礼貌用语,详细做好预订记录;3、了解和
收集宾客的建议和意见并及时反馈给上级领导;4、以规范的服务礼节,树立公司品牌优质,文雅的服务形象。
工作经历:
2007/05-2010/03 深圳市有棵树科技有限公司 拼多多运营
工作内容:
1.负责规定区域的产品销售,做好产品介绍,确认订单,回款等销售相关工作;2.做好客户背景资料调查,竞争对手分析,
产品适用性分析;3.按公司规定完成SalesPipeline信息记录
"""# 运行智能体
rec_data = resume_openai.run(input_data)
print(rec_data)
OpenAI实现阅卷智能体
import os
from dotenv import load_dotenv# ======================
# 1. 加载环境变量和初始化客户端
# ======================
load_dotenv()api_key = os.getenv("DASHSCOPE_API_KEY")
base_url = "https://dashscope.aliyuncs.com/compatible-mode/v1"
chat_model = "qwen-max-latest"from openai import OpenAI
client = OpenAI(api_key=api_key, base_url=base_url)def get_completion(prompt):response = client.chat.completions.create(model=chat_model, # 填写需要调用的模型名称messages=[{"role": "user", "content": prompt},],)return response.choices[0].message.content#response = get_completion("你是谁?")
#print(response)import json
import redef extract_json_content(text):# 这个函数的目标是提取大模型输出内容中的json部分,并对json中的换行符、首位空白符进行删除text = text.replace("\n","")pattern = r"```json(.*?)```"matches = re.findall(pattern, text, re.DOTALL)if matches:return matches[0].strip()return textclass JsonOutputParser:def parse(self, result):# 这个函数的目标是把json字符串解析成python对象# 其实这里写的这个函数性能很差,经常解析失败,有很大的优化空间try:result = extract_json_content(result)parsed_result = json.loads(result)return parsed_resultexcept json.JSONDecodeError as e:raise Exception(f"Invalid json output: {result}") from eclass GradingOpenAI:def __init__(self):self.model = "qwen-max-latest"self.output_parser = JsonOutputParser()self.template = """你是一位中国专利代理师考试阅卷专家,
擅长根据给定的题目和答案为考生生成符合要求的评分和中文评语,
并按照特定的格式输出。
你的任务是,根据我输入的考题和答案,针对考生的作答生成评分和中文的评语,并以JSON格式返回。
阅卷标准适当宽松一些,只要考生回答出基本的意思就应当给分。
答案如果有数字标注,含义是考生如果答出这个知识点,这道题就会得到几分。
生成的中文评语需要能够被json.loads()这个函数正确解析。
生成的整个中文评语需要用英文的双引号包裹,在被包裹的字符串内部,请用中文的双引号。
中文评语中不可以出现换行符、转义字符等等。输出格式为JSON:
{{"llmgetscore": 0,"llmcomments": "中文评语"
}}比较学生的回答与正确答案,
并给出满分为10分的评分和中文评语。
题目:{ques_title}
答案:{answer}
学生的回复:{reply}"""def create_prompt(self, ques_title, answer, reply):return self.template.format(ques_title=ques_title,answer=answer,reply=reply)def grade_answer(self, ques_title, answer, reply):success = Falsewhile not success:# 这里是一个不得已的权宜之计# 上面的json解析函数不是表现很差吗,那就多生成几遍,直到解析成功# 对大模型生成的内容先解析一下,如果解析失败,就再让大模型生成一遍try:response = client.chat.completions.create(model=self.model,messages=[{"role": "system", "content": "你是一位专业的考试阅卷专家。"},{"role": "user", "content": self.create_prompt(ques_title, answer, reply)}],temperature=0.7)result = self.output_parser.parse(response.choices[0].message.content)success = Trueexcept Exception as e:print(f"Error occurred: {e}")continuereturn result['llmgetscore'], result['llmcomments']def run(self, input_data):output = []for item in input_data:score, comment = self.grade_answer(item['ques_title'], item['answer'], item['reply'])item['llmgetscore'] = scoreitem['llmcomments'] = commentoutput.append(item)return output
grading_openai = GradingOpenAI()# 示例输入数据
input_data = [{'ques_title': '请解释共有技术特征、区别技术特征、附加技术特征、必要技术特征的含义','answer': '共有技术特征:与最接近的现有技术共有的技术特征(2.5分); 区别技术特征:区别于最接近的现有技术的技术特征(2.5分); 附加技术特征:对所引用的技术特征进一步限定的技术特征,增加的技术特征(2.5分); 必要技术特征:为解决其技术问题所不可缺少的技术特征(2.5分)。','fullscore': 10,'reply': '共有技术特征:与所对比的技术方案相同的技术特征\n区别技术特征:与所对比的技术方案相区别的技术特征\n附加技术特征:对引用的技术特征进一步限定的技术特征\n必要技术特征:解决技术问题必须可少的技术特征'},{'ques_title': '请解释前序部分、特征部分、引用部分、限定部分','answer': '前序部分:独权中,主题+与最接近的现有技术共有的技术特征,在其特征在于之前(2.5分); 特征部分:独权中,与区别于最接近的现有技术的技术特征,在其特征在于之后(2.5分);引用部分:从权中引用的权利要求编号及主题 (2.5分);限定部分:从权中附加技术特征(2.5分)。','fullscore': 10,'reply': '前序部分:独立权利要求中与现有技术相同的技术特征\n特征部分:独立权利要求中区别于现有技术的技术特征\n引用部分:从属权利要求中引用其他权利要求的部分\n限定部分:对所引用的权利要求进一步限定的技术特征'}]# 运行智能体
graded_data = grading_openai.run(input_data)
print(graded_data)
第03章-openai-agents
01-安装与配置
- 安装依赖。
pip install "openai-agents[litellm]" -i https://pypi.tuna.tsinghua.edu.cn/simple --trusted-host pypi.tuna.tsinghua.edu.cn
2. 安装类型注解回溯包
pip install eval_type_backport
给我讲个程序员相亲的笑话 程序:
import os
from dotenv import load_dotenv# ======================
# 1. 加载环境变量和初始化客户端
# ======================
load_dotenv()api_key = os.getenv("DASHSCOPE_API_KEY")
base_url = "https://dashscope.aliyuncs.com/compatible-mode/v1"
chat_model = "dashscope/qwen-max-latest"from litellm import completion'''
response = completion(model="dashscope/qwen-max-latest", messages=[{ "content": "你有什么技能?","role": "user"}], api_base="https://dashscope.aliyuncs.com/compatible-mode/v1"
)
print(response.choices[0].message.content)
'''from agents import Agent, Runner, set_tracing_disabled
from agents.extensions.models.litellm_model import LitellmModel
set_tracing_disabled(disabled=True)
llm = LitellmModel(model=chat_model, api_key=api_key, base_url=base_url)
agent = Agent(name="Assistant", model=llm, instructions="You are a helpful assistant")
result = Runner.run_sync(agent, "给我讲个程序员相亲的笑话")
print(result.final_output)
qwen的额度用光了,改写下面这句:
chat_model = "dashscope/qwen2.5-7b-instruct-1m"
02-初步尝鲜
作业
does drinking tea good for the body?
from agents import Agent, Runner, set_tracing_disabled, GuardrailFunctionOutput, InputGuardrail
from agents.extensions.models.litellm_model import LitellmModel
from agents.exceptions import InputGuardrailTripwireTriggered
import os
import asyncio
from dotenv import load_dotenv
from pydantic import BaseModel# 加载环境变量
load_dotenv()
# 从环境变量中读取api_key - 修改为 DashScope
api_key = os.getenv("DASHSCOPE_API_KEY")
base_url = "https://dashscope.aliyuncs.com/compatible-mode/v1"
chat_model = "dashscope/qwen-turbo" # 改为更稳定的模型
set_tracing_disabled(disabled=True)
llm = LitellmModel(model=chat_model, api_key=api_key, base_url=base_url)class HomeworkOutput(BaseModel):is_homework: boolreasoning: strhistory_tutor_agent = Agent(name="History Tutor",handoff_description="Specialist agent for historical questions",instructions="You provide assistance with historical queries. Explain important events and context clearly.",model=llm,
)math_tutor_agent = Agent(name="Math Tutor",handoff_description="Specialist agent for math questions",instructions="You provide help with math problems. Explain your reasoning at each step and include examples",model=llm,
)# 修改 guardrail_agent 的指令,使其更宽松
guardrail_agent = Agent(name="Guardrail check",instructions="""Check if the user is asking about homework or educational topics.If it's related to learning, education, or could be a homework question, mark it as homework.Output your response as JSON with two fields: 'is_homework' (true/false) and 'reasoning' (explanation of your decision).Example: {"is_homework": true, "reasoning": "This is a question about history, which is an educational topic."}""",output_type=HomeworkOutput,model=llm,
)async def homework_guardrail(ctx, agent, input_data):try:result = await Runner.run(guardrail_agent, input_data, context=ctx.context)final_output = result.final_output_as(HomeworkOutput)print(f"守卫检查结果: is_homework={final_output.is_homework}, reasoning={final_output.reasoning}")return GuardrailFunctionOutput(output_info=final_output,tripwire_triggered=not final_output.is_homework,)except Exception as e:print(f"守卫检查出错: {e}")# 如果守卫检查失败,默认允许通过return GuardrailFunctionOutput(output_info=HomeworkOutput(is_homework=True, reasoning="Guardrail check failed, allowing by default"),tripwire_triggered=False,)triage_agent = Agent(name="Triage Agent",instructions="You determine which agent to use based on the user's question. If it's about history, use the history tutor. If it's about math, use the math tutor. Otherwise, answer it yourself.",handoffs=[history_tutor_agent, math_tutor_agent],input_guardrails=[InputGuardrail(guardrail_function=homework_guardrail),],model=llm,
)# 添加一个通用代理来处理非作业问题
general_agent = Agent(name="General Assistant",handoff_description="General purpose assistant for non-homework questions",instructions="You are a helpful assistant that answers general questions.",model=llm,
)async def main():try:result = await Runner.run(triage_agent, "does drinking tea good for the body?")print("回答:", result.final_output)except InputGuardrailTripwireTriggered as e:print("守卫被触发: 这个问题不是作业问题")# 当守卫触发时,使用通用代理print("使用通用代理回答...")result = await Runner.run(general_agent, "does drinking tea good for the body?")print("回答:", result.final_output)except Exception as e:print(f"其他错误: {e}")if __name__ == "__main__":asyncio.run(main())
结果显示:
(wow-agent) PS E:\Datawhale\wow-agent 202510\wow-agent> python 6.py
守卫检查结果: is_homework=False, reasoning=The question is about the health benefits of drinking tea, which is a general knowledge or health-related inquiry, not specifically tied to homework or an educational assignment.
守卫被触发: 这个问题不是作业问题
使用通用代理回答...
回答: Yes, **drinking tea** can be **good for the body** when consumed in moderation and without excessive added sugar or other unhealthy additives. Tea is one of the most widely consumed beverages in the world and offers a range of health benefits due to its rich content of **antioxidants**, **polyphenols**, and other bioactive compounds.### Here are some **health benefits of drinking tea**:
#### 1. **Rich in Antioxidants**
- Tea contains **flavonoids** and **catechins** (especially in green tea) that help neutralize harmful free radicals in the body.
- These antioxidants may reduce oxidative stress, which is linked to chronic diseases like heart disease, cancer, and diabetes.#### 2. **May Improve Heart Health**
- Studies suggest that regular tea consumption may help lower the risk of **heart disease** by improving cholesterol levels, reducing inflammation, and supporting healthy blood vessel function.#### 3. **Supports Brain Function**
- Some teas, especially green tea, contain **L-theanine**, an amino acid that promotes relaxation and improves focus and attention.
- Caffeine in tea can also enhance mental alertness, but usually in smaller amounts than coffee.#### 4. **May Aid in Weight Management**
- Certain teas, like **green tea**, may support fat oxidation and boost metabolism slightly, which could help with weight management when combined with a healthy diet and exercise.#### 5. **Boosts Immune System**
- The antioxidants and other compounds in tea may help strengthen the immune system and protect against infections.#### 6. **Promotes Oral Health**
- Some research suggests that tea, especially green tea, may help reduce bacteria in the mouth and lower the risk of tooth decay and gum disease.---
### Types of Tea and Their Benefits:
| Type of Tea | Key Benefits |
|-------------|--------------|
| **Green Tea** | High in EGCG, supports heart and brain health, may aid weight loss |
| **Black Tea** | Rich in flavonoids, may improve gut health and reduce heart disease risk |
| **White Tea** | Less processed, high in antioxidants, may have anti-aging properties |
| **Oolong Tea** | May help regulate blood sugar and support weight management |
| **Herbal Teas** (e.g., chamomile, ginger, peppermint) | Caffeine-free, may help with digestion, sleep, or relaxation |---
### Things to Keep in Mind:
- **Caffeine Content**: Some teas (like black and green tea) contain caffeine. People sensitive to caffeine should choose decaf or herbal options.
- **Additives**: Avoid adding too much sugar, honey, or cream, as this can negate the health benefits.
- **Moderation**: While tea is generally healthy, excessive consumption (especially of caffeinated varieties) may lead to insomnia, anxiety, or digestive issues.---
### Conclusion:
Yes, **drinking tea is good for the body** when enjoyed as part of a balanced diet. It can contribute to better overall health, but it's not a magic pill — it works best when combined with healthy lifestyle choices.
如何证明勾股定理?
守卫检查结果: is_homework=False, reasoning=The question is about the health effects of drinking tea, which is a general knowledge or health-related inquiry rather than a specific homework or educational assignment.
守卫被触发: 这个问题不是作业问题
使用通用代理回答...
回答: 勾股定理是几何学中的一个基本定理,它指出:在**直角三角形**中,斜边(即与直角相对的边)的平方等于另外两条直角边的平方和。用公式表示为:$$
a^2 + b^2 = c^2
$$其中,$ a $ 和 $ b $ 是直角边,$ c $ 是斜边。
---
### 一、常见的几种证明方法
#### ✅ 方法1:几何拼图法(欧几里得证明)
1. 画一个直角三角形,设两直角边为 $ a $ 和 $ b $,斜边为 $ c $。
2. 构造一个边长为 $ a + b $ 的正方形,内部放入四个这样的直角三角形。
3. 中间形成一个边长为 $ c $ 的小正方形。
4. 计算整个大正方形的面积:
- 大正方形面积:$(a + b)^2 = a^2 + 2ab + b^2$
- 四个三角形面积之和:$4 \times \frac{1}{2}ab = 2ab$
- 中间小正方形面积:$c^2$5. 所以有:
$$
a^2 + 2ab + b^2 = 2ab + c^2
$$
两边同时减去 $2ab$,得到:
$$
a^2 + b^2 = c^2
$$---
#### ✅ 方法2:相似三角形法
1. 在直角三角形 $ \triangle ABC $ 中,$ \angle C = 90^\circ $,从点 $ C $ 向斜边 $ AB $ 作垂线,交于点 $ D $。
2. 得到两个小三角形 $ \triangle ACD $ 和 $ \triangle CBD $,它们都与原三角形 $ \triangle ABC $ 相似。
3. 根据相似三角形的性质,可以写出比例关系:
- $ \frac{AC}{AB} = \frac{AD}{AC} \Rightarrow AC^2 = AB \cdot AD $
- $ \frac{BC}{AB} = \frac{BD}{BC} \Rightarrow BC^2 = AB \cdot BD $4. 将两式相加:
$$
AC^2 + BC^2 = AB \cdot (AD + BD) = AB \cdot AB = AB^2
$$
即:
$$
a^2 + b^2 = c^2
$$---
#### ✅ 方法3:代数法(利用坐标系)
1. 设直角三角形的两个直角边分别在坐标轴上,顶点为 $ (0, 0) $、$ (a, 0) $、$ (0, b) $。
2. 则斜边的长度为两点之间的距离:
$$
c = \sqrt{(a - 0)^2 + (0 - b)^2} = \sqrt{a^2 + b^2}
$$
3. 两边平方,得到:
$$
c^2 = a^2 + b^2
$$---
### 二、总结
勾股定理可以用多种方式证明,包括几何拼图、相似三角形、坐标代数等方法。无论哪种方式,最终都验证了:
$$
a^2 + b^2 = c^2
$$这是数学中最著名的定理之一,也是许多几何、三角学和物理问题的基础。
如果你需要更详细的图示或具体步骤,我可以进一步说明!
-
who was the first president of the united states?
守卫检查结果: is_homework=False, reasoning=The question is asking about the health effects of drinking tea, which is a general inquiry rather than a specific homework or educational task.
守卫被触发: 这个问题不是作业问题
使用通用代理回答...
回答: The first president of the United States was **George Washington**. He took office on **April 30, 1789**, after being unanimously elected by the Electoral College. Washington served two terms as president and is often referred to as the "Father of His Country" for his leadership during the American Revolutionary War and his role in establishing the foundations of the U.S. government.
-
what is life?
守卫检查结果: is_homework=False, reasoning=The question is about the health effects of drinking tea, which is a general inquiry rather than a specific homework or educational assignment.
守卫被触发: 这个问题不是作业问题
使用通用代理回答...
回答: The question "What is life?" has been explored for centuries by philosophers, scientists, and thinkers across cultures. While there's no single, definitive answer, here's a synthesis of perspectives:### **Scientific Perspective**
In biology, life is typically defined by characteristics such as:
- **Organization**: Living things are made of cells (the basic unit of life).
- **Metabolism**: They take in energy and nutrients to grow, maintain structures, and reproduce.
- **Homeostasis**: They regulate internal conditions (e.g., temperature, pH) to survive.
- **Reproduction**: They produce offspring, passing on genetic material.
- **Adaptation**: Over time, populations evolve through natural selection to better suit their environment.However, even this framework has edge cases (e.g., viruses, which lack some traits but can replicate inside hosts).
---
### **Philosophical Perspective**
Philosophers often ask *why* life exists or what gives it meaning. For example:
- **Existentialism** (e.g., Sartre) emphasizes that life has no inherent meaning—it’s up to individuals to create purpose.
- **Stoicism** (e.g., Marcus Aurelius) focuses on living in harmony with nature and cultivating virtue.
- **Eastern philosophies** (e.g., Buddhism, Taoism) often view life as part of a larger cycle, emphasizing impermanence, interconnectedness, or balance.---
### **Spiritual/Religious Perspective**
Many traditions see life as a sacred gift or journey:
- In **Abrahamic religions**, life is seen as a test or opportunity to connect with the divine.
- **Hinduism and Buddhism** emphasize reincarnation and liberation (moksha or nirvana) from the cycle of birth and death.
- **Indigenous traditions** often view life as part of a web of relationships with nature and ancestors.---
### **Poetic/Subjective Perspective**
For many, life is about experiences, emotions, and connections:
- It might be seen as a series of moments—joy, love, struggle, growth.
- Some describe it as "the art of being alive," focusing on how one chooses to live rather than just existing.---
### **Final Thought**
Life is both a biological phenomenon and a deeply personal experience. It’s shaped by science, culture, and individual interpretation. As the poet Rumi wrote, *"You are not a drop in the ocean. You are the entire ocean in a drop."* Ultimately, life may be what you make of it. 🌱