Azure OpenAI assistant create output binding for Azure Functions

Important

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

The Azure OpenAI assistant create output binding allows you to create a new assistant chat bot from your function code execution.

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

This example demonstrates the creation process, where the HTTP PUT function that creates a new assistant chat bot with the specified ID. The response to the prompt is returned in the HTTP response.

/// HTTP PUT function that creates a new assistant chat bot with the specified ID.
/// </summary>
[Function(nameof(CreateAssistant))]
public static async Task<CreateChatBotOutput> CreateAssistant(
    [HttpTrigger(AuthorizationLevel.Anonymous, "put", Route = "assistants/{assistantId}")] HttpRequestData req,
    string assistantId)
{
    var responseJson = new { assistantId };

    string instructions =
       """
        Don't make assumptions about what values to plug into functions.
        Ask for clarification if a user request is ambiguous.
        """;

    using StreamReader reader = new(req.Body);

    string request = await reader.ReadToEndAsync();


    return new CreateChatBotOutput
    {
        HttpResponse = new ObjectResult(new { assistantId }) { StatusCode = 202 },
        ChatBotCreateRequest = new AssistantCreateRequest(assistantId, instructions),
    };
}

This example demonstrates the creation process, where the HTTP PUT function that creates a new assistant chat bot with the specified ID. The response to the prompt is returned in the HTTP response.

@FunctionName("CreateAssistant")
public HttpResponseMessage createAssistant(
    @HttpTrigger(
        name = "req", 
        methods = {HttpMethod.PUT}, 
        authLevel = AuthorizationLevel.ANONYMOUS, 
        route = "assistants/{assistantId}") 
        HttpRequestMessage<Optional<String>> request,
    @BindingName("assistantId") String assistantId,
    @AssistantCreate(name = "AssistantCreate") OutputBinding<AssistantCreateRequest> message,
    final ExecutionContext context) {
        context.getLogger().info("Java HTTP trigger processed a request.");
        
        String instructions = "Don't make assumptions about what values to plug into functions.\n" +
                "Ask for clarification if a user request is ambiguous.";

        AssistantCreateRequest assistantCreateRequest = new AssistantCreateRequest(assistantId, instructions);
        message.setValue(assistantCreateRequest);
        JSONObject response = new JSONObject();
        response.put("assistantId", assistantId);
        
        return request.createResponseBuilder(HttpStatus.CREATED)
            .header("Content-Type", "application/json")
            .body(response.toString())
            .build();    
}

Examples aren't yet available.

This example demonstrates the creation process, where the HTTP PUT function that creates a new assistant chat bot with the specified ID. The response to the prompt is returned in the HTTP response.

const chatBotCreateOutput = output.generic({
    type: 'assistantCreate'
})
app.http('CreateAssistant', {
    methods: ['PUT'],
    route: 'assistants/{assistantId}',
    authLevel: 'anonymous',
    extraOutputs: [chatBotCreateOutput],
    handler: async (request: HttpRequest, context: InvocationContext) => {
        const assistantId = request.params.assistantId
        const instructions =
            `
            Don't make assumptions about what values to plug into functions.
            Ask for clarification if a user request is ambiguous.
            `
        const createRequest = {
            id: assistantId,
            instructions: instructions,
        }
        context.extraOutputs.set(chatBotCreateOutput, createRequest)
        return { status: 202, jsonBody: { assistantId: assistantId } }
    }
})

This example demonstrates the creation process, where the HTTP PUT function that creates a new assistant chat bot with the specified ID. The response to the prompt is returned in the HTTP response.

Here's the function.json file for Create Assistant:

{
  "bindings": [
    {
      "authLevel": "function",
      "type": "httpTrigger",
      "direction": "in",
      "name": "Request",
      "route": "assistants/{assistantId}",
      "methods": [
        "put"
      ]
    },
    {
      "type": "http",
      "direction": "out",
      "name": "Response"
    },
    {
      "type": "assistantCreate",
      "direction": "out",
      "dataType": "string",
      "name": "Requests"
    }
  ]
}

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

{{This comes from the example code comment}}

using namespace System.Net

param($Request, $TriggerMetadata)

$assistantId = $Request.params.assistantId

$instructions = "Don't make assumptions about what values to plug into functions."
$instructions += "\nAsk for clarification if a user request is ambiguous."

$create_request = @{
    "id" = $assistantId
    "instructions" = $instructions
}

Push-OutputBinding -Name Requests -Value (ConvertTo-Json $create_request)

Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{
    StatusCode = [HttpStatusCode]::Accepted
    Body       = (ConvertTo-Json @{ "assistantId" = $assistantId})
    Headers    = @{
        "Content-Type" = "application/json"
    }
})

This example demonstrates the creation process, where the HTTP PUT function that creates a new assistant chat bot with the specified ID. The response to the prompt is returned in the HTTP response.

@apis.function_name("CreateAssistant")
@apis.route(route="assistants/{assistantId}", methods=["PUT"])
@apis.assistant_create_output(arg_name="requests")
def create_assistant(req: func.HttpRequest, requests: func.Out[str]) -> func.HttpResponse:
    assistantId = req.route_params.get("assistantId")
    instructions = """
            Don't make assumptions about what values to plug into functions.
            Ask for clarification if a user request is ambiguous.
            """
    create_request = {
        "id": assistantId,
        "instructions": instructions
    }
    requests.set(json.dumps(create_request))
    response_json = {"assistantId": assistantId}
    return func.HttpResponse(json.dumps(response_json), status_code=202, mimetype="application/json")

Attributes

Apply the CreateAssistant attribute to define an assistant create output binding, which supports these parameters:

Parameter Description
Id The identifier of the assistant to create.
Instructions Optional. The instructions that are provided to assistant to follow.

Annotations

The CreateAssistant annotation enables you to define an assistant create output binding, which supports these parameters:

Element Description
name Gets or sets the name of the output binding.
id The identifier of the assistant to create.
instructions Optional. The instructions that are provided to assistant to follow.

Decorators

During the preview, define the output binding as a generic_output_binding binding of type createAssistant, which supports these parameters:

Parameter Description
arg_name The name of the variable that represents the binding parameter.
id The identifier of the assistant to create.
instructions Optional. The instructions that are provided to assistant to follow.

Configuration

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

Property Description
type Must be CreateAssistant.
direction Must be out.
name The name of the output binding.
id The identifier of the assistant to create.
instructions Optional. The instructions that are provided to assistant to follow.

Configuration

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

Property Description
id The identifier of the assistant to create.
instructions Optional. The instructions that are provided to assistant to follow.

Usage

See the Example section for complete examples.