Skip to content

Examples and guides for using the OpenAI API

Add notebooks for Azure OpenAI with the v1 Python SDK (#833)

Krista Praticofeef1bf3982e
diff --git a/examples/azure/DALL-E.ipynb b/examples/azure/archive/DALL-E.ipynb
similarity index 97%
rename from examples/azure/DALL-E.ipynb
rename to examples/azure/archive/DALL-E.ipynb
index b9c62fdf..c4aeb3d2 100644
--- a/examples/azure/DALL-E.ipynb
+++ b/examples/azure/archive/DALL-E.ipynb
@@ -7,6 +7,8 @@
"source": [
"# Azure DALL·E image generation example\n",
"\n",
+ "> Note: There is a newer version of the openai library available. See https://github.com/openai/openai-python/discussions/742\n",
+ "\n",
"This notebook shows how to generate images with the Azure OpenAI service."
]
},
@@ -26,7 +28,7 @@
"metadata": {},
"outputs": [],
"source": [
- "! pip install openai\n",
+ "! pip install \"openai>=0.28.1,<1.0.0\"\n",
"# We need requests to retrieve the generated image\n",
"! pip install requests\n",
"# We use Pillow to display the generated image\n",
diff --git a/examples/azure/archive/chat.ipynb b/examples/azure/archive/chat.ipynb
new file mode 100644
index 00000000..4788ad3e
--- /dev/null
+++ b/examples/azure/archive/chat.ipynb
@@ -0,0 +1,287 @@
+{
+ "cells": [
+ {
+ "attachments": {},
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "# Azure chat completions example (preview)\n",
+ "\n",
+ "> Note: There is a newer version of the openai library available. See https://github.com/openai/openai-python/discussions/742\n",
+ "\n",
+ "This example will cover chat completions using the Azure OpenAI service."
+ ]
+ },
+ {
+ "attachments": {},
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Setup\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "First, we install the necessary dependencies."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "! pip install \"openai>=0.28.1,<1.0.0\""
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "For the following sections to work properly we first have to setup some things. Let's start with the `api_base` and `api_version`. To find your `api_base` go to https://portal.azure.com, find your resource and then under \"Resource Management\" -> \"Keys and Endpoints\" look for the \"Endpoint\" value."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import os\n",
+ "import openai"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "openai.api_version = '2023-05-15'\n",
+ "openai.api_base = '' # Please add your endpoint here"
+ ]
+ },
+ {
+ "attachments": {},
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We next have to setup the `api_type` and `api_key`. We can either get the key from the portal or we can get it through Microsoft Active Directory Authentication. Depending on this the `api_type` is either `azure` or `azure_ad`."
+ ]
+ },
+ {
+ "attachments": {},
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Setup: Portal\n",
+ "Let's first look at getting the key from the portal. Go to https://portal.azure.com, find your resource and then under \"Resource Management\" -> \"Keys and Endpoints\" look for one of the \"Keys\" values."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "openai.api_type = 'azure'\n",
+ "openai.api_key = os.environ[\"OPENAI_API_KEY\"]\n"
+ ]
+ },
+ {
+ "attachments": {},
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "> Note: In this example, we configured the library to use the Azure API by setting the variables in code. For development, consider setting the environment variables instead:\n",
+ "\n",
+ "```\n",
+ "OPENAI_API_BASE\n",
+ "OPENAI_API_KEY\n",
+ "OPENAI_API_TYPE\n",
+ "OPENAI_API_VERSION\n",
+ "```"
+ ]
+ },
+ {
+ "attachments": {},
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### (Optional) Setup: Microsoft Active Directory Authentication\n",
+ "Let's now see how we can get a key via Microsoft Active Directory Authentication. Uncomment the following code if you want to use Active Directory Authentication instead of keys from the portal."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# from azure.identity import DefaultAzureCredential\n",
+ "\n",
+ "# default_credential = DefaultAzureCredential()\n",
+ "# token = default_credential.get_token(\"https://cognitiveservices.azure.com/.default\")\n",
+ "\n",
+ "# openai.api_type = 'azure_ad'\n",
+ "# openai.api_key = token.token"
+ ]
+ },
+ {
+ "attachments": {},
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "A token is valid for a period of time, after which it will expire. To ensure a valid token is sent with every request, you can refresh an expiring token by hooking into requests.auth:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import typing\n",
+ "import time\n",
+ "import requests\n",
+ "if typing.TYPE_CHECKING:\n",
+ " from azure.core.credentials import TokenCredential\n",
+ "\n",
+ "class TokenRefresh(requests.auth.AuthBase):\n",
+ "\n",
+ " def __init__(self, credential: \"TokenCredential\", scopes: typing.List[str]) -> None:\n",
+ " self.credential = credential\n",
+ " self.scopes = scopes\n",
+ " self.cached_token: typing.Optional[str] = None\n",
+ "\n",
+ " def __call__(self, req):\n",
+ " if not self.cached_token or self.cached_token.expires_on - time.time() < 300:\n",
+ " self.cached_token = self.credential.get_token(*self.scopes)\n",
+ " req.headers[\"Authorization\"] = f\"Bearer {self.cached_token.token}\"\n",
+ " return req\n",
+ "\n",
+ "session = requests.Session()\n",
+ "session.auth = TokenRefresh(default_credential, [\"https://cognitiveservices.azure.com/.default\"])\n",
+ "\n",
+ "openai.requestssession = session"
+ ]
+ },
+ {
+ "attachments": {},
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Deployments\n",
+ "In this section we are going to create a deployment using the `gpt-35-turbo` model that we can then use to create chat completions."
+ ]
+ },
+ {
+ "attachments": {},
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Deployments: Create manually\n",
+ "Let's create a deployment using the `gpt-35-turbo` model. Go to https://portal.azure.com, find your resource and then under \"Resource Management\" -> \"Model deployments\" create a new `gpt-35-turbo` deployment. "
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "deployment_id = '' # Fill in the deployment id from the portal here"
+ ]
+ },
+ {
+ "attachments": {},
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Create chat completion\n",
+ "Now let's send a sample chat completion to the deployment."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# For all possible arguments see https://platform.openai.com/docs/api-reference/chat-completions/create\n",
+ "response = openai.ChatCompletion.create(\n",
+ " deployment_id=deployment_id,\n",
+ " messages=[\n",
+ " {\"role\": \"system\", \"content\": \"You are a helpful assistant.\"},\n",
+ " {\"role\": \"user\", \"content\": \"Knock knock.\"},\n",
+ " {\"role\": \"assistant\", \"content\": \"Who's there?\"},\n",
+ " {\"role\": \"user\", \"content\": \"Orange.\"},\n",
+ " ],\n",
+ " temperature=0,\n",
+ ")\n",
+ "\n",
+ "print(f\"{response.choices[0].message.role}: {response.choices[0].message.content}\")"
+ ]
+ },
+ {
+ "attachments": {},
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We can also stream the response.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "response = openai.ChatCompletion.create(\n",
+ " deployment_id=deployment_id,\n",
+ " messages=[\n",
+ " {\"role\": \"system\", \"content\": \"You are a helpful assistant.\"},\n",
+ " {\"role\": \"user\", \"content\": \"Knock knock.\"},\n",
+ " {\"role\": \"assistant\", \"content\": \"Who's there?\"},\n",
+ " {\"role\": \"user\", \"content\": \"Orange.\"},\n",
+ " ],\n",
+ " temperature=0,\n",
+ " stream=True\n",
+ ")\n",
+ "\n",
+ "for chunk in response:\n",
+ " if len(chunk.choices) > 0:\n",
+ " delta = chunk.choices[0].delta\n",
+ "\n",
+ " if \"role\" in delta.keys():\n",
+ " print(delta.role + \": \", end=\"\", flush=True)\n",
+ " if \"content\" in delta.keys():\n",
+ " print(delta.content, end=\"\", flush=True)"
+ ]
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "Python 3",
+ "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.3"
+ },
+ "orig_nbformat": 4
+ },
+ "nbformat": 4,
+ "nbformat_minor": 2
+}
diff --git a/examples/azure/archive/chat_with_your_own_data.ipynb b/examples/azure/archive/chat_with_your_own_data.ipynb
new file mode 100644
index 00000000..1c8eca72
--- /dev/null
+++ b/examples/azure/archive/chat_with_your_own_data.ipynb
@@ -0,0 +1,448 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "# Azure chat completion models with your own data (preview)\n",
+ "\n",
+ "> Note: There is a newer version of the openai library available. See https://github.com/openai/openai-python/discussions/742\n",
+ "\n",
+ "This example shows how to use Azure OpenAI service models with your own data. The feature is currently in preview. \n",
+ "\n",
+ "Azure OpenAI on your data enables you to run supported chat models such as GPT-3.5-Turbo and GPT-4 on your data without needing to train or fine-tune models. Running models on your data enables you to chat on top of, and analyze your data with greater accuracy and speed. One of the key benefits of Azure OpenAI on your data is its ability to tailor the content of conversational AI. Because the model has access to, and can reference specific sources to support its responses, answers are not only based on its pretrained knowledge but also on the latest information available in the designated data source. This grounding data also helps the model avoid generating responses based on outdated or incorrect information.\n",
+ "\n",
+ "Azure OpenAI on your own data with Azure Cognitive Search provides a customizable, pre-built solution for knowledge retrieval, from which a conversational AI application can be built. To see alternative methods for knowledge retrieval and semantic search, check out the cookbook examples for [vector databases](https://github.com/openai/openai-cookbook/tree/main/examples/vector_databases)."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## How it works\n",
+ "\n",
+ "[Azure OpenAI on your own data](https://learn.microsoft.com/azure/ai-services/openai/concepts/use-your-data) connects the model with your data, giving it the ability to retrieve and utilize data in a way that enhances the model's output. Together with Azure Cognitive Search, data is retrieved from designated data sources based on the user input and provided conversation history. The data is then augmented and resubmitted as a prompt to the model, giving the model contextual information it can use to generate a response.\n",
+ "\n",
+ "See the [Data, privacy, and security for Azure OpenAI Service](https://learn.microsoft.com/legal/cognitive-services/openai/data-privacy?context=%2Fazure%2Fai-services%2Fopenai%2Fcontext%2Fcontext) for more information."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Prerequisites\n",
+ "To get started, we'll cover a few prequisites. \n",
+ "\n",
+ "To properly access the Azure OpenAI Service, we need to create the proper resources at the [Azure Portal](https://portal.azure.com) (you can check a detailed guide on how to do this in the [Microsoft Docs](https://learn.microsoft.com/azure/cognitive-services/openai/how-to/create-resource?pivots=web-portal))\n",
+ "\n",
+ "To use your own data with Azure OpenAI models, you will need:\n",
+ "\n",
+ "1. Azure OpenAI access and a resource with a chat model deployed (for example, GPT-3 or GPT-4)\n",
+ "2. Azure Cognitive Search resource\n",
+ "3. Azure Blob Storage resource\n",
+ "4. Your documents to be used as data (See [data source options](https://learn.microsoft.com/azure/ai-services/openai/concepts/use-your-data#data-source-options))\n",
+ "\n",
+ "\n",
+ "For a full walk-through on how to upload your documents to blob storage and create an index using the Azure AI Studio, see this [Quickstart](https://learn.microsoft.com/azure/ai-services/openai/use-your-data-quickstart?pivots=programming-language-studio&tabs=command-line)."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Setup\n",
+ "\n",
+ "First, we install the necessary dependencies."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "! pip install \"openai>=0.28.1,<1.0.0\"\n",
+ "! pip install python-dotenv"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "In this example, we'll use `dotenv` to load our environment variables. To connect with Azure OpenAI and the Search index, the following variables should be added to a `.env` file in `KEY=VALUE` format:\n",
+ "\n",
+ "* `OPENAI_API_BASE` - the Azure OpenAI endpoint. This can be found under \"Keys and Endpoints\" for your Azure OpenAI resource in the Azure Portal.\n",
+ "* `OPENAI_API_KEY` - the Azure OpenAI API key. This can be found under \"Keys and Endpoints\" for your Azure OpenAI resource in the Azure Portal. Omit if using Azure Active Directory authentication (see below `Authentication using Microsoft Active Directory`)\n",
+ "* `SEARCH_ENDPOINT` - the Cognitive Search endpoint. This URL be found on the \"Overview\" of your Search resource on the Azure Portal.\n",
+ "* `SEARCH_KEY` - the Cognitive Search API key. Found under \"Keys\" for your Search resource in the Azure Portal.\n",
+ "* `SEARCH_INDEX_NAME` - the name of the index you created with your own data."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import os\n",
+ "import openai\n",
+ "import dotenv\n",
+ "\n",
+ "dotenv.load_dotenv()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 2,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "openai.api_base = os.environ[\"OPENAI_API_BASE\"]\n",
+ "\n",
+ "# Azure OpenAI on your own data is only supported by the 2023-08-01-preview API version\n",
+ "openai.api_version = \"2023-08-01-preview\""
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Authentication\n",
+ "\n",
+ "The Azure OpenAI service supports multiple authentication mechanisms that include API keys and Azure credentials."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 3,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "use_azure_active_directory = False # Set this flag to True if you are using Azure Active Directory"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "#### Authentication using API key\n",
+ "\n",
+ "To set up the OpenAI SDK to use an *Azure API Key*, we need to set up the `api_type` to `azure` and set `api_key` to a key associated with your endpoint (you can find this key in *\"Keys and Endpoints\"* under *\"Resource Management\"* in the [Azure Portal](https://portal.azure.com))"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 4,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "if not use_azure_active_directory:\n",
+ " openai.api_type = 'azure'\n",
+ " openai.api_key = os.environ[\"OPENAI_API_KEY\"]"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "#### Authentication using Microsoft Active Directory\n",
+ "Let's now see how we can get a key via Microsoft Active Directory Authentication. See the [documentation](https://learn.microsoft.com/azure/ai-services/openai/how-to/managed-identity) for more information on how to set this up."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "! pip install azure-identity"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 5,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from azure.identity import DefaultAzureCredential\n",
+ "\n",
+ "if use_azure_active_directory:\n",
+ " default_credential = DefaultAzureCredential()\n",
+ " token = default_credential.get_token(\"https://cognitiveservices.azure.com/.default\")\n",
+ "\n",
+ " openai.api_type = \"azure_ad\"\n",
+ " openai.api_key = token.token"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "A token is valid for a period of time, after which it will expire. To ensure a valid token is sent with every request, you can refresh an expiring token by hooking into requests.auth:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 8,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import typing\n",
+ "import time\n",
+ "import requests\n",
+ "\n",
+ "if typing.TYPE_CHECKING:\n",
+ " from azure.core.credentials import TokenCredential\n",
+ "\n",
+ "class TokenRefresh(requests.auth.AuthBase):\n",
+ "\n",
+ " def __init__(self, credential: \"TokenCredential\", scopes: typing.List[str]) -> None:\n",
+ " self.credential = credential\n",
+ " self.scopes = scopes\n",
+ " self.cached_token: typing.Optional[str] = None\n",
+ "\n",
+ " def __call__(self, req):\n",
+ " if not self.cached_token or self.cached_token.expires_on - time.time() < 300:\n",
+ " self.cached_token = self.credential.get_token(*self.scopes)\n",
+ " req.headers[\"Authorization\"] = f\"Bearer {self.cached_token.token}\"\n",
+ " return req\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Chat completion model with your own data"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Setting the context"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "In this example, we want our model to base its responses on Azure AI services documentation data. Following the [Quickstart](https://learn.microsoft.com/azure/ai-services/openai/use-your-data-quickstart?tabs=command-line&pivots=programming-language-studio) shared previously, we have added the [markdown](https://github.com/MicrosoftDocs/azure-docs/blob/main/articles/ai-services/cognitive-services-and-machine-learning.md) file for the [Azure AI services and machine learning](https://learn.microsoft.com/azure/ai-services/cognitive-services-and-machine-learning) documentation page to our search index. The model is now ready to answer questions about Azure AI services and machine learning."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Code"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "To chat with Azure OpenAI models using your own data with the Python SDK, we must first set up the code to target the chat completions extensions endpoint which is designed to work with your own data. To do this, we've created a convenience function that can be called to set a custom adapter for the library which will target the extensions endpoint for a given deployment ID."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 5,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import requests\n",
+ "\n",
+ "def setup_byod(deployment_id: str) -> None:\n",
+ " \"\"\"Sets up the OpenAI Python SDK to use your own data for the chat endpoint.\n",
+ " \n",
+ " :param deployment_id: The deployment ID for the model to use with your own data.\n",
+ "\n",
+ " To remove this configuration, simply set openai.requestssession to None.\n",
+ " \"\"\"\n",
+ "\n",
+ " class BringYourOwnDataAdapter(requests.adapters.HTTPAdapter):\n",
+ "\n",
+ " def send(self, request, **kwargs):\n",
+ " request.url = f\"{openai.api_base}/openai/deployments/{deployment_id}/extensions/chat/completions?api-version={openai.api_version}\"\n",
+ " return super().send(request, **kwargs)\n",
+ "\n",
+ " session = requests.Session()\n",
+ "\n",
+ " # Mount a custom adapter which will use the extensions endpoint for any call using the given `deployment_id`\n",
+ " session.mount(\n",
+ " prefix=f\"{openai.api_base}/openai/deployments/{deployment_id}\",\n",
+ " adapter=BringYourOwnDataAdapter()\n",
+ " )\n",
+ "\n",
+ " if use_azure_active_directory:\n",
+ " session.auth = TokenRefresh(default_credential, [\"https://cognitiveservices.azure.com/.default\"])\n",
+ "\n",
+ " openai.requestssession = session\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Now we can call the convenience function to configure the SDK with the model we plan to use for our own data."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 6,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "setup_byod(\"gpt-4\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Providing our search endpoint, key, and index name for the `dataSources` keyword argument, any questions posed to the model will now be grounded in our own data. An additional property, `context`, will be provided to show the data the model referenced to answer the question."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 7,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "{\n",
+ " \"id\": \"65b485bb-b3c9-48da-8b6f-7d3a219f0b40\",\n",
+ " \"model\": \"gpt-4\",\n",
+ " \"created\": 1693338769,\n",
+ " \"object\": \"extensions.chat.completion\",\n",
+ " \"choices\": [\n",
+ " {\n",
+ " \"index\": 0,\n",
+ " \"finish_reason\": \"stop\",\n",
+ " \"message\": {\n",
+ " \"role\": \"assistant\",\n",
+ " \"content\": \"Azure AI services and Azure Machine Learning (AML) both aim to apply artificial intelligence (AI) to enhance business operations, but they target different audiences and offer different capabilities [doc1]. \\n\\nAzure AI services are designed for developers without machine learning experience and provide pre-trained models to solve general problems such as text analysis, image recognition, and natural language processing [doc5]. These services require general knowledge about your data without needing experience with machine learning or data science and provide REST APIs and language-based SDKs [doc2].\\n\\nOn the other hand, Azure Machine Learning is tailored for data scientists and involves a longer process of data collection, cleaning, transformation, algorithm selection, model training, and deployment [doc5]. It allows users to create custom solutions for highly specialized and specific problems, requiring familiarity with the subject matter, data, and expertise in data science [doc5].\\n\\nIn summary, Azure AI services offer pre-trained models for developers without machine learning experience, while Azure Machine Learning is designed for data scientists to create custom solutions for specific problems.\",\n",
+ " \"end_turn\": true,\n",
+ " \"context\": {\n",
+ " \"messages\": [\n",
+ " {\n",
+ " \"role\": \"tool\",\n",
+ " \"content\": \"{\\\"citations\\\": [{\\\"content\\\": \\\"<h2 id=\\\\\\\"how-are-azure-ai-services-and-azure-machine-learning-aml-similar\\\\\\\">How are Azure AI services and Azure Machine Learning (AML) similar?.</h2>\\\\n<p>Both have the end-goal of applying artificial intelligence (AI) to enhance business operations, though how each provides this in the respective offerings is different..</p>\\\\n<p>Generally, the audiences are different:</p>\\\\n<ul>\\\\n<li>Azure AI services are for developers without machine-learning experience..</li>\\\\n<li>Azure Machine Learning is tailored for data scientists.\\\", \\\"id\\\": null, \\\"title\\\": \\\"Azure AI services and machine learning\\\", \\\"filepath\\\": \\\"cognitive-services-and-machine-learning.md\\\", \\\"url\\\": \\\"https://krpraticstorageacc.blob.core.windows.net/azure-openai/cognitive-services-and-machine-learning.md\\\", \\\"metadata\\\": {\\\"chunking\\\": \\\"orignal document size=1188. Scores=5.689296 and None.Org Highlight count=160.Filtering to chunk no. 2/Highlights=30 of size=137\\\"}, \\\"chunk_id\\\": \\\"2\\\"}, {\\\"content\\\": \\\"<td>Convert speech into text and text into natural-sounding speech..Translate from one language to another and enable speaker verification and recognition..</td>\\\\n</tr>\\\\n<tr>\\\\n<td><a href=\\\\\\\"https://azure.microsoft.com/services/cognitive-services/directory/vision/\\\\\\\">Vision</a></td>\\\\n<td>Recognize, identify, caption, index, and moderate your pictures, videos, and digital ink content..</td>\\\\n</tr>\\\\n<p></tbody>\\\\n</table></p>\\\\n<p>Use Azure AI services when you:</p>\\\\n<ul>\\\\n<li>Can use a generalized solution..</li>\\\\n</ul>\\\\n<p>Use other machine-learning solutions when you:</p>\\\\n<ul>\\\\n<li>Need to choose the algorithm and need to train on very specific data..</li>\\\\n</ul>\\\\n<h2 id=\\\\\\\"what-is-machine-learning\\\\\\\">What is machine learning?.</h2>\\\\n<p>Machine learning is a concept where you bring together data and an algorithm to solve a specific need..Once the data and algorithm are trained, the output is a model that you can use again with different data..The trained model provides insights based on the new data..</p>\\\\n<p>The process of building a machine learning system requires some knowledge of machine learning or data science..</p>\\\\n<p>Machine learning is provided using <a href=\\\\\\\"/azure/architecture/data-guide/technology-choices/data-science-and-machine-learning?.context=azure%2fmachine-learning%2fstudio%2fcontext%2fml-context\\\\\\\">Azure Machine Learning (AML) products and services</a>..</p>\\\\n<h2 id=\\\\\\\"what-is-an-azure-ai-service\\\\\\\">What is an Azure AI service?.</h2>\\\\n<p>An Azure AI service provides part or all of the components in a machine learning solution: data, algorithm, and trained model..These services are meant to require general knowledge about your data without needing experience with machine learning or data science..These services provide both REST API(s) and language-based SDKs..As a result, you need to have programming language knowledge to use the services..</p>\\\", \\\"id\\\": null, \\\"title\\\": \\\"Azure AI services and machine learning\\\", \\\"filepath\\\": \\\"cognitive-services-and-machine-learning.md\\\", \\\"url\\\": \\\"https://krpraticstorageacc.blob.core.windows.net/azure-openai/cognitive-services-and-machine-learning.md\\\", \\\"metadata\\\": {\\\"chunking\\\": \\\"orignal document size=1188. Scores=5.689296 and None.Org Highlight count=160.Filtering to chunk no. 1/Highlights=67 of size=506\\\"}, \\\"chunk_id\\\": \\\"1\\\"}, {\\\"content\\\": \\\"<hr />\\\\n<p>title: Azure AI services and Machine Learning\\\\ntitleSuffix: Azure AI services\\\\ndescription: Learn where Azure AI services fits in with other Azure offerings for machine learning.\\\\nservices: cognitive-services\\\\nmanager: nitinme\\\\nauthor: aahill\\\\nms.author: aahi\\\\nms.service: cognitive-services\\\\nms.topic: conceptual\\\\nms.date: 10/28/2021</p>\\\\n<hr />\\\\n<h1 id=\\\\\\\"azure-ai-services-and-machine-learning\\\\\\\">Azure AI services and machine learning</h1>\\\\n<p>Azure AI services provides machine learning capabilities to solve general problems such as analyzing text for emotional sentiment or analyzing images to recognize objects or faces..You don't need special machine learning or data science knowledge to use these services../what-are-ai-services.md\\\\\\\">Azure AI services</a> is a group of services, each supporting different, generalized prediction capabilities..The services are divided into different categories to help you find the right service..</p>\\\\n<table>\\\\n<thead>\\\\n<tr>\\\\n<th>Service category</th>\\\\n<th>Purpose</th>\\\\n</tr>\\\\n</thead>\\\\n<tbody>\\\\n<tr>\\\\n<td><a href=\\\\\\\"https://azure.microsoft.com/services/cognitive-services/directory/decision/\\\\\\\">Decision</a></td>\\\\n<td>Build apps that surface recommendations for informed and efficient decision-making..</td>\\\\n</tr>\\\\n<tr>\\\\n<td><a href=\\\\\\\"https://azure.microsoft.com/services/cognitive-services/directory/lang/\\\\\\\">Language</a></td>\\\\n<td>Allow your apps to process natural language with pre-built scripts, evaluate sentiment and learn how to recognize what users want..</td>\\\\n</tr>\\\\n<tr>\\\\n<td><a href=\\\\\\\"https://azure.microsoft.com/services/cognitive-services/directory/search/\\\\\\\">Search</a></td>\\\\n<td>Add Bing Search APIs to your apps and harness the ability to comb billions of webpages, images, videos, and news with a single API call..</td>\\\\n</tr>\\\\n<tr>\\\\n<td><a href=\\\\\\\"https://azure.microsoft.com/services/cognitive-services/directory/speech/\\\\\\\">Speech</a></td>\\\", \\\"id\\\": null, \\\"title\\\": \\\"Azure AI services and machine learning\\\", \\\"filepath\\\": \\\"cognitive-services-and-machine-learning.md\\\", \\\"url\\\": \\\"https://krpraticstorageacc.blob.core.windows.net/azure-openai/cognitive-services-and-machine-learning.md\\\", \\\"metadata\\\": {\\\"chunking\\\": \\\"orignal document size=1188. Scores=5.689296 and None.Org Highlight count=160.Filtering to chunk no. 0/Highlights=63 of size=526\\\"}, \\\"chunk_id\\\": \\\"0\\\"}, {\\\"content\\\": \\\"<p>How is Azure Cognitive Search related to Azure AI services?</p>\\\\n<p><a href=\\\\\\\"../search/search-what-is-azure-search.md\\\\\\\">Azure Cognitive Search</a> is a separate cloud search service that optionally uses Azure AI services to add image and natural language processing to indexing workloads. Azure AI services is exposed in Azure Cognitive Search through <a href=\\\\\\\"../search/cognitive-search-predefined-skills.md\\\\\\\">built-in skills</a> that wrap individual APIs. You can use a free resource for walkthroughs, but plan on creating and attaching a <a href=\\\\\\\"../search/cognitive-search-attach-cognitive-services.md\\\\\\\">billable resource</a> for larger volumes.</p>\\\\n<h2 id=\\\\\\\"how-can-you-use-azure-ai-services\\\\\\\">How can you use Azure AI services?</h2>\\\\n<p>Each service provides information about your data. You can combine services together to chain solutions such as converting speech (audio) to text, translating the text into many languages, then using the translated languages to get answers from a knowledge base. While Azure AI services can be used to create intelligent solutions on their own, they can also be combined with traditional machine learning projects to supplement models or accelerate the development process. </p>\\\\n<p>Azure AI services that provide exported models for other machine learning tools:</p>\\\\n<table>\\\\n<thead>\\\\n<tr>\\\\n<th>Azure AI service</th>\\\\n<th>Model information</th>\\\\n</tr>\\\\n</thead>\\\\n<tbody>\\\\n<tr>\\\\n<td><a href=\\\\\\\"./custom-vision-service/overview.md\\\\\\\">Custom Vision</a></td>\\\\n<td><a href=\\\\\\\"./custom-vision-service/export-model-python.md\\\\\\\">Export</a> for Tensorflow for Android, CoreML for iOS11, ONNX for Windows ML</td>\\\\n</tr>\\\\n</tbody>\\\\n</table>\\\\n<h2 id=\\\\\\\"learn-more\\\\\\\">Learn more</h2>\\\\n<ul>\\\\n<li><a href=\\\\\\\"/azure/architecture/data-guide/technology-choices/data-science-and-machine-learning\\\\\\\">Architecture Guide - What are the machine learning products at Microsoft?</a></li>\\\\n<li><a href=\\\\\\\"../machine-learning/concept-deep-learning-vs-machine-learning.md\\\\\\\">Machine learning - Introduction to deep learning vs. machine learning</a></li>\\\\n</ul>\\\\n<h2 id=\\\\\\\"next-steps\\\\\\\">Next steps</h2>\\\\n<ul>\\\\n<li>Create your Azure AI services resource in the <a href=\\\\\\\"multi-service-resource.md?pivots=azportal\\\\\\\">Azure portal</a> or with <a href=\\\\\\\"./multi-service-resource.md?pivots=azcli\\\\\\\">Azure CLI</a>.</li>\\\\n<li>Learn how to <a href=\\\\\\\"authentication.md\\\\\\\">authenticate</a> with your Azure AI service.</li>\\\\n<li>Use <a href=\\\\\\\"diagnostic-logging.md\\\\\\\">diagnostic logging</a> for issue identification and debugging. </li>\\\\n<li>Deploy an Azure AI service in a Docker <a href=\\\\\\\"cognitive-services-container-support.md\\\\\\\">container</a>.</li>\\\\n<li>Keep up to date with <a href=\\\\\\\"https://azure.microsoft.com/updates/?product=cognitive-services\\\\\\\">service updates</a>.</li>\\\\n</ul>\\\", \\\"id\\\": null, \\\"title\\\": \\\"Azure AI services and machine learning\\\", \\\"filepath\\\": \\\"cognitive-services-and-machine-learning.md\\\", \\\"url\\\": \\\"https://krpraticstorageacc.blob.core.windows.net/azure-openai/cognitive-services-and-machine-learning.md\\\", \\\"metadata\\\": {\\\"chunking\\\": \\\"orignal document size=793. Scores=3.3767838 and None.Org Highlight count=69.\\\"}, \\\"chunk_id\\\": \\\"3\\\"}, {\\\"content\\\": \\\"<p>How are Azure AI services different from machine learning?.</p>\\\\n<p>Azure AI services provide a trained model for you..This brings data and an algorithm together, available from a REST API(s) or SDK..An Azure AI service provides answers to general problems such as key phrases in text or item identification in images..</p>\\\\n<p>Machine learning is a process that generally requires a longer period of time to implement successfully..This time is spent on data collection, cleaning, transformation, algorithm selection, model training, and deployment to get to the same level of functionality provided by an Azure AI service..With machine learning, it is possible to provide answers to highly specialized and/or specific problems..Machine learning problems require familiarity with the specific subject matter and data of the problem under consideration, as well as expertise in data science..</p>\\\\n<h2 id=\\\\\\\"what-kind-of-data-do-you-have\\\\\\\">What kind of data do you have?.</h2>\\\\n<p>Azure AI services, as a group of services, can require none, some, or all custom data for the trained model..</p>\\\\n<h3 id=\\\\\\\"no-additional-training-data-required\\\\\\\">No additional training data required</h3>\\\\n<p>Services that provide a fully-trained model can be treated as a <em>opaque box</em>..You don't need to know how they work or what data was used to train them..</p>\\\\n<h3 id=\\\\\\\"some-or-all-training-data-required\\\\\\\">Some or all training data required</h3>\\\\n<p>Some services allow you to bring your own data, then train a model..This allows you to extend the model using the Service's data and algorithm with your own data..The output matches your needs..When you bring your own data, you may need to tag the data in a way specific to the service..For example, if you are training a model to identify flowers, you can provide a catalog of flower images along with the location of the flower in each image to train the model..These services process significant amounts of model data..</p>\\\\n<h2 id=\\\\\\\"service-requirements-for-the-data-model\\\\\\\">Service requirements for the data model</h2>\\\\n<p>The following data categorizes each service by which kind of data it allows or requires..</p>\\\\n<table>\\\\n<thead>\\\\n<tr>\\\\n<th>Azure AI service</th>\\\\n<th>No training data required</th>\\\\n<th>You provide some or all training data</th>\\\\n<th>Real-time or near real-time data collection</th>\\\\n</tr>\\\\n</thead>\\\\n<tbody>\\\\n<tr>\\\\n<td><a href=\\\\\\\"../LUIS/what-is-luis.md\\\\\\\">Language Understanding (LUIS)</a></td>\\\\n<td></td>\\\\n<td>x</td>\\\\n<td></td>\\\\n</tr>\\\\n<tr>\\\\n<td><a href=\\\\\\\"../personalizer/what-is-personalizer.md\\\\\\\">Personalizer</a><sup>1</sup></sup></td>\\\\n<td>x</td>\\\\n<td>x</td>\\\\n<td>x</td>\\\\n</tr>\\\\n<tr>\\\\n<td><a href=\\\\\\\"../computer-vision/overview.md\\\\\\\">Vision</a></td>\\\\n<td>x</td>\\\\n<td></td>\\\\n<td></td>\\\\n</tr>\\\\n</tbody>\\\\n</table>\\\\n<p><sup>1</sup> Personalizer only needs training data collected by the service (as it operates in real-time) to evaluate your policy and data..</p>\\\\n<h2 id=\\\\\\\"where-can-you-use-azure-ai-services\\\\\\\">Where can you use Azure AI services?.</h2>\\\\n<p>The services are used in any application that can make REST API(s) or SDK calls..Examples of applications include web sites, bots, virtual or mixed reality, desktop and mobile applications.\\\", \\\"id\\\": null, \\\"title\\\": \\\"Azure AI services and machine learning\\\", \\\"filepath\\\": \\\"cognitive-services-and-machine-learning.md\\\", \\\"url\\\": \\\"https://krpraticstorageacc.blob.core.windows.net/azure-openai/cognitive-services-and-machine-learning.md\\\", \\\"metadata\\\": {\\\"chunking\\\": \\\"orignal document size=1734. Scores=3.1447978 and None.Org Highlight count=66.Filtering to highlight size=891\\\"}, \\\"chunk_id\\\": \\\"4\\\"}], \\\"intent\\\": \\\"[\\\\\\\"What are the differences between Azure Machine Learning and Azure AI services?\\\\\\\"]\\\"}\",\n",
+ " \"end_turn\": false\n",
+ " }\n",
+ " ]\n",
+ " }\n",
+ " }\n",
+ " }\n",
+ " ]\n",
+ "}\n"
+ ]
+ }
+ ],
+ "source": [
+ "completion = openai.ChatCompletion.create(\n",
+ " messages=[{\"role\": \"user\", \"content\": \"What are the differences between Azure Machine Learning and Azure AI services?\"}],\n",
+ " deployment_id=\"gpt-4\",\n",
+ " dataSources=[ # camelCase is intentional, as this is the format the API expects\n",
+ " {\n",
+ " \"type\": \"AzureCognitiveSearch\",\n",
+ " \"parameters\": {\n",
+ " \"endpoint\": os.environ[\"SEARCH_ENDPOINT\"],\n",
+ " \"key\": os.environ[\"SEARCH_KEY\"],\n",
+ " \"indexName\": os.environ[\"SEARCH_INDEX_NAME\"],\n",
+ " }\n",
+ " }\n",
+ " ]\n",
+ ")\n",
+ "print(completion)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "If you would prefer to stream the response from the model, you can pass the `stream=True` keyword argument:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 8,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Context: {\n",
+ " \"messages\": [\n",
+ " {\n",
+ " \"role\": \"tool\",\n",
+ " \"content\": \"{\\\"citations\\\":[{\\\"content\\\":\\\"<h2 id=\\\\\\\"how-are-azure-ai-services-and-azure-machine-learning-aml-similar\\\\\\\">How are Azure AI services and Azure Machine Learning (AML) similar?.</h2>\\\\n<p>Both have the end-goal of applying artificial intelligence (AI) to enhance business operations, though how each provides this in the respective offerings is different..</p>\\\\n<p>Generally, the audiences are different:</p>\\\\n<ul>\\\\n<li>Azure AI services are for developers without machine-learning experience..</li>\\\\n<li>Azure Machine Learning is tailored for data scientists.\\\",\\\"id\\\":null,\\\"title\\\":\\\"Azure AI services and machine learning\\\",\\\"filepath\\\":\\\"cognitive-services-and-machine-learning.md\\\",\\\"url\\\":\\\"https://krpraticstorageacc.blob.core.windows.net/azure-openai/cognitive-services-and-machine-learning.md\\\",\\\"metadata\\\":{\\\"chunking\\\":\\\"orignal document size=1188. Scores=5.689296 and None.Org Highlight count=160.Filtering to chunk no. 2/Highlights=30 of size=137\\\"},\\\"chunk_id\\\":\\\"2\\\"},{\\\"content\\\":\\\"<td>Convert speech into text and text into natural-sounding speech..Translate from one language to another and enable speaker verification and recognition..</td>\\\\n</tr>\\\\n<tr>\\\\n<td><a href=\\\\\\\"https://azure.microsoft.com/services/cognitive-services/directory/vision/\\\\\\\">Vision</a></td>\\\\n<td>Recognize, identify, caption, index, and moderate your pictures, videos, and digital ink content..</td>\\\\n</tr>\\\\n<p></tbody>\\\\n</table></p>\\\\n<p>Use Azure AI services when you:</p>\\\\n<ul>\\\\n<li>Can use a generalized solution..</li>\\\\n</ul>\\\\n<p>Use other machine-learning solutions when you:</p>\\\\n<ul>\\\\n<li>Need to choose the algorithm and need to train on very specific data..</li>\\\\n</ul>\\\\n<h2 id=\\\\\\\"what-is-machine-learning\\\\\\\">What is machine learning?.</h2>\\\\n<p>Machine learning is a concept where you bring together data and an algorithm to solve a specific need..Once the data and algorithm are trained, the output is a model that you can use again with different data..The trained model provides insights based on the new data..</p>\\\\n<p>The process of building a machine learning system requires some knowledge of machine learning or data science..</p>\\\\n<p>Machine learning is provided using <a href=\\\\\\\"/azure/architecture/data-guide/technology-choices/data-science-and-machine-learning?.context=azure%2fmachine-learning%2fstudio%2fcontext%2fml-context\\\\\\\">Azure Machine Learning (AML) products and services</a>..</p>\\\\n<h2 id=\\\\\\\"what-is-an-azure-ai-service\\\\\\\">What is an Azure AI service?.</h2>\\\\n<p>An Azure AI service provides part or all of the components in a machine learning solution: data, algorithm, and trained model..These services are meant to require general knowledge about your data without needing experience with machine learning or data science..These services provide both REST API(s) and language-based SDKs..As a result, you need to have programming language knowledge to use the services..</p>\\\",\\\"id\\\":null,\\\"title\\\":\\\"Azure AI services and machine learning\\\",\\\"filepath\\\":\\\"cognitive-services-and-machine-learning.md\\\",\\\"url\\\":\\\"https://krpraticstorageacc.blob.core.windows.net/azure-openai/cognitive-services-and-machine-learning.md\\\",\\\"metadata\\\":{\\\"chunking\\\":\\\"orignal document size=1188. Scores=5.689296 and None.Org Highlight count=160.Filtering to chunk no. 1/Highlights=67 of size=506\\\"},\\\"chunk_id\\\":\\\"1\\\"},{\\\"content\\\":\\\"<hr />\\\\n<p>title: Azure AI services and Machine Learning\\\\ntitleSuffix: Azure AI services\\\\ndescription: Learn where Azure AI services fits in with other Azure offerings for machine learning.\\\\nservices: cognitive-services\\\\nmanager: nitinme\\\\nauthor: aahill\\\\nms.author: aahi\\\\nms.service: cognitive-services\\\\nms.topic: conceptual\\\\nms.date: 10/28/2021</p>\\\\n<hr />\\\\n<h1 id=\\\\\\\"azure-ai-services-and-machine-learning\\\\\\\">Azure AI services and machine learning</h1>\\\\n<p>Azure AI services provides machine learning capabilities to solve general problems such as analyzing text for emotional sentiment or analyzing images to recognize objects or faces..You don't need special machine learning or data science knowledge to use these services../what-are-ai-services.md\\\\\\\">Azure AI services</a> is a group of services, each supporting different, generalized prediction capabilities..The services are divided into different categories to help you find the right service..</p>\\\\n<table>\\\\n<thead>\\\\n<tr>\\\\n<th>Service category</th>\\\\n<th>Purpose</th>\\\\n</tr>\\\\n</thead>\\\\n<tbody>\\\\n<tr>\\\\n<td><a href=\\\\\\\"https://azure.microsoft.com/services/cognitive-services/directory/decision/\\\\\\\">Decision</a></td>\\\\n<td>Build apps that surface recommendations for informed and efficient decision-making..</td>\\\\n</tr>\\\\n<tr>\\\\n<td><a href=\\\\\\\"https://azure.microsoft.com/services/cognitive-services/directory/lang/\\\\\\\">Language</a></td>\\\\n<td>Allow your apps to process natural language with pre-built scripts, evaluate sentiment and learn how to recognize what users want..</td>\\\\n</tr>\\\\n<tr>\\\\n<td><a href=\\\\\\\"https://azure.microsoft.com/services/cognitive-services/directory/search/\\\\\\\">Search</a></td>\\\\n<td>Add Bing Search APIs to your apps and harness the ability to comb billions of webpages, images, videos, and news with a single API call..</td>\\\\n</tr>\\\\n<tr>\\\\n<td><a href=\\\\\\\"https://azure.microsoft.com/services/cognitive-services/directory/speech/\\\\\\\">Speech</a></td>\\\",\\\"id\\\":null,\\\"title\\\":\\\"Azure AI services and machine learning\\\",\\\"filepath\\\":\\\"cognitive-services-and-machine-learning.md\\\",\\\"url\\\":\\\"https://krpraticstorageacc.blob.core.windows.net/azure-openai/cognitive-services-and-machine-learning.md\\\",\\\"metadata\\\":{\\\"chunking\\\":\\\"orignal document size=1188. Scores=5.689296 and None.Org Highlight count=160.Filtering to chunk no. 0/Highlights=63 of size=526\\\"},\\\"chunk_id\\\":\\\"0\\\"},{\\\"content\\\":\\\"<p>How is Azure Cognitive Search related to Azure AI services?</p>\\\\n<p><a href=\\\\\\\"../search/search-what-is-azure-search.md\\\\\\\">Azure Cognitive Search</a> is a separate cloud search service that optionally uses Azure AI services to add image and natural language processing to indexing workloads. Azure AI services is exposed in Azure Cognitive Search through <a href=\\\\\\\"../search/cognitive-search-predefined-skills.md\\\\\\\">built-in skills</a> that wrap individual APIs. You can use a free resource for walkthroughs, but plan on creating and attaching a <a href=\\\\\\\"../search/cognitive-search-attach-cognitive-services.md\\\\\\\">billable resource</a> for larger volumes.</p>\\\\n<h2 id=\\\\\\\"how-can-you-use-azure-ai-services\\\\\\\">How can you use Azure AI services?</h2>\\\\n<p>Each service provides information about your data. You can combine services together to chain solutions such as converting speech (audio) to text, translating the text into many languages, then using the translated languages to get answers from a knowledge base. While Azure AI services can be used to create intelligent solutions on their own, they can also be combined with traditional machine learning projects to supplement models or accelerate the development process. </p>\\\\n<p>Azure AI services that provide exported models for other machine learning tools:</p>\\\\n<table>\\\\n<thead>\\\\n<tr>\\\\n<th>Azure AI service</th>\\\\n<th>Model information</th>\\\\n</tr>\\\\n</thead>\\\\n<tbody>\\\\n<tr>\\\\n<td><a href=\\\\\\\"./custom-vision-service/overview.md\\\\\\\">Custom Vision</a></td>\\\\n<td><a href=\\\\\\\"./custom-vision-service/export-model-python.md\\\\\\\">Export</a> for Tensorflow for Android, CoreML for iOS11, ONNX for Windows ML</td>\\\\n</tr>\\\\n</tbody>\\\\n</table>\\\\n<h2 id=\\\\\\\"learn-more\\\\\\\">Learn more</h2>\\\\n<ul>\\\\n<li><a href=\\\\\\\"/azure/architecture/data-guide/technology-choices/data-science-and-machine-learning\\\\\\\">Architecture Guide - What are the machine learning products at Microsoft?</a></li>\\\\n<li><a href=\\\\\\\"../machine-learning/concept-deep-learning-vs-machine-learning.md\\\\\\\">Machine learning - Introduction to deep learning vs. machine learning</a></li>\\\\n</ul>\\\\n<h2 id=\\\\\\\"next-steps\\\\\\\">Next steps</h2>\\\\n<ul>\\\\n<li>Create your Azure AI services resource in the <a href=\\\\\\\"multi-service-resource.md?pivots=azportal\\\\\\\">Azure portal</a> or with <a href=\\\\\\\"./multi-service-resource.md?pivots=azcli\\\\\\\">Azure CLI</a>.</li>\\\\n<li>Learn how to <a href=\\\\\\\"authentication.md\\\\\\\">authenticate</a> with your Azure AI service.</li>\\\\n<li>Use <a href=\\\\\\\"diagnostic-logging.md\\\\\\\">diagnostic logging</a> for issue identification and debugging. </li>\\\\n<li>Deploy an Azure AI service in a Docker <a href=\\\\\\\"cognitive-services-container-support.md\\\\\\\">container</a>.</li>\\\\n<li>Keep up to date with <a href=\\\\\\\"https://azure.microsoft.com/updates/?product=cognitive-services\\\\\\\">service updates</a>.</li>\\\\n</ul>\\\",\\\"id\\\":null,\\\"title\\\":\\\"Azure AI services and machine learning\\\",\\\"filepath\\\":\\\"cognitive-services-and-machine-learning.md\\\",\\\"url\\\":\\\"https://krpraticstorageacc.blob.core.windows.net/azure-openai/cognitive-services-and-machine-learning.md\\\",\\\"metadata\\\":{\\\"chunking\\\":\\\"orignal document size=793. Scores=3.3767838 and None.Org Highlight count=69.\\\"},\\\"chunk_id\\\":\\\"3\\\"},{\\\"content\\\":\\\"<p>How are Azure AI services different from machine learning?.</p>\\\\n<p>Azure AI services provide a trained model for you..This brings data and an algorithm together, available from a REST API(s) or SDK..An Azure AI service provides answers to general problems such as key phrases in text or item identification in images..</p>\\\\n<p>Machine learning is a process that generally requires a longer period of time to implement successfully..This time is spent on data collection, cleaning, transformation, algorithm selection, model training, and deployment to get to the same level of functionality provided by an Azure AI service..With machine learning, it is possible to provide answers to highly specialized and/or specific problems..Machine learning problems require familiarity with the specific subject matter and data of the problem under consideration, as well as expertise in data science..</p>\\\\n<h2 id=\\\\\\\"what-kind-of-data-do-you-have\\\\\\\">What kind of data do you have?.</h2>\\\\n<p>Azure AI services, as a group of services, can require none, some, or all custom data for the trained model..</p>\\\\n<h3 id=\\\\\\\"no-additional-training-data-required\\\\\\\">No additional training data required</h3>\\\\n<p>Services that provide a fully-trained model can be treated as a <em>opaque box</em>..You don't need to know how they work or what data was used to train them..</p>\\\\n<h3 id=\\\\\\\"some-or-all-training-data-required\\\\\\\">Some or all training data required</h3>\\\\n<p>Some services allow you to bring your own data, then train a model..This allows you to extend the model using the Service's data and algorithm with your own data..The output matches your needs..When you bring your own data, you may need to tag the data in a way specific to the service..For example, if you are training a model to identify flowers, you can provide a catalog of flower images along with the location of the flower in each image to train the model..These services process significant amounts of model data..</p>\\\\n<h2 id=\\\\\\\"service-requirements-for-the-data-model\\\\\\\">Service requirements for the data model</h2>\\\\n<p>The following data categorizes each service by which kind of data it allows or requires..</p>\\\\n<table>\\\\n<thead>\\\\n<tr>\\\\n<th>Azure AI service</th>\\\\n<th>No training data required</th>\\\\n<th>You provide some or all training data</th>\\\\n<th>Real-time or near real-time data collection</th>\\\\n</tr>\\\\n</thead>\\\\n<tbody>\\\\n<tr>\\\\n<td><a href=\\\\\\\"../LUIS/what-is-luis.md\\\\\\\">Language Understanding (LUIS)</a></td>\\\\n<td></td>\\\\n<td>x</td>\\\\n<td></td>\\\\n</tr>\\\\n<tr>\\\\n<td><a href=\\\\\\\"../personalizer/what-is-personalizer.md\\\\\\\">Personalizer</a><sup>1</sup></sup></td>\\\\n<td>x</td>\\\\n<td>x</td>\\\\n<td>x</td>\\\\n</tr>\\\\n<tr>\\\\n<td><a href=\\\\\\\"../computer-vision/overview.md\\\\\\\">Vision</a></td>\\\\n<td>x</td>\\\\n<td></td>\\\\n<td></td>\\\\n</tr>\\\\n</tbody>\\\\n</table>\\\\n<p><sup>1</sup> Personalizer only needs training data collected by the service (as it operates in real-time) to evaluate your policy and data..</p>\\\\n<h2 id=\\\\\\\"where-can-you-use-azure-ai-services\\\\\\\">Where can you use Azure AI services?.</h2>\\\\n<p>The services are used in any application that can make REST API(s) or SDK calls..Examples of applications include web sites, bots, virtual or mixed reality, desktop and mobile applications.\\\",\\\"id\\\":null,\\\"title\\\":\\\"Azure AI services and machine learning\\\",\\\"filepath\\\":\\\"cognitive-services-and-machine-learning.md\\\",\\\"url\\\":\\\"https://krpraticstorageacc.blob.core.windows.net/azure-openai/cognitive-services-and-machine-learning.md\\\",\\\"metadata\\\":{\\\"chunking\\\":\\\"orignal document size=1734. Scores=3.1447978 and None.Org Highlight count=66.Filtering to highlight size=891\\\"},\\\"chunk_id\\\":\\\"4\\\"}],\\\"intent\\\":\\\"[\\\\\\\"What are the differences between Azure Machine Learning and Azure AI services?\\\\\\\"]\\\"}\",\n",
+ " \"end_turn\": false\n",
+ " }\n",
+ " ]\n",
+ "}\n",
+ "assistant: Azure AI services and Azure Machine Learning (AML) both aim to apply artificial intelligence (AI) to enhance business operations, but they target different audiences and offer different capabilities [doc1]. \n",
+ "\n",
+ "Azure AI services are designed for developers without machine learning experience and provide pre-trained models to solve general problems such as text analysis, image recognition, and natural language processing [doc5]. These services require general knowledge about your data without needing experience with machine learning or data science and provide REST APIs and language-based SDKs [doc2].\n",
+ "\n",
+ "On the other hand, Azure Machine Learning is tailored for data scientists and offers a platform to build, train, and deploy custom machine learning models [doc1]. It requires knowledge of machine learning or data science and allows users to choose the algorithm and train on very specific data [doc2].\n",
+ "\n",
+ "In summary, Azure AI services offer pre-trained models for developers without machine learning experience, while Azure Machine Learning is a platform for data scientists to build and deploy custom machine learning models."
+ ]
+ }
+ ],
+ "source": [
+ "response = openai.ChatCompletion.create(\n",
+ " messages=[{\"role\": \"user\", \"content\": \"What are the differences between Azure Machine Learning and Azure AI services?\"}],\n",
+ " deployment_id=\"gpt-4\",\n",
+ " dataSources=[\n",
+ " {\n",
+ " \"type\": \"AzureCognitiveSearch\",\n",
+ " \"parameters\": {\n",
+ " \"endpoint\": os.environ[\"SEARCH_ENDPOINT\"],\n",
+ " \"key\": os.environ[\"SEARCH_KEY\"],\n",
+ " \"indexName\": os.environ[\"SEARCH_INDEX_NAME\"],\n",
+ " }\n",
+ " }\n",
+ " ],\n",
+ " stream=True,\n",
+ ")\n",
+ "\n",
+ "for chunk in response:\n",
+ " delta = chunk.choices[0].delta\n",
+ "\n",
+ " if \"role\" in delta:\n",
+ " print(\"\\n\"+ delta.role + \": \", end=\"\", flush=True)\n",
+ " if \"content\" in delta:\n",
+ " print(delta.content, end=\"\", flush=True)\n",
+ " if \"context\" in delta:\n",
+ " print(f\"Context: {delta.context}\", end=\"\", flush=True)"
+ ]
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": ".venv",
+ "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.10.0"
+ },
+ "orig_nbformat": 4
+ },
+ "nbformat": 4,
+ "nbformat_minor": 2
+}
diff --git a/examples/azure/archive/completions.ipynb b/examples/azure/archive/completions.ipynb
new file mode 100644
index 00000000..77fb3ead
--- /dev/null
+++ b/examples/azure/archive/completions.ipynb
@@ -0,0 +1,247 @@
+{
+ "cells": [
+ {
+ "attachments": {},
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "# Azure completions example\n",
+ "\n",
+ "> Note: There is a newer version of the openai library available. See https://github.com/openai/openai-python/discussions/742\n",
+ "\n",
+ "This example will cover completions using the Azure OpenAI service."
+ ]
+ },
+ {
+ "attachments": {},
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Setup\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "First, we install the necessary dependencies."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "! pip install \"openai>=0.28.1,<1.0.0\""
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "For the following sections to work properly we first have to setup some things. Let's start with the `api_base` and `api_version`. To find your `api_base` go to https://portal.azure.com, find your resource and then under \"Resource Management\" -> \"Keys and Endpoints\" look for the \"Endpoint\" value."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import os\n",
+ "import openai"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "openai.api_version = '2023-05-15'\n",
+ "openai.api_base = '' # Please add your endpoint here"
+ ]
+ },
+ {
+ "attachments": {},
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We next have to setup the `api_type` and `api_key`. We can either get the key from the portal or we can get it through Microsoft Active Directory Authentication. Depending on this the `api_type` is either `azure` or `azure_ad`."
+ ]
+ },
+ {
+ "attachments": {},
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Setup: Portal\n",
+ "Let's first look at getting the key from the portal. Go to https://portal.azure.com, find your resource and then under \"Resource Management\" -> \"Keys and Endpoints\" look for one of the \"Keys\" values."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "openai.api_type = 'azure'\n",
+ "openai.api_key = os.environ[\"OPENAI_API_KEY\"]"
+ ]
+ },
+ {
+ "attachments": {},
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "> Note: In this example, we configured the library to use the Azure API by setting the variables in code. For development, consider setting the environment variables instead:\n",
+ "\n",
+ "```\n",
+ "OPENAI_API_BASE\n",
+ "OPENAI_API_KEY\n",
+ "OPENAI_API_TYPE\n",
+ "OPENAI_API_VERSION\n",
+ "```"
+ ]
+ },
+ {
+ "attachments": {},
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### (Optional) Setup: Microsoft Active Directory Authentication\n",
+ "Let's now see how we can get a key via Microsoft Active Directory Authentication. Uncomment the following code if you want to use Active Directory Authentication instead of keys from the portal."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# from azure.identity import DefaultAzureCredential\n",
+ "\n",
+ "# default_credential = DefaultAzureCredential()\n",
+ "# token = default_credential.get_token(\"https://cognitiveservices.azure.com/.default\")\n",
+ "\n",
+ "# openai.api_type = 'azure_ad'\n",
+ "# openai.api_key = token.token"
+ ]
+ },
+ {
+ "attachments": {},
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "A token is valid for a period of time, after which it will expire. To ensure a valid token is sent with every request, you can refresh an expiring token by hooking into requests.auth:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import typing\n",
+ "import time\n",
+ "import requests\n",
+ "if typing.TYPE_CHECKING:\n",
+ " from azure.core.credentials import TokenCredential\n",
+ "\n",
+ "class TokenRefresh(requests.auth.AuthBase):\n",
+ "\n",
+ " def __init__(self, credential: \"TokenCredential\", scopes: typing.List[str]) -> None:\n",
+ " self.credential = credential\n",
+ " self.scopes = scopes\n",
+ " self.cached_token: typing.Optional[str] = None\n",
+ "\n",
+ " def __call__(self, req):\n",
+ " if not self.cached_token or self.cached_token.expires_on - time.time() < 300:\n",
+ " self.cached_token = self.credential.get_token(*self.scopes)\n",
+ " req.headers[\"Authorization\"] = f\"Bearer {self.cached_token.token}\"\n",
+ " return req\n",
+ "\n",
+ "session = requests.Session()\n",
+ "session.auth = TokenRefresh(default_credential, [\"https://cognitiveservices.azure.com/.default\"])\n",
+ "\n",
+ "openai.requestssession = session"
+ ]
+ },
+ {
+ "attachments": {},
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Deployments\n",
+ "In this section we are going to create a deployment using the `text-davinci-002` model that we can then use to create completions."
+ ]
+ },
+ {
+ "attachments": {},
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Deployments: Create manually\n",
+ "Create a new deployment by going to your Resource in your portal under \"Resource Management\" -> \"Model deployments\". Select `text-davinci-002` as the model."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "deployment_id = '' # Fill in the deployment id from the portal here"
+ ]
+ },
+ {
+ "attachments": {},
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Completions\n",
+ "Now let's send a sample completion to the deployment."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "prompt = \"The food was delicious and the waiter\"\n",
+ "completion = openai.Completion.create(deployment_id=deployment_id,\n",
+ " prompt=prompt, stop=\".\", temperature=0)\n",
+ " \n",
+ "print(f\"{prompt}{completion['choices'][0]['text']}.\")"
+ ]
+ }
+ ],
+ "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.3"
+ },
+ "vscode": {
+ "interpreter": {
+ "hash": "3a5103089ab7e7c666b279eeded403fcec76de49a40685dbdfe9f9c78ad97c17"
+ }
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 2
+}
diff --git a/examples/azure/archive/embeddings.ipynb b/examples/azure/archive/embeddings.ipynb
new file mode 100644
index 00000000..ccea1c4b
--- /dev/null
+++ b/examples/azure/archive/embeddings.ipynb
@@ -0,0 +1,279 @@
+{
+ "cells": [
+ {
+ "attachments": {},
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "# Azure embeddings example\n",
+ "\n",
+ "> Note: There is a newer version of the openai library available. See https://github.com/openai/openai-python/discussions/742\n",
+ "\n",
+ "This example will cover embeddings using the Azure OpenAI service."
+ ]
+ },
+ {
+ "attachments": {},
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Setup"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "First, we install the necessary dependencies."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "! pip install \"openai>=0.28.1,<1.0.0\""
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "For the following sections to work properly we first have to setup some things. Let's start with the `api_base` and `api_version`. To find your `api_base` go to https://portal.azure.com, find your resource and then under \"Resource Management\" -> \"Keys and Endpoints\" look for the \"Endpoint\" value."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import os\n",
+ "import openai"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "openai.api_version = '2023-05-15'\n",
+ "openai.api_base = '' # Please add your endpoint here"
+ ]
+ },
+ {
+ "attachments": {},
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We next have to setup the `api_type` and `api_key`. We can either get the key from the portal or we can get it through Microsoft Active Directory Authentication. Depending on this the `api_type` is either `azure` or `azure_ad`."
+ ]
+ },
+ {
+ "attachments": {},
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Setup: Portal\n",
+ "Let's first look at getting the key from the portal. Go to https://portal.azure.com, find your resource and then under \"Resource Management\" -> \"Keys and Endpoints\" look for one of the \"Keys\" values."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "openai.api_type = 'azure'\n",
+ "openai.api_key = os.environ[\"OPENAI_API_KEY\"]"
+ ]
+ },
+ {
+ "attachments": {},
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "> Note: In this example, we configured the library to use the Azure API by setting the variables in code. For development, consider setting the environment variables instead:\n",
+ "\n",
+ "```\n",
+ "OPENAI_API_BASE\n",
+ "OPENAI_API_KEY\n",
+ "OPENAI_API_TYPE\n",
+ "OPENAI_API_VERSION\n",
+ "```"
+ ]
+ },
+ {
+ "attachments": {},
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### (Optional) Setup: Microsoft Active Directory Authentication\n",
+ "Let's now see how we can get a key via Microsoft Active Directory Authentication. Uncomment the following code if you want to use Active Directory Authentication instead of keys from the portal."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# from azure.identity import DefaultAzureCredential\n",
+ "\n",
+ "# default_credential = DefaultAzureCredential()\n",
+ "# token = default_credential.get_token(\"https://cognitiveservices.azure.com/.default\")\n",
+ "\n",
+ "# openai.api_type = 'azure_ad'\n",
+ "# openai.api_key = token.token"
+ ]
+ },
+ {
+ "attachments": {},
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "A token is valid for a period of time, after which it will expire. To ensure a valid token is sent with every request, you can refresh an expiring token by hooking into requests.auth:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import typing\n",
+ "import time\n",
+ "import requests\n",
+ "if typing.TYPE_CHECKING:\n",
+ " from azure.core.credentials import TokenCredential\n",
+ "\n",
+ "class TokenRefresh(requests.auth.AuthBase):\n",
+ "\n",
+ " def __init__(self, credential: \"TokenCredential\", scopes: typing.List[str]) -> None:\n",
+ " self.credential = credential\n",
+ " self.scopes = scopes\n",
+ " self.cached_token: typing.Optional[str] = None\n",
+ "\n",
+ " def __call__(self, req):\n",
+ " if not self.cached_token or self.cached_token.expires_on - time.time() < 300:\n",
+ " self.cached_token = self.credential.get_token(*self.scopes)\n",
+ " req.headers[\"Authorization\"] = f\"Bearer {self.cached_token.token}\"\n",
+ " return req\n",
+ "\n",
+ "session = requests.Session()\n",
+ "session.auth = TokenRefresh(default_credential, [\"https://cognitiveservices.azure.com/.default\"])\n",
+ "\n",
+ "openai.requestssession = session"
+ ]
+ },
+ {
+ "attachments": {},
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Deployments\n",
+ "In this section we are going to create a deployment that we can use to create embeddings."
+ ]
+ },
+ {
+ "attachments": {},
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Deployments: Create manually\n",
+ "Let's create a deployment using the `text-similarity-curie-001` model. Create a new deployment by going to your Resource in your portal under \"Resource Management\" -> \"Model deployments\"."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "deployment_id = '' # Fill in the deployment id from the portal here"
+ ]
+ },
+ {
+ "attachments": {},
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Deployments: Listing\n",
+ "Now because creating a new deployment takes a long time, let's look in the subscription for an already finished deployment that succeeded."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "print('While deployment running, selecting a completed one that supports embeddings.')\n",
+ "deployment_id = None\n",
+ "result = openai.Deployment.list()\n",
+ "for deployment in result.data:\n",
+ " if deployment[\"status\"] != \"succeeded\":\n",
+ " continue\n",
+ " \n",
+ " model = openai.Model.retrieve(deployment[\"model\"])\n",
+ " if model[\"capabilities\"][\"embeddings\"] != True:\n",
+ " continue\n",
+ " \n",
+ " deployment_id = deployment[\"id\"]\n",
+ " break\n",
+ "\n",
+ "if not deployment_id:\n",
+ " print('No deployment with status: succeeded found.')\n",
+ "else:\n",
+ " print(f'Found a succeeded deployment that supports embeddings with id: {deployment_id}.')"
+ ]
+ },
+ {
+ "attachments": {},
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Embeddings\n",
+ "Now let's send a sample embedding to the deployment."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "embeddings = openai.Embedding.create(deployment_id=deployment_id,\n",
+ " input=\"The food was delicious and the waiter...\")\n",
+ " \n",
+ "print(embeddings)"
+ ]
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "Python 3",
+ "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.3"
+ },
+ "vscode": {
+ "interpreter": {
+ "hash": "3a5103089ab7e7c666b279eeded403fcec76de49a40685dbdfe9f9c78ad97c17"
+ }
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 2
+}
diff --git a/examples/azure/archive/functions.ipynb b/examples/azure/archive/functions.ipynb
new file mode 100644
index 00000000..638179e0
--- /dev/null
+++ b/examples/azure/archive/functions.ipynb
@@ -0,0 +1,449 @@
+{
+ "cells": [
+ {
+ "attachments": {},
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "# Azure functions example\n",
+ "\n",
+ "> Note: There is a newer version of the openai library available. See https://github.com/openai/openai-python/discussions/742\n",
+ "\n",
+ "This notebook shows how to use the function calling capability with the Azure OpenAI service. Functions allow a caller of chat completions to define capabilities that the model can use to extend its\n",
+ "functionality into external tools and data sources.\n",
+ "\n",
+ "You can read more about chat functions on OpenAI's blog: https://openai.com/blog/function-calling-and-other-api-updates\n",
+ "\n",
+ "**NOTE**: Chat functions require model versions beginning with gpt-4 and gpt-35-turbo's `-0613` labels. They are not supported by older versions of the models."
+ ]
+ },
+ {
+ "attachments": {},
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Setup\n",
+ "\n",
+ "First, we install the necessary dependencies."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "! pip install \"openai>=0.28.1,<1.0.0\"\n",
+ "# (Optional) If you want to use Microsoft Active Directory\n",
+ "! pip install azure-identity"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 3,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import os\n",
+ "import openai"
+ ]
+ },
+ {
+ "attachments": {},
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "Additionally, to properly access the Azure OpenAI Service, we need to create the proper resources at the [Azure Portal](https://portal.azure.com) (you can check a detailed guide on how to do this in the [Microsoft Docs](https://learn.microsoft.com/en-us/azure/cognitive-services/openai/how-to/create-resource?pivots=web-portal))\n",
+ "\n",
+ "Once the resource is created, the first thing we need to use is its endpoint. You can get the endpoint by looking at the *\"Keys and Endpoints\"* section under the *\"Resource Management\"* section. Having this, we will set up the SDK using this information:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 27,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "openai.api_base = \"\" # Add your endpoint here\n",
+ "\n",
+ "# functions is only supported by the 2023-07-01-preview API version\n",
+ "openai.api_version = \"2023-07-01-preview\""
+ ]
+ },
+ {
+ "attachments": {},
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Authentication\n",
+ "\n",
+ "The Azure OpenAI service supports multiple authentication mechanisms that include API keys and Azure credentials."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 4,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "use_azure_active_directory = False"
+ ]
+ },
+ {
+ "attachments": {},
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "#### Authentication using API key\n",
+ "\n",
+ "To set up the OpenAI SDK to use an *Azure API Key*, we need to set up the `api_type` to `azure` and set `api_key` to a key associated with your endpoint (you can find this key in *\"Keys and Endpoints\"* under *\"Resource Management\"* in the [Azure Portal](https://portal.azure.com))"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "if not use_azure_active_directory:\n",
+ " openai.api_type = \"azure\"\n",
+ " openai.api_key = os.environ[\"OPENAI_API_KEY\"]"
+ ]
+ },
+ {
+ "attachments": {},
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "> Note: In this example, we configured the library to use the Azure API by setting the variables in code. For development, consider setting the environment variables instead:\n",
+ "\n",
+ "```\n",
+ "OPENAI_API_BASE\n",
+ "OPENAI_API_KEY\n",
+ "OPENAI_API_TYPE\n",
+ "OPENAI_API_VERSION\n",
+ "```"
+ ]
+ },
+ {
+ "attachments": {},
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "#### Authentication using Microsoft Active Directory\n",
+ "Let's now see how we can get a key via Microsoft Active Directory Authentication."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from azure.identity import DefaultAzureCredential\n",
+ "\n",
+ "if use_azure_active_directory:\n",
+ " default_credential = DefaultAzureCredential()\n",
+ " token = default_credential.get_token(\"https://cognitiveservices.azure.com/.default\")\n",
+ "\n",
+ " openai.api_type = \"azure_ad\"\n",
+ " openai.api_key = token.token"
+ ]
+ },
+ {
+ "attachments": {},
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "A token is valid for a period of time, after which it will expire. To ensure a valid token is sent with every request, you can refresh an expiring token by hooking into requests.auth:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import typing\n",
+ "import time\n",
+ "import requests\n",
+ "\n",
+ "if typing.TYPE_CHECKING:\n",
+ " from azure.core.credentials import TokenCredential\n",
+ "\n",
+ "class TokenRefresh(requests.auth.AuthBase):\n",
+ "\n",
+ " def __init__(self, credential: \"TokenCredential\", scopes: typing.List[str]) -> None:\n",
+ " self.credential = credential\n",
+ " self.scopes = scopes\n",
+ " self.cached_token: typing.Optional[str] = None\n",
+ "\n",
+ " def __call__(self, req):\n",
+ " if not self.cached_token or self.cached_token.expires_on - time.time() < 300:\n",
+ " self.cached_token = self.credential.get_token(*self.scopes)\n",
+ " req.headers[\"Authorization\"] = f\"Bearer {self.cached_token.token}\"\n",
+ " return req\n",
+ "\n",
+ "if use_azure_active_directory:\n",
+ " session = requests.Session()\n",
+ " session.auth = TokenRefresh(default_credential, [\"https://cognitiveservices.azure.com/.default\"])\n",
+ "\n",
+ " openai.requestssession = session"
+ ]
+ },
+ {
+ "attachments": {},
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Functions\n",
+ "\n",
+ "With setup and authentication complete, you can now use functions with the Azure OpenAI service. This will be split into a few steps:\n",
+ "\n",
+ "1. Define the function(s)\n",
+ "2. Pass function definition(s) into chat completions API\n",
+ "3. Call function with arguments from the response\n",
+ "4. Feed function response back into chat completions API"
+ ]
+ },
+ {
+ "attachments": {},
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "#### 1. Define the function(s)\n",
+ "\n",
+ "A list of functions can be defined, each containing the name of the function, an optional description, and the parameters the function accepts (described as a JSON schema)."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 21,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "functions = [\n",
+ " {\n",
+ " \"name\": \"get_current_weather\",\n",
+ " \"description\": \"Get the current weather\",\n",
+ " \"parameters\": {\n",
+ " \"type\": \"object\",\n",
+ " \"properties\": {\n",
+ " \"location\": {\n",
+ " \"type\": \"string\",\n",
+ " \"description\": \"The city and state, e.g. San Francisco, CA\",\n",
+ " },\n",
+ " \"format\": {\n",
+ " \"type\": \"string\",\n",
+ " \"enum\": [\"celsius\", \"fahrenheit\"],\n",
+ " \"description\": \"The temperature unit to use. Infer this from the users location.\",\n",
+ " },\n",
+ " },\n",
+ " \"required\": [\"location\"],\n",
+ " },\n",
+ " }\n",
+ "]"
+ ]
+ },
+ {
+ "attachments": {},
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "#### 2. Pass function definition(s) into chat completions API\n",
+ "\n",
+ "Now we can pass the function into the chat completions API. If the model determines it should call the function, a `finish_reason` of \"function_call\" will be populated on the choice and the details of which function to call and its arguments will be present in the `message`. Optionally, you can set the `function_call` keyword argument to force the model to call a particular function (e.g. `function_call={\"name\": get_current_weather}`). By default, this is set to `auto`, allowing the model to choose whether to call the function or not. "
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "{\n",
+ " \"choices\": [\n",
+ " {\n",
+ " \"content_filter_results\": {},\n",
+ " \"finish_reason\": \"function_call\",\n",
+ " \"index\": 0,\n",
+ " \"message\": {\n",
+ " \"function_call\": {\n",
+ " \"arguments\": \"{\\n \\\"location\\\": \\\"Seattle, WA\\\"\\n}\",\n",
+ " \"name\": \"get_current_weather\"\n",
+ " },\n",
+ " \"role\": \"assistant\"\n",
+ " }\n",
+ " }\n",
+ " ],\n",
+ " \"created\": 1689702512,\n",
+ " \"id\": \"chatcmpl-7dj6GkYdM7Vw9eGn02bc2qqjN70Ps\",\n",
+ " \"model\": \"gpt-4\",\n",
+ " \"object\": \"chat.completion\",\n",
+ " \"prompt_annotations\": [\n",
+ " {\n",
+ " \"content_filter_results\": {\n",
+ " \"hate\": {\n",
+ " \"filtered\": false,\n",
+ " \"severity\": \"safe\"\n",
+ " },\n",
+ " \"self_harm\": {\n",
+ " \"filtered\": false,\n",
+ " \"severity\": \"safe\"\n",
+ " },\n",
+ " \"sexual\": {\n",
+ " \"filtered\": false,\n",
+ " \"severity\": \"safe\"\n",
+ " },\n",
+ " \"violence\": {\n",
+ " \"filtered\": false,\n",
+ " \"severity\": \"safe\"\n",
+ " }\n",
+ " },\n",
+ " \"prompt_index\": 0\n",
+ " }\n",
+ " ],\n",
+ " \"usage\": {\n",
+ " \"completion_tokens\": 18,\n",
+ " \"prompt_tokens\": 115,\n",
+ " \"total_tokens\": 133\n",
+ " }\n",
+ "}\n"
+ ]
+ }
+ ],
+ "source": [
+ "messages = [\n",
+ " {\"role\": \"system\", \"content\": \"Don't make assumptions about what values to plug into functions. Ask for clarification if a user request is ambiguous.\"},\n",
+ " {\"role\": \"user\", \"content\": \"What's the weather like today in Seattle?\"}\n",
+ "]\n",
+ "\n",
+ "chat_completion = openai.ChatCompletion.create(\n",
+ " deployment_id=\"gpt-35-turbo-0613\",\n",
+ " messages=messages,\n",
+ " functions=functions,\n",
+ ")\n",
+ "print(chat_completion)"
+ ]
+ },
+ {
+ "attachments": {},
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "#### 3. Call function with arguments from the response\n",
+ "\n",
+ "The name of the function call will be one that was provided initially and the arguments will include JSON matching the schema included in the function definition."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "get_current_weather\n",
+ "{\n",
+ " \"location\": \"Seattle, WA\"\n",
+ "}\n"
+ ]
+ }
+ ],
+ "source": [
+ "import json\n",
+ "\n",
+ "def get_current_weather(request):\n",
+ " \"\"\"\n",
+ " This function is for illustrative purposes.\n",
+ " The location and unit should be used to determine weather\n",
+ " instead of returning a hardcoded response.\n",
+ " \"\"\"\n",
+ " location = request.get(\"location\")\n",
+ " unit = request.get(\"unit\")\n",
+ " return {\"temperature\": \"22\", \"unit\": \"celsius\", \"description\": \"Sunny\"}\n",
+ "\n",
+ "function_call = chat_completion.choices[0].message.function_call\n",
+ "print(function_call.name)\n",
+ "print(function_call.arguments)\n",
+ "\n",
+ "if function_call.name == \"get_current_weather\":\n",
+ " response = get_current_weather(json.loads(function_call.arguments))"
+ ]
+ },
+ {
+ "attachments": {},
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "#### 4. Feed function response back into chat completions API\n",
+ "\n",
+ "The response from the function should be serialized into a new message with the role set to \"function\". Now the model will use the response data to formulate its answer."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Today in Seattle, the weather is sunny with a temperature of 22 degrees celsius.\n"
+ ]
+ }
+ ],
+ "source": [
+ "messages.append(\n",
+ " {\n",
+ " \"role\": \"function\",\n",
+ " \"name\": \"get_current_weather\",\n",
+ " \"content\": json.dumps(response)\n",
+ " }\n",
+ ")\n",
+ "\n",
+ "function_completion = openai.ChatCompletion.create(\n",
+ " deployment_id=\"gpt-35-turbo-0613\",\n",
+ " messages=messages,\n",
+ " functions=functions,\n",
+ ")\n",
+ "\n",
+ "print(function_completion.choices[0].message.content.strip())"
+ ]
+ }
+ ],
+ "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.10.0"
+ },
+ "vscode": {
+ "interpreter": {
+ "hash": "3a5103089ab7e7c666b279eeded403fcec76de49a40685dbdfe9f9c78ad97c17"
+ }
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 2
+}
diff --git a/examples/azure/archive/whisper.ipynb b/examples/azure/archive/whisper.ipynb
new file mode 100644
index 00000000..fb40bf2a
--- /dev/null
+++ b/examples/azure/archive/whisper.ipynb
@@ -0,0 +1,276 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "# Azure audio whisper (preview) example\n",
+ "\n",
+ "> Note: There is a newer version of the openai library available. See https://github.com/openai/openai-python/discussions/742\n",
+ "\n",
+ "The example shows how to use the Azure OpenAI Whisper model to transcribe audio files."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Setup\n",
+ "\n",
+ "First, we install the necessary dependencies."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "! pip install \"openai>=0.28.1,<1.0.0\"\n",
+ "! pip install python-dotenv"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Next, we'll import our libraries and configure the Python OpenAI SDK to work with the Azure OpenAI service."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "> Note: In this example, we configured the library to use the Azure API by setting the variables in code. For development, consider setting the environment variables instead:\n",
+ "\n",
+ "```\n",
+ "OPENAI_API_BASE\n",
+ "OPENAI_API_KEY\n",
+ "OPENAI_API_TYPE\n",
+ "OPENAI_API_VERSION\n",
+ "```"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 1,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "True"
+ ]
+ },
+ "execution_count": 1,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "import os\n",
+ "import dotenv\n",
+ "import openai\n",
+ "\n",
+ "\n",
+ "dotenv.load_dotenv()"
+ ]
+ },
+ {
+ "attachments": {},
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "To properly access the Azure OpenAI Service, we need to create the proper resources at the [Azure Portal](https://portal.azure.com) (you can check a detailed guide on how to do this in the [Microsoft Docs](https://learn.microsoft.com/en-us/azure/cognitive-services/openai/how-to/create-resource?pivots=web-portal))\n",
+ "\n",
+ "Once the resource is created, the first thing we need to use is its endpoint. You can get the endpoint by looking at the *\"Keys and Endpoints\"* section under the *\"Resource Management\"* section. Having this, we will set up the SDK using this information:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 2,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "openai.api_base = os.environ[\"OPENAI_API_BASE\"]\n",
+ "\n",
+ "# Min API version that supports Whisper\n",
+ "openai.api_version = \"2023-09-01-preview\"\n",
+ "\n",
+ "# Enter the deployment_id to use for the Whisper model\n",
+ "deployment_id = \"<deployment-id-for-your-whisper-model>\""
+ ]
+ },
+ {
+ "attachments": {},
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Authentication\n",
+ "\n",
+ "The Azure OpenAI service supports multiple authentication mechanisms that include API keys and Azure credentials."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 3,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# set to True if using Azure Active Directory authentication\n",
+ "use_azure_active_directory = False"
+ ]
+ },
+ {
+ "attachments": {},
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n",
+ "#### Authentication using API key\n",
+ "\n",
+ "To set up the OpenAI SDK to use an *Azure API Key*, we need to set up the `api_type` to `azure` and set `api_key` to a key associated with your endpoint (you can find this key in *\"Keys and Endpoints\"* under *\"Resource Management\"* in the [Azure Portal](https://portal.azure.com))"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 4,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "if not use_azure_active_directory:\n",
+ " openai.api_type = 'azure'\n",
+ " openai.api_key = os.environ[\"OPENAI_API_KEY\"]"
+ ]
+ },
+ {
+ "attachments": {},
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "#### Authentication using Azure Active Directory\n",
+ "Let's now see how we can get a key via Microsoft Active Directory Authentication."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from azure.identity import DefaultAzureCredential\n",
+ "\n",
+ "if use_azure_active_directory:\n",
+ " default_credential = DefaultAzureCredential()\n",
+ " token = default_credential.get_token(\"https://cognitiveservices.azure.com/.default\")\n",
+ "\n",
+ " openai.api_type = 'azure_ad'\n",
+ " openai.api_key = token.token"
+ ]
+ },
+ {
+ "attachments": {},
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "A token is valid for a period of time, after which it will expire. To ensure a valid token is sent with every request, you can refresh an expiring token by hooking into requests.auth:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import typing\n",
+ "import time\n",
+ "import requests\n",
+ "\n",
+ "if typing.TYPE_CHECKING:\n",
+ " from azure.core.credentials import TokenCredential\n",
+ "\n",
+ "class TokenRefresh(requests.auth.AuthBase):\n",
+ "\n",
+ " def __init__(self, credential: \"TokenCredential\", scopes: typing.List[str]) -> None:\n",
+ " self.credential = credential\n",
+ " self.scopes = scopes\n",
+ " self.cached_token: typing.Optional[str] = None\n",
+ "\n",
+ " def __call__(self, req):\n",
+ " if not self.cached_token or self.cached_token.expires_on - time.time() < 300:\n",
+ " self.cached_token = self.credential.get_token(*self.scopes)\n",
+ " req.headers[\"Authorization\"] = f\"Bearer {self.cached_token.token}\"\n",
+ " return req\n",
+ "\n",
+ "if use_azure_active_directory:\n",
+ " session = requests.Session()\n",
+ " session.auth = TokenRefresh(default_credential, [\"https://cognitiveservices.azure.com/.default\"])\n",
+ "\n",
+ " openai.requestssession = session"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Audio transcription\n",
+ "\n",
+ "Audio transcription, or speech-to-text, is the process of converting spoken words into text. Use the `openai.Audio.transcribe` method to transcribe an audio file stream to text.\n",
+ "\n",
+ "You can get sample audio files from the [Azure AI Speech SDK repository at GitHub](https://github.com/Azure-Samples/cognitive-services-speech-sdk/tree/master/sampledata/audiofiles)."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 9,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# download sample audio file\n",
+ "import requests\n",
+ "\n",
+ "sample_audio_url = \"https://github.com/Azure-Samples/cognitive-services-speech-sdk/raw/master/sampledata/audiofiles/wikipediaOcelot.wav\"\n",
+ "audio_file = requests.get(sample_audio_url)\n",
+ "with open(\"wikipediaOcelot.wav\", \"wb\") as f:\n",
+ " f.write(audio_file.content)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "transcription = openai.Audio.transcribe(\n",
+ " file=open(\"wikipediaOcelot.wav\", \"rb\"),\n",
+ " model=\"whisper-1\",\n",
+ " deployment_id=deployment_id,\n",
+ ")\n",
+ "print(transcription.text)"
+ ]
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "venv",
+ "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.10.0"
+ },
+ "orig_nbformat": 4
+ },
+ "nbformat": 4,
+ "nbformat_minor": 2
+}
diff --git a/examples/azure/chat.ipynb b/examples/azure/chat.ipynb
index 12c400c1..7fd9b736 100644
--- a/examples/azure/chat.ipynb
+++ b/examples/azure/chat.ipynb
@@ -5,28 +5,18 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "# Azure chat completions example (preview)\n",
- "In this example we'll try to go over all operations needed to get chat completions working using the Azure endpoints. \\\n",
- "This example focuses on chat completions but also touches on some other operations that are also available using the API. This example is meant to be a quick way of showing simple operations and is not meant as a tutorial."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "import os\n",
- "import openai"
+ "# Azure chat completions example\n",
+ "\n",
+ "This example will cover chat completions using the Azure OpenAI service. It also includes information on content filtering."
]
},
{
- "attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"## Setup\n",
- "For the following sections to work properly we first have to setup some things. Let's start with the `api_base` and `api_version`. To find your `api_base` go to https://portal.azure.com, find your resource and then under \"Resource Management\" -> \"Keys and Endpoints\" look for the \"Endpoint\" value."
+ "\n",
+ "First, we install the necessary dependencies and import the libraries we will be using."
]
},
{
@@ -35,113 +25,115 @@
"metadata": {},
"outputs": [],
"source": [
- "openai.api_version = '2023-05-15'\n",
- "openai.api_base = '' # Please add your endpoint here"
+ "! pip install \"openai>=1.0.0,<2.0.0\"\n",
+ "! pip install python-dotenv"
]
},
{
- "attachments": {},
- "cell_type": "markdown",
+ "cell_type": "code",
+ "execution_count": null,
"metadata": {},
+ "outputs": [],
"source": [
- "We next have to setup the `api_type` and `api_key`. We can either get the key from the portal or we can get it through Microsoft Active Directory Authentication. Depending on this the `api_type` is either `azure` or `azure_ad`."
+ "import os\n",
+ "import openai\n",
+ "import dotenv\n",
+ "\n",
+ "dotenv.load_dotenv()"
]
},
{
- "attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
- "### Setup: Portal\n",
- "Let's first look at getting the key from the portal. Go to https://portal.azure.com, find your resource and then under \"Resource Management\" -> \"Keys and Endpoints\" look for one of the \"Keys\" values."
+ "### Authentication\n",
+ "\n",
+ "The Azure OpenAI service supports multiple authentication mechanisms that include API keys and Azure Active Directory token credentials."
]
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
- "openai.api_type = 'azure'\n",
- "openai.api_key = os.environ[\"OPENAI_API_KEY\"]\n"
+ "use_azure_active_directory = False # Set this flag to True if you are using Azure Active Directory"
]
},
{
- "attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
- "> Note: In this example, we configured the library to use the Azure API by setting the variables in code. For development, consider setting the environment variables instead:\n",
+ "#### Authentication using API key\n",
"\n",
- "```\n",
- "OPENAI_API_BASE\n",
- "OPENAI_API_KEY\n",
- "OPENAI_API_TYPE\n",
- "OPENAI_API_VERSION\n",
- "```"
+ "To set up the OpenAI SDK to use an *Azure API Key*, we need to set `api_key` to a key associated with your endpoint (you can find this key in *\"Keys and Endpoints\"* under *\"Resource Management\"* in the [Azure Portal](https://portal.azure.com)). You'll also find the endpoint for your resource here."
]
},
{
- "attachments": {},
- "cell_type": "markdown",
+ "cell_type": "code",
+ "execution_count": 13,
"metadata": {},
+ "outputs": [],
"source": [
- "### (Optional) Setup: Microsoft Active Directory Authentication\n",
- "Let's now see how we can get a key via Microsoft Active Directory Authentication. Uncomment the following code if you want to use Active Directory Authentication instead of keys from the portal."
+ "if not use_azure_active_directory:\n",
+ " endpoint = os.environ[\"AZURE_OPENAI_ENDPOINT\"]\n",
+ " api_key = os.environ[\"AZURE_OPENAI_API_KEY\"]\n",
+ "\n",
+ " client = openai.AzureOpenAI(\n",
+ " azure_endpoint=endpoint,\n",
+ " api_key=api_key,\n",
+ " api_version=\"2023-09-01-preview\"\n",
+ " )"
]
},
{
- "cell_type": "code",
- "execution_count": null,
+ "cell_type": "markdown",
"metadata": {},
- "outputs": [],
"source": [
- "# from azure.identity import DefaultAzureCredential\n",
- "\n",
- "# default_credential = DefaultAzureCredential()\n",
- "# token = default_credential.get_token(\"https://cognitiveservices.azure.com/.default\")\n",
+ "#### Authentication using Azure Active Directory\n",
+ "Let's now see how we can autheticate via Azure Active Directory. We'll start by installing the `azure-identity` library. This library will provide the token credentials we need to authenticate and help us build a token credential provider through the `get_bearer_token_provider` helper function. It's recommended to use `get_bearer_token_provider` over providing a static token to `AzureOpenAI` because this API will automatically cache and refresh tokens for you. \n",
"\n",
- "# openai.api_type = 'azure_ad'\n",
- "# openai.api_key = token.token"
+ "For more information on how to set up Azure Active Directory authentication with Azure OpenAI, see the [documentation](https://learn.microsoft.com/azure/ai-services/openai/how-to/managed-identity)."
]
},
{
- "attachments": {},
- "cell_type": "markdown",
+ "cell_type": "code",
+ "execution_count": null,
"metadata": {},
+ "outputs": [],
"source": [
- "A token is valid for a period of time, after which it will expire. To ensure a valid token is sent with every request, you can refresh an expiring token by hooking into requests.auth:"
+ "! pip install \"azure-identity>=1.15.0\""
]
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 5,
"metadata": {},
"outputs": [],
"source": [
- "import typing\n",
- "import time\n",
- "import requests\n",
- "if typing.TYPE_CHECKING:\n",
- " from azure.core.credentials import TokenCredential\n",
+ "from azure.identity import DefaultAzureCredential, get_bearer_token_provider\n",
"\n",
- "class TokenRefresh(requests.auth.AuthBase):\n",
+ "if use_azure_active_directory:\n",
+ " endpoint = os.environ[\"AZURE_OPENAI_ENDPOINT\"]\n",
+ " api_key = os.environ[\"AZURE_OPENAI_API_KEY\"]\n",
"\n",
- " def __init__(self, credential: \"TokenCredential\", scopes: typing.List[str]) -> None:\n",
- " self.credential = credential\n",
- " self.scopes = scopes\n",
- " self.cached_token: typing.Optional[str] = None\n",
- "\n",
- " def __call__(self, req):\n",
- " if not self.cached_token or self.cached_token.expires_on - time.time() < 300:\n",
- " self.cached_token = self.credential.get_token(*self.scopes)\n",
- " req.headers[\"Authorization\"] = f\"Bearer {self.cached_token.token}\"\n",
- " return req\n",
- "\n",
- "session = requests.Session()\n",
- "session.auth = TokenRefresh(default_credential, [\"https://cognitiveservices.azure.com/.default\"])\n",
+ " client = openai.AzureOpenAI(\n",
+ " azure_endpoint=endpoint,\n",
+ " azure_ad_token_provider=get_bearer_token_provider(DefaultAzureCredential(), \"https://cognitiveservices.azure.com/.default\"),\n",
+ " api_version=\"2023-09-01-preview\"\n",
+ " )"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "> Note: the AzureOpenAI infers the following arguments from their corresponding environment variables if they are not provided:\n",
"\n",
- "openai.requestssession = session"
+ "- `api_key` from `AZURE_OPENAI_API_KEY`\n",
+ "- `azure_ad_token` from `AZURE_OPENAI_AD_TOKEN`\n",
+ "- `api_version` from `OPENAI_API_VERSION`\n",
+ "- `azure_endpoint` from `AZURE_OPENAI_ENDPOINT`\n"
]
},
{
@@ -150,7 +142,8 @@
"metadata": {},
"source": [
"## Deployments\n",
- "In this section we are going to create a deployment using the `gpt-35-turbo` model that we can then use to create chat completions."
+ "\n",
+ "In this section we are going to create a deployment of a GPT model that we can use to create chat completions."
]
},
{
@@ -158,17 +151,17 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "### Deployments: Create manually\n",
- "Let's create a deployment using the `gpt-35-turbo` model. Go to https://portal.azure.com, find your resource and then under \"Resource Management\" -> \"Model deployments\" create a new `gpt-35-turbo` deployment. "
+ "### Deployments: Create in the Azure OpenAI Studio\n",
+ "Let's deploy a model to use with chat completions. Go to https://portal.azure.com, find your Azure OpenAI resource, and then navigate to the Azure OpenAI Studio. Click on the \"Deployments\" tab and then create a deployment for the model you want to use for chat completions. The deployment name that you give the model will be used in the code below."
]
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 4,
"metadata": {},
"outputs": [],
"source": [
- "deployment_id = '' # Fill in the deployment id from the portal here"
+ "deployment = \"\" # Fill in the deployment name from the portal here"
]
},
{
@@ -176,8 +169,9 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "### Create chat completion\n",
- "Now let's send a sample chat completion to the deployment."
+ "## Create chat completions\n",
+ "\n",
+ "Now let's create a chat completion using the client we built."
]
},
{
@@ -187,8 +181,8 @@
"outputs": [],
"source": [
"# For all possible arguments see https://platform.openai.com/docs/api-reference/chat-completions/create\n",
- "response = openai.ChatCompletion.create(\n",
- " deployment_id=deployment_id,\n",
+ "response = client.chat.completions.create(\n",
+ " model=deployment,\n",
" messages=[\n",
" {\"role\": \"system\", \"content\": \"You are a helpful assistant.\"},\n",
" {\"role\": \"user\", \"content\": \"Knock knock.\"},\n",
@@ -206,7 +200,9 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "We can also stream the response.\n"
+ "### Create a streaming chat completion\n",
+ "\n",
+ "We can also stream the response."
]
},
{
@@ -215,8 +211,8 @@
"metadata": {},
"outputs": [],
"source": [
- "response = openai.ChatCompletion.create(\n",
- " deployment_id=deployment_id,\n",
+ "response = client.chat.completions.create(\n",
+ " model=deployment,\n",
" messages=[\n",
" {\"role\": \"system\", \"content\": \"You are a helpful assistant.\"},\n",
" {\"role\": \"user\", \"content\": \"Knock knock.\"},\n",
@@ -228,12 +224,95 @@
")\n",
"\n",
"for chunk in response:\n",
- " delta = chunk.choices[0].delta\n",
+ " if len(chunk.choices) > 0:\n",
+ " delta = chunk.choices[0].delta\n",
+ "\n",
+ " if delta.role:\n",
+ " print(delta.role + \": \", end=\"\", flush=True)\n",
+ " if delta.content:\n",
+ " print(delta.content, end=\"\", flush=True)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Content filtering\n",
+ "\n",
+ "Azure OpenAI service includes content filtering of prompts and completion responses. You can learn more about content filtering and how to configure it [here](https://learn.microsoft.com/azure/ai-services/openai/concepts/content-filter).\n",
+ "\n",
+ "If the prompt is flagged by the content filter, the library will raise a `BadRequestError` exception with a `content_filter` error code. Otherwise, you can access the `prompt_filter_results` and `content_filter_results` on the response to see the results of the content filtering and what categories were flagged."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "#### Prompt flagged by content filter"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import json\n",
+ "\n",
+ "messages = [\n",
+ " {\"role\": \"system\", \"content\": \"You are a helpful assistant.\"},\n",
+ " {\"role\": \"user\", \"content\": \"<text violating the content policy>\"}\n",
+ "]\n",
+ "\n",
+ "try:\n",
+ " completion = client.chat.completions.create(\n",
+ " messages=messages,\n",
+ " model=deployment,\n",
+ " )\n",
+ "except openai.BadRequestError as e:\n",
+ " err = json.loads(e.response.text)\n",
+ " if err[\"error\"][\"code\"] == \"content_filter\":\n",
+ " print(\"Content filter triggered!\")\n",
+ " content_filter_result = err[\"error\"][\"innererror\"][\"content_filter_result\"]\n",
+ " for category, details in content_filter_result.items():\n",
+ " print(f\"{category}:\\n filtered={details['filtered']}\\n severity={details['severity']}\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Checking the result of the content filter"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "messages = [\n",
+ " {\"role\": \"system\", \"content\": \"You are a helpful assistant.\"},\n",
+ " {\"role\": \"user\", \"content\": \"What's the biggest city in Washington?\"}\n",
+ "]\n",
+ "\n",
+ "completion = client.chat.completions.create(\n",
+ " messages=messages,\n",
+ " model=deployment,\n",
+ ")\n",
+ "print(f\"Answer: {completion.choices[0].message.content}\")\n",
+ "\n",
+ "# prompt content filter result in \"model_extra\" for azure\n",
+ "prompt_filter_result = completion.model_extra[\"prompt_filter_results\"][0][\"content_filter_results\"]\n",
+ "print(\"\\nPrompt content filter results:\")\n",
+ "for category, details in prompt_filter_result.items():\n",
+ " print(f\"{category}:\\n filtered={details['filtered']}\\n severity={details['severity']}\")\n",
"\n",
- " if \"role\" in delta.keys():\n",
- " print(delta.role + \": \", end=\"\", flush=True)\n",
- " if \"content\" in delta.keys():\n",
- " print(delta.content, end=\"\", flush=True)"
+ "# completion content filter result\n",
+ "print(\"\\nCompletion content filter results:\")\n",
+ "completion_filter_result = completion.choices[0].model_extra[\"content_filter_results\"]\n",
+ "for category, details in completion_filter_result.items():\n",
+ " print(f\"{category}:\\n filtered={details['filtered']}\\n severity={details['severity']}\")"
]
}
],
@@ -253,7 +332,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
- "version": "3.11.3"
+ "version": "3.10.0"
},
"orig_nbformat": 4
},
diff --git a/examples/azure/chat_with_your_own_data.ipynb b/examples/azure/chat_with_your_own_data.ipynb
index 5ef1a43d..4a6ddbec 100644
--- a/examples/azure/chat_with_your_own_data.ipynb
+++ b/examples/azure/chat_with_your_own_data.ipynb
@@ -58,7 +58,7 @@
"metadata": {},
"outputs": [],
"source": [
- "! pip install \"openai>=0.27.6\"\n",
+ "! pip install \"openai>=1.0.0,<2.0.0\"\n",
"! pip install python-dotenv"
]
},
@@ -68,8 +68,8 @@
"source": [
"In this example, we'll use `dotenv` to load our environment variables. To connect with Azure OpenAI and the Search index, the following variables should be added to a `.env` file in `KEY=VALUE` format:\n",
"\n",
- "* `OPENAI_API_BASE` - the Azure OpenAI endpoint. This can be found under \"Keys and Endpoints\" for your Azure OpenAI resource in the Azure Portal.\n",
- "* `OPENAI_API_KEY` - the Azure OpenAI API key. This can be found under \"Keys and Endpoints\" for your Azure OpenAI resource in the Azure Portal. Omit if using Azure Active Directory authentication (see below `Authentication using Microsoft Active Directory`)\n",
+ "* `AZURE_OPENAI_ENDPOINT` - the Azure OpenAI endpoint. This can be found under \"Keys and Endpoints\" for your Azure OpenAI resource in the Azure Portal.\n",
+ "* `AZURE_OPENAI_API_KEY` - the Azure OpenAI API key. This can be found under \"Keys and Endpoints\" for your Azure OpenAI resource in the Azure Portal. Omit if using Azure Active Directory authentication (see below `Authentication using Microsoft Active Directory`)\n",
"* `SEARCH_ENDPOINT` - the Cognitive Search endpoint. This URL be found on the \"Overview\" of your Search resource on the Azure Portal.\n",
"* `SEARCH_KEY` - the Cognitive Search API key. Found under \"Keys\" for your Search resource in the Azure Portal.\n",
"* `SEARCH_INDEX_NAME` - the name of the index you created with your own data."
@@ -88,30 +88,18 @@
"dotenv.load_dotenv()"
]
},
- {
- "cell_type": "code",
- "execution_count": 2,
- "metadata": {},
- "outputs": [],
- "source": [
- "openai.api_base = os.environ[\"OPENAI_API_BASE\"]\n",
- "\n",
- "# Azure OpenAI on your own data is only supported by the 2023-08-01-preview API version\n",
- "openai.api_version = \"2023-08-01-preview\""
- ]
- },
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Authentication\n",
"\n",
- "The Azure OpenAI service supports multiple authentication mechanisms that include API keys and Azure credentials."
+ "The Azure OpenAI service supports multiple authentication mechanisms that include API keys and Azure Active Directory token credentials."
]
},
{
"cell_type": "code",
- "execution_count": 3,
+ "execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
@@ -122,29 +110,38 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "\n",
"#### Authentication using API key\n",
"\n",
- "To set up the OpenAI SDK to use an *Azure API Key*, we need to set up the `api_type` to `azure` and set `api_key` to a key associated with your endpoint (you can find this key in *\"Keys and Endpoints\"* under *\"Resource Management\"* in the [Azure Portal](https://portal.azure.com))"
+ "To set up the OpenAI SDK to use an *Azure API Key*, we need to set `api_key` to a key associated with your endpoint (you can find this key in *\"Keys and Endpoints\"* under *\"Resource Management\"* in the [Azure Portal](https://portal.azure.com)). You'll also find the endpoint for your resource here."
]
},
{
"cell_type": "code",
- "execution_count": 4,
+ "execution_count": 3,
"metadata": {},
"outputs": [],
"source": [
"if not use_azure_active_directory:\n",
- " openai.api_type = 'azure'\n",
- " openai.api_key = os.environ[\"OPENAI_API_KEY\"]"
+ " endpoint = os.environ[\"AZURE_OPENAI_ENDPOINT\"]\n",
+ " api_key = os.environ[\"AZURE_OPENAI_API_KEY\"]\n",
+ " # set the deployment name for the model we want to use\n",
+ " deployment = \"<deployment-id-of-the-model-to-use>\"\n",
+ "\n",
+ " client = openai.AzureOpenAI(\n",
+ " base_url=f\"{endpoint}/openai/deployments/{deployment}/extensions\",\n",
+ " api_key=api_key,\n",
+ " api_version=\"2023-09-01-preview\"\n",
+ " )"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
- "#### Authentication using Microsoft Active Directory\n",
- "Let's now see how we can get a key via Microsoft Active Directory Authentication. See the [documentation](https://learn.microsoft.com/azure/ai-services/openai/how-to/managed-identity) for more information on how to set this up."
+ "#### Authentication using Azure Active Directory\n",
+ "Let's now see how we can autheticate via Azure Active Directory. We'll start by installing the `azure-identity` library. This library will provide the token credentials we need to authenticate and help us build a token credential provider through the `get_bearer_token_provider` helper function. It's recommended to use `get_bearer_token_provider` over providing a static token to `AzureOpenAI` because this API will automatically cache and refresh tokens for you. \n",
+ "\n",
+ "For more information on how to set up Azure Active Directory authentication with Azure OpenAI, see the [documentation](https://learn.microsoft.com/azure/ai-services/openai/how-to/managed-identity)."
]
},
{
@@ -153,7 +150,7 @@
"metadata": {},
"outputs": [],
"source": [
- "! pip install azure-identity"
+ "! pip install \"azure-identity>=1.15.0\""
]
},
{
@@ -162,48 +159,31 @@
"metadata": {},
"outputs": [],
"source": [
- "from azure.identity import DefaultAzureCredential\n",
+ "from azure.identity import DefaultAzureCredential, get_bearer_token_provider\n",
"\n",
"if use_azure_active_directory:\n",
- " default_credential = DefaultAzureCredential()\n",
- " token = default_credential.get_token(\"https://cognitiveservices.azure.com/.default\")\n",
- "\n",
- " openai.api_type = \"azure_ad\"\n",
- " openai.api_key = token.token"
+ " endpoint = os.environ[\"AZURE_OPENAI_ENDPOINT\"]\n",
+ " api_key = os.environ[\"AZURE_OPENAI_API_KEY\"]\n",
+ " # set the deployment name for the model we want to use\n",
+ " deployment = \"<deployment-id-of-the-model-to-use>\"\n",
+ "\n",
+ " client = openai.AzureOpenAI(\n",
+ " base_url=f\"{endpoint}/openai/deployments/{deployment}/extensions\",\n",
+ " azure_ad_token_provider=get_bearer_token_provider(DefaultAzureCredential(), \"https://cognitiveservices.azure.com/.default\"),\n",
+ " api_version=\"2023-09-01-preview\"\n",
+ " )"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
- "A token is valid for a period of time, after which it will expire. To ensure a valid token is sent with every request, you can refresh an expiring token by hooking into requests.auth:"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 8,
- "metadata": {},
- "outputs": [],
- "source": [
- "import typing\n",
- "import time\n",
- "import requests\n",
- "\n",
- "if typing.TYPE_CHECKING:\n",
- " from azure.core.credentials import TokenCredential\n",
- "\n",
- "class TokenRefresh(requests.auth.AuthBase):\n",
+ "> Note: the AzureOpenAI infers the following arguments from their corresponding environment variables if they are not provided:\n",
"\n",
- " def __init__(self, credential: \"TokenCredential\", scopes: typing.List[str]) -> None:\n",
- " self.credential = credential\n",
- " self.scopes = scopes\n",
- " self.cached_token: typing.Optional[str] = None\n",
- "\n",
- " def __call__(self, req):\n",
- " if not self.cached_token or self.cached_token.expires_on - time.time() < 300:\n",
- " self.cached_token = self.credential.get_token(*self.scopes)\n",
- " req.headers[\"Authorization\"] = f\"Bearer {self.cached_token.token}\"\n",
- " return req\n"
+ "- `api_key` from `AZURE_OPENAI_API_KEY`\n",
+ "- `azure_ad_token` from `AZURE_OPENAI_AD_TOKEN`\n",
+ "- `api_version` from `OPENAI_API_VERSION`\n",
+ "- `azure_endpoint` from `AZURE_OPENAI_ENDPOINT`\n"
]
},
{
@@ -238,122 +218,35 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "To chat with Azure OpenAI models using your own data with the Python SDK, we must first set up the code to target the chat completions extensions endpoint which is designed to work with your own data. To do this, we've created a convenience function that can be called to set a custom adapter for the library which will target the extensions endpoint for a given deployment ID."
+ "Now we can use Azure on your own data with Chat Completions. Providing our search endpoint, key, and index name in `dataSources`, any questions posed to the model will now be grounded in our own data. An additional property, `context`, will be provided in the response to show the data the model referenced to answer the question."
]
},
{
"cell_type": "code",
- "execution_count": 5,
- "metadata": {},
- "outputs": [],
- "source": [
- "import requests\n",
- "\n",
- "def setup_byod(deployment_id: str) -> None:\n",
- " \"\"\"Sets up the OpenAI Python SDK to use your own data for the chat endpoint.\n",
- " \n",
- " :param deployment_id: The deployment ID for the model to use with your own data.\n",
- "\n",
- " To remove this configuration, simply set openai.requestssession to None.\n",
- " \"\"\"\n",
- "\n",
- " class BringYourOwnDataAdapter(requests.adapters.HTTPAdapter):\n",
- "\n",
- " def send(self, request, **kwargs):\n",
- " request.url = f\"{openai.api_base}/openai/deployments/{deployment_id}/extensions/chat/completions?api-version={openai.api_version}\"\n",
- " return super().send(request, **kwargs)\n",
- "\n",
- " session = requests.Session()\n",
- "\n",
- " # Mount a custom adapter which will use the extensions endpoint for any call using the given `deployment_id`\n",
- " session.mount(\n",
- " prefix=f\"{openai.api_base}/openai/deployments/{deployment_id}\",\n",
- " adapter=BringYourOwnDataAdapter()\n",
- " )\n",
- "\n",
- " if use_azure_active_directory:\n",
- " session.auth = TokenRefresh(default_credential, [\"https://cognitiveservices.azure.com/.default\"])\n",
- "\n",
- " openai.requestssession = session\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "Now we can call the convenience function to configure the SDK with the model we plan to use for our own data."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 6,
+ "execution_count": null,
"metadata": {},
"outputs": [],
"source": [
- "setup_byod(\"gpt-4\")"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "Providing our search endpoint, key, and index name for the `dataSources` keyword argument, any questions posed to the model will now be grounded in our own data. An additional property, `context`, will be provided to show the data the model referenced to answer the question."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 7,
- "metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "{\n",
- " \"id\": \"65b485bb-b3c9-48da-8b6f-7d3a219f0b40\",\n",
- " \"model\": \"gpt-4\",\n",
- " \"created\": 1693338769,\n",
- " \"object\": \"extensions.chat.completion\",\n",
- " \"choices\": [\n",
- " {\n",
- " \"index\": 0,\n",
- " \"finish_reason\": \"stop\",\n",
- " \"message\": {\n",
- " \"role\": \"assistant\",\n",
- " \"content\": \"Azure AI services and Azure Machine Learning (AML) both aim to apply artificial intelligence (AI) to enhance business operations, but they target different audiences and offer different capabilities [doc1]. \\n\\nAzure AI services are designed for developers without machine learning experience and provide pre-trained models to solve general problems such as text analysis, image recognition, and natural language processing [doc5]. These services require general knowledge about your data without needing experience with machine learning or data science and provide REST APIs and language-based SDKs [doc2].\\n\\nOn the other hand, Azure Machine Learning is tailored for data scientists and involves a longer process of data collection, cleaning, transformation, algorithm selection, model training, and deployment [doc5]. It allows users to create custom solutions for highly specialized and specific problems, requiring familiarity with the subject matter, data, and expertise in data science [doc5].\\n\\nIn summary, Azure AI services offer pre-trained models for developers without machine learning experience, while Azure Machine Learning is designed for data scientists to create custom solutions for specific problems.\",\n",
- " \"end_turn\": true,\n",
- " \"context\": {\n",
- " \"messages\": [\n",
- " {\n",
- " \"role\": \"tool\",\n",
- " \"content\": \"{\\\"citations\\\": [{\\\"content\\\": \\\"<h2 id=\\\\\\\"how-are-azure-ai-services-and-azure-machine-learning-aml-similar\\\\\\\">How are Azure AI services and Azure Machine Learning (AML) similar?.</h2>\\\\n<p>Both have the end-goal of applying artificial intelligence (AI) to enhance business operations, though how each provides this in the respective offerings is different..</p>\\\\n<p>Generally, the audiences are different:</p>\\\\n<ul>\\\\n<li>Azure AI services are for developers without machine-learning experience..</li>\\\\n<li>Azure Machine Learning is tailored for data scientists.\\\", \\\"id\\\": null, \\\"title\\\": \\\"Azure AI services and machine learning\\\", \\\"filepath\\\": \\\"cognitive-services-and-machine-learning.md\\\", \\\"url\\\": \\\"https://krpraticstorageacc.blob.core.windows.net/azure-openai/cognitive-services-and-machine-learning.md\\\", \\\"metadata\\\": {\\\"chunking\\\": \\\"orignal document size=1188. Scores=5.689296 and None.Org Highlight count=160.Filtering to chunk no. 2/Highlights=30 of size=137\\\"}, \\\"chunk_id\\\": \\\"2\\\"}, {\\\"content\\\": \\\"<td>Convert speech into text and text into natural-sounding speech..Translate from one language to another and enable speaker verification and recognition..</td>\\\\n</tr>\\\\n<tr>\\\\n<td><a href=\\\\\\\"https://azure.microsoft.com/services/cognitive-services/directory/vision/\\\\\\\">Vision</a></td>\\\\n<td>Recognize, identify, caption, index, and moderate your pictures, videos, and digital ink content..</td>\\\\n</tr>\\\\n<p></tbody>\\\\n</table></p>\\\\n<p>Use Azure AI services when you:</p>\\\\n<ul>\\\\n<li>Can use a generalized solution..</li>\\\\n</ul>\\\\n<p>Use other machine-learning solutions when you:</p>\\\\n<ul>\\\\n<li>Need to choose the algorithm and need to train on very specific data..</li>\\\\n</ul>\\\\n<h2 id=\\\\\\\"what-is-machine-learning\\\\\\\">What is machine learning?.</h2>\\\\n<p>Machine learning is a concept where you bring together data and an algorithm to solve a specific need..Once the data and algorithm are trained, the output is a model that you can use again with different data..The trained model provides insights based on the new data..</p>\\\\n<p>The process of building a machine learning system requires some knowledge of machine learning or data science..</p>\\\\n<p>Machine learning is provided using <a href=\\\\\\\"/azure/architecture/data-guide/technology-choices/data-science-and-machine-learning?.context=azure%2fmachine-learning%2fstudio%2fcontext%2fml-context\\\\\\\">Azure Machine Learning (AML) products and services</a>..</p>\\\\n<h2 id=\\\\\\\"what-is-an-azure-ai-service\\\\\\\">What is an Azure AI service?.</h2>\\\\n<p>An Azure AI service provides part or all of the components in a machine learning solution: data, algorithm, and trained model..These services are meant to require general knowledge about your data without needing experience with machine learning or data science..These services provide both REST API(s) and language-based SDKs..As a result, you need to have programming language knowledge to use the services..</p>\\\", \\\"id\\\": null, \\\"title\\\": \\\"Azure AI services and machine learning\\\", \\\"filepath\\\": \\\"cognitive-services-and-machine-learning.md\\\", \\\"url\\\": \\\"https://krpraticstorageacc.blob.core.windows.net/azure-openai/cognitive-services-and-machine-learning.md\\\", \\\"metadata\\\": {\\\"chunking\\\": \\\"orignal document size=1188. Scores=5.689296 and None.Org Highlight count=160.Filtering to chunk no. 1/Highlights=67 of size=506\\\"}, \\\"chunk_id\\\": \\\"1\\\"}, {\\\"content\\\": \\\"<hr />\\\\n<p>title: Azure AI services and Machine Learning\\\\ntitleSuffix: Azure AI services\\\\ndescription: Learn where Azure AI services fits in with other Azure offerings for machine learning.\\\\nservices: cognitive-services\\\\nmanager: nitinme\\\\nauthor: aahill\\\\nms.author: aahi\\\\nms.service: cognitive-services\\\\nms.topic: conceptual\\\\nms.date: 10/28/2021</p>\\\\n<hr />\\\\n<h1 id=\\\\\\\"azure-ai-services-and-machine-learning\\\\\\\">Azure AI services and machine learning</h1>\\\\n<p>Azure AI services provides machine learning capabilities to solve general problems such as analyzing text for emotional sentiment or analyzing images to recognize objects or faces..You don't need special machine learning or data science knowledge to use these services../what-are-ai-services.md\\\\\\\">Azure AI services</a> is a group of services, each supporting different, generalized prediction capabilities..The services are divided into different categories to help you find the right service..</p>\\\\n<table>\\\\n<thead>\\\\n<tr>\\\\n<th>Service category</th>\\\\n<th>Purpose</th>\\\\n</tr>\\\\n</thead>\\\\n<tbody>\\\\n<tr>\\\\n<td><a href=\\\\\\\"https://azure.microsoft.com/services/cognitive-services/directory/decision/\\\\\\\">Decision</a></td>\\\\n<td>Build apps that surface recommendations for informed and efficient decision-making..</td>\\\\n</tr>\\\\n<tr>\\\\n<td><a href=\\\\\\\"https://azure.microsoft.com/services/cognitive-services/directory/lang/\\\\\\\">Language</a></td>\\\\n<td>Allow your apps to process natural language with pre-built scripts, evaluate sentiment and learn how to recognize what users want..</td>\\\\n</tr>\\\\n<tr>\\\\n<td><a href=\\\\\\\"https://azure.microsoft.com/services/cognitive-services/directory/search/\\\\\\\">Search</a></td>\\\\n<td>Add Bing Search APIs to your apps and harness the ability to comb billions of webpages, images, videos, and news with a single API call..</td>\\\\n</tr>\\\\n<tr>\\\\n<td><a href=\\\\\\\"https://azure.microsoft.com/services/cognitive-services/directory/speech/\\\\\\\">Speech</a></td>\\\", \\\"id\\\": null, \\\"title\\\": \\\"Azure AI services and machine learning\\\", \\\"filepath\\\": \\\"cognitive-services-and-machine-learning.md\\\", \\\"url\\\": \\\"https://krpraticstorageacc.blob.core.windows.net/azure-openai/cognitive-services-and-machine-learning.md\\\", \\\"metadata\\\": {\\\"chunking\\\": \\\"orignal document size=1188. Scores=5.689296 and None.Org Highlight count=160.Filtering to chunk no. 0/Highlights=63 of size=526\\\"}, \\\"chunk_id\\\": \\\"0\\\"}, {\\\"content\\\": \\\"<p>How is Azure Cognitive Search related to Azure AI services?</p>\\\\n<p><a href=\\\\\\\"../search/search-what-is-azure-search.md\\\\\\\">Azure Cognitive Search</a> is a separate cloud search service that optionally uses Azure AI services to add image and natural language processing to indexing workloads. Azure AI services is exposed in Azure Cognitive Search through <a href=\\\\\\\"../search/cognitive-search-predefined-skills.md\\\\\\\">built-in skills</a> that wrap individual APIs. You can use a free resource for walkthroughs, but plan on creating and attaching a <a href=\\\\\\\"../search/cognitive-search-attach-cognitive-services.md\\\\\\\">billable resource</a> for larger volumes.</p>\\\\n<h2 id=\\\\\\\"how-can-you-use-azure-ai-services\\\\\\\">How can you use Azure AI services?</h2>\\\\n<p>Each service provides information about your data. You can combine services together to chain solutions such as converting speech (audio) to text, translating the text into many languages, then using the translated languages to get answers from a knowledge base. While Azure AI services can be used to create intelligent solutions on their own, they can also be combined with traditional machine learning projects to supplement models or accelerate the development process. </p>\\\\n<p>Azure AI services that provide exported models for other machine learning tools:</p>\\\\n<table>\\\\n<thead>\\\\n<tr>\\\\n<th>Azure AI service</th>\\\\n<th>Model information</th>\\\\n</tr>\\\\n</thead>\\\\n<tbody>\\\\n<tr>\\\\n<td><a href=\\\\\\\"./custom-vision-service/overview.md\\\\\\\">Custom Vision</a></td>\\\\n<td><a href=\\\\\\\"./custom-vision-service/export-model-python.md\\\\\\\">Export</a> for Tensorflow for Android, CoreML for iOS11, ONNX for Windows ML</td>\\\\n</tr>\\\\n</tbody>\\\\n</table>\\\\n<h2 id=\\\\\\\"learn-more\\\\\\\">Learn more</h2>\\\\n<ul>\\\\n<li><a href=\\\\\\\"/azure/architecture/data-guide/technology-choices/data-science-and-machine-learning\\\\\\\">Architecture Guide - What are the machine learning products at Microsoft?</a></li>\\\\n<li><a href=\\\\\\\"../machine-learning/concept-deep-learning-vs-machine-learning.md\\\\\\\">Machine learning - Introduction to deep learning vs. machine learning</a></li>\\\\n</ul>\\\\n<h2 id=\\\\\\\"next-steps\\\\\\\">Next steps</h2>\\\\n<ul>\\\\n<li>Create your Azure AI services resource in the <a href=\\\\\\\"multi-service-resource.md?pivots=azportal\\\\\\\">Azure portal</a> or with <a href=\\\\\\\"./multi-service-resource.md?pivots=azcli\\\\\\\">Azure CLI</a>.</li>\\\\n<li>Learn how to <a href=\\\\\\\"authentication.md\\\\\\\">authenticate</a> with your Azure AI service.</li>\\\\n<li>Use <a href=\\\\\\\"diagnostic-logging.md\\\\\\\">diagnostic logging</a> for issue identification and debugging. </li>\\\\n<li>Deploy an Azure AI service in a Docker <a href=\\\\\\\"cognitive-services-container-support.md\\\\\\\">container</a>.</li>\\\\n<li>Keep up to date with <a href=\\\\\\\"https://azure.microsoft.com/updates/?product=cognitive-services\\\\\\\">service updates</a>.</li>\\\\n</ul>\\\", \\\"id\\\": null, \\\"title\\\": \\\"Azure AI services and machine learning\\\", \\\"filepath\\\": \\\"cognitive-services-and-machine-learning.md\\\", \\\"url\\\": \\\"https://krpraticstorageacc.blob.core.windows.net/azure-openai/cognitive-services-and-machine-learning.md\\\", \\\"metadata\\\": {\\\"chunking\\\": \\\"orignal document size=793. Scores=3.3767838 and None.Org Highlight count=69.\\\"}, \\\"chunk_id\\\": \\\"3\\\"}, {\\\"content\\\": \\\"<p>How are Azure AI services different from machine learning?.</p>\\\\n<p>Azure AI services provide a trained model for you..This brings data and an algorithm together, available from a REST API(s) or SDK..An Azure AI service provides answers to general problems such as key phrases in text or item identification in images..</p>\\\\n<p>Machine learning is a process that generally requires a longer period of time to implement successfully..This time is spent on data collection, cleaning, transformation, algorithm selection, model training, and deployment to get to the same level of functionality provided by an Azure AI service..With machine learning, it is possible to provide answers to highly specialized and/or specific problems..Machine learning problems require familiarity with the specific subject matter and data of the problem under consideration, as well as expertise in data science..</p>\\\\n<h2 id=\\\\\\\"what-kind-of-data-do-you-have\\\\\\\">What kind of data do you have?.</h2>\\\\n<p>Azure AI services, as a group of services, can require none, some, or all custom data for the trained model..</p>\\\\n<h3 id=\\\\\\\"no-additional-training-data-required\\\\\\\">No additional training data required</h3>\\\\n<p>Services that provide a fully-trained model can be treated as a <em>opaque box</em>..You don't need to know how they work or what data was used to train them..</p>\\\\n<h3 id=\\\\\\\"some-or-all-training-data-required\\\\\\\">Some or all training data required</h3>\\\\n<p>Some services allow you to bring your own data, then train a model..This allows you to extend the model using the Service's data and algorithm with your own data..The output matches your needs..When you bring your own data, you may need to tag the data in a way specific to the service..For example, if you are training a model to identify flowers, you can provide a catalog of flower images along with the location of the flower in each image to train the model..These services process significant amounts of model data..</p>\\\\n<h2 id=\\\\\\\"service-requirements-for-the-data-model\\\\\\\">Service requirements for the data model</h2>\\\\n<p>The following data categorizes each service by which kind of data it allows or requires..</p>\\\\n<table>\\\\n<thead>\\\\n<tr>\\\\n<th>Azure AI service</th>\\\\n<th>No training data required</th>\\\\n<th>You provide some or all training data</th>\\\\n<th>Real-time or near real-time data collection</th>\\\\n</tr>\\\\n</thead>\\\\n<tbody>\\\\n<tr>\\\\n<td><a href=\\\\\\\"../LUIS/what-is-luis.md\\\\\\\">Language Understanding (LUIS)</a></td>\\\\n<td></td>\\\\n<td>x</td>\\\\n<td></td>\\\\n</tr>\\\\n<tr>\\\\n<td><a href=\\\\\\\"../personalizer/what-is-personalizer.md\\\\\\\">Personalizer</a><sup>1</sup></sup></td>\\\\n<td>x</td>\\\\n<td>x</td>\\\\n<td>x</td>\\\\n</tr>\\\\n<tr>\\\\n<td><a href=\\\\\\\"../computer-vision/overview.md\\\\\\\">Vision</a></td>\\\\n<td>x</td>\\\\n<td></td>\\\\n<td></td>\\\\n</tr>\\\\n</tbody>\\\\n</table>\\\\n<p><sup>1</sup> Personalizer only needs training data collected by the service (as it operates in real-time) to evaluate your policy and data..</p>\\\\n<h2 id=\\\\\\\"where-can-you-use-azure-ai-services\\\\\\\">Where can you use Azure AI services?.</h2>\\\\n<p>The services are used in any application that can make REST API(s) or SDK calls..Examples of applications include web sites, bots, virtual or mixed reality, desktop and mobile applications.\\\", \\\"id\\\": null, \\\"title\\\": \\\"Azure AI services and machine learning\\\", \\\"filepath\\\": \\\"cognitive-services-and-machine-learning.md\\\", \\\"url\\\": \\\"https://krpraticstorageacc.blob.core.windows.net/azure-openai/cognitive-services-and-machine-learning.md\\\", \\\"metadata\\\": {\\\"chunking\\\": \\\"orignal document size=1734. Scores=3.1447978 and None.Org Highlight count=66.Filtering to highlight size=891\\\"}, \\\"chunk_id\\\": \\\"4\\\"}], \\\"intent\\\": \\\"[\\\\\\\"What are the differences between Azure Machine Learning and Azure AI services?\\\\\\\"]\\\"}\",\n",
- " \"end_turn\": false\n",
- " }\n",
- " ]\n",
- " }\n",
- " }\n",
- " }\n",
- " ]\n",
- "}\n"
- ]
- }
- ],
- "source": [
- "completion = openai.ChatCompletion.create(\n",
+ "completion = client.chat.completions.create(\n",
" messages=[{\"role\": \"user\", \"content\": \"What are the differences between Azure Machine Learning and Azure AI services?\"}],\n",
- " deployment_id=\"gpt-4\",\n",
- " dataSources=[ # camelCase is intentional, as this is the format the API expects\n",
- " {\n",
- " \"type\": \"AzureCognitiveSearch\",\n",
- " \"parameters\": {\n",
- " \"endpoint\": os.environ[\"SEARCH_ENDPOINT\"],\n",
- " \"key\": os.environ[\"SEARCH_KEY\"],\n",
- " \"indexName\": os.environ[\"SEARCH_INDEX_NAME\"],\n",
+ " model=deployment,\n",
+ " extra_body={\n",
+ " \"dataSources\": [\n",
+ " {\n",
+ " \"type\": \"AzureCognitiveSearch\",\n",
+ " \"parameters\": {\n",
+ " \"endpoint\": os.environ[\"SEARCH_ENDPOINT\"],\n",
+ " \"key\": os.environ[\"SEARCH_KEY\"],\n",
+ " \"indexName\": os.environ[\"SEARCH_INDEX_NAME\"],\n",
+ " }\n",
" }\n",
- " }\n",
- " ]\n",
+ " ]\n",
+ " }\n",
")\n",
- "print(completion)"
+ "print(f\"{completion.choices[0].message.role}: {completion.choices[0].message.content}\")\n",
+ "\n",
+ "# `context` is in the model_extra for Azure\n",
+ "print(f\"\\nContext: {completion.choices[0].message.model_extra['context']['messages'][0]['content']}\")"
]
},
{
@@ -365,58 +258,37 @@
},
{
"cell_type": "code",
- "execution_count": 8,
+ "execution_count": null,
"metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Context: {\n",
- " \"messages\": [\n",
- " {\n",
- " \"role\": \"tool\",\n",
- " \"content\": \"{\\\"citations\\\":[{\\\"content\\\":\\\"<h2 id=\\\\\\\"how-are-azure-ai-services-and-azure-machine-learning-aml-similar\\\\\\\">How are Azure AI services and Azure Machine Learning (AML) similar?.</h2>\\\\n<p>Both have the end-goal of applying artificial intelligence (AI) to enhance business operations, though how each provides this in the respective offerings is different..</p>\\\\n<p>Generally, the audiences are different:</p>\\\\n<ul>\\\\n<li>Azure AI services are for developers without machine-learning experience..</li>\\\\n<li>Azure Machine Learning is tailored for data scientists.\\\",\\\"id\\\":null,\\\"title\\\":\\\"Azure AI services and machine learning\\\",\\\"filepath\\\":\\\"cognitive-services-and-machine-learning.md\\\",\\\"url\\\":\\\"https://krpraticstorageacc.blob.core.windows.net/azure-openai/cognitive-services-and-machine-learning.md\\\",\\\"metadata\\\":{\\\"chunking\\\":\\\"orignal document size=1188. Scores=5.689296 and None.Org Highlight count=160.Filtering to chunk no. 2/Highlights=30 of size=137\\\"},\\\"chunk_id\\\":\\\"2\\\"},{\\\"content\\\":\\\"<td>Convert speech into text and text into natural-sounding speech..Translate from one language to another and enable speaker verification and recognition..</td>\\\\n</tr>\\\\n<tr>\\\\n<td><a href=\\\\\\\"https://azure.microsoft.com/services/cognitive-services/directory/vision/\\\\\\\">Vision</a></td>\\\\n<td>Recognize, identify, caption, index, and moderate your pictures, videos, and digital ink content..</td>\\\\n</tr>\\\\n<p></tbody>\\\\n</table></p>\\\\n<p>Use Azure AI services when you:</p>\\\\n<ul>\\\\n<li>Can use a generalized solution..</li>\\\\n</ul>\\\\n<p>Use other machine-learning solutions when you:</p>\\\\n<ul>\\\\n<li>Need to choose the algorithm and need to train on very specific data..</li>\\\\n</ul>\\\\n<h2 id=\\\\\\\"what-is-machine-learning\\\\\\\">What is machine learning?.</h2>\\\\n<p>Machine learning is a concept where you bring together data and an algorithm to solve a specific need..Once the data and algorithm are trained, the output is a model that you can use again with different data..The trained model provides insights based on the new data..</p>\\\\n<p>The process of building a machine learning system requires some knowledge of machine learning or data science..</p>\\\\n<p>Machine learning is provided using <a href=\\\\\\\"/azure/architecture/data-guide/technology-choices/data-science-and-machine-learning?.context=azure%2fmachine-learning%2fstudio%2fcontext%2fml-context\\\\\\\">Azure Machine Learning (AML) products and services</a>..</p>\\\\n<h2 id=\\\\\\\"what-is-an-azure-ai-service\\\\\\\">What is an Azure AI service?.</h2>\\\\n<p>An Azure AI service provides part or all of the components in a machine learning solution: data, algorithm, and trained model..These services are meant to require general knowledge about your data without needing experience with machine learning or data science..These services provide both REST API(s) and language-based SDKs..As a result, you need to have programming language knowledge to use the services..</p>\\\",\\\"id\\\":null,\\\"title\\\":\\\"Azure AI services and machine learning\\\",\\\"filepath\\\":\\\"cognitive-services-and-machine-learning.md\\\",\\\"url\\\":\\\"https://krpraticstorageacc.blob.core.windows.net/azure-openai/cognitive-services-and-machine-learning.md\\\",\\\"metadata\\\":{\\\"chunking\\\":\\\"orignal document size=1188. Scores=5.689296 and None.Org Highlight count=160.Filtering to chunk no. 1/Highlights=67 of size=506\\\"},\\\"chunk_id\\\":\\\"1\\\"},{\\\"content\\\":\\\"<hr />\\\\n<p>title: Azure AI services and Machine Learning\\\\ntitleSuffix: Azure AI services\\\\ndescription: Learn where Azure AI services fits in with other Azure offerings for machine learning.\\\\nservices: cognitive-services\\\\nmanager: nitinme\\\\nauthor: aahill\\\\nms.author: aahi\\\\nms.service: cognitive-services\\\\nms.topic: conceptual\\\\nms.date: 10/28/2021</p>\\\\n<hr />\\\\n<h1 id=\\\\\\\"azure-ai-services-and-machine-learning\\\\\\\">Azure AI services and machine learning</h1>\\\\n<p>Azure AI services provides machine learning capabilities to solve general problems such as analyzing text for emotional sentiment or analyzing images to recognize objects or faces..You don't need special machine learning or data science knowledge to use these services../what-are-ai-services.md\\\\\\\">Azure AI services</a> is a group of services, each supporting different, generalized prediction capabilities..The services are divided into different categories to help you find the right service..</p>\\\\n<table>\\\\n<thead>\\\\n<tr>\\\\n<th>Service category</th>\\\\n<th>Purpose</th>\\\\n</tr>\\\\n</thead>\\\\n<tbody>\\\\n<tr>\\\\n<td><a href=\\\\\\\"https://azure.microsoft.com/services/cognitive-services/directory/decision/\\\\\\\">Decision</a></td>\\\\n<td>Build apps that surface recommendations for informed and efficient decision-making..</td>\\\\n</tr>\\\\n<tr>\\\\n<td><a href=\\\\\\\"https://azure.microsoft.com/services/cognitive-services/directory/lang/\\\\\\\">Language</a></td>\\\\n<td>Allow your apps to process natural language with pre-built scripts, evaluate sentiment and learn how to recognize what users want..</td>\\\\n</tr>\\\\n<tr>\\\\n<td><a href=\\\\\\\"https://azure.microsoft.com/services/cognitive-services/directory/search/\\\\\\\">Search</a></td>\\\\n<td>Add Bing Search APIs to your apps and harness the ability to comb billions of webpages, images, videos, and news with a single API call..</td>\\\\n</tr>\\\\n<tr>\\\\n<td><a href=\\\\\\\"https://azure.microsoft.com/services/cognitive-services/directory/speech/\\\\\\\">Speech</a></td>\\\",\\\"id\\\":null,\\\"title\\\":\\\"Azure AI services and machine learning\\\",\\\"filepath\\\":\\\"cognitive-services-and-machine-learning.md\\\",\\\"url\\\":\\\"https://krpraticstorageacc.blob.core.windows.net/azure-openai/cognitive-services-and-machine-learning.md\\\",\\\"metadata\\\":{\\\"chunking\\\":\\\"orignal document size=1188. Scores=5.689296 and None.Org Highlight count=160.Filtering to chunk no. 0/Highlights=63 of size=526\\\"},\\\"chunk_id\\\":\\\"0\\\"},{\\\"content\\\":\\\"<p>How is Azure Cognitive Search related to Azure AI services?</p>\\\\n<p><a href=\\\\\\\"../search/search-what-is-azure-search.md\\\\\\\">Azure Cognitive Search</a> is a separate cloud search service that optionally uses Azure AI services to add image and natural language processing to indexing workloads. Azure AI services is exposed in Azure Cognitive Search through <a href=\\\\\\\"../search/cognitive-search-predefined-skills.md\\\\\\\">built-in skills</a> that wrap individual APIs. You can use a free resource for walkthroughs, but plan on creating and attaching a <a href=\\\\\\\"../search/cognitive-search-attach-cognitive-services.md\\\\\\\">billable resource</a> for larger volumes.</p>\\\\n<h2 id=\\\\\\\"how-can-you-use-azure-ai-services\\\\\\\">How can you use Azure AI services?</h2>\\\\n<p>Each service provides information about your data. You can combine services together to chain solutions such as converting speech (audio) to text, translating the text into many languages, then using the translated languages to get answers from a knowledge base. While Azure AI services can be used to create intelligent solutions on their own, they can also be combined with traditional machine learning projects to supplement models or accelerate the development process. </p>\\\\n<p>Azure AI services that provide exported models for other machine learning tools:</p>\\\\n<table>\\\\n<thead>\\\\n<tr>\\\\n<th>Azure AI service</th>\\\\n<th>Model information</th>\\\\n</tr>\\\\n</thead>\\\\n<tbody>\\\\n<tr>\\\\n<td><a href=\\\\\\\"./custom-vision-service/overview.md\\\\\\\">Custom Vision</a></td>\\\\n<td><a href=\\\\\\\"./custom-vision-service/export-model-python.md\\\\\\\">Export</a> for Tensorflow for Android, CoreML for iOS11, ONNX for Windows ML</td>\\\\n</tr>\\\\n</tbody>\\\\n</table>\\\\n<h2 id=\\\\\\\"learn-more\\\\\\\">Learn more</h2>\\\\n<ul>\\\\n<li><a href=\\\\\\\"/azure/architecture/data-guide/technology-choices/data-science-and-machine-learning\\\\\\\">Architecture Guide - What are the machine learning products at Microsoft?</a></li>\\\\n<li><a href=\\\\\\\"../machine-learning/concept-deep-learning-vs-machine-learning.md\\\\\\\">Machine learning - Introduction to deep learning vs. machine learning</a></li>\\\\n</ul>\\\\n<h2 id=\\\\\\\"next-steps\\\\\\\">Next steps</h2>\\\\n<ul>\\\\n<li>Create your Azure AI services resource in the <a href=\\\\\\\"multi-service-resource.md?pivots=azportal\\\\\\\">Azure portal</a> or with <a href=\\\\\\\"./multi-service-resource.md?pivots=azcli\\\\\\\">Azure CLI</a>.</li>\\\\n<li>Learn how to <a href=\\\\\\\"authentication.md\\\\\\\">authenticate</a> with your Azure AI service.</li>\\\\n<li>Use <a href=\\\\\\\"diagnostic-logging.md\\\\\\\">diagnostic logging</a> for issue identification and debugging. </li>\\\\n<li>Deploy an Azure AI service in a Docker <a href=\\\\\\\"cognitive-services-container-support.md\\\\\\\">container</a>.</li>\\\\n<li>Keep up to date with <a href=\\\\\\\"https://azure.microsoft.com/updates/?product=cognitive-services\\\\\\\">service updates</a>.</li>\\\\n</ul>\\\",\\\"id\\\":null,\\\"title\\\":\\\"Azure AI services and machine learning\\\",\\\"filepath\\\":\\\"cognitive-services-and-machine-learning.md\\\",\\\"url\\\":\\\"https://krpraticstorageacc.blob.core.windows.net/azure-openai/cognitive-services-and-machine-learning.md\\\",\\\"metadata\\\":{\\\"chunking\\\":\\\"orignal document size=793. Scores=3.3767838 and None.Org Highlight count=69.\\\"},\\\"chunk_id\\\":\\\"3\\\"},{\\\"content\\\":\\\"<p>How are Azure AI services different from machine learning?.</p>\\\\n<p>Azure AI services provide a trained model for you..This brings data and an algorithm together, available from a REST API(s) or SDK..An Azure AI service provides answers to general problems such as key phrases in text or item identification in images..</p>\\\\n<p>Machine learning is a process that generally requires a longer period of time to implement successfully..This time is spent on data collection, cleaning, transformation, algorithm selection, model training, and deployment to get to the same level of functionality provided by an Azure AI service..With machine learning, it is possible to provide answers to highly specialized and/or specific problems..Machine learning problems require familiarity with the specific subject matter and data of the problem under consideration, as well as expertise in data science..</p>\\\\n<h2 id=\\\\\\\"what-kind-of-data-do-you-have\\\\\\\">What kind of data do you have?.</h2>\\\\n<p>Azure AI services, as a group of services, can require none, some, or all custom data for the trained model..</p>\\\\n<h3 id=\\\\\\\"no-additional-training-data-required\\\\\\\">No additional training data required</h3>\\\\n<p>Services that provide a fully-trained model can be treated as a <em>opaque box</em>..You don't need to know how they work or what data was used to train them..</p>\\\\n<h3 id=\\\\\\\"some-or-all-training-data-required\\\\\\\">Some or all training data required</h3>\\\\n<p>Some services allow you to bring your own data, then train a model..This allows you to extend the model using the Service's data and algorithm with your own data..The output matches your needs..When you bring your own data, you may need to tag the data in a way specific to the service..For example, if you are training a model to identify flowers, you can provide a catalog of flower images along with the location of the flower in each image to train the model..These services process significant amounts of model data..</p>\\\\n<h2 id=\\\\\\\"service-requirements-for-the-data-model\\\\\\\">Service requirements for the data model</h2>\\\\n<p>The following data categorizes each service by which kind of data it allows or requires..</p>\\\\n<table>\\\\n<thead>\\\\n<tr>\\\\n<th>Azure AI service</th>\\\\n<th>No training data required</th>\\\\n<th>You provide some or all training data</th>\\\\n<th>Real-time or near real-time data collection</th>\\\\n</tr>\\\\n</thead>\\\\n<tbody>\\\\n<tr>\\\\n<td><a href=\\\\\\\"../LUIS/what-is-luis.md\\\\\\\">Language Understanding (LUIS)</a></td>\\\\n<td></td>\\\\n<td>x</td>\\\\n<td></td>\\\\n</tr>\\\\n<tr>\\\\n<td><a href=\\\\\\\"../personalizer/what-is-personalizer.md\\\\\\\">Personalizer</a><sup>1</sup></sup></td>\\\\n<td>x</td>\\\\n<td>x</td>\\\\n<td>x</td>\\\\n</tr>\\\\n<tr>\\\\n<td><a href=\\\\\\\"../computer-vision/overview.md\\\\\\\">Vision</a></td>\\\\n<td>x</td>\\\\n<td></td>\\\\n<td></td>\\\\n</tr>\\\\n</tbody>\\\\n</table>\\\\n<p><sup>1</sup> Personalizer only needs training data collected by the service (as it operates in real-time) to evaluate your policy and data..</p>\\\\n<h2 id=\\\\\\\"where-can-you-use-azure-ai-services\\\\\\\">Where can you use Azure AI services?.</h2>\\\\n<p>The services are used in any application that can make REST API(s) or SDK calls..Examples of applications include web sites, bots, virtual or mixed reality, desktop and mobile applications.\\\",\\\"id\\\":null,\\\"title\\\":\\\"Azure AI services and machine learning\\\",\\\"filepath\\\":\\\"cognitive-services-and-machine-learning.md\\\",\\\"url\\\":\\\"https://krpraticstorageacc.blob.core.windows.net/azure-openai/cognitive-services-and-machine-learning.md\\\",\\\"metadata\\\":{\\\"chunking\\\":\\\"orignal document size=1734. Scores=3.1447978 and None.Org Highlight count=66.Filtering to highlight size=891\\\"},\\\"chunk_id\\\":\\\"4\\\"}],\\\"intent\\\":\\\"[\\\\\\\"What are the differences between Azure Machine Learning and Azure AI services?\\\\\\\"]\\\"}\",\n",
- " \"end_turn\": false\n",
- " }\n",
- " ]\n",
- "}\n",
- "assistant: Azure AI services and Azure Machine Learning (AML) both aim to apply artificial intelligence (AI) to enhance business operations, but they target different audiences and offer different capabilities [doc1]. \n",
- "\n",
- "Azure AI services are designed for developers without machine learning experience and provide pre-trained models to solve general problems such as text analysis, image recognition, and natural language processing [doc5]. These services require general knowledge about your data without needing experience with machine learning or data science and provide REST APIs and language-based SDKs [doc2].\n",
- "\n",
- "On the other hand, Azure Machine Learning is tailored for data scientists and offers a platform to build, train, and deploy custom machine learning models [doc1]. It requires knowledge of machine learning or data science and allows users to choose the algorithm and train on very specific data [doc2].\n",
- "\n",
- "In summary, Azure AI services offer pre-trained models for developers without machine learning experience, while Azure Machine Learning is a platform for data scientists to build and deploy custom machine learning models."
- ]
- }
- ],
+ "outputs": [],
"source": [
- "response = openai.ChatCompletion.create(\n",
+ "response = client.chat.completions.create(\n",
" messages=[{\"role\": \"user\", \"content\": \"What are the differences between Azure Machine Learning and Azure AI services?\"}],\n",
- " deployment_id=\"gpt-4\",\n",
- " dataSources=[\n",
- " {\n",
- " \"type\": \"AzureCognitiveSearch\",\n",
- " \"parameters\": {\n",
- " \"endpoint\": os.environ[\"SEARCH_ENDPOINT\"],\n",
- " \"key\": os.environ[\"SEARCH_KEY\"],\n",
- " \"indexName\": os.environ[\"SEARCH_INDEX_NAME\"],\n",
+ " model=deployment,\n",
+ " extra_body={\n",
+ " \"dataSources\": [\n",
+ " {\n",
+ " \"type\": \"AzureCognitiveSearch\",\n",
+ " \"parameters\": {\n",
+ " \"endpoint\": os.environ[\"SEARCH_ENDPOINT\"],\n",
+ " \"key\": os.environ[\"SEARCH_KEY\"],\n",
+ " \"indexName\": os.environ[\"SEARCH_INDEX_NAME\"],\n",
+ " }\n",
" }\n",
- " }\n",
- " ],\n",
+ " ]\n",
+ " },\n",
" stream=True,\n",
")\n",
"\n",
"for chunk in response:\n",
" delta = chunk.choices[0].delta\n",
"\n",
- " if \"role\" in delta:\n",
+ " if delta.role:\n",
" print(\"\\n\"+ delta.role + \": \", end=\"\", flush=True)\n",
- " if \"content\" in delta:\n",
+ " if delta.content:\n",
" print(delta.content, end=\"\", flush=True)\n",
- " if \"context\" in delta:\n",
- " print(f\"Context: {delta.context}\", end=\"\", flush=True)"
+ " if delta.model_extra.get(\"context\"):\n",
+ " print(f\"Context: {delta.model_extra['context']}\", end=\"\", flush=True)"
]
}
],
diff --git a/examples/azure/completions.ipynb b/examples/azure/completions.ipynb
index b8d4b5f1..94a817c4 100644
--- a/examples/azure/completions.ipynb
+++ b/examples/azure/completions.ipynb
@@ -6,8 +6,27 @@
"metadata": {},
"source": [
"# Azure completions example\n",
- "In this example we'll try to go over all operations needed to get completions working using the Azure endpoints. \\\n",
- "This example focuses on completions but also touches on some other operations that are also available using the API. This example is meant to be a quick way of showing simple operations and is not meant as a tutorial."
+ "\n",
+ "This example will cover completions using the Azure OpenAI service. It also includes information on content filtering."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Setup\n",
+ "\n",
+ "First, we install the necessary dependencies and import the libraries we will be using."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "! pip install \"openai>=1.0.0,<2.0.0\"\n",
+ "! pip install python-dotenv"
]
},
{
@@ -17,43 +36,64 @@
"outputs": [],
"source": [
"import os\n",
- "import openai"
+ "import openai\n",
+ "import dotenv\n",
+ "\n",
+ "dotenv.load_dotenv()"
]
},
{
- "attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
- "## Setup\n",
- "For the following sections to work properly we first have to setup some things. Let's start with the `api_base` and `api_version`. To find your `api_base` go to https://portal.azure.com, find your resource and then under \"Resource Management\" -> \"Keys and Endpoints\" look for the \"Endpoint\" value."
+ "### Authentication\n",
+ "\n",
+ "The Azure OpenAI service supports multiple authentication mechanisms that include API keys and Azure Active Directory token credentials."
]
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
- "openai.api_version = '2023-05-15'\n",
- "openai.api_base = '' # Please add your endpoint here"
+ "use_azure_active_directory = False # Set this flag to True if you are using Azure Active Directory"
]
},
{
- "attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
- "We next have to setup the `api_type` and `api_key`. We can either get the key from the portal or we can get it through Microsoft Active Directory Authentication. Depending on this the `api_type` is either `azure` or `azure_ad`."
+ "#### Authentication using API key\n",
+ "\n",
+ "To set up the OpenAI SDK to use an *Azure API Key*, we need to set `api_key` to a key associated with your endpoint (you can find this key in *\"Keys and Endpoints\"* under *\"Resource Management\"* in the [Azure Portal](https://portal.azure.com)). You'll also find the endpoint for your resource here."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 3,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "if not use_azure_active_directory:\n",
+ " endpoint = os.environ[\"AZURE_OPENAI_ENDPOINT\"]\n",
+ " api_key = os.environ[\"AZURE_OPENAI_API_KEY\"]\n",
+ "\n",
+ " client = openai.AzureOpenAI(\n",
+ " azure_endpoint=endpoint,\n",
+ " api_key=api_key,\n",
+ " api_version=\"2023-09-01-preview\"\n",
+ " )"
]
},
{
- "attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
- "### Setup: Portal\n",
- "Let's first look at getting the key from the portal. Go to https://portal.azure.com, find your resource and then under \"Resource Management\" -> \"Keys and Endpoints\" look for one of the \"Keys\" values."
+ "#### Authentication using Azure Active Directory\n",
+ "Let's now see how we can autheticate via Azure Active Directory. We'll start by installing the `azure-identity` library. This library will provide the token credentials we need to authenticate and help us build a token credential provider through the `get_bearer_token_provider` helper function. It's recommended to use `get_bearer_token_provider` over providing a static token to `AzureOpenAI` because this API will automatically cache and refresh tokens for you. \n",
+ "\n",
+ "For more information on how to set up Azure Active Directory authentication with Azure OpenAI, see the [documentation](https://learn.microsoft.com/azure/ai-services/openai/how-to/managed-identity)."
]
},
{
@@ -62,8 +102,38 @@
"metadata": {},
"outputs": [],
"source": [
- "openai.api_type = 'azure'\n",
- "openai.api_key = os.environ[\"OPENAI_API_KEY\"]"
+ "! pip install \"azure-identity>=1.15.0\""
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 5,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from azure.identity import DefaultAzureCredential, get_bearer_token_provider\n",
+ "\n",
+ "if use_azure_active_directory:\n",
+ " endpoint = os.environ[\"AZURE_OPENAI_ENDPOINT\"]\n",
+ " api_key = os.environ[\"AZURE_OPENAI_API_KEY\"]\n",
+ "\n",
+ " client = openai.AzureOpenAI(\n",
+ " azure_endpoint=endpoint,\n",
+ " azure_ad_token_provider=get_bearer_token_provider(DefaultAzureCredential(), \"https://cognitiveservices.azure.com/.default\"),\n",
+ " api_version=\"2023-09-01-preview\"\n",
+ " )"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "> Note: the AzureOpenAI infers the following arguments from their corresponding environment variables if they are not provided:\n",
+ "\n",
+ "- `api_key` from `AZURE_OPENAI_API_KEY`\n",
+ "- `azure_ad_token` from `AZURE_OPENAI_AD_TOKEN`\n",
+ "- `api_version` from `OPENAI_API_VERSION`\n",
+ "- `azure_endpoint` from `AZURE_OPENAI_ENDPOINT`\n"
]
},
{
@@ -71,14 +141,9 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "> Note: In this example, we configured the library to use the Azure API by setting the variables in code. For development, consider setting the environment variables instead:\n",
+ "## Deployments\n",
"\n",
- "```\n",
- "OPENAI_API_BASE\n",
- "OPENAI_API_KEY\n",
- "OPENAI_API_TYPE\n",
- "OPENAI_API_VERSION\n",
- "```"
+ "In this section we are going to create a deployment of a model that we can use to create completions."
]
},
{
@@ -86,23 +151,17 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "### (Optional) Setup: Microsoft Active Directory Authentication\n",
- "Let's now see how we can get a key via Microsoft Active Directory Authentication. Uncomment the following code if you want to use Active Directory Authentication instead of keys from the portal."
+ "### Deployments: Create in the Azure OpenAI Studio\n",
+ "Let's deploy a model to use with completions. Go to https://portal.azure.com, find your Azure OpenAI resource, and then navigate to the Azure OpenAI Studio. Click on the \"Deployments\" tab and then create a deployment for the model you want to use for completions. The deployment name that you give the model will be used in the code below."
]
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 4,
"metadata": {},
"outputs": [],
"source": [
- "# from azure.identity import DefaultAzureCredential\n",
- "\n",
- "# default_credential = DefaultAzureCredential()\n",
- "# token = default_credential.get_token(\"https://cognitiveservices.azure.com/.default\")\n",
- "\n",
- "# openai.api_type = 'azure_ad'\n",
- "# openai.api_key = token.token"
+ "deployment = \"\" # Fill in the deployment name from the portal here"
]
},
{
@@ -110,7 +169,9 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "A token is valid for a period of time, after which it will expire. To ensure a valid token is sent with every request, you can refresh an expiring token by hooking into requests.auth:"
+ "## Completions\n",
+ "\n",
+ "Now let's create a completion using the client we built."
]
},
{
@@ -119,47 +180,59 @@
"metadata": {},
"outputs": [],
"source": [
- "import typing\n",
- "import time\n",
- "import requests\n",
- "if typing.TYPE_CHECKING:\n",
- " from azure.core.credentials import TokenCredential\n",
- "\n",
- "class TokenRefresh(requests.auth.AuthBase):\n",
- "\n",
- " def __init__(self, credential: \"TokenCredential\", scopes: typing.List[str]) -> None:\n",
- " self.credential = credential\n",
- " self.scopes = scopes\n",
- " self.cached_token: typing.Optional[str] = None\n",
- "\n",
- " def __call__(self, req):\n",
- " if not self.cached_token or self.cached_token.expires_on - time.time() < 300:\n",
- " self.cached_token = self.credential.get_token(*self.scopes)\n",
- " req.headers[\"Authorization\"] = f\"Bearer {self.cached_token.token}\"\n",
- " return req\n",
- "\n",
- "session = requests.Session()\n",
- "session.auth = TokenRefresh(default_credential, [\"https://cognitiveservices.azure.com/.default\"])\n",
+ "prompt = \"The food was delicious and the waiter\"\n",
+ "completion = client.completions.create(\n",
+ " model=deployment,\n",
+ " prompt=prompt,\n",
+ " stop=\".\",\n",
+ " temperature=0\n",
+ ")\n",
+ " \n",
+ "print(f\"{prompt}{completion.choices[0].text}.\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Create a streaming completion\n",
"\n",
- "openai.requestssession = session"
+ "We can also stream the response."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "prompt = \"The food was delicious and the waiter\"\n",
+ "response = client.completions.create(\n",
+ " model=deployment,\n",
+ " prompt=prompt,\n",
+ " stream=True,\n",
+ ")\n",
+ "for completion in response:\n",
+ " if len(completion.choices) > 0:\n",
+ " print(f\"{completion.choices[0].text}\")"
]
},
{
- "attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
- "## Deployments\n",
- "In this section we are going to create a deployment using the `text-davinci-002` model that we can then use to create completions."
+ "### Content filtering\n",
+ "\n",
+ "Azure OpenAI service includes content filtering of prompts and completion responses. You can learn more about content filtering and how to configure it [here](https://learn.microsoft.com/azure/ai-services/openai/concepts/content-filter).\n",
+ "\n",
+ "If the prompt is flagged by the content filter, the library will raise a `BadRequestError` exception with a `content_filter` error code. Otherwise, you can access the `prompt_filter_results` and `content_filter_results` on the response to see the results of the content filtering and what categories were flagged."
]
},
{
- "attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
- "### Deployments: Create manually\n",
- "Create a new deployment by going to your Resource in your portal under \"Resource Management\" -> \"Model deployments\". Select `text-davinci-002` as the model."
+ "#### Prompt flagged by content filter"
]
},
{
@@ -168,16 +241,27 @@
"metadata": {},
"outputs": [],
"source": [
- "deployment_id = '' # Fill in the deployment id from the portal here"
+ "import json\n",
+ "\n",
+ "try:\n",
+ " completion = client.completions.create(\n",
+ " prompt=\"<text violating the content policy>\",\n",
+ " model=deployment,\n",
+ " )\n",
+ "except openai.BadRequestError as e:\n",
+ " err = json.loads(e.response.text)\n",
+ " if err[\"error\"][\"code\"] == \"content_filter\":\n",
+ " print(\"Content filter triggered!\")\n",
+ " content_filter_result = err[\"error\"][\"innererror\"][\"content_filter_result\"]\n",
+ " for category, details in content_filter_result.items():\n",
+ " print(f\"{category}:\\n filtered={details['filtered']}\\n severity={details['severity']}\")"
]
},
{
- "attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
- "### Completions\n",
- "Now let's send a sample completion to the deployment."
+ "### Checking the result of the content filter"
]
},
{
@@ -186,11 +270,24 @@
"metadata": {},
"outputs": [],
"source": [
- "prompt = \"The food was delicious and the waiter\"\n",
- "completion = openai.Completion.create(deployment_id=deployment_id,\n",
- " prompt=prompt, stop=\".\", temperature=0)\n",
- " \n",
- "print(f\"{prompt}{completion['choices'][0]['text']}.\")"
+ "completion = client.completions.create(\n",
+ " prompt=\"What's the biggest city in Washington?\",\n",
+ " model=deployment,\n",
+ ")\n",
+ "\n",
+ "print(f\"Answer: {completion.choices[0].text}\")\n",
+ "\n",
+ "# prompt content filter result in \"model_extra\" for azure\n",
+ "prompt_filter_result = completion.model_extra[\"prompt_filter_results\"][0][\"content_filter_results\"]\n",
+ "print(\"\\nPrompt content filter results:\")\n",
+ "for category, details in prompt_filter_result.items():\n",
+ " print(f\"{category}:\\n filtered={details['filtered']}\\n severity={details['severity']}\")\n",
+ "\n",
+ "# completion content filter result\n",
+ "print(\"\\nCompletion content filter results:\")\n",
+ "completion_filter_result = completion.choices[0].model_extra[\"content_filter_results\"]\n",
+ "for category, details in completion_filter_result.items():\n",
+ " print(f\"{category}:\\n filtered={details['filtered']}\\n severity={details['severity']}\")"
]
}
],
@@ -210,7 +307,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
- "version": "3.11.3"
+ "version": "3.10.0"
},
"vscode": {
"interpreter": {
diff --git a/examples/azure/embeddings.ipynb b/examples/azure/embeddings.ipynb
index 1a5387f1..776d2cb3 100644
--- a/examples/azure/embeddings.ipynb
+++ b/examples/azure/embeddings.ipynb
@@ -6,27 +6,17 @@
"metadata": {},
"source": [
"# Azure embeddings example\n",
- "In this example we'll try to go over all operations for embeddings that can be done using the Azure endpoints. \\\n",
- "This example focuses on embeddings but also touches some other operations that are also available using the API. This example is meant to be a quick way of showing simple operations and is not meant as a tutorial."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "import os\n",
- "import openai"
+ "\n",
+ "This example will cover embeddings using the Azure OpenAI service."
]
},
{
- "attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"## Setup\n",
- "For the following sections to work properly we first have to setup some things. Let's start with the `api_base` and `api_version`. To find your `api_base` go to https://portal.azure.com, find your resource and then under \"Resource Management\" -> \"Keys and Endpoints\" look for the \"Endpoint\" value."
+ "\n",
+ "First, we install the necessary dependencies and import the libraries we will be using."
]
},
{
@@ -35,82 +25,75 @@
"metadata": {},
"outputs": [],
"source": [
- "openai.api_version = '2023-05-15'\n",
- "openai.api_base = '' # Please add your endpoint here"
+ "! pip install \"openai>=1.0.0,<2.0.0\"\n",
+ "! pip install python-dotenv"
]
},
{
- "attachments": {},
- "cell_type": "markdown",
+ "cell_type": "code",
+ "execution_count": null,
"metadata": {},
+ "outputs": [],
"source": [
- "We next have to setup the `api_type` and `api_key`. We can either get the key from the portal or we can get it through Microsoft Active Directory Authentication. Depending on this the `api_type` is either `azure` or `azure_ad`."
+ "import os\n",
+ "import openai\n",
+ "import dotenv\n",
+ "\n",
+ "dotenv.load_dotenv()"
]
},
{
- "attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
- "### Setup: Portal\n",
- "Let's first look at getting the key from the portal. Go to https://portal.azure.com, find your resource and then under \"Resource Management\" -> \"Keys and Endpoints\" look for one of the \"Keys\" values."
+ "### Authentication\n",
+ "\n",
+ "The Azure OpenAI service supports multiple authentication mechanisms that include API keys and Azure Active Directory token credentials."
]
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
- "openai.api_type = 'azure'\n",
- "openai.api_key = os.environ[\"OPENAI_API_KEY\"]"
+ "use_azure_active_directory = False # Set this flag to True if you are using Azure Active Directory"
]
},
{
- "attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
- "> Note: In this example, we configured the library to use the Azure API by setting the variables in code. For development, consider setting the environment variables instead:\n",
+ "#### Authentication using API key\n",
"\n",
- "```\n",
- "OPENAI_API_BASE\n",
- "OPENAI_API_KEY\n",
- "OPENAI_API_TYPE\n",
- "OPENAI_API_VERSION\n",
- "```"
- ]
- },
- {
- "attachments": {},
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### (Optional) Setup: Microsoft Active Directory Authentication\n",
- "Let's now see how we can get a key via Microsoft Active Directory Authentication. Uncomment the following code if you want to use Active Directory Authentication instead of keys from the portal."
+ "To set up the OpenAI SDK to use an *Azure API Key*, we need to set `api_key` to a key associated with your endpoint (you can find this key in *\"Keys and Endpoints\"* under *\"Resource Management\"* in the [Azure Portal](https://portal.azure.com)). You'll also find the endpoint for your resource here."
]
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 3,
"metadata": {},
"outputs": [],
"source": [
- "# from azure.identity import DefaultAzureCredential\n",
+ "if not use_azure_active_directory:\n",
+ " endpoint = os.environ[\"AZURE_OPENAI_ENDPOINT\"]\n",
+ " api_key = os.environ[\"AZURE_OPENAI_API_KEY\"]\n",
"\n",
- "# default_credential = DefaultAzureCredential()\n",
- "# token = default_credential.get_token(\"https://cognitiveservices.azure.com/.default\")\n",
- "\n",
- "# openai.api_type = 'azure_ad'\n",
- "# openai.api_key = token.token"
+ " client = openai.AzureOpenAI(\n",
+ " azure_endpoint=endpoint,\n",
+ " api_key=api_key,\n",
+ " api_version=\"2023-09-01-preview\"\n",
+ " )"
]
},
{
- "attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
- "A token is valid for a period of time, after which it will expire. To ensure a valid token is sent with every request, you can refresh an expiring token by hooking into requests.auth:"
+ "#### Authentication using Azure Active Directory\n",
+ "Let's now see how we can autheticate via Azure Active Directory. We'll start by installing the `azure-identity` library. This library will provide the token credentials we need to authenticate and help us build a token credential provider through the `get_bearer_token_provider` helper function. It's recommended to use `get_bearer_token_provider` over providing a static token to `AzureOpenAI` because this API will automatically cache and refresh tokens for you. \n",
+ "\n",
+ "For more information on how to set up Azure Active Directory authentication with Azure OpenAI, see the [documentation](https://learn.microsoft.com/azure/ai-services/openai/how-to/managed-identity)."
]
},
{
@@ -119,56 +102,48 @@
"metadata": {},
"outputs": [],
"source": [
- "import typing\n",
- "import time\n",
- "import requests\n",
- "if typing.TYPE_CHECKING:\n",
- " from azure.core.credentials import TokenCredential\n",
- "\n",
- "class TokenRefresh(requests.auth.AuthBase):\n",
- "\n",
- " def __init__(self, credential: \"TokenCredential\", scopes: typing.List[str]) -> None:\n",
- " self.credential = credential\n",
- " self.scopes = scopes\n",
- " self.cached_token: typing.Optional[str] = None\n",
- "\n",
- " def __call__(self, req):\n",
- " if not self.cached_token or self.cached_token.expires_on - time.time() < 300:\n",
- " self.cached_token = self.credential.get_token(*self.scopes)\n",
- " req.headers[\"Authorization\"] = f\"Bearer {self.cached_token.token}\"\n",
- " return req\n",
- "\n",
- "session = requests.Session()\n",
- "session.auth = TokenRefresh(default_credential, [\"https://cognitiveservices.azure.com/.default\"])\n",
- "\n",
- "openai.requestssession = session"
+ "! pip install \"azure-identity>=1.15.0\""
]
},
{
- "attachments": {},
- "cell_type": "markdown",
+ "cell_type": "code",
+ "execution_count": 5,
"metadata": {},
+ "outputs": [],
"source": [
- "## Deployments\n",
- "In this section we are going to create a deployment that we can use to create embeddings."
+ "from azure.identity import DefaultAzureCredential, get_bearer_token_provider\n",
+ "\n",
+ "if use_azure_active_directory:\n",
+ " endpoint = os.environ[\"AZURE_OPENAI_ENDPOINT\"]\n",
+ " api_key = os.environ[\"AZURE_OPENAI_API_KEY\"]\n",
+ "\n",
+ " client = openai.AzureOpenAI(\n",
+ " azure_endpoint=endpoint,\n",
+ " azure_ad_token_provider=get_bearer_token_provider(DefaultAzureCredential(), \"https://cognitiveservices.azure.com/.default\"),\n",
+ " api_version=\"2023-09-01-preview\"\n",
+ " )"
]
},
{
- "attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
- "### Deployments: Create manually\n",
- "Let's create a deployment using the `text-similarity-curie-001` model. Create a new deployment by going to your Resource in your portal under \"Resource Management\" -> \"Model deployments\"."
+ "> Note: the AzureOpenAI infers the following arguments from their corresponding environment variables if they are not provided:\n",
+ "\n",
+ "- `api_key` from `AZURE_OPENAI_API_KEY`\n",
+ "- `azure_ad_token` from `AZURE_OPENAI_AD_TOKEN`\n",
+ "- `api_version` from `OPENAI_API_VERSION`\n",
+ "- `azure_endpoint` from `AZURE_OPENAI_ENDPOINT`\n"
]
},
{
- "cell_type": "code",
- "execution_count": null,
+ "attachments": {},
+ "cell_type": "markdown",
"metadata": {},
- "outputs": [],
"source": [
- "deployment_id = '' # Fill in the deployment id from the portal here"
+ "## Deployments\n",
+ "\n",
+ "In this section we are going to create a deployment of a model that we can use to create embeddings."
]
},
{
@@ -176,34 +151,17 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "### Deployments: Listing\n",
- "Now because creating a new deployment takes a long time, let's look in the subscription for an already finished deployment that succeeded."
+ "### Deployments: Create in the Azure OpenAI Studio\n",
+ "Let's deploy a model to use with embeddings. Go to https://portal.azure.com, find your Azure OpenAI resource, and then navigate to the Azure OpenAI Studio. Click on the \"Deployments\" tab and then create a deployment for the model you want to use for embeddings. The deployment name that you give the model will be used in the code below."
]
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 4,
"metadata": {},
"outputs": [],
"source": [
- "print('While deployment running, selecting a completed one that supports embeddings.')\n",
- "deployment_id = None\n",
- "result = openai.Deployment.list()\n",
- "for deployment in result.data:\n",
- " if deployment[\"status\"] != \"succeeded\":\n",
- " continue\n",
- " \n",
- " model = openai.Model.retrieve(deployment[\"model\"])\n",
- " if model[\"capabilities\"][\"embeddings\"] != True:\n",
- " continue\n",
- " \n",
- " deployment_id = deployment[\"id\"]\n",
- " break\n",
- "\n",
- "if not deployment_id:\n",
- " print('No deployment with status: succeeded found.')\n",
- "else:\n",
- " print(f'Found a succeeded deployment that supports embeddings with id: {deployment_id}.')"
+ "deployment = \"\" # Fill in the deployment name from the portal here"
]
},
{
@@ -211,8 +169,9 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "### Embeddings\n",
- "Now let's send a sample embedding to the deployment."
+ "## Embeddings\n",
+ "\n",
+ "Now let's create embeddings using the client we built."
]
},
{
@@ -221,8 +180,10 @@
"metadata": {},
"outputs": [],
"source": [
- "embeddings = openai.Embedding.create(deployment_id=deployment_id,\n",
- " input=\"The food was delicious and the waiter...\")\n",
+ "embeddings = client.embeddings.create(\n",
+ " model=deployment,\n",
+ " input=\"The food was delicious and the waiter...\"\n",
+ ")\n",
" \n",
"print(embeddings)"
]
@@ -244,7 +205,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
- "version": "3.11.3"
+ "version": "3.10.0"
},
"vscode": {
"interpreter": {
diff --git a/examples/azure/functions.ipynb b/examples/azure/functions.ipynb
index fb78223e..41084f20 100644
--- a/examples/azure/functions.ipynb
+++ b/examples/azure/functions.ipynb
@@ -16,13 +16,12 @@
]
},
{
- "attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"## Setup\n",
"\n",
- "First, we install the necessary dependencies."
+ "First, we install the necessary dependencies and import the libraries we will be using."
]
},
{
@@ -31,72 +30,75 @@
"metadata": {},
"outputs": [],
"source": [
- "! pip install openai\n",
- "# (Optional) If you want to use Microsoft Active Directory\n",
- "! pip install azure-identity"
+ "! pip install \"openai>=1.0.0,<2.0.0\"\n",
+ "! pip install python-dotenv"
]
},
{
"cell_type": "code",
- "execution_count": 3,
+ "execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import os\n",
- "import openai"
+ "import openai\n",
+ "import dotenv\n",
+ "\n",
+ "dotenv.load_dotenv()"
]
},
{
- "attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
+ "### Authentication\n",
"\n",
- "Additionally, to properly access the Azure OpenAI Service, we need to create the proper resources at the [Azure Portal](https://portal.azure.com) (you can check a detailed guide on how to do this in the [Microsoft Docs](https://learn.microsoft.com/en-us/azure/cognitive-services/openai/how-to/create-resource?pivots=web-portal))\n",
- "\n",
- "Once the resource is created, the first thing we need to use is its endpoint. You can get the endpoint by looking at the *\"Keys and Endpoints\"* section under the *\"Resource Management\"* section. Having this, we will set up the SDK using this information:"
+ "The Azure OpenAI service supports multiple authentication mechanisms that include API keys and Azure Active Directory token credentials."
]
},
{
"cell_type": "code",
- "execution_count": 27,
+ "execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
- "openai.api_base = \"\" # Add your endpoint here\n",
- "\n",
- "# functions is only supported by the 2023-07-01-preview API version\n",
- "openai.api_version = \"2023-07-01-preview\""
+ "use_azure_active_directory = False # Set this flag to True if you are using Azure Active Directory"
]
},
{
- "attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
- "### Authentication\n",
+ "#### Authentication using API key\n",
"\n",
- "The Azure OpenAI service supports multiple authentication mechanisms that include API keys and Azure credentials."
+ "To set up the OpenAI SDK to use an *Azure API Key*, we need to set `api_key` to a key associated with your endpoint (you can find this key in *\"Keys and Endpoints\"* under *\"Resource Management\"* in the [Azure Portal](https://portal.azure.com)). You'll also find the endpoint for your resource here."
]
},
{
"cell_type": "code",
- "execution_count": 4,
+ "execution_count": 3,
"metadata": {},
"outputs": [],
"source": [
- "use_azure_active_directory = False"
+ "if not use_azure_active_directory:\n",
+ " endpoint = os.environ[\"AZURE_OPENAI_ENDPOINT\"]\n",
+ " api_key = os.environ[\"AZURE_OPENAI_API_KEY\"]\n",
+ "\n",
+ " client = openai.AzureOpenAI(\n",
+ " azure_endpoint=endpoint,\n",
+ " api_key=api_key,\n",
+ " api_version=\"2023-09-01-preview\"\n",
+ " )"
]
},
{
- "attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
+ "#### Authentication using Azure Active Directory\n",
+ "Let's now see how we can autheticate via Azure Active Directory. We'll start by installing the `azure-identity` library. This library will provide the token credentials we need to authenticate and help us build a token credential provider through the `get_bearer_token_provider` helper function. It's recommended to use `get_bearer_token_provider` over providing a static token to `AzureOpenAI` because this API will automatically cache and refresh tokens for you. \n",
"\n",
- "#### Authentication using API key\n",
- "\n",
- "To set up the OpenAI SDK to use an *Azure API Key*, we need to set up the `api_type` to `azure` and set `api_key` to a key associated with your endpoint (you can find this key in *\"Keys and Endpoints\"* under *\"Resource Management\"* in the [Azure Portal](https://portal.azure.com))"
+ "For more information on how to set up Azure Active Directory authentication with Azure OpenAI, see the [documentation](https://learn.microsoft.com/azure/ai-services/openai/how-to/managed-identity)."
]
},
{
@@ -105,90 +107,64 @@
"metadata": {},
"outputs": [],
"source": [
- "if not use_azure_active_directory:\n",
- " openai.api_type = \"azure\"\n",
- " openai.api_key = os.environ[\"OPENAI_API_KEY\"]"
+ "! pip install \"azure-identity>=1.15.0\""
]
},
{
- "attachments": {},
- "cell_type": "markdown",
+ "cell_type": "code",
+ "execution_count": 5,
"metadata": {},
+ "outputs": [],
"source": [
- "> Note: In this example, we configured the library to use the Azure API by setting the variables in code. For development, consider setting the environment variables instead:\n",
+ "from azure.identity import DefaultAzureCredential, get_bearer_token_provider\n",
+ "\n",
+ "if use_azure_active_directory:\n",
+ " endpoint = os.environ[\"AZURE_OPENAI_ENDPOINT\"]\n",
+ " api_key = os.environ[\"AZURE_OPENAI_API_KEY\"]\n",
"\n",
- "```\n",
- "OPENAI_API_BASE\n",
- "OPENAI_API_KEY\n",
- "OPENAI_API_TYPE\n",
- "OPENAI_API_VERSION\n",
- "```"
+ " client = openai.AzureOpenAI(\n",
+ " azure_endpoint=endpoint,\n",
+ " azure_ad_token_provider=get_bearer_token_provider(DefaultAzureCredential(), \"https://cognitiveservices.azure.com/.default\"),\n",
+ " api_version=\"2023-09-01-preview\"\n",
+ " )"
]
},
{
- "attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
- "#### Authentication using Microsoft Active Directory\n",
- "Let's now see how we can get a key via Microsoft Active Directory Authentication."
+ "> Note: the AzureOpenAI infers the following arguments from their corresponding environment variables if they are not provided:\n",
+ "\n",
+ "- `api_key` from `AZURE_OPENAI_API_KEY`\n",
+ "- `azure_ad_token` from `AZURE_OPENAI_AD_TOKEN`\n",
+ "- `api_version` from `OPENAI_API_VERSION`\n",
+ "- `azure_endpoint` from `AZURE_OPENAI_ENDPOINT`\n"
]
},
{
- "cell_type": "code",
- "execution_count": null,
+ "cell_type": "markdown",
"metadata": {},
- "outputs": [],
"source": [
- "from azure.identity import DefaultAzureCredential\n",
+ "## Deployments\n",
"\n",
- "if use_azure_active_directory:\n",
- " default_credential = DefaultAzureCredential()\n",
- " token = default_credential.get_token(\"https://cognitiveservices.azure.com/.default\")\n",
- "\n",
- " openai.api_type = \"azure_ad\"\n",
- " openai.api_key = token.token"
+ "In this section we are going to create a deployment of a GPT model that we can use to call functions."
]
},
{
- "attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
- "A token is valid for a period of time, after which it will expire. To ensure a valid token is sent with every request, you can refresh an expiring token by hooking into requests.auth:"
+ "### Deployments: Create in the Azure OpenAI Studio\n",
+ "Let's deploy a model to use with chat completions. Go to https://portal.azure.com, find your Azure OpenAI resource, and then navigate to the Azure OpenAI Studio. Click on the \"Deployments\" tab and then create a deployment for the model you want to use for chat completions. The deployment name that you give the model will be used in the code below."
]
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 4,
"metadata": {},
"outputs": [],
"source": [
- "import typing\n",
- "import time\n",
- "import requests\n",
- "\n",
- "if typing.TYPE_CHECKING:\n",
- " from azure.core.credentials import TokenCredential\n",
- "\n",
- "class TokenRefresh(requests.auth.AuthBase):\n",
- "\n",
- " def __init__(self, credential: \"TokenCredential\", scopes: typing.List[str]) -> None:\n",
- " self.credential = credential\n",
- " self.scopes = scopes\n",
- " self.cached_token: typing.Optional[str] = None\n",
- "\n",
- " def __call__(self, req):\n",
- " if not self.cached_token or self.cached_token.expires_on - time.time() < 300:\n",
- " self.cached_token = self.credential.get_token(*self.scopes)\n",
- " req.headers[\"Authorization\"] = f\"Bearer {self.cached_token.token}\"\n",
- " return req\n",
- "\n",
- "if use_azure_active_directory:\n",
- " session = requests.Session()\n",
- " session.auth = TokenRefresh(default_credential, [\"https://cognitiveservices.azure.com/.default\"])\n",
- "\n",
- " openai.requestssession = session"
+ "deployment = \"\" # Fill in the deployment name from the portal here"
]
},
{
@@ -218,7 +194,7 @@
},
{
"cell_type": "code",
- "execution_count": 21,
+ "execution_count": 5,
"metadata": {},
"outputs": [],
"source": [
@@ -257,72 +233,17 @@
},
{
"cell_type": "code",
- "execution_count": 22,
+ "execution_count": null,
"metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "{\n",
- " \"choices\": [\n",
- " {\n",
- " \"content_filter_results\": {},\n",
- " \"finish_reason\": \"function_call\",\n",
- " \"index\": 0,\n",
- " \"message\": {\n",
- " \"function_call\": {\n",
- " \"arguments\": \"{\\n \\\"location\\\": \\\"Seattle, WA\\\"\\n}\",\n",
- " \"name\": \"get_current_weather\"\n",
- " },\n",
- " \"role\": \"assistant\"\n",
- " }\n",
- " }\n",
- " ],\n",
- " \"created\": 1689702512,\n",
- " \"id\": \"chatcmpl-7dj6GkYdM7Vw9eGn02bc2qqjN70Ps\",\n",
- " \"model\": \"gpt-4\",\n",
- " \"object\": \"chat.completion\",\n",
- " \"prompt_annotations\": [\n",
- " {\n",
- " \"content_filter_results\": {\n",
- " \"hate\": {\n",
- " \"filtered\": false,\n",
- " \"severity\": \"safe\"\n",
- " },\n",
- " \"self_harm\": {\n",
- " \"filtered\": false,\n",
- " \"severity\": \"safe\"\n",
- " },\n",
- " \"sexual\": {\n",
- " \"filtered\": false,\n",
- " \"severity\": \"safe\"\n",
- " },\n",
- " \"violence\": {\n",
- " \"filtered\": false,\n",
- " \"severity\": \"safe\"\n",
- " }\n",
- " },\n",
- " \"prompt_index\": 0\n",
- " }\n",
- " ],\n",
- " \"usage\": {\n",
- " \"completion_tokens\": 18,\n",
- " \"prompt_tokens\": 115,\n",
- " \"total_tokens\": 133\n",
- " }\n",
- "}\n"
- ]
- }
- ],
+ "outputs": [],
"source": [
"messages = [\n",
" {\"role\": \"system\", \"content\": \"Don't make assumptions about what values to plug into functions. Ask for clarification if a user request is ambiguous.\"},\n",
" {\"role\": \"user\", \"content\": \"What's the weather like today in Seattle?\"}\n",
"]\n",
"\n",
- "chat_completion = openai.ChatCompletion.create(\n",
- " deployment_id=\"gpt-35-turbo-0613\",\n",
+ "chat_completion = client.chat.completions.create(\n",
+ " model=deployment,\n",
" messages=messages,\n",
" functions=functions,\n",
")\n",
@@ -341,20 +262,9 @@
},
{
"cell_type": "code",
- "execution_count": 23,
+ "execution_count": null,
"metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "get_current_weather\n",
- "{\n",
- " \"location\": \"Seattle, WA\"\n",
- "}\n"
- ]
- }
- ],
+ "outputs": [],
"source": [
"import json\n",
"\n",
@@ -368,7 +278,7 @@
" unit = request.get(\"unit\")\n",
" return {\"temperature\": \"22\", \"unit\": \"celsius\", \"description\": \"Sunny\"}\n",
"\n",
- "function_call = chat_completion.choices[0].message.function_call\n",
+ "function_call = chat_completion.choices[0].message.function_call\n",
"print(function_call.name)\n",
"print(function_call.arguments)\n",
"\n",
@@ -388,17 +298,9 @@
},
{
"cell_type": "code",
- "execution_count": 24,
+ "execution_count": null,
"metadata": {},
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "Today in Seattle, the weather is sunny with a temperature of 22 degrees celsius.\n"
- ]
- }
- ],
+ "outputs": [],
"source": [
"messages.append(\n",
" {\n",
@@ -408,8 +310,8 @@
" }\n",
")\n",
"\n",
- "function_completion = openai.ChatCompletion.create(\n",
- " deployment_id=\"gpt-35-turbo-0613\",\n",
+ "function_completion = client.chat.completions.create(\n",
+ " model=deployment,\n",
" messages=messages,\n",
" functions=functions,\n",
")\n",
diff --git a/examples/azure/whisper.ipynb b/examples/azure/whisper.ipynb
new file mode 100644
index 00000000..38f206b5
--- /dev/null
+++ b/examples/azure/whisper.ipynb
@@ -0,0 +1,228 @@
+{
+ "cells": [
+ {
+ "attachments": {},
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "# Azure audio whisper (preview) example\n",
+ "\n",
+ "The example shows how to use the Azure OpenAI Whisper model to transcribe audio files.\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Setup\n",
+ "\n",
+ "First, we install the necessary dependencies and import the libraries we will be using."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "! pip install \"openai>=1.0.0,<2.0.0\"\n",
+ "! pip install python-dotenv"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import os\n",
+ "import openai\n",
+ "import dotenv\n",
+ "\n",
+ "dotenv.load_dotenv()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Authentication\n",
+ "\n",
+ "The Azure OpenAI service supports multiple authentication mechanisms that include API keys and Azure Active Directory token credentials."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 4,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "use_azure_active_directory = False # Set this flag to True if you are using Azure Active Directory"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "#### Authentication using API key\n",
+ "\n",
+ "To set up the OpenAI SDK to use an *Azure API Key*, we need to set `api_key` to a key associated with your endpoint (you can find this key in *\"Keys and Endpoints\"* under *\"Resource Management\"* in the [Azure Portal](https://portal.azure.com)). You'll also find the endpoint for your resource here."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 5,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "if not use_azure_active_directory:\n",
+ " endpoint = os.environ[\"AZURE_OPENAI_ENDPOINT\"]\n",
+ " api_key = os.environ[\"AZURE_OPENAI_API_KEY\"]\n",
+ "\n",
+ " client = openai.AzureOpenAI(\n",
+ " azure_endpoint=endpoint,\n",
+ " api_key=api_key,\n",
+ " api_version=\"2023-09-01-preview\"\n",
+ " )"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "#### Authentication using Azure Active Directory\n",
+ "Let's now see how we can autheticate via Azure Active Directory. We'll start by installing the `azure-identity` library. This library will provide the token credentials we need to authenticate and help us build a token credential provider through the `get_bearer_token_provider` helper function. It's recommended to use `get_bearer_token_provider` over providing a static token to `AzureOpenAI` because this API will automatically cache and refresh tokens for you. \n",
+ "\n",
+ "For more information on how to set up Azure Active Directory authentication with Azure OpenAI, see the [documentation](https://learn.microsoft.com/azure/ai-services/openai/how-to/managed-identity)."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "! pip install \"azure-identity>=1.15.0\""
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 5,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from azure.identity import DefaultAzureCredential, get_bearer_token_provider\n",
+ "\n",
+ "if use_azure_active_directory:\n",
+ " endpoint = os.environ[\"AZURE_OPENAI_ENDPOINT\"]\n",
+ " api_key = os.environ[\"AZURE_OPENAI_API_KEY\"]\n",
+ "\n",
+ " client = openai.AzureOpenAI(\n",
+ " azure_endpoint=endpoint,\n",
+ " azure_ad_token_provider=get_bearer_token_provider(DefaultAzureCredential(), \"https://cognitiveservices.azure.com/.default\"),\n",
+ " api_version=\"2023-09-01-preview\"\n",
+ " )"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "> Note: the AzureOpenAI infers the following arguments from their corresponding environment variables if they are not provided:\n",
+ "\n",
+ "- `api_key` from `AZURE_OPENAI_API_KEY`\n",
+ "- `azure_ad_token` from `AZURE_OPENAI_AD_TOKEN`\n",
+ "- `api_version` from `OPENAI_API_VERSION`\n",
+ "- `azure_endpoint` from `AZURE_OPENAI_ENDPOINT`\n"
+ ]
+ },
+ {
+ "attachments": {},
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Deployments\n",
+ "\n",
+ "In this section we are going to create a deployment using the `whisper-1` model to transcribe audio files."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Deployments: Create in the Azure OpenAI Studio\n",
+ "Let's deploy a model to use with whisper. Go to https://portal.azure.com, find your Azure OpenAI resource, and then navigate to the Azure OpenAI Studio. Click on the \"Deployments\" tab and then create a deployment for the model you want to use for whisper. The deployment name that you give the model will be used in the code below."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 6,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "deployment = \"whisper-deployment\" # Fill in the deployment name from the portal here"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Audio transcription\n",
+ "\n",
+ "Audio transcription, or speech-to-text, is the process of converting spoken words into text. Use the `openai.Audio.transcribe` method to transcribe an audio file stream to text.\n",
+ "\n",
+ "You can get sample audio files from the [Azure AI Speech SDK repository at GitHub](https://github.com/Azure-Samples/cognitive-services-speech-sdk/tree/master/sampledata/audiofiles)."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 7,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# download sample audio file\n",
+ "import requests\n",
+ "\n",
+ "sample_audio_url = \"https://github.com/Azure-Samples/cognitive-services-speech-sdk/raw/master/sampledata/audiofiles/wikipediaOcelot.wav\"\n",
+ "audio_file = requests.get(sample_audio_url)\n",
+ "with open(\"wikipediaOcelot.wav\", \"wb\") as f:\n",
+ " f.write(audio_file.content)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "transcription = client.audio.transcriptions.create(\n",
+ " file=open(\"wikipediaOcelot.wav\", \"rb\"),\n",
+ " model=deployment,\n",
+ ")\n",
+ "print(transcription.text)"
+ ]
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "venv",
+ "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.10.0"
+ },
+ "orig_nbformat": 4
+ },
+ "nbformat": 4,
+ "nbformat_minor": 2
+}