Skip to content

Commit 7169644

Browse files
authored
Merge pull request #276794 from ggailey777/openai-bindings
[Functions] OpenAI tutorial for text completion
2 parents d3ee900 + 3f110c4 commit 7169644

File tree

4 files changed

+349
-15
lines changed

4 files changed

+349
-15
lines changed

articles/azure-functions/TOC.yml

Lines changed: 28 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -189,6 +189,26 @@
189189
- name: Azure SQL
190190
displayName: Connect to a database, Azure SQL
191191
href: functions-add-output-binding-azure-sql-vs-code.md?pivots=programming-language-python
192+
- name: Connect to OpenAI
193+
items:
194+
- name: C#
195+
href: functions-add-openai-text-completion.md?pivots=programming-language-csharp
196+
displayName: Connect to OpenAI, text completion
197+
- name: Java
198+
href: functions-add-openai-text-completion.md?pivots=programming-language-java
199+
displayName: Connect to OpenAI, text completion
200+
- name: JavaScript
201+
href: functions-add-openai-text-completion.md?pivots=programming-language-javascript
202+
displayName: Connect to OpenAI, text completion
203+
- name: PowerShell
204+
href: functions-add-openai-text-completion.md?pivots=programming-language-powershell
205+
displayName: Connect to OpenAI, text completion
206+
- name: Python
207+
href: functions-add-openai-text-completion.md?pivots=programming-language-python
208+
displayName: Connect to OpenAI, text completion
209+
- name: TypeScript
210+
href: functions-add-openai-text-completion.md?pivots=programming-language-typescript
211+
displayName: Connect to OpenAI, text completion
192212
- name: Tutorials
193213
items:
194214
- name: Functions with Logic Apps
@@ -222,10 +242,14 @@
222242
href: ../event-grid/resize-images-on-storage-blob-upload-event.md?toc=/azure/azure-functions/toc.json
223243
- name: Create a serverless web app
224244
href: /training/modules/automatic-update-of-a-webapp-using-azure-functions-and-signalr/
225-
- name: Machine learning with TensorFlow
226-
href: functions-machine-learning-tensorflow.md
227-
- name: Image classification with PyTorch
228-
href: machine-learning-pytorch.md
245+
- name: Data + AI
246+
items:
247+
- name: Azure OpenAI for text completion
248+
href: functions-add-openai-text-completion.md
249+
- name: Machine learning with TensorFlow
250+
href: functions-machine-learning-tensorflow.md
251+
- name: Image classification with PyTorch
252+
href: machine-learning-pytorch.md
229253
- name: Functions on IoT Edge device
230254
href: ../iot-edge/tutorial-deploy-function.md?toc=/azure/azure-functions/toc.json
231255
- name: Java with Azure Cosmos DB and Event Hubs
Lines changed: 275 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,275 @@
1+
---
2+
title: 'Tutorial: Add Azure OpenAI text completions to your functions in Visual Studio Code'
3+
description: Learn how to connect Azure Functions to OpenAI by adding an output binding to your Visual Studio Code project.
4+
ms.date: 07/11/2024
5+
ms.topic: tutorial
6+
author: dbandaru
7+
ms.author: dbandaru
8+
zone_pivot_groups: programming-languages-set-functions
9+
#customer intent: As an Azure developer, I want learn how to integrate Azure OpenAI capabilities in my function code to leverage AI benefits in my colud-based code executions.
10+
---
11+
12+
# Tutorial: Add Azure OpenAI text completion hints to your functions in Visual Studio Code
13+
14+
This article shows you how to use Visual Studio Code to add an HTTP endpoint to the function app you created in the previous quickstart article. When triggered, this new HTTP endpoint uses an [Azure Open AI text completion input binding](functions-bindings-openai-textcompletion-input.md) to get text completion hints from your data model.
15+
16+
During this tutorial, you learn how to accomplish these tasks:
17+
18+
> [!div class="checklist"]
19+
> * Create resources in Azure OpenAI.
20+
> * Deploy a model in OpenAI the resource.
21+
> * Set access permissions to the model resource.
22+
> * Enable your function app to connect to OpenAI.
23+
> * Add OpenAI bindings to your HTTP triggered function.
24+
25+
## 1. Check prerequisites
26+
:::zone pivot="programming-language-csharp"
27+
* Complete the steps in [part 1 of the Visual Studio Code quickstart](create-first-function-vs-code-csharp.md).
28+
:::zone-end
29+
:::zone pivot="programming-language-java"
30+
* Complete the steps in [part 1 of the Visual Studio Code quickstart](create-first-function-vs-code-java.md).
31+
:::zone-end
32+
:::zone pivot="programming-language-javascript"
33+
* Complete the steps in [part 1 of the Visual Studio Code quickstart](create-first-function-vs-code-node.md).
34+
:::zone-end
35+
:::zone pivot="programming-language-typescript"
36+
* Complete the steps in [part 1 of the Visual Studio Code quickstart](create-first-function-vs-code-typescript.md).
37+
:::zone-end
38+
:::zone pivot="programming-language-python"
39+
* Complete the steps in [part 1 of the Visual Studio Code quickstart](create-first-function-vs-code-python.md).
40+
:::zone-end
41+
:::zone pivot="programming-language-powershell"
42+
* Complete the steps in [part 1 of the Visual Studio Code quickstart](create-first-function-vs-code-powershell.md).
43+
:::zone-end
44+
* Obtain access to Azure OpenAI in your Azure subscription. If you haven't already been granted access, complete [this form](https://aka.ms/oai/access) to request access.
45+
:::zone pivot="programming-language-csharp"
46+
* Install [.NET Core CLI tools](/dotnet/core/tools/?tabs=netcore2x).
47+
:::zone-end
48+
* The [Azurite storage emulator](../storage/common/storage-use-azurite.md?tabs=npm#install-azurite). While you can also use an actual Azure Storage account, the article assumes you're using this emulator.
49+
50+
## 2. Create your Azure OpenAI resources
51+
52+
The following steps show how to create an Azure OpenAI data model in the Azure portal.
53+
54+
1. Sign in with your Azure subscription in the [Azure portal](https://portal.azure.com).
55+
56+
1. Select **Create a resource** and search for the **Azure OpenAI**. When you locate the service, select **Create**.
57+
58+
1. On the **Create Azure OpenAI** page, provide the following information for the fields on the **Basics** tab:
59+
60+
| Field | Description |
61+
|---|---|
62+
| **Subscription** | Your subscription, which has been onboarded to use Azure OpenAI. |
63+
| **Resource group** | The resource group you created for the function app in the previous article. You can find this resource group name by right-clicking the function app in the Azure Resources browser, selecting properties, and then searching for the `resourceGroup` setting in the returned JSON resource file. |
64+
| **Region** | Ideally, the same location as the function app. |
65+
| **Name** | A descriptive name for your Azure OpenAI Service resource, such as _mySampleOpenAI_. |
66+
| **Pricing Tier** | The pricing tier for the resource. Currently, only the Standard tier is available for the Azure OpenAI Service. For more info on pricing visit the [Azure OpenAI pricing page](https://azure.microsoft.com/pricing/details/cognitive-services/openai-service/) |
67+
68+
:::image type="content" source="../ai-services/openai/media/create-resource/create-resource-basic-settings.png" alt-text="Screenshot that shows how to configure an Azure OpenAI resource in the Azure portal.":::
69+
70+
1. Select **Next** twice to accept the default values for both the **Network** and **Tags** tabs. The service you create doesn't have any network restrictions, including from the internet.
71+
72+
1. Select **Next** a final time to move to the final stage in the process: **Review + submit**.
73+
74+
1. Confirm your configuration settings, and select **Create**.
75+
76+
The Azure portal displays a notification when the new resource is available. Select **Go to resource** in the notification or search for your new Azure OpenAI resource by name.
77+
78+
1. In the Azure OpenAI resource page for your new resource, select **Click here to view endpoints** under **Essentials** > **Endpoints**. Copy the **endpoint** URL and the **keys**. Save these values, you need them later.
79+
80+
Now that you have the credentials to connect to your model in Azure OpenAI, you need to set these access credentials in application settings.
81+
82+
## 3. Deploy a model
83+
84+
Now you can deploy a model. You can select from one of several available models in Azure OpenAI Studio.
85+
86+
To deploy a model, follow these steps:
87+
88+
1. Sign in to [Azure OpenAI Studio](https://oai.azure.com).
89+
90+
1. Choose the subscription and the Azure OpenAI resource you created, and select **Use resource**.
91+
92+
1. Under **Management** select **Deployments**.
93+
94+
1. Select **Create new deployment** and configure the following fields:
95+
96+
| Field | Description |
97+
|---|---|
98+
| **Deployment name** | Choose a name carefully. The deployment name is used in your code to call the model by using the client libraries and the REST APIs, so you must save for use later on. |
99+
| **Select a model** | Model availability varies by region. For a list of available models per region, see [Model summary table and region availability](../ai-services/openai/concepts/models.md#model-summary-table-and-region-availability). |
100+
101+
> [!IMPORTANT]
102+
> When you access the model via the API, you need to refer to the deployment name rather than the underlying model name in API calls, which is one of the key differences between OpenAI and Azure OpenAI. OpenAI only requires the model name. Azure OpenAI always requires deployment name, even when using the model parameter. In our docs, we often have examples where deployment names are represented as identical to model names to help indicate which model works with a particular API endpoint. Ultimately your deployment names can follow whatever naming convention is best for your use case.
103+
104+
1. Accept the default values for the rest of the setting and select **Create**.
105+
106+
The deployments table shows a new entry that corresponds to your newly created model.
107+
108+
You now have everything you need to add Azure OpenAI-based text completion to your function app.
109+
110+
## 4. Update application settings
111+
112+
1. In Visual Studio Code, open the local code project you created when you completed the [previous article](./create-first-function-vs-code-csharp.md).
113+
114+
1. In the local.settings.json file in the project root folder, update the `AzureWebJobsStorage` setting to `UseDevelopmentStorage=true`. You can skip this step if the `AzureWebJobsStorage` setting in *local.settings.json* is set to the connection string for an existing Azure Storage account instead of `UseDevelopmentStorage=true`.
115+
116+
1. In the local.settings.json file, add these settings values:
117+
118+
+ **`AZURE_OPENAI_ENDPOINT`**: required by the binding extension. Set this value to the endpoint of the Azure OpenAI resource you created earlier.
119+
+ **`AZURE_OPENAI_KEY`**: required by the binding extension. Set this value to the key for the Azure OpenAI resource.
120+
+ **`CHAT_MODEL_DEPLOYMENT_NAME`**: used to define the input binding. Set this value to the name you chose for your model deployment.
121+
122+
1. Save the file. When you deploy to Azure, you must also add these settings to your function app.
123+
124+
:::zone pivot="programming-language-csharp"
125+
## 5. Register binding extensions
126+
127+
Because you're using an Azure OpenAI output binding, you must have the corresponding bindings extension installed before you run the project.
128+
129+
Except for HTTP and timer triggers, bindings are implemented as extension packages. To add the Azure OpenAI extension package to your project, run this [dotnet add package](/dotnet/core/tools/dotnet-add-package) command in the **Terminal** window:
130+
131+
```bash
132+
dotnet add package Microsoft.Azure.Functions.Worker.Extensions.OpenAI --prerelease
133+
```
134+
:::zone-end
135+
:::zone pivot="programming-language-java,programming-language-javascript,programming-language-typescript,programming-language-python,programming-language-powershell"
136+
<!---NOTE: Update this after preview to `## Verify the extension bundle`-->
137+
## 5. Update the extension bundle
138+
139+
To access the preview Azure OpenAI bindings, you must use a preview version of the extension bundle that contains this extension.
140+
141+
Replace the `extensionBundle` setting in your current `host.json` file with this JSON:
142+
143+
```json
144+
"extensionBundle": {
145+
"id": "Microsoft.Azure.Functions.ExtensionBundle.Preview",
146+
"version": "[4.*, 5.0.0)"
147+
}
148+
```
149+
:::zone-end
150+
Now, you can use the Azure OpenAI output binding in your project.
151+
152+
## 6. Return text completion from the model
153+
154+
The code you add creates a `whois` HTTP function endpoint in your existing project. In this function, data passed in a URL `name` parameter of a GET request is used to dynamically create a completion prompt. This dynamic prompt is bound to a text completion input binding, which returns a response from the model based on the prompt. The completion from the model is returned in the HTTP response.
155+
:::zone pivot="programming-language-csharp"
156+
1. In your existing `HttpExample` class file, add this `using` statement:
157+
158+
:::code language="csharp" source="~/functions-openai-extension/samples/textcompletion/csharp-ooproc/TextCompletions.cs" range="5" :::
159+
160+
1. In the same file, add this code that defines a new HTTP trigger endpoint named `whois`:
161+
162+
```csharp
163+
[Function(nameof(WhoIs))]
164+
public IActionResult WhoIs([HttpTrigger(AuthorizationLevel.Function, Route = "whois/{name}")] HttpRequest req,
165+
[TextCompletionInput("Who is {name}?", Model = "%CHAT_MODEL_DEPLOYMENT_NAME%")] TextCompletionResponse response)
166+
{
167+
if(!String.IsNullOrEmpty(response.Content))
168+
{
169+
return new OkObjectResult(response.Content);
170+
}
171+
else
172+
{
173+
return new NotFoundObjectResult("Something went wrong.");
174+
}
175+
}
176+
```
177+
178+
:::zone-end
179+
:::zone pivot="programming-language-java"
180+
1. Update the `pom.xml` project file to add this reference to the `properties` collection:
181+
182+
:::code language="xml" source="~/functions-openai-extension/samples/textcompletion/java/pom.xml" range="18" :::
183+
184+
1. In the same file, add this dependency to the `dependencies` collection:
185+
186+
:::code language="xml" source="~/functions-openai-extension/samples/textcompletion/java/pom.xml" range="29-33" :::
187+
188+
1. In the existing `Function.java` project file, add these `import` statements:
189+
190+
:::code language="java" source="~/functions-openai-extension/samples/textcompletion/java/src/main/java/com/azfs/TextCompletions.java" range="19-20" :::
191+
192+
1. In the same file, add this code that defines a new HTTP trigger endpoint named `whois`:
193+
194+
:::code language="java" source="~/functions-openai-extension/samples/textcompletion/java/src/main/java/com/azfs/TextCompletions.java" range="31-46" :::
195+
196+
:::zone-end
197+
:::zone pivot="programming-language-javascript"
198+
1. In Visual Studio Code, Press F1 and in the command palette type `Azure Functions: Create Function...`, select **HTTP trigger**, type the function name `whois`, and press Enter.
199+
200+
1. In the new `whois.js` code file, replace the contents of the file with this code:
201+
202+
:::code language="javascript" source="~/functions-openai-extension/samples/textcompletion/javascript/src/functions/whois.js" :::
203+
204+
:::zone-end
205+
:::zone pivot="programming-language-typescript"
206+
1. In Visual Studio Code, Press F1 and in the command palette type `Azure Functions: Create Function...`, select **HTTP trigger**, type the function name `whois`, and press Enter.
207+
208+
1. In the new `whois.ts` code file, replace the contents of the file with this code:
209+
210+
:::code language="typescript" source="~/functions-openai-extension/samples/textcompletion/typescript/src/functions/whois.ts" :::
211+
212+
:::zone-end
213+
:::zone pivot="programming-language-python"
214+
1. In the existing `function_app.py` project file, add this `import` statement:
215+
216+
:::code language="python" source="~/functions-openai-extension/samples/textcompletion/python/function_app.py" range="1" :::
217+
218+
1. In the same file, add this code that defines a new HTTP trigger endpoint named `whois`:
219+
:::code language="python" source="~/functions-openai-extension/samples/textcompletion/python/function_app.py" range="7-18" :::
220+
221+
:::zone-end
222+
:::zone pivot="programming-language-powershell"
223+
1. In Visual Studio Code, Press F1 and in the command palette type `Azure Functions: Create Function...`, select **HTTP trigger**, type the function name `whois`, select **Anonymous**, and press Enter.
224+
225+
1. Open the new `whois/function.json` code file and replace its contents with this code, which adds a definition for the `TextCompletionResponse` input binding:
226+
227+
:::code language="json" source="~/functions-openai-extension/samples/textcompletion/powershell/WhoIs/function.json" :::
228+
229+
1. Replace the content of the `whois/run.ps1` code file with this code, which returns the input binding response:
230+
231+
:::code language="powershell" source="~/functions-openai-extension/samples/textcompletion/powershell/WhoIs/run.ps1" :::
232+
233+
:::zone-end
234+
235+
## 7. Run the function
236+
237+
1. In Visual Studio Code, Press F1 and in the command palette type `Azurite: Start` and press Enter to start the Azurite storage emulator.
238+
239+
1. Press <kbd>F5</kbd> to start the function app project and Core Tools in debug mode.
240+
241+
1. With the Core Tools running, send a GET request to the `whois` endpoint function, with a name in the path, like this URL:
242+
243+
`http://localhost:7071/api/whois/<NAME>`
244+
245+
Replace the `<NAME>` string with the value you want passed to the `"Who is {name}?"` prompt. The `<NAME>` must be the URL-encoded name of a public figure, like `Abraham%20Lincoln`.
246+
247+
The response you see is the text completion response from your Azure OpenAI model.
248+
249+
1. After a response is returned, press <kbd>Ctrl + C</kbd> to stop Core Tools.
250+
251+
<!-- enable managed identities
252+
## 8. Set access permissions
253+
{{move this info into the main article}}
254+
[create Azure OpenAI resources and to deploy models](../ai-services/openai/how-to/role-based-access-control.md).
255+
256+
## 9. Deploy to Azure
257+
-->
258+
259+
## 8. Clean up resources
260+
261+
In Azure, *resources* refer to function apps, functions, storage accounts, and so forth. They're grouped into *resource groups*, and you can delete everything in a group by deleting the group.
262+
263+
You created resources to complete these quickstarts. You could be billed for these resources, depending on your [account status](https://azure.microsoft.com/account/) and [service pricing](https://azure.microsoft.com/pricing/). If you don't need the resources anymore, here's how to delete them:
264+
265+
[!INCLUDE [functions-cleanup-resources-vs-code-inner.md](../../includes/functions-cleanup-resources-vs-code-inner.md)]
266+
267+
## Related content
268+
269+
+ [Azure OpenAI extension for Azure Functions](functions-bindings-openai.md)
270+
+ [Azure OpenAI extension samples](https://github.com/Azure/azure-functions-openai-extension/tree/main/samples)
271+
+ [Machine learning and AI](functions-scenarios.md#machine-learning-and-ai)
272+
273+
274+
275+

articles/azure-functions/functions-bindings-openai.md

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,19 @@ You can add the preview extension by adding or replacing the following code in y
8282

8383
::: zone-end
8484

85+
## Application settings
86+
87+
To use the Azure OpenAI binding extension, you need to add one or more of these settings, which are used to connect to your OpenAI resource. During local development, you also need to add these settings to your `local.settings.json` file.
88+
89+
| Setting name | Description |
90+
| ---- | ----- |
91+
| **`AZURE_OPENAI_ENDPOINT`** | Required. Sets the endpoint of the OpenAI resource used by your bindings. |
92+
| **`AZURE_OPENAI_KEY`** | Sets the key used to access an Azure OpenAI resource. |
93+
| **`OPENAI_API_KEY`** | Sets the key used to access a non-Azure OpenAI resource. |
94+
| **`AZURE_CLIENT_ID`** | Sets a user-assigned managed identity used to access the Azure OpenAI resource. |
95+
96+
For more information, see [Work with application settings](functions-how-to-use-azure-function-app-settings.md#settings).
97+
8598
<!---Include this section if there are any host.json settings defined by the extension:
8699
## host.json settings
87100
-->

0 commit comments

Comments
 (0)