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

openai-agents-python中 agents_as_tools.py 示例

代码

import asyncio
import os

from openai import AsyncOpenAI

from agents import (
    Agent,
    Runner,
    function_tool,
    set_default_openai_api,
    set_default_openai_client,
    set_tracing_disabled,
)

BASE_URL ="https://open.bigmodel.cn/api/paas/v4/"
API_KEY = "your api key"
client = AsyncOpenAI(
    base_url=BASE_URL,
    api_key=API_KEY,
)
set_default_openai_client(client=client, use_for_tracing=False)
set_default_openai_api("chat_completions")
set_tracing_disabled(disabled=True)



import asyncio

from agents import Agent, ItemHelpers, MessageOutputItem, Runner, trace,FunctionToolResult

"""
This example shows the agents-as-tools pattern. The frontline agent receives a user message and
then picks which agents to call, as tools. In this case, it picks from a set of translation
agents.
"""

spanish_agent = Agent(
    model="glm-4",
    name="spanish_agent",
    instructions="You translate the user's message to Spanish",
    handoff_description="An english to spanish translator",
)

french_agent = Agent(
    model="glm-4",
    name="french_agent",
    instructions="You translate the user's message to French",
    handoff_description="An english to french translator",
)

italian_agent = Agent(
    model="glm-4",
    name="italian_agent",
    instructions="You translate the user's message to Italian",
    handoff_description="An english to italian translator",
)

orchestrator_agent = Agent(
    model="glm-4",
    name="orchestrator_agent",
    instructions=(
        "You are a translation agent. You use the tools given to you to translate."
        "If asked for multiple translations, you call the relevant tools in order."
        "You never translate on your own, you always use the provided tools."
    ),
    tools=[
        spanish_agent.as_tool(
            tool_name="translate_to_spanish",
            tool_description="Translate the user's message to Spanish",
        ),
        french_agent.as_tool(
            tool_name="translate_to_french",
            tool_description="Translate the user's message to French",
        ),
        italian_agent.as_tool(
            tool_name="translate_to_italian",
            tool_description="Translate the user's message to Italian",
        ),
    ],
)
synthesizer_agent = Agent(
    model="glm-4",
    name="synthesizer_agent",
    instructions="You inspect translations, correct them if needed, and produce a final concatenated response.",
)

async def main():
    # msg = input("Hi! What would you like translated, and to which languages? ")
    msg="translate 'hello world' in italian and french and spanish"

    # Run the entire orchestration in a single trace
    with trace("Orchestrator evaluator"):
        orchestrator_result = await Runner.run(orchestrator_agent, msg)
        
        for item in orchestrator_result.new_items:
            if isinstance(item, MessageOutputItem):
                text = ItemHelpers.text_message_output(item)
                if text:
                    print(f"  - Message output: {text}")
                
        synthesizer_result = await Runner.run(
            synthesizer_agent, orchestrator_result.to_input_list()
        )

    print(f"\n\nFinal response:\n{synthesizer_result.final_output}")



if __name__ == "__main__":
    asyncio.run(main())

"""
python agents_as_tool.py
  - Message output: The translations of 'hello world' are: 
Italian: Ciao mondo!
French: Bonjour le monde !
Spanish: Hola mundo!


Final response:
Concatenated response: Ciao mondo! Bonjour le monde! Hola mundo!
"""    

代码解释

  1. 基础设置部分
  • 设置了智谱AI的API配置(BASE_URL和API_KEY)
  • 使用AsyncOpenAI客户端进行初始化
  • 设置了一些默认配置,如禁用追踪等
  1. 翻译代理定义
    代码定义了三个专门的翻译代理:
  • spanish_agent:英语到西班牙语翻译
  • french_agent:英语到法语翻译
  • italian_agent:英语到意大利语翻译
  1. 协调器代理
  • orchestrator_agent是一个管理者角色
  • 它可以调用上述三个翻译代理作为工具
  • 根据用户的请求选择合适的翻译工具
  1. 合成代理
  • synthesizer_agent负责检查翻译结果
  • 纠正可能的错误并生成最终的合并响应
  1. 主函数流程
    main函数中:
  • 设置了一个固定的测试消息:“translate ‘hello world’ in italian and french and spanish”
  • 使用trace追踪整个翻译过程
  • orchestrator_agent处理请求并调用相应的翻译工具
  • 输出中间翻译结果
  • synthesizer_agent生成最终的合并响应
  1. 执行结果
    代码会输出:
  • 各语言的翻译结果
  • 最终合并后的响应

类似例子

import asyncio
from openai import AsyncOpenAI
from agents import (
    Agent,
    Runner,
    set_default_openai_api,
    set_default_openai_client,
    set_tracing_disabled,
    ItemHelpers,
    MessageOutputItem,
    trace,
)

# 设置API配置
BASE_URL = "https://open.bigmodel.cn/api/paas/v4/"
API_KEY = "your api key"
client = AsyncOpenAI(
    base_url=BASE_URL,
    api_key=API_KEY,
)
set_default_openai_client(client=client, use_for_tracing=False)
set_default_openai_api("chat_completions")
set_tracing_disabled(disabled=True)

# 定义情感分析代理
positive_agent = Agent(
    model="glm-4",
    name="positive_detector",
    instructions="分析文本中的积极情感,返回积极情感的关键词和分数(0-10)",
    handoff_description="积极情感分析器",
)

