From 455cbfb995b0b30b76e45a2e0708dc92725209c0 Mon Sep 17 00:00:00 2001 From: henachng <116464575+henachng@users.noreply.github.com> Date: Wed, 10 Apr 2024 16:41:12 -0700 Subject: [PATCH] Migration to the v1.X version of Python OpenAI --- .../basic_chatcompletions_example_sdk.ipynb | 335 +++++++++--------- 1 file changed, 165 insertions(+), 170 deletions(-) diff --git a/Basic_Samples/Chat/basic_chatcompletions_example_sdk.ipynb b/Basic_Samples/Chat/basic_chatcompletions_example_sdk.ipynb index e2f0fedf..9c876a40 100644 --- a/Basic_Samples/Chat/basic_chatcompletions_example_sdk.ipynb +++ b/Basic_Samples/Chat/basic_chatcompletions_example_sdk.ipynb @@ -1,170 +1,165 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "id": "278e7451", - "metadata": {}, - "source": [ - "

Python SDK Sample

\n", - "
\n", - "\n", - "# Chat Completions\n", - "\n", - "Chat models take a series of messages as input, and return a model-generated message as output.\n", - "The main input is the messages parameter. Messages must be an array of message objects, where each object has a role (either \"system\", \"user\", or \"assistant\") and content (the content of the message). " - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "fb97123e", - "metadata": {}, - "outputs": [], - "source": [ - "# if needed, install and/or upgrade to the latest version of the OpenAI Python library\n", - "%pip install --upgrade openai" - ] - }, - { - "cell_type": "code", - "execution_count": 1, - "id": "ccbb9a99", - "metadata": {}, - "outputs": [], - "source": [ - "# import os module & the OpenAI Python library for calling the OpenAI API\n", - "import os\n", - "import openai\n", - "import json" - ] - }, - { - "cell_type": "markdown", - "id": "6d33f92a", - "metadata": {}, - "source": [ - "### Setup Parameters" - ] - }, - { - "cell_type": "code", - "execution_count": 2, - "id": "1d67d3b6", - "metadata": {}, - "outputs": [], - "source": [ - "# Load config values\n", - "with open(r'config.json') as config_file:\n", - " config_details = json.load(config_file)\n", - " \n", - "# Setting up the deployment name\n", - "chatgpt_model_name = config_details['CHATGPT_MODEL']\n", - "\n", - "# This is set to `azure`\n", - "openai.api_type = \"azure\"\n", - "\n", - "# The API key for your Azure OpenAI resource.\n", - "openai.api_key = os.getenv(\"OPENAI_API_KEY\")\n", - "\n", - "# The base URL for your Azure OpenAI resource. e.g. \"https://.openai.azure.com\"\n", - "openai.api_base = config_details['OPENAI_API_BASE']\n", - "\n", - "# Currently Chat Completion API have the following versions available: 2023-03-15-preview\n", - "openai.api_version = config_details['OPENAI_API_VERSION']" - ] - }, - { - "cell_type": "code", - "execution_count": 3, - "id": "150a3db0", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "The Los Angeles Dodgers won the World Series in 2020.\n" - ] - } - ], - "source": [ - "# A sample API call for chat completions looks as follows:\n", - "# Messages must be an array of message objects, where each object has a role (either \"system\", \"user\", or \"assistant\") and content (the content of the message).\n", - "# For more info: https://learn.microsoft.com/en-us/azure/cognitive-services/openai/reference#chat-completions\n", - "\n", - "try:\n", - " response = openai.ChatCompletion.create(\n", - " engine=chatgpt_model_name,\n", - " messages=[\n", - " {\"role\": \"system\", \"content\": \"You are a helpful assistant.\"},\n", - " {\"role\": \"user\", \"content\": \"Who won the world series in 2020?\"}\n", - " ]\n", - " )\n", - "\n", - " # print the response\n", - " print(response['choices'][0]['message']['content'])\n", - " \n", - "except openai.error.APIError as e:\n", - " # Handle API error here, e.g. retry or log\n", - " print(f\"OpenAI API returned an API Error: {e}\")\n", - "\n", - "except openai.error.AuthenticationError as e:\n", - " # Handle Authentication error here, e.g. invalid API key\n", - " print(f\"OpenAI API returned an Authentication Error: {e}\")\n", - "\n", - "except openai.error.APIConnectionError as e:\n", - " # Handle connection error here\n", - " print(f\"Failed to connect to OpenAI API: {e}\")\n", - "\n", - "except openai.error.InvalidRequestError as e:\n", - " # Handle connection error here\n", - " print(f\"Invalid Request Error: {e}\")\n", - "\n", - "except openai.error.RateLimitError as e:\n", - " # Handle rate limit error\n", - " print(f\"OpenAI API request exceeded rate limit: {e}\")\n", - "\n", - "except openai.error.ServiceUnavailableError as e:\n", - " # Handle Service Unavailable error\n", - " print(f\"Service Unavailable: {e}\")\n", - "\n", - "except openai.error.Timeout as e:\n", - " # Handle request timeout\n", - " print(f\"Request timed out: {e}\")\n", - " \n", - "except:\n", - " # Handles all other exceptions\n", - " print(\"An exception has occured.\")" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "cc92fe64", - "metadata": {}, - "outputs": [], - "source": [] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3 (ipykernel)", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.11.1" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} +{ + "cells": [ + { + "cell_type": "markdown", + "id": "278e7451", + "metadata": {}, + "source": [ + "

Python SDK Sample

\n", + "
\n", + "\n", + "# Chat Completions\n", + "\n", + "Chat models take a series of messages as input, and return a model-generated message as output.\n", + "The main input is the messages parameter. Messages must be an array of message objects, where each object has a role (either \"system\", \"user\", or \"assistant\") and content (the content of the message). " + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "fb97123e", + "metadata": {}, + "outputs": [], + "source": [ + "# if needed, install and/or upgrade to the latest version of the OpenAI Python library\n", + "%pip install --upgrade openai" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "id": "ccbb9a99", + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 9, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# import os module & the OpenAI Python library for calling the OpenAI API\n", + "import os\n", + "from openai import AzureOpenAI\n", + "import dotenv\n", + "dotenv.load_dotenv()\n" + ] + }, + { + "cell_type": "markdown", + "id": "6d33f92a", + "metadata": {}, + "source": [ + "### Setup Parameters" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "id": "1d67d3b6", + "metadata": {}, + "outputs": [], + "source": [ + "# Setting up the deployment name\n", + "deployment_name = os.environ['COMPLETIONS_MODEL']\n", + "\n", + "# The API key for your Azure OpenAI resource.\n", + "api_key = os.environ[\"AZURE_OPENAI_API_KEY\"]\n", + "\n", + "# The base URL for your Azure OpenAI resource. e.g. \"https://.openai.azure.com\"\n", + "azure_endpoint = os.environ['AZURE_OPENAI_ENDPOINT']\n", + "\n", + "# Currently Chat Completion API have the following versions available: 2023-03-15-preview\n", + "api_version = os.environ['OPENAI_API_VERSION']\n", + "\n", + "client = AzureOpenAI(\n", + " api_key=api_key, \n", + " azure_endpoint=azure_endpoint,\n", + " api_version=api_version\n", + ")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "150a3db0", + "metadata": {}, + "outputs": [], + "source": [ + "# A sample API call for chat completions looks as follows:\n", + "# Messages must be an array of message objects, where each object has a role (either \"system\", \"user\", or \"assistant\") and content (the content of the message).\n", + "# For more info: https://learn.microsoft.com/en-us/azure/cognitive-services/openai/reference#chat-completions\n", + "\n", + "try:\n", + " response = client.chat.completions.create(\n", + " model=deployment_name,\n", + " messages=[\n", + " {\"role\": \"system\", \"content\": \"You are a helpful assistant.\"},\n", + " {\"role\": \"user\", \"content\": \"Who won the world series in 2020?\"}\n", + " ]\n", + " )\n", + "\n", + " # print the response\n", + " print(response.choices[0].message.content)\n", + "\n", + "except openai.AuthenticationError as e:\n", + " # Handle Authentication error here, e.g. invalid API key\n", + " print(f\"OpenAI API returned an Authentication Error: {e}\")\n", + "\n", + "except openai.APIConnectionError as e:\n", + " # Handle connection error here\n", + " print(f\"Failed to connect to OpenAI API: {e}\")\n", + "\n", + "except openai.BadRequestError as e:\n", + " # Handle connection error here\n", + " print(f\"Invalid Request Error: {e}\")\n", + "\n", + "except openai.RateLimitError as e:\n", + " # Handle rate limit error\n", + " print(f\"OpenAI API request exceeded rate limit: {e}\")\n", + "\n", + "except openai.InternalServerError as e:\n", + " # Handle Service Unavailable error\n", + " print(f\"Service Unavailable: {e}\")\n", + "\n", + "except openai.APITimeoutError as e:\n", + " # Handle request timeout\n", + " print(f\"Request timed out: {e}\")\n", + " \n", + "except openai.APIError as e:\n", + " # Handle API error here, e.g. retry or log\n", + " print(f\"OpenAI API returned an API Error: {e}\")\n", + "\n", + "except:\n", + " # Handles all other exceptions\n", + " print(\"An exception has occured.\")" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.1" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +}