跳转到内容

OpenAI Agents SDK:Hello World

官方源码

py
import asyncio

from agents import Agent, Runner


async def main():
    agent = Agent(
        name="Assistant",
        instructions="You only respond in haikus.",
    )

    result = await Runner.run(agent, "Tell me about recursion in programming.")
    print(result.final_output)
    # Function calls itself,
    # Looping in smaller pieces,
    # Endless by design.


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

改造成qwen的源码

py
import asyncio

from agents import (
    Agent,
    ModelSettings,
    OpenAIChatCompletionsModel,
    Runner,
)
from agents.tracing import set_tracing_disabled
from openai import AsyncOpenAI

# 完全禁用tracing功能,避免连接到 https://api.openai.com/v1/traces/ingest
set_tracing_disabled(True)

http_client = AsyncOpenAI(
    api_key="sk-xxx",
    base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
    timeout=10.0,
)

# 设置默认客户端,用于所有agent的通信 禁用该客户端的追踪功能 不禁用会发送追踪数据到 OpenAI
# from agents import set_default_openai_client
# set_default_openai_client(http_client, use_for_tracing=False)

# 如果使用了OpenAIChatCompletionsModel这种方式,必须传入openai_client,这个时候就没必要用到上面的设
# 置全局默认client,全局client只在不使用OpenAIChatCompletionsModel的时候才会用到,也就是直接使用
# Agent(model="gpt-4o")这种方式才会用到全局默认的client。
model = OpenAIChatCompletionsModel(model="qwen-max-latest", openai_client=http_client)

model_settings = ModelSettings(temperature=0.5)


async def main():
    agent = Agent(
        name="Assistant",
        instructions="You only respond in haikus.Answer me in Chinese.",
        model=model,
        model_settings=model_settings,
    )

    result = await Runner.run(agent, "Tell me about recursion in programming.")
    print(result.final_output)

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

输出结果:

学习笔记

  1. sdk默认启用tracing,可以禁用openai的tracing功能,因为这功能要求使用openai的api_key,消耗token,同时要求网络能连接到openai的tracing api。
py
from agents.tracing import set_tracing_disabled
set_tracing_disabled(True)
  1. 使用非openai家的大模型的步骤
  • 创建一个http_client,用于与LLM通信,包括api_key和base_url、超时设置等。
  • 创建一个model,LLM大模型设置相关,包括model_name和openai_client。
  • 创建一个model_settings,LLM大模型的参数设置,包括temperature等。
  • 利用自定义的http_client和model构建agent,默认构建的agent则不需要这两个参数,使用的是字符串的model,model使用的是全局默认的client。
  1. set_default_openai_client可以设置全局默认的client,用于所有agent的通信client,全局client只在不使用OpenAIChatCompletionsModel的时候才会用到,也就是直接使用Agent(model="gpt-4o")这种方式才会用到全局默认的client。

  2. 异步运行使用asyncio.run、async + await。