Azure OpenAI API with openai 1.0

Ravi K 70 Reputation points
2023-11-29T16:03:58.6433333+00:00

I was using the following script with openai==0.28.0. But it broke with openai==1.0.0

With the new version, one has to create an OpenAI client passing the api key and use client.chat.completions.create

I'm not sure how to work with the new API

import openai
openai.api_key = 'xxxxxxxxxx'
openai.api_base = 'https://xxxxxxx.openai.azure.com/'
openai.api_type = 'azure'
openai.api_version = '2023-08-01-preview'
deployment_name='gpt4'
# Send a completion call to generate an answer
response = openai.ChatCompletion.create(engine=deployment_name, temperature = 1,
  messages = [
   {'role': 'user', 'content': 'what is the meaning of life'}
  ])
print(response)
Azure OpenAI Service
Azure OpenAI Service
An Azure service that provides access to OpenAI’s GPT-3 models with enterprise capabilities.
3,984 questions
{count} votes

Accepted answer
  1. Saurabh Sharma 23,841 Reputation points Microsoft Employee
    2023-11-29T23:59:47.7666667+00:00

    Hi @Ravi K

    Welcome to Microsoft Q&A! Thanks for posting the question.

    If you are using openai version > 0.28.1 then you need to change your python code like below to call a gpt-35-turbo or gpt-4 model

    import os
    from openai import AzureOpenAI
    
    client = AzureOpenAI(
      api_key = os.getenv("AZURE_OPENAI_KEY"),  
      api_version = "2023-05-15",
      azure_endpoint = os.getenv("AZURE_OPENAI_ENDPOINT")
    )
    
    response = client.chat.completions.create(
        model="mygpt4", # model = "deployment_name".
        messages=[
            {"role": "system", "content": "Assistant is a large language model trained by OpenAI."},
            {"role": "user", "content": "Who were the founders of Microsoft?"}
        ]
    )
    
    #print(response)
    print(response.model_dump_json(indent=2))
    print(response.choices[0].message.content)
    

    Please refer to the documentation for details.

    Please let me know if you have any other questions.


    Please 'Accept as answer' and Upvote if it helped so that it can help others in the community looking for help on similar topics.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.