构建一次 API 调用

使用 OpenAI API 构建 AI 系统

Francesca Donadoni

Curriculum Manager, DataCamp

进度快照

一个黑白标志,上面写着"opal library"

使用 OpenAI API 构建 AI 系统

进度快照

一个图示,包含 OpenAI 库及其标志、以及带有 API 图标的 API 调用

使用 OpenAI API 构建 AI 系统

进度快照

一个图示,包含 OpenAI 库及标志、通用 API 调用及图标、以及响应消息与其图标

使用 OpenAI API 构建 AI 系统

进度快照

from openai import OpenAI
client = OpenAI(api_key="ENTER YOUR KEY HERE")

response = client.chat.completions.create( model="gpt-4o-mini", messages=[ {"role": "user", "content": "Who developed ChatGPT?"} ] )
print(response.choices[0].message.content)
ChatGPT was developed by OpenAI, an artificial intelligence research lab.
使用 OpenAI API 构建 AI 系统

生产环境的挑战

  两个人用罗盘研究地图,规划路线

  一部手机显示使用 GPS 的地图应用

使用 OpenAI API 构建 AI 系统

生产环境的挑战

 

  • 错误处理
    • 显示友好的错误信息
    • 服务不可用时的替代方案

 

  • 审核与安全
    • 控制不当输入
    • 降低数据泄露风险

 

  • 测试与验证
    • 检查离题响应
    • 测试不一致行为

 

  • 与外部系统通信
    • 调用外部函数和 API
    • 优化响应时间
使用 OpenAI API 构建 AI 系统

OpenAI API 请求的组成部分

from openai import OpenAI

client = OpenAI(api_key="ENTER YOUR KEY HERE")

response = client.chat.completions.create(
  model="gpt-4o-mini",

messages=[ {"role": "user", "content": "Please write down five trees with their scientific names in json format."} ],
response_format={"type": "json_object"}
)
使用 OpenAI API 构建 AI 系统

OpenAI API 响应的组成部分

 

print(response.choices[0].message.content)
{
  "trees": [
    {"commonName": "Oak", "scientificName": "Quercus"},
    {"commonName": "Maple", "scientificName": "Acer"},
    {"commonName": "Pine", "scientificName": "Pinus"},
    {"commonName": "Birch", "scientificName": "Betula"},
    {"commonName": "Willow", "scientificName": "Salix"}
  ]
}
使用 OpenAI API 构建 AI 系统

下一步

 

  • 生产集成
  • 调用外部函数
  • 最佳实践

一位背包客拿着地图指向目的地

使用 OpenAI API 构建 AI 系统

开始练习!

使用 OpenAI API 构建 AI 系统

Preparing Video For Download...