代码
pip show openai-agents
Name: openai-agents
Version: 0.0.4
Summary: OpenAI Agents SDK
Home-page: https://github.com/openai/openai-agents-python
Author:
Author-email: OpenAI <support@openai.com>
License-Expression: MIT
Location: d:\soft\anaconda\envs\oi_agents\Lib\site-packages
Requires: griffe, openai, pydantic, requests, types-requests, typing-extensions
Required-by:
Note: you may need to restart the kernel to use updated packages.
import asyncio
import osfrom openai import AsyncOpenAIfrom agents import Agent, OpenAIChatCompletionsModel, Runner, function_tool, set_tracing_disabledBASE_URL = "https://open.bigmodel.cn/api/paas/v4/"
API_KEY = "your api key"
MODEL_NAME = "glm-4-flash"if not BASE_URL or not API_KEY or not MODEL_NAME:raise ValueError("Please set EXAMPLE_BASE_URL, EXAMPLE_API_KEY, EXAMPLE_MODEL_NAME via env var or code.")client = AsyncOpenAI(base_url=BASE_URL, api_key=API_KEY)
set_tracing_disabled(disabled=True)@function_tool
def get_weather(city: str):print(f"[debug] getting weather for {city}")return f"The weather in {city} is sunny."async def main():# This agent will use the custom LLM provideragent = Agent(name="Assistant",instructions="You only respond in haikus.",model=OpenAIChatCompletionsModel(model=MODEL_NAME, openai_client=client),tools=[get_weather],)result = await Runner.run(agent, "What's the weather in Tokyo?")print(result.final_output)await main()
[debug] getting weather for Tokyo
Sunny skies in Tokyo.
代码解释
- 环境信息展示:
pip show openai-agents
这个命令显示了当前安装的 openai-agents 包的信息,包括版本号(0.0.4)、依赖项等。
版本号(0.0.3)不可用
- 主要代码结构:
-
导入必要模块:
asyncio
: 用于异步编程AsyncOpenAI
: OpenAI 的异步客户端agents
模块中导入了必要的组件
-
配置设置:
BASE_URL = "https://open.bigmodel.cn/api/paas/v4/" API_KEY = "..." MODEL_NAME = "glm-4-flash"
这里配置了智谱 AI 的接口地址和认证信息。
-
工具函数定义:
@function_tool def get_weather(city: str):
定义了一个获取天气的工具函数,这是一个模拟函数,总是返回晴天。
-
主要逻辑:
async def main():agent = Agent(...)result = await Runner.run(agent, "What's the weather in Tokyo?")
创建了一个智能助手,它:
- 被设置为只用俳句形式回答
- 使用智谱 AI 的 GLM-4-flash 模型
- 具备查询天气的能力
- 被要求查询东京的天气
- 运行结果:
[debug] getting weather for Tokyo
Sunny skies in Tokyo.
显示了调用天气工具的调试信息和最终的响应结果。
这是一个展示如何使用自定义 LLM 提供商(这里是智谱 AI)来创建智能助手的示例,通过异步方式执行,并且集成了自定义工具函数。助手被特别设置为用俳句形式回答,这是一个有趣的约束条件。
参考链接:https://github.com/openai/openai-agents-python/tree/main/examples/model_providers