Edit

Azure OpenAI assistant trigger for Azure Functions

Important

The Azure OpenAI extension for Azure Functions is currently in preview.

The Azure OpenAI assistant trigger lets you run your code based on custom chat bot or skill request made to an assistant.

For information on setup and configuration details of the Azure OpenAI extension, see Azure OpenAI extensions for Azure Functions. To learn more about Azure OpenAI assistants, see Azure OpenAI Assistants API.

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 demonstrates how to create an assistant that adds a new todo task to a database. The trigger has a static description of Create a new todo task used by the model. The function itself takes a string, which represents a new task to add. When executed, the function adds the task as a new todo item in a custom item store and returns a response from the store.

[Function(nameof(AddTodo))]
public Task AddTodo([AssistantSkillTrigger("Create a new todo task")] string taskDescription)
{
    if (string.IsNullOrEmpty(taskDescription))
    {
        throw new ArgumentException("Task description cannot be empty");
    }

    this.logger.LogInformation("Adding todo: {task}", taskDescription);

    string todoId = Guid.NewGuid().ToString()[..6];
    return this.todoManager.AddTodoAsync(new TodoItem(todoId, taskDescription));
}

This example demonstrates how to create an assistant that adds a new todo task to a database. The trigger has a static description of Create a new todo task used by the model. The function itself takes a string, which represents a new task to add. When executed, the function adds the task as a new todo item in a custom item store and returns a response from the store.

/**
 * Called by the assistant to create new todo tasks.
 */
@FunctionName("AddTodo")
public void addTodo(
    @AssistantSkillTrigger(
            name = "assistantSkillCreateTodo",
            functionDescription = "Create a new todo task"
    ) String taskDescription,
    final ExecutionContext context) {

    if (taskDescription == null || taskDescription.isEmpty()) {
        throw new IllegalArgumentException("Task description cannot be empty");
    }
    context.getLogger().info("Adding todo: " + taskDescription);

    String todoId = UUID.randomUUID().toString().substring(0, 6);
    TodoItem todoItem = new TodoItem(todoId, taskDescription);
    todoManager.addTodo(todoItem);
}

This example demonstrates how to create an assistant that adds a new todo task to a database. The trigger has a static description of Create a new todo task used by the model. The function itself takes a string, which represents a new task to add. When executed, the function adds the task as a new todo item in a custom item store and returns a response from the store.

const { app, trigger } = require("@azure/functions");
const { TodoItem, CreateTodoManager } = require("../services/todoManager");
const { randomUUID } = require('crypto');

const todoManager = CreateTodoManager()

app.generic('AddTodo', {
    trigger: trigger.generic({
        type: 'assistantSkillTrigger',
        functionDescription: 'Create a new todo task'
    }),
    handler: async (taskDescription, context) => {
        if (!taskDescription) {
            throw new Error('Task description cannot be empty')
        }

        context.log(`Adding todo: ${taskDescription}`)

        const todoId = randomUUID().substring(0, 6)
        return todoManager.AddTodo(new TodoItem(todoId, taskDescription))
    }
})
import { InvocationContext, app, trigger } from "@azure/functions"
import { TodoItem, ITodoManager, CreateTodoManager } from "../services/todoManager"
import { randomUUID } from 'crypto';

const todoManager: ITodoManager = CreateTodoManager()

app.generic('AddTodo', {
    trigger: trigger.generic({
        type: 'assistantSkillTrigger',
        functionDescription: 'Create a new todo task'
    }),
    handler: async (taskDescription: string, context: InvocationContext) => {
        if (!taskDescription) {
            throw new Error('Task description cannot be empty')
        }

        context.log(`Adding todo: ${taskDescription}`)

        const todoId = randomUUID().substring(0, 6)
        return todoManager.AddTodo(new TodoItem(todoId, taskDescription))
    }
})

This example demonstrates how to create an assistant that adds a new todo task to a database. The trigger has a static description of Create a new todo task used by the model. The function itself takes a string, which represents a new task to add. When executed, the function adds the task as a new todo item in a custom item store and returns a response from the store.

Here's the function.json file for Add Todo:

