赞
踩
OpenAI 刚刚发布了新版本的OpenAI Python API 库。本指南是OpenAI 迁移指南的补充,将帮助你快速了解特定于 Azure OpenAI 的更改。
pip install openai
,pip install openai --upgrade
将安装version 1.x
OpenAI Python 库。version 0.28.1
到version 1.x
是一项重大更改,您需要测试和更新代码。DALL-E3
最新的 1.x 版本完全支持。通过对 代码DALL-E2
进行以下修改,可以与 1.x 一起使用。 embeddings_utils.py
用于提供语义文本搜索的余弦相似度等功能的OpenAI Python API 库不再是其一部分。 您还应该检查OpenAI Python 库的活跃GitHub 问题。
重要的
openai migrate
Azure OpenAI 不支持自动迁移代码。
由于这是该库的新版本,具有重大更改,因此您应该在迁移任何生产应用程序以依赖版本 1.x 之前针对新版本广泛测试您的代码。您还应该检查您的代码和内部流程,以确保您遵循最佳实践并将生产代码仅固定到您已经完全测试过的版本。
为了使迁移过程更容易,我们将 Python 文档中的现有代码示例更新为选项卡式体验:
OpenAI Python 1.x
Console
pip install openai --upgrade
OpenAI Python 0.28.1
Console
pip install openai==0.28.1
这提供了更改的上下文,并允许您并行测试新库,同时继续提供对 version 的支持0.28.1
。如果您升级到1.x
并意识到需要暂时恢复到以前的版本,您可以随时pip uninstall openai
重新安装目标0.28.1
到pip install openai==0.28.1
.
OpenAI Pythin 1.x
您需要将该model
变量设置为部署 GPT-3.5-Turbo 或 GPT-4 模型时选择的部署名称。输入模型名称会导致错误,除非您选择与基础模型名称相同的部署名称。
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="2023-05-15"
)
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)
OpenAI Python 0.28.1
您需要将该engine
变量设置为部署 GPT-3.5-Turbo 或 GPT-4 模型时选择的部署名称。输入模型名称将导致错误,除非您选择与基础模型名称相同的部署名称。
Python
import os
import openai
openai.api_type = "azure"
openai.api_base = os.getenv("AZURE_OPENAI_ENDPOINT")
openai.api_key = os.getenv("AZURE_OPENAI_API_KEY")
openai.api_version = "2023-05-15"
response = openai.ChatCompletion.create(
engine="gpt-35-turbo", # engine = "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)
print(response['choices'][0]['message']['content'])
import os
from openai import AzureOpenAI
client = AzureOpenAI(
api_key=os.getenv("AZURE_OPENAI_API_KEY"),
api_version="2023-12-01-preview",
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)
print(response.choices[0].text)
OpenAI Python 0.28.1
Python
import os
import openai
openai.api_key = os.getenv("AZURE_OPENAI_API_KEY")
openai.api_base = os.getenv("AZURE_OPENAI_ENDPOINT") # your endpoint should look like the following https://YOUR_RESOURCE_NAME.openai.azure.com/
openai.api_type = 'azure'
openai.api_version = '2023-05-15' # this might change in the future
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 = openai.Completion.create(engine=deployment_name, prompt=start_phrase, max_tokens=10)
text = response['choices'][0]['text'].replace('\n', '').replace(' .', '.').strip()
print(start_phrase+text)
OpenAI Python 1.x
Python
import os
from openai import AzureOpenAI
client = AzureOpenAI(
api_key = os.getenv("AZURE_OPENAI_API_KEY"),
api_version = "2023-05-15",
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
中找到。
OpenAI Python 0.29.1
Python
import openai
openai.api_type = "azure"
openai.api_key = YOUR_API_KEY
openai.api_base = "https://YOUR_RESOURCE_NAME.openai.azure.com"
openai.api_version = "2023-05-15"
response = openai.Embedding.create(
input="Your text string goes here",
engine="YOUR_DEPLOYMENT_NAME"
)
embeddings = response['data'][0]['embedding']
print(embeddings)
OpenAI 不支持在模块级客户端中调用异步方法,您应该实例化一个异步客户端。
import os
import asyncio
from openai import AsyncAzureOpenAI
async def main():
client = AsyncAzureOpenAI(
api_key = os.getenv("AZURE_OPENAI_API_KEY"),
api_version = "2023-12-01-preview",
azure_endpoint = os.getenv("AZURE_OPENAI_ENDPOINT")
)
response = await client.chat.completions.create(model="gpt-35-turbo", messages=[{"role": "user", "content": "Hello world"}])
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 = "2023-12-01-preview"
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", # gpt-35-instant
messages=[
{
"role": "user",
"content": "How do I output all files in a directory using Python?",
},
],
)
print(completion.model_dump_json(indent=2))
有关使这些代码示例正常工作所需的完整配置步骤,请参阅使用数据快速入门。
OpenAI Python 1.x
Python
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,
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))
DALLE 修复
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)
DALLE-修复异步
import time
import asyncio
import json
import httpx
import openai
class AsyncCustomHTTPTransport(httpx.AsyncHTTPTransport):
async def handle_async_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 = await super().handle_async_request(request)
operation_location_url = response.headers["operation-location"]
request.url = httpx.URL(operation_location_url)
request.method = "GET"
response = await super().handle_async_request(request)
await response.aread()
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,
)
await asyncio.sleep(int(response.headers.get("retry-after")) or 10)
response = await super().handle_async_request(request)
await response.aread()
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 await super().handle_async_request(request)
async def dall_e():
client = openai.AsyncAzureOpenAI(
azure_endpoint="<azure_endpoint>",
api_key="<api_key>",
api_version="<api_version>",
http_client=httpx.AsyncClient(
transport=AsyncCustomHTTPTransport(),
),
)
image = await client.images.generate(prompt="a cute baby seal")
print(image.data[0].url)
asyncio.run(dall_e())
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()
即将推出:整个 2024 年,我们将逐步淘汰 GitHub Issues 作为内容反馈机制,并用新的反馈系统取而代之。有关详细信息,请参阅:Provide feedback for Microsoft Learn content - Contributor guide | Microsoft Learn。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。