Jensen的个人学习小站

🏷️难度:入门 ⏱️预计阅读:20 分钟 📅更新时间:2026-02-28

OpenAI API 使用教程:从基础调用到进阶操作

目录
  1. 安装与凭证配置
  2. 基础:Chat Completions API
  3. 进阶:流式输出 (Streaming)
  4. 核心:Function Calling (函数调用)
  5. 向量:Embeddings API

无论是使用 LangChain 还是自己手写 Agent 逻辑,底层通常依赖的都是各大厂提供的 LLM API。其中,OpenAI 提供的 API 是行业的事实标准。本教程将带你系统掌握 OpenAI API 的各种用法。

1. 安装与凭证配置

首先,安装官方提供的 Python SDK:

pip install openai

建议将 API 密钥存储在系统的环境变量中,或者使用 python-dotenv.env 文件读取。

from openai import OpenAI
import os

# 初始化客户端,默认会自动寻找 os.environ.get("OPENAI_API_KEY")
client = OpenAI()

2. 基础:Chat Completions API

这是最常用的接口,用于生成对话回复。在此模式下,你需要以特定角色(System, User, Assistant)构建消息列表传给 API。

response = client.chat.completions.create(
  model="gpt-3.5-turbo", # 或者 gpt-4
  messages=[
    {"role": "system", "content": "你是一个严谨的科学助理。"},
    {"role": "user", "content": "引力波是什么?"}
  ]
)

print(response.choices[0].message.content)
📝 角色说明

system: 设定模型的身份和基本行为准则。
user: 用户真实的提问或指令。
assistant: 模型之前的回复,用于提供对话上下文。

3. 进阶:流式输出 (Streaming)

对于长文本生成,等待完整的 API 响应可能需要几十秒。使用流式输出可以实现"打字机"效果,显著提升用户体验。

stream = client.chat.completions.create(
  model="gpt-4",
  messages=[{"role": "user", "content": "写一首关于秋天的诗。"}],
  stream=True, # 开启流式输出
)

for chunk in stream:
    if chunk.choices[0].delta.content is not None:
        print(chunk.choices[0].delta.content, end="")

4. 核心:Function Calling (函数调用)

Function Calling 是构建 AI Agent 的核心技术。它允许你向模型描述外部函数(如查询天气、读写数据库),模型将智能判断何种情况下需要调用这些函数,并生成 JSON 格式的函数参数。

# 1. 定义函数描述
tools = [
  {
    "type": "function",
    "function": {
      "name": "get_current_weather",
      "description": "获取指定城市的天气",
      "parameters": {
        "type": "object",
        "properties": {
          "location": {
            "type": "string",
            "description": "城市名,如 北京, 上海",
          },
        },
        "required": ["location"],
      },
    }
  }
]

# 2. 发起请求
response = client.chat.completions.create(
  model="gpt-3.5-turbo",
  messages=[{"role": "user", "content": "今天北京天气怎么样?"}],
  tools=tools, # 传入可以调用的工具列表
  tool_choice="auto" 
)

# 3. 解析模型决策
tool_calls = response.choices[0].message.tool_calls
if tool_calls:
    for tool_call in tool_calls:
        print(f"需要调用的函数: {tool_call.function.name}")
        print(f"提取的参数: {tool_call.function.arguments}")
        # 输出:提取的参数: {"location":"北京"}

拿到模型输出的参数后,你可以在代码中实际调用对应的方法(例如去请求天气 API),然后再将结果包装成一条特殊的 `tool` 角色消息返回给模型,模型就能根据数据给出最终回答。

5. 向量:Embeddings API

Embeddings (嵌入) 接口用来将文本转化成高维浮点数数组(向量)。这些向量捕捉了文本的语义,内容相似的文本拥有相近的向量。这是 RAG (检索增强生成) 应用的地基。

response = client.embeddings.create(
  input="机器人的未来将会如何?",
  model="text-embedding-3-small"
)

# 获取 1536 维度的浮点数数组
vector = response.data[0].embedding
print(f"向量维度大小: {len(vector)}")