Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
Important
The Azure OpenAI extension for Azure Functions is currently in preview.
The Azure OpenAI embeddings store output binding allows you to write files to a semantic document store that can be referenced later in a semantic search.
For information on setup and configuration details of the Azure OpenAI extension, see Azure OpenAI extensions for Azure Functions. To learn more about semantic ranking in Azure AI Search, see Semantic ranking in Azure AI Search.
Note
References and examples are only provided for the Node.js v4 model.
Note
References and examples are only provided for the Python v2 model.
Note
While both C# process models are supported, only isolated worker model examples are provided.
Example
Go support isn't currently available for this binding.
This example writes an HTTP input stream to a semantic document store at the provided URL.
public class EmbeddingsRequest
{
[JsonPropertyName("url")]
public string? Url { get; set; }
}
[Function("IngestFile")]
public static async Task<EmbeddingsStoreOutputResponse> IngestFile(
[HttpTrigger(AuthorizationLevel.Function, "post")] HttpRequestData req)
{
using StreamReader reader = new(req.Body);
string request = await reader.ReadToEndAsync();
EmbeddingsStoreOutputResponse badRequestResponse = new()
{
HttpResponse = new BadRequestResult(),
SearchableDocument = new SearchableDocument(string.Empty)
};
if (string.IsNullOrWhiteSpace(request))
{
return badRequestResponse;
}
EmbeddingsRequest? requestBody = JsonSerializer.Deserialize<EmbeddingsRequest>(request);
if (string.IsNullOrWhiteSpace(requestBody?.Url))
{
throw new ArgumentException("Invalid request body. Make sure that you pass in {\"url\": value } as the request body.");
}
if (!Uri.TryCreate(requestBody.Url, UriKind.Absolute, out Uri? uri))
{
return badRequestResponse;
}
string filename = Path.GetFileName(uri.AbsolutePath);
return new EmbeddingsStoreOutputResponse
{
HttpResponse = new OkObjectResult(new { status = HttpStatusCode.OK }),
SearchableDocument = new SearchableDocument(filename)
};
}
This example writes an HTTP input stream to a semantic document store at the provided URL.
@FunctionName("IngestFile")
public HttpResponseMessage ingestFile(
@HttpTrigger(
name = "req",
methods = {HttpMethod.POST},
authLevel = AuthorizationLevel.FUNCTION)
HttpRequestMessage<EmbeddingsRequest> request,
@EmbeddingsStoreOutput(name="EmbeddingsStoreOutput", input = "{url}", inputType = InputType.Url,
storeConnectionName = "AISearchEndpoint", collection = "openai-index",
embeddingsModel = "%EMBEDDING_MODEL_DEPLOYMENT_NAME%") OutputBinding<EmbeddingsStoreOutputResponse> output,
final ExecutionContext context) throws URISyntaxException {
if (request.getBody() == null || request.getBody().getUrl() == null)
{
throw new IllegalArgumentException("Invalid request body. Make sure that you pass in {\"url\": value } as the request body.");
}
URI uri = new URI(request.getBody().getUrl());
String filename = Paths.get(uri.getPath()).getFileName().toString();
EmbeddingsStoreOutputResponse embeddingsStoreOutputResponse = new EmbeddingsStoreOutputResponse(new SearchableDocument(filename));
output.setValue(embeddingsStoreOutputResponse);
JSONObject response = new JSONObject();
response.put("status", "success");
response.put("title", filename);
return request.createResponseBuilder(HttpStatus.CREATED)
.header("Content-Type", "application/json")
.body(response)
.build();
}
public class EmbeddingsStoreOutputResponse {
private SearchableDocument searchableDocument;
public EmbeddingsStoreOutputResponse(SearchableDocument searchableDocument) {
this.searchableDocument = searchableDocument;
}
public SearchableDocument getSearchableDocument() {
return searchableDocument;
}
}
This example writes an HTTP input stream to a semantic document store at the provided URL.
const embeddingsStoreOutput = output.generic({
type: "embeddingsStore",
input: "{url}",
inputType: "url",
storeConnectionName: "AISearchEndpoint",
collection: "openai-index",
embeddingsModel: "%EMBEDDING_MODEL_DEPLOYMENT_NAME%"
});
app.http('IngestFile', {
methods: ['POST'],
authLevel: 'function',
extraOutputs: [embeddingsStoreOutput],
handler: async (request, context) => {
let requestBody = await request.json();
if (!requestBody || !requestBody.url) {
throw new Error("Invalid request body. Make sure that you pass in {\"url\": value } as the request body.");
}
let uri = requestBody.url;
let url = new URL(uri);
let fileName = path.basename(url.pathname);
context.extraOutputs.set(embeddingsStoreOutput, { title: fileName });
let response = {
status: "success",
title: fileName
};
return { status: 202, jsonBody: response }
}
});
interface EmbeddingsRequest {
url?: string;
}
const embeddingsStoreOutput = output.generic({
type: "embeddingsStore",
input: "{url}",
inputType: "url",
storeConnectionName: "AISearchEndpoint",
collection: "openai-index",
embeddingsModel: "%EMBEDDING_MODEL_DEPLOYMENT_NAME%"
});
app.http('IngestFile', {
methods: ['POST'],
authLevel: 'function',
extraOutputs: [embeddingsStoreOutput],
handler: async (request, context) => {
let requestBody: EmbeddingsRequest | null = await request.json();
if (!requestBody || !requestBody.url) {
throw new Error("Invalid request body. Make sure that you pass in {\"url\": value } as the request body.");
}
let uri = requestBody.url;
let url = new URL(uri);
let fileName = path.basename(url.pathname);
context.extraOutputs.set(embeddingsStoreOutput, { title: fileName });
let response = {
status: "success",
title: fileName
};
return { status: 202, jsonBody: response }
}
});
This example writes an HTTP input stream to a semantic document store at the provided URL.
Here's the function.json file for ingesting files:
{
"bindings": [
{
"authLevel": "function",
"type": "httpTrigger",
"direction": "in",
"name": "Request",
"methods": [
"post"
]
},
{
"type": "http",
"direction": "out",
"name": "Response"
},
{
"name": "EmbeddingsStoreOutput",
"type": "embeddingsStore",
"direction": "out",
"input": "{url}",
"inputType": "Url",
"storeConnectionName": "AISearchEndpoint",
"collection": "openai-index",
"embeddingsModel": "%EMBEDDING_MODEL_DEPLOYMENT_NAME%"
}
]
}
For more information about function.json file properties, see the Configuration section.
using namespace System.Net
param($Request, $TriggerMetadata)
$ErrorActionPreference = 'Stop'
$inputJson = $Request.Body
if (-not $inputJson -or -not $inputJson.Url) {
throw 'Invalid request body. Make sure that you pass in {\"url\": value } as the request body.'
}
$uri = [URI]$inputJson.Url
$filename = [System.IO.Path]::GetFileName($uri.AbsolutePath)
Push-OutputBinding -Name EmbeddingsStoreOutput -Value @{
"title" = $filename
}
$response = @{
"status" = "success"
"title" = $filename
}
Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{
StatusCode = [HttpStatusCode]::OK
Body = $response
Headers = @{
"Content-Type" = "application/json"
}
})
This example writes an HTTP input stream to a semantic document store at the provided URL.
@app.function_name("IngestFile")
@app.route(methods=["POST"])
@app.embeddings_store_output(
arg_name="requests",
input="{url}",
input_type="url",
store_connection_name="AISearchEndpoint",
collection="openai-index",
embeddings_model="%EMBEDDING_MODEL_DEPLOYMENT_NAME%",
)
def ingest_file(
req: func.HttpRequest, requests: func.Out[str]
) -> func.HttpResponse:
user_message = req.get_json()
if not user_message:
return func.HttpResponse(
json.dumps({"message": "No message provided"}),
status_code=400,
mimetype="application/json",
)
file_name_with_extension = os.path.basename(user_message["url"])
title = os.path.splitext(file_name_with_extension)[0]
create_request = {"title": title}
requests.set(json.dumps(create_request))
response_json = {"status": "success", "title": title}
return func.HttpResponse(
json.dumps(response_json), status_code=200, mimetype="application/json"
)
Attributes
Apply the EmbeddingsStoreOutput attribute to define an embeddings store output binding, which supports these parameters:
| Parameter | Description |
|---|---|
| Input | The input string for which to generate embeddings. |
| AIConnectionName | Optional. Gets or sets the name of the configuration section for AI service connectivity settings. For Azure OpenAI: If specified, looks for "Endpoint" and "Key" values in this configuration section. If not specified or the section doesn't exist, falls back to environment variables: AZURE_OPENAI_ENDPOINT and AZURE_OPENAI_KEY. For user-assigned managed identity authentication, this property is required. For OpenAI service (non-Azure), set the OPENAI_API_KEY environment variable. |
| EmbeddingsModel | Optional. The ID of the model to use, which defaults to text-embedding-ada-002. You shouldn't change the model for an existing database. For more information, see Usage. |
| MaxChunkLength | Optional. The maximum number of characters used for chunking the input. For more information, see Usage. |
| MaxOverlap | Optional. Gets or sets the maximum number of characters to overlap between chunks. |
| InputType | Optional. Gets the type of the input. |
| StoreConnectionName | The name of an app setting or environment variable that contains the connection string value. This property supports binding expressions. |
| Collection | The name of the collection or table or index to search. This property supports binding expressions. |
Annotations
The EmbeddingsStoreOutput annotation enables you to define an embeddings store output binding, which supports these parameters:
| Element | Description |
|---|---|
| name | Gets or sets the name of the output binding. |
| input | The input string for which to generate embeddings. |
| aiConnectionName | Optional. Gets or sets the name of the configuration section for AI service connectivity settings. For Azure OpenAI: If specified, looks for "Endpoint" and "Key" values in this configuration section. If not specified or the section doesn't exist, falls back to environment variables: AZURE_OPENAI_ENDPOINT and AZURE_OPENAI_KEY. For user-assigned managed identity authentication, this property is required. For OpenAI service (non-Azure), set the OPENAI_API_KEY environment variable. |
| embeddingsModel | Optional. The ID of the model to use, which defaults to text-embedding-ada-002. You shouldn't change the model for an existing database. For more information, see Usage. |
| maxChunkLength | Optional. The maximum number of characters used for chunking the input. For more information, see Usage. |
| maxOverlap | Optional. Gets or sets the maximum number of characters to overlap between chunks. |
| inputType | Optional. Gets the type of the input. |
| storeConnectionName | The name of an app setting or environment variable that contains the connection string value. This property supports binding expressions. |
| collection | The name of the collection or table or index to search. This property supports binding expressions. |
Decorators
During the preview, define the output binding as a generic_output_binding binding of type semanticSearch, which supports these parameters:
| Parameter | Description |
|---|---|
| arg_name | The name of the variable that represents the binding parameter. |
| input | The input string for which to generate embeddings. |
| ai_connection_name | Optional. Gets or sets the name of the configuration section for AI service connectivity settings. For Azure OpenAI: If specified, looks for "Endpoint" and "Key" values in this configuration section. If not specified or the section doesn't exist, falls back to environment variables: AZURE_OPENAI_ENDPOINT and AZURE_OPENAI_KEY. For user-assigned managed identity authentication, this property is required. For OpenAI service (non-Azure), set the OPENAI_API_KEY environment variable. |
| embeddings_model | Optional. The ID of the model to use, which defaults to text-embedding-ada-002. You shouldn't change the model for an existing database. For more information, see Usage. |
| maxChunkLength | Optional. The maximum number of characters used for chunking the input. For more information, see Usage. |
| max_overlap | Optional. Gets or sets the maximum number of characters to overlap between chunks. |
| input_type | Gets the type of the input. |
| store_connection_name | The name of an app setting or environment variable that contains the connection string value. This property supports binding expressions. |
| collection | The name of the collection or table or index to search. This property supports binding expressions. |
Configuration
The binding supports these configuration properties that you set in the function.json file.
| Property | Description |
|---|---|
| type | Must be embeddingsStore. |
| direction | Must be out. |
| name | The name of the output binding. |
| input | The input string for which to generate embeddings. |
| aiConnectionName | Optional. Gets or sets the name of the configuration section for AI service connectivity settings. For Azure OpenAI: If specified, looks for "Endpoint" and "Key" values in this configuration section. If not specified or the section doesn't exist, falls back to environment variables: AZURE_OPENAI_ENDPOINT and AZURE_OPENAI_KEY. For user-assigned managed identity authentication, this property is required. For OpenAI service (non-Azure), set the OPENAI_API_KEY environment variable. |
| embeddingsModel | Optional. The ID of the model to use, which defaults to text-embedding-ada-002. You shouldn't change the model for an existing database. For more information, see Usage. |
| maxChunkLength | Optional. The maximum number of characters used for chunking the input. For more information, see Usage. |
| maxOverlap | Optional. Gets or sets the maximum number of characters to overlap between chunks. |
| inputType | Optional. Gets the type of the input. |
| storeConnectionName | The name of an app setting or environment variable that contains the connection string value. This property supports binding expressions. |
| collection | The name of the collection or table or index to search. This property supports binding expressions. |
Configuration
The binding supports these properties, which are defined in your code:
| Property | Description |
|---|---|
| input | The input string for which to generate embeddings. |
| aiConnectionName | Optional. Gets or sets the name of the configuration section for AI service connectivity settings. For Azure OpenAI: If specified, looks for "Endpoint" and "Key" values in this configuration section. If not specified or the section doesn't exist, falls back to environment variables: AZURE_OPENAI_ENDPOINT and AZURE_OPENAI_KEY. For user-assigned managed identity authentication, this property is required. For OpenAI service (non-Azure), set the OPENAI_API_KEY environment variable. |
| embeddingsModel | Optional. The ID of the model to use, which defaults to text-embedding-ada-002. You shouldn't change the model for an existing database. For more information, see Usage. |
| maxChunkLength | Optional. The maximum number of characters used for chunking the input. For more information, see Usage. |
| maxOverlap | Optional. Gets or sets the maximum number of characters to overlap between chunks. |
| inputType | Optional. Gets the type of the input. |
| storeConnectionName | The name of an app setting or environment variable that contains the connection string value. This property supports binding expressions. |
| collection | The name of the collection or table or index to search. This property supports binding expressions. |
Usage
See the Example section for complete examples.
Connections
To use the Azure OpenAI binding extension, you need to specify a connection to an OpenAI model definition. Set the OpenAI model connection in your bindings by using one of these approaches:
- Use the
AIConnectionNamebinding property (preferred for Azure OpenAI). - Set
AZURE_OPENAI_ENDPOINTandAZURE_OPENAI_KEYin app settings (for Azure OpenAI). - Set only
Open_API_Keyin app settings (forhttps://api.openai.com).
The way you set the connection depends on both the model API and the authentication method, as indicated by the following table:
| Authentication/Model API | Azure OpenAI | OpenAI (https://api.openai.com) |
|---|---|---|
| Managed identity connection | AIConnectionName |
Not supported |
| Key Vault reference | AZURE_OPENAI_ENDPOINTAZURE_OPENAI_KEY |
Open_API_Key |
| App Configuration reference | AZURE_OPENAI_ENDPOINTAZURE_OPENAI_KEY |
Open_API_Key |
| Shared secret | AZURE_OPENAI_ENDPOINTAZURE_OPENAI_KEY |
Open_API_Key |
Use managed identity-based connections and the AIConnectionName property.
When you use AIConnectionName, the value of this property setting depends on the type of connection:
- Managed identity connection: The
AIConnectionNameproperty is a<CONNECTION_NAME_PREFIX>shared by a group of settings that together define an identity-based connection to Azure OpenAI. For more information, see Define identity connections. - Key Vault reference: The
AIConnectionNameproperty setting returns an Azure Key Vault reference to the location where the API key is centrally maintained. For more information, see Define Key Vault connections. - App Configuration reference: The
AIConnectionNameproperty setting returns an Azure App Configuration reference that returns an API key or a Key Vault reference. For more information, see Azure App Configuration in the connections article. - API key: The
AIConnectionNameproperty setting resolves to app settings containing the endpoint and key directly. Because shared keys can be compromised, use managed identity connections when possible. For more information, see Define connections.
To learn more about bindings connections, see Manage connections in Azure Functions.
The OpenAI bindings include an AIConnectionName property that you can use to specify the <ConnectionNamePrefix> for the group of app settings that define the connection to Azure OpenAI:
| Setting name | Description |
|---|---|
<CONNECTION_NAME_PREFIX>__endpoint |
Sets the URI endpoint of the Azure OpenAI service. This setting is always required. |
<CONNECTION_NAME_PREFIX>__clientId |
Sets the specific user-assigned identity to use when obtaining an access token. Requires that <CONNECTION_NAME_PREFIX>__credential is set to managedidentity. The property accepts a client ID corresponding to a user-assigned identity assigned to the application. It's invalid to specify both a Resource ID and a client ID. If you don't specify this property, the system-assigned identity is used. This property is used differently in local development scenarios, when credential shouldn't be set. |
<CONNECTION_NAME_PREFIX>__credential |
Defines how an access token is obtained for the connection. Use managedidentity for managed identity authentication. This value is only valid when a managed identity is available in the hosting environment. |
<CONNECTION_NAME_PREFIX>__managedIdentityResourceId |
When credential is set to managedidentity, set this property to specify the resource Identifier to use when obtaining a token. The property accepts a resource identifier corresponding to the resource ID of the user-defined managed identity. It's invalid to specify both a resource ID and a client ID. If you don't specify either, the system-assigned identity is used. This property is used differently in local development scenarios, when credential shouldn't be set. |
<CONNECTION_NAME_PREFIX>__key |
Sets the shared secret key required to access the endpoint of the Azure OpenAI service by using key-based authentication. As a security best practice, always use Microsoft Entra ID with managed identities for authentication. |
Consider these managed identity connection settings when you set the AIConnectionName property to myAzureOpenAI:
myAzureOpenAI__endpoint=https://contoso.openai.azure.com/myAzureOpenAI__credential=managedidentitymyAzureOpenAI__clientId=aaaaaaaa-bbbb-cccc-1111-222222222222
At runtime, the host interprets these settings as a single myAzureOpenAI setting:
"myAzureOpenAI":
{
"endpoint": "https://contoso.openai.azure.com/",
"credential": "managedidentity",
"clientId": "aaaaaaaa-bbbb-cccc-1111-222222222222"
}
When you use managed identities, make sure to add your identity to the Cognitive Services OpenAI User role.
When running locally, add these settings to the local.settings.json project file. For more information, see Local development with identity-based connections.
For more information, see Work with application settings.