{
  "bindings": [
    {
      "name": "TaskDescription",
      "type": "assistantSkillTrigger",
      "dataType": "string",
      "direction": "in",
      "functionDescription": "Create a new todo task"
    }
  ]
}

For more information about function.json file properties, see the Configuration section.

using namespace System.Net

param($TaskDescription, $TriggerMetadata)
$ErrorActionPreference = "Stop"

if (-not $TaskDescription) {
    throw "Task description cannot be empty"
}

Write-Information "Adding todo: $TaskDescription"
$todoID = [Guid]::NewGuid().ToString().Substring(0, 5)
Add-Todo $todoId $TaskDescription

This example demonstrates how to create an assistant that adds a new todo task to a database. The trigger has a static description of Create a new todo task used by the model. The function itself takes a string, which represents a new task to add. When executed, the function adds the task as a new todo item in a custom item store and returns a response from the store.

@skills.function_name("AddTodo")
@skills.assistant_skill_trigger(
    arg_name="taskDescription", function_description="Create a new todo task"
)
def add_todo(taskDescription: str) -> None:
    if not taskDescription:
        raise ValueError("Task description cannot be empty")

    logging.info(f"Adding todo: {taskDescription}")

    todo_id = str(uuid.uuid4())[0:6]
    todo_manager.add_todo(TodoItem(id=todo_id, task=taskDescription))
    return

Attributes

Apply the AssistantSkillTrigger attribute to define an assistant trigger, which supports these parameters:

Parameter Description
FunctionDescription Gets the description of the assistant function, which is provided to the model.
FunctionName Optional. Gets or sets the name of the function called by the assistant.
ParameterDescriptionJson Optional. Gets or sets a JSON description of the function parameter, which is provided to the model. For more information, see Usage.

Annotations

The AssistantSkillTrigger annotation enables you to define an assistant trigger, which supports these parameters:

Element Description
name Gets or sets the name of the input binding.
functionDescription Gets the description of the assistant function, which is provided to the model.
functionName Optional. Gets or sets the name of the function called by the assistant.
parameterDescriptionJson Optional. Gets or sets a JSON description of the function parameter, which is provided to the model. For more information, see Usage.

Decorators

During the preview, define the input binding as a generic_trigger binding of type assistantSkillTrigger, which supports these parameters:

Parameter Description
function_description Gets the description of the assistant function, which is provided to the model.
function_name Optional. Gets or sets the name of a function called by the assistant.
parameterDescriptionJson Optional. Gets or sets a JSON description of the function parameter, which is provided to the model. For more information, see Usage.

Configuration

The binding supports these configuration properties that you set in the function.json file.

Property Description
type Must be AssistantSkillTrigger.
direction Must be in.
name The name of the trigger.
functionName Gets or sets the name of the function called by the assistant.
functionDescription Gets the description of the assistant function, which is provided to the language model.
parameterDescriptionJson Optional. Gets or sets a JSON description of the function parameter, which is provided to the model. For more information, see Usage.

Configuration

The binding supports these properties, which are defined in your code:

Property Description
type Must be AssistantSkillTrigger.
name The name of the trigger.
functionName Gets or sets the name of the function called by the assistant.
functionDescription Gets the description of the assistant function, which is provided to the LLM
parameterDescriptionJson Optional. Gets or sets a JSON description of the function parameter, which is provided to the model. For more information, see Usage.

See the Example section for complete examples.

Usage

When parameterDescriptionJson JSON value isn't provided, it's autogenerated. For more information on the syntax of this object, see the OpenAI function calling documentation.

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 AIConnectionName binding property (preferred for Azure OpenAI).
  • Set AZURE_OPENAI_ENDPOINT and AZURE_OPENAI_KEY in app settings (for Azure OpenAI).
  • Set only Open_API_Key in app settings (for https://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_ENDPOINT
AZURE_OPENAI_KEY
Open_API_Key
App Configuration reference AZURE_OPENAI_ENDPOINT
AZURE_OPENAI_KEY
Open_API_Key
Shared secret AZURE_OPENAI_ENDPOINT
AZURE_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 AIConnectionName property 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 AIConnectionName property 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 AIConnectionName property 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 AIConnectionName property 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=managedidentity
  • myAzureOpenAI__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.