目录
- 安装
- 第一个例子
安装
- 克隆仓库:
git clone https://github.com/openai/openai-agents-python.git
- 创建 conda 环境:
conda create --name oi_agents python=3.12 -y
- 激活环境并安装依赖:
activate oi_agents && pip install -e .
这三个命令分别用于:
- 从 GitHub 下载项目代码
- 创建一个 Python 3.12 的 conda 虚拟环境
- 激活创建的环境并以开发模式安装项目依赖
请注意在执行这些命令时要确保:
- 已安装 Git
- 已安装 Conda
- 在正确的目录下执行命令
第一个例子
# 查看 openai-agents 包的详细信息
pip show openai-agents
# 输出显示包的版本、安装位置、依赖项等信息# 从 agents 包中导入必要的类
from agents import Agent, Runner, RunConfig, OpenAIProvider# 创建 AI 助手实例
# - name: 设置助手名称为 "Assistant"
# - instructions: 设置助手的基本指令
# - model: 使用 glm-4-flash 模型
agent = Agent(name="Assistant", instructions="You are a helpful assistant", model="glm-4-flash")# 配置运行环境
# - api_key: 智谱 AI 的 API 密钥
# - base_url: 智谱 AI 的 API 接口地址
# - use_responses: 禁用 responses 库
run_config = RunConfig(model_provider = OpenAIProvider(api_key="your api key",base_url="https://open.bigmodel.cn/api/paas/v4/",use_responses=False)
)# 导入并应用 nest_asyncio 来解决 Jupyter 中的异步运行问题
import nest_asyncio
nest_asyncio.apply()# 同步运行 AI 助手
# - 让助手创作一首关于编程中递归的俳句
# - 使用之前配置的 run_config
result = Runner.run_sync(agent, "Write a haiku about recursion in programming.", run_config=run_config)
# 打印助手生成的俳句
print(result.final_output)
运行结果:
pip show openai-agents
Name: openai-agents
Version: 0.0.3
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
Editable project location: D:\llm\openai-agents-python
Requires: griffe, openai, pydantic, requests, types-requests, typing-extensions
Required-by:
Note: you may need to restart the kernel to use updated packages.
from agents import Agent, Runner,RunConfig,OpenAIProvider
agent = Agent(name="Assistant", instructions="You are a helpful assistant",model="glm-4-flash")run_config = RunConfig(model_provider = OpenAIProvider(api_key="your api key",base_url="https://open.bigmodel.cn/api/paas/v4/",use_responses=False)
)import nest_asyncio
nest_asyncio.apply()result = Runner.run_sync(agent, "Write a haiku about recursion in programming.",run_config=run_config)
print(result.final_output)
Branches of code weave,
Echoing loops in endless dance,
Logic's intricate maze.