当前位置:   article > 正文

迁移到 OpenAI Python API 库 1.x_openai migrate

openai migrate

在本文中

  1. 更新
  2. 已知的问题
  3. 迁移前进行测试
  4. 聊天完成情况
  5. 竣工数量
  6. 嵌入
  7. 异步
  8. 验证
  9. 使用您的数据
  10. DALL-E修复
  11. 名称变更

OpenAI 刚刚发布了新版本的OpenAI Python API 库。本指南是OpenAI 迁移指南的补充,将帮助你快速了解特定于 Azure OpenAI 的更改。

更新

  • 这是 OpenAI Python API 库的新版本。
  • 从 2023 年 11 月 6 日开始pip install openaipip install openai --upgrade将安装version 1.xOpenAI Python 库。
  • 从 升级version 0.28.1version 1.x是一项重大更改,您需要测试和更新代码。
  • 如果出现错误,则自动重试并进行退避
  • 正确的类型(对于 mypy/pyright/editors)
  • 您现在可以实例化客户端,而不是使用全局默认值。
  • 切换到显式客户端实例化
  • 名称变更

已知的问题

DALL-E3最新的 1.x 版本完全支持。通过对 代码DALL-E2进行以下修改,可以与 1.x 一起使用。 embeddings_utils.py用于提供语义文本搜索的余弦相似度等功能的OpenAI Python API 库不再是其一部分。 您还应该检查OpenAI Python 库的活跃GitHub 问题。

迁移前进行测试

重要的

openai migrateAzure 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.1pip 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'])

竣工数量

OpenAI Python 1.x

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 不支持在模块级客户端中调用异步方法,您应该实例化一个异步客户端。

Python

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())

验证

Python

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))

DALL-E修复

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())

名称变更

笔记

所有 a* 方法已被删除;必须改用异步客户端。

已删除

  • 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

 



  •  
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Gausst松鼠会/article/detail/611766
推荐阅读
相关标签
  

闽ICP备14008679号