前提
官方更新(最近更新:2023年11月08日)
[查看出处](https://github.com/openai/openai-python/discussions/742)
0. 2023年11月08日:OpenAI更新了大量的openai-python库内容,并招来了大量开发者的不满。其中,包括 function_call->tool_choice 等大量接口(这就很招人烦,本来代码都写好了,现在好了名称一改又得重来)。
---原文&译文---
rattrayalex 2 weeks ago Collaborator
We have released a new major version of our SDK, and we recommend upgrading promptly.
我们发布了 SDK 的新主要版本,建议及时升级。
It's a total rewrite of the library, so many things have changed, but we've made upgrading easy with a code migration script and detailed docs below. It was extensively beta tested prior to release.
这是对库的完全重写,很多事情都发生了变化,但我们通过下面的代码迁移脚本和详细文档使升级变得容易。它在发布前进行了广泛的 beta 测试。
速览内容
首页
打开 https://openai.com/ 首页,点击顶部栏 -> API -> Docs
文档
Documentation(文档):GET STARTED(开始) -> CAPABILITIES(能力) -> ASSISTANTS(助理) -> GUIDES(指南) -> ChatGPT(对话)
接口
API Reference(接口参考):GETTING STARTED(开始) -> ENDPOINTS(端点) -> BETA(试用) -> LEGACY(遗产)
示例
Examples(示例):感觉有点过时,但是可以参考一下
测试
左侧边栏:Playground(测试场) -> Assistants(助理) -> Fine-tuning(微调) -> API keys(密钥) -> Files(文件) -> Usage(用法) -> Settings(设置)
代码
默认对话
from openai import OpenAI
OPENAI_API_KEY = "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"
client = OpenAI(
api_key=OPENAI_API_KEY,
)
completion = client.chat.completions.create(
model="gpt-3.5-turbo",
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Hello!"},
],
)
print(completion.choices[0].message)
语境对话
基于上下文对话内容的提问,具有记忆功能。
from openai import OpenAI
OPENAI_API_KEY = "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"
client = OpenAI(
api_key=OPENAI_API_KEY,
)
response = client.chat.completions.create(
model="gpt-3.5-turbo",
messages=[
{"role": "system", "content": "You are a helpful assistant."}, # 变化点1
{"role": "user", "content": "Who won the world series in 2020?"}, # 变化点2
{"role": "assistant", "content": "The Los Angeles Dodgers won the World Series in 2020.",},
{"role": "user", "content": "Where was it played?"},
],
)
print(response.choices[0].message)
流式对话
基于Streaming功能,可实现逐字回答的对话效果。
from openai import OpenAI
OPENAI_API_KEY = "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"
client = OpenAI(
api_key=OPENAI_API_KEY,
)
completion = client.chat.completions.create(
model="gpt-3.5-turbo",
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Hello!"},
],
stream=True, # 变化点1
)
# 变化点2
for chunk in completion:
print(chunk.choices[0].delta)