negative_agent = Agent(
    model="glm-4",
    name="negative_detector",
    instructions="分析文本中的消极情感,返回消极情感的关键词和分数(0-10)",
    handoff_description="消极情感分析器",
)

neutral_agent = Agent(
    model="glm-4",
    name="neutral_detector",
    instructions="分析文本中的中性/客观表述,返回客观事实的关键信息",
    handoff_description="中性情感分析器",
)

# 定义协调器代理
orchestrator_agent = Agent(
    model="glm-4",
    name="orchestrator_agent",
    instructions=(
        "你是一个情感分析协调器。收到文本后,你需要:"
        "1. 调用积极情感分析工具"
        "2. 调用消极情感分析工具"
        "3. 调用中性情感分析工具"
        "始终使用提供的工具进行分析,不要自行分析。"
    ),
    tools=[
        positive_agent.as_tool(
            tool_name="analyze_positive",
            tool_description="分析文本中的积极情感",
        ),
        negative_agent.as_tool(
            tool_name="analyze_negative",
            tool_description="分析文本中的消极情感",
        ),
        neutral_agent.as_tool(
            tool_name="analyze_neutral",
            tool_description="分析文本中的中性表述",
        ),
    ],
)

# 定义结果合成代理
synthesizer_agent = Agent(
    model="glm-4",
    name="synthesizer_agent",
    instructions="综合所有情感分析结果,生成最终的情感分析报告,包括整体情感倾向判断。",
)

async def main():
    # 示例文本
    text = """
    这款新手机的设计非常漂亮,屏幕显示效果出色,但是电池续航较差,
    而且价格偏贵。总的来说,这是一款配置参数不错的中端手机。
    """

    # 运行情感分析
    with trace("Sentiment Analysis"):
        orchestrator_result = await Runner.run(orchestrator_agent, text)
        
        for item in orchestrator_result.new_items:
            if isinstance(item, MessageOutputItem):
                analysis = ItemHelpers.text_message_output(item)
                if analysis:
                    print(f"分析结果: {analysis}")
                
        final_result = await Runner.run(
            synthesizer_agent, orchestrator_result.to_input_list()
        )

    print(f"\n最终分析报告:\n{final_result.final_output}")

if __name__ == "__main__":
    asyncio.run(main())


"""
分析结果: ```根据您提供的文本,我们可以分析出以下积极情感:

1. 设计漂亮
2. 屏幕显示效果出色
3. 配置参数不错

下面是针对这些积极情感的关键词和分数评估(分数范围0-10,分数越高表示积极情感越强烈):

1. 设计漂亮
   - 关键词:漂亮
   - 分数:8(设计被描述为漂亮,这是一个很高的评价)

2. 屏幕显示效果出色
   - 关键词:显示效果出色
   - 分数:9(显示效果出色意味着在使用过程中会带来良好的视觉体验)

3. 配置参数不错
   - 关键词:配置参数不错
   - 分数:7(虽然评价没有前两者高,但“不错”的配置参数仍然是一个正面的评价)

需要注意的是,这个分数是基于主观判断的,不同的人可能会有不同的评估标准。此外,“电池续航较差”和“价 格偏贵”是负面情感,不在此次积极情感分析的范围之内。

最终分析报告:
以下是针对负面情感的分析:

消极情感分析:

1. 电池续航较差
   - 关键词:电池续航较差
   - 分数:7(电池续航是用户非常关注的一个点,较差的续航会带来较大的不便,因此分数较高)

2. 价格偏贵
   - 关键词:价格偏贵
   - 分数:6(价格因素会影响消费者的购买决策,偏贵的价格会让潜在买家产生犹豫,但具体分数也会受到目标用户群体和产品定位的影响)

综合以上分析,我们可以得出以下情感分析报告:

整体情感倾向:正面偏向中性
这款新手机在设计、屏幕显示效果和配置参数方面得到了较高的评价,表现出积极的情感倾向。然而,电池续航和价格方面的问题带来了一定的消极情感。综合来看,整体情感倾向为正面偏向中性。

请注意,这个分析是基于文本内容的主观解读,实际情况可能因个人观点和需求而异。```
"""

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


http://www.kler.cn/a/601043.html

相关文章:

  • vue-如何将组件内容作为图片生成-html2canvas
  • Android ADB工具使用教程(从安装到使用)
  • 代理记账的第三个十年
  • Matlab多种算法解决未来杯B的多分类问题
  • 处理json,将接口返回的数据转成list<T>,和几个时间处理方法的工具类
  • 【杂记四】刚体运动 +SE(3)
  • Linux 安装 Redis
  • 【AI】NLP
  • 生活电子常识——浏览器解决DNS劫持,避免自动跳转非法网站
  • 2025.3.25总结
  • SPPAS安装及问题汇总
  • StarRocks数据导出到Hive
  • Pear Admin Flask 开发问题
  • 深入理解现代C++在IT行业中的核心地位与应用实践
  • 【Linux网络-多路转接select】
  • PhotoShop学习02
  • 【蓝桥杯】每日练习 Day11 逆序对问题和多路归并
  • VMware 安装 mac os系统
  • vue项目中播放ws(Websocket协议)视频流
  • PHP开发:小区物业管理缴费小程序uniapp在线报修系统、活动报名、在线商城