OpenAI SDK 智能体 (Agentic AI) AsyncOpenAI 功能 和 Agent 功能
本文为Agentic AI所需的大模型 API调用 的一些API示范,注重于使用SCNet以及DeepSeek的基于OpenAI 以及 OpenAI SDK 的 API调用。本文为公益类代码,由DeepSeek辅助生成,经过实例测试。
有关SCNet和DeepSeek API的调用,见原文https://blog.csdn.net/YucongCai/article/details/159774133?spm=1001.2014.3001.5502
https://blog.csdn.net/YucongCai/article/details/159774133?spm=1001.2014.3001.5502
1. 在安装OpenAI agents library
pip install openai python-dotenv openai-agents
2. 在前文所示获取API Key并保存入".env" 文件后,可以调用大模型的API。
DeepSeek
import os
from dotenv import load_dotenv
from openai import AsyncOpenAI
from agents import Agent, Runner, OpenAIChatCompletionsModel
from agents import set_tracing_disabled
load_dotenv(override=True)
# Disable tracing (not needed for DeepSeek)
set_tracing_disabled(True)
# OPENAI_AGENTS_DISABLE_TRACING=1
# 1. Configure DeepSeek client
client = AsyncOpenAI(
api_key=os.getenv('DEEPSEEK_API_KEY'), # Your DeepSeek API key
base_url="https://api.deepseek.com/v1"
)
SCNet
# Initialize SCNet client
client = AsyncOpenAI(
api_key=os.getenv("SCNET_API_KEY"),
base_url="https://api.scnet.cn/api/llm/v1"
)
注意,与前文不同的是,本文采用了AsyncOpenAI功能,这一功能有Non blocking 特性,可在不增加线程,即在同一线程下,模拟多线程形式,以方便处理IO延迟较大的API调用。
3. 为了保持与OpenAI的GPT系列模型调用的一致性,需要使用“OpenAIChatCompletionsModel” 功能,接入OpenAI SDK生态。在此生态下,大模型的输入和输出为特定的json formate, 并且支持 function_call 等原生调用。相关构架已成为国际通行标准,国内主流大模型,如 DeepSeek Minimax Moonshot AI(Kimi) Zhipu AI(GLM) ByteDance(Doubao) Baidu(ERNIE) 等,都已完全支持相关功能并作为统一标准化接口,为当前Agentic AI 以及国内大模型服务的基础性构架,且暂无替代需求,可较为稳定地使用。
DeepSeek
# 2. Wrap it with the bridge class
model = OpenAIChatCompletionsModel(
model="deepseek-chat", # or "deepseek-reasoner" (note: reasoner doesn't support tools)
openai_client=client
)
SCNet
# 2. Wrap it with the bridge class
model = OpenAIChatCompletionsModel(
model="DeepSeek-R1-0528", # or "Qwen3-30B-A3B" etc.
openai_client=client
)
4. 定义Agent,其特性由instruction(即“system”)
# 3. Create your agent with this model
agent = Agent(
name="Albert Einstein",
instructions="You are an insightful academician.", # fixed typo
model=model,
)
5. 定义一个async function并且使用await 让AI Agent 处理一个事项。
# 4. Define the async function
async def main():
result = await Runner.run(agent, "Explain the theory of relativity in simple terms.")
print(result.final_output)
# 5. In Jupyter, directly await the main function
await main()
至此,一个简单的使用OpenAI SDK定义并使用一个简单的AI Agent便完成了。
我在找工作,HR或项目合作请联系:yucongcai_business@outlook.com
与科研相关的请联系:yucongcai_research@outlook.com
AtomGit 是由开放原子开源基金会联合 CSDN 等生态伙伴共同推出的新一代开源与人工智能协作平台。平台坚持“开放、中立、公益”的理念,把代码托管、模型共享、数据集托管、智能体开发体验和算力服务整合在一起,为开发者提供从开发、训练到部署的一站式体验。
更多推荐


所有评论(0)