移轉至 OpenAI Python API 程式庫 1.x
OpenAI 剛剛發行了新版本的 OpenAI Python API 程式庫。 本指南是 OpenAI 移轉指南 補充,可協助您加快 Azure OpenAI 的特定變更速度。
更新
- 這是新版本的 OpenAI Python API 程式庫。
- 從 2023 年 11 月 6 日開始,
pip install openai
和pip install openai --upgrade
將會安裝 OpenAI Python 程式庫的version 1.x
。 - 從
version 0.28.1
升級至version 1.x
是一項中斷性變更,您必須測試及更新程式碼。 - 如果發生錯誤,請自動重試與輪詢
- 適當的類型 (適用於 mypy/pyright/編輯器)
- 您現在可以具現化用戶端,而不是使用全域預設值。
- 切換至明確的用戶端具現化
- 名稱變更
已知問題
- 最新的 1.x 版本完全支援
DALL-E3
。DALL-E2
可以搭配 1.x 使用,方法是對程式碼進行下列修改。 embeddings_utils.py
,用來提供語意文字搜尋餘弦相似度等功能,已不再屬於 OpenAI Python API 程式庫。- 您也應該檢查 OpenAI Python 程式庫的作用中 GitHub 問題。
移轉之前先進行測試
重要
Azure OpenAI 不支援使用 openai migrate
自動移轉程式代碼。
由於這是具有中斷性變更的新版本程式庫,因此您應該先針對新版本測試程式碼,再移轉任何生產應用程式,以依賴 1.x 版。 您也應該檢閱您的程式碼和內部流程,以確保您遵循最佳做法,並將生產程式碼釘選到已完整測試過的版本。
為了簡化移轉程式,我們將 Python 檔中的現有程式碼範例更新為分頁體驗:
pip install openai --upgrade
這會提供已變更的內容,並可讓您平行測試新程式庫,同時繼續提供版本 0.28.1
的支援。 如果您升級至 1.x
,並意識到您需要暫時還原回舊版,您一律可以 pip uninstall openai
,然後使用 pip install openai==0.28.1
重新安裝目標 0.28.1
。
聊天完成
當您部署 GPT-3.5-Turbo 或 GPT-4 模型時,您需要將 model
變數設定為您選擇的部署名稱。 除非您選擇與基礎模型名稱相同的部署名稱,否則輸入模型名稱會導致錯誤。
import os
from openai import AzureOpenAI
client = AzureOpenAI(
azure_endpoint = os.getenv("AZURE_OPENAI_ENDPOINT"),
api_key=os.getenv("AZURE_OPENAI_API_KEY"),
api_version="2024-02-01"
)
response = client.chat.completions.create(
model="gpt-35-turbo", # model = "deployment_name"
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Does Azure OpenAI support customer managed keys?"},
{"role": "assistant", "content": "Yes, customer managed keys are supported by Azure OpenAI."},
{"role": "user", "content": "Do other Azure AI services support this too?"}
]
)
print(response.choices[0].message.content)
如需其他範例,請參閱 深入聊天完成一文。
完成
import os
from openai import AzureOpenAI
client = AzureOpenAI(
api_key=os.getenv("AZURE_OPENAI_API_KEY"),
api_version="2024-02-01",
azure_endpoint = os.getenv("AZURE_OPENAI_ENDPOINT")
)
deployment_name='REPLACE_WITH_YOUR_DEPLOYMENT_NAME' #This will correspond to the custom name you chose for your deployment when you deployed a model.
# Send a completion call to generate an answer
print('Sending a test completion job')
start_phrase = 'Write a tagline for an ice cream shop. '
response = client.completions.create(model=deployment_name, prompt=start_phrase, max_tokens=10) # model = "deployment_name"
print(response.choices[0].text)
Embeddings
import os
from openai import AzureOpenAI
client = AzureOpenAI(
api_key = os.getenv("AZURE_OPENAI_API_KEY"),
api_version = "2024-02-01",
azure_endpoint =os.getenv("AZURE_OPENAI_ENDPOINT")
)
response = client.embeddings.create(
input = "Your text string goes here",
model= "text-embedding-ada-002" # model = "deployment_name".
)
print(response.model_dump_json(indent=2))
如需其他範例,包括如何處理不含 embeddings_utils.py
的語意文字搜尋,請參閱我們的 內嵌教學課程。
Async
OpenAI 不支援在模組層級用戶端中呼叫異步方法,相反地,您應該具現化異步用戶端。
import os
import asyncio
from openai import AsyncAzureOpenAI
async def main():
client = AsyncAzureOpenAI(
api_key = os.getenv("AZURE_OPENAI_API_KEY"),
api_version = "2024-02-01",
azure_endpoint = os.getenv("AZURE_OPENAI_ENDPOINT")
)
response = await client.chat.completions.create(model="gpt-35-turbo", messages=[{"role": "user", "content": "Hello world"}]) # model = model deployment name
print(response.model_dump_json(indent=2))
asyncio.run(main())
驗證
from azure.identity import DefaultAzureCredential, get_bearer_token_provider
from openai import AzureOpenAI
token_provider = get_bearer_token_provider(DefaultAzureCredential(), "https://cognitiveservices.azure.com/.default")
api_version = "2024-02-01"
endpoint = "https://my-resource.openai.azure.com"
client = AzureOpenAI(
api_version=api_version,
azure_endpoint=endpoint,
azure_ad_token_provider=token_provider,
)
completion = client.chat.completions.create(
model="deployment-name", # model = "deployment_name"
messages=[
{
"role": "user",
"content": "How do I output all files in a directory using Python?",
},
],
)
print(completion.model_dump_json(indent=2))
使用您的資料
如需讓這些程式碼範例運作所需的完整設定步驟,請參閱 使用您的資料快速入門。
import os
import openai
import dotenv
dotenv.load_dotenv()
endpoint = os.environ.get("AZURE_OPENAI_ENDPOINT")
api_key = os.environ.get("AZURE_OPENAI_API_KEY")
deployment = os.environ.get("AZURE_OPEN_AI_DEPLOYMENT_ID")
client = openai.AzureOpenAI(
base_url=f"{endpoint}/openai/deployments/{deployment}/extensions",
api_key=api_key,
api_version="2023-08-01-preview",
)
completion = client.chat.completions.create(
model=deployment, # model = "deployment_name"
messages=[
{
"role": "user",
"content": "How is Azure machine learning different than Azure OpenAI?",
},
],
extra_body={
"dataSources": [
{
"type": "AzureCognitiveSearch",
"parameters": {
"endpoint": os.environ["AZURE_AI_SEARCH_ENDPOINT"],
"key": os.environ["AZURE_AI_SEARCH_API_KEY"],
"indexName": os.environ["AZURE_AI_SEARCH_INDEX"]
}
}
]
}
)
print(completion.model_dump_json(indent=2))
DALL-E 修正程式
import time
import json
import httpx
import openai
class CustomHTTPTransport(httpx.HTTPTransport):
def handle_request(
self,
request: httpx.Request,
) -> httpx.Response:
if "images/generations" in request.url.path and request.url.params[
"api-version"
] in [
"2023-06-01-preview",
"2023-07-01-preview",
"2023-08-01-preview",
"2023-09-01-preview",
"2023-10-01-preview",
]:
request.url = request.url.copy_with(path="/openai/images/generations:submit")
response = super().handle_request(request)
operation_location_url = response.headers["operation-location"]
request.url = httpx.URL(operation_location_url)
request.method = "GET"
response = super().handle_request(request)
response.read()
timeout_secs: int = 120
start_time = time.time()
while response.json()["status"] not in ["succeeded", "failed"]:
if time.time() - start_time > timeout_secs:
timeout = {"error": {"code": "Timeout", "message": "Operation polling timed out."}}
return httpx.Response(
status_code=400,
headers=response.headers,
content=json.dumps(timeout).encode("utf-8"),
request=request,
)
time.sleep(int(response.headers.get("retry-after")) or 10)
response = super().handle_request(request)
response.read()
if response.json()["status"] == "failed":
error_data = response.json()
return httpx.Response(
status_code=400,
headers=response.headers,
content=json.dumps(error_data).encode("utf-8"),
request=request,
)
result = response.json()["result"]
return httpx.Response(
status_code=200,
headers=response.headers,
content=json.dumps(result).encode("utf-8"),
request=request,
)
return super().handle_request(request)
client = openai.AzureOpenAI(
azure_endpoint="<azure_endpoint>",
api_key="<api_key>",
api_version="<api_version>",
http_client=httpx.Client(
transport=CustomHTTPTransport(),
),
)
image = client.images.generate(prompt="a cute baby seal")
print(image.data[0].url)
名稱變更
注意
已移除所有 a* 方法;必須改用異步客戶端。
OpenAI Python 0.28.1 | OpenAI Python 1.x |
---|---|
openai.api_base |
openai.base_url |
openai.proxy |
openai.proxies |
openai.InvalidRequestError |
openai.BadRequestError |
openai.Audio.transcribe() |
client.audio.transcriptions.create() |
openai.Audio.translate() |
client.audio.translations.create() |
openai.ChatCompletion.create() |
client.chat.completions.create() |
openai.Completion.create() |
client.completions.create() |
openai.Edit.create() |
client.edits.create() |
openai.Embedding.create() |
client.embeddings.create() |
openai.File.create() |
client.files.create() |
openai.File.list() |
client.files.list() |
openai.File.retrieve() |
client.files.retrieve() |
openai.File.download() |
client.files.retrieve_content() |
openai.FineTune.cancel() |
client.fine_tunes.cancel() |
openai.FineTune.list() |
client.fine_tunes.list() |
openai.FineTune.list_events() |
client.fine_tunes.list_events() |
openai.FineTune.stream_events() |
client.fine_tunes.list_events(stream=True) |
openai.FineTune.retrieve() |
client.fine_tunes.retrieve() |
openai.FineTune.delete() |
client.fine_tunes.delete() |
openai.FineTune.create() |
client.fine_tunes.create() |
openai.FineTuningJob.create() |
client.fine_tuning.jobs.create() |
openai.FineTuningJob.cancel() |
client.fine_tuning.jobs.cancel() |
openai.FineTuningJob.delete() |
client.fine_tuning.jobs.create() |
openai.FineTuningJob.retrieve() |
client.fine_tuning.jobs.retrieve() |
openai.FineTuningJob.list() |
client.fine_tuning.jobs.list() |
openai.FineTuningJob.list_events() |
client.fine_tuning.jobs.list_events() |
openai.Image.create() |
client.images.generate() |
openai.Image.create_variation() |
client.images.create_variation() |
openai.Image.create_edit() |
client.images.edit() |
openai.Model.list() |
client.models.list() |
openai.Model.delete() |
client.models.delete() |
openai.Model.retrieve() |
client.models.retrieve() |
openai.Moderation.create() |
client.moderations.create() |
openai.api_resources |
openai.resources |
已移除
openai.api_key_path
openai.app_info
openai.debug
openai.log
openai.OpenAIError
openai.Audio.transcribe_raw()
openai.Audio.translate_raw()
openai.ErrorObject
openai.Customer
openai.api_version
openai.verify_ssl_certs
openai.api_type
openai.enable_telemetry
openai.ca_bundle_path
openai.requestssession
(OpenAI 現在使用httpx
)openai.aiosession
(OpenAI 現在使用httpx
)openai.Deployment
(先前用於 Azure OpenAI)openai.Engine
openai.File.find_matching_files()