次の方法で共有


Azure Functions 用の Azure OpenAI アシスタント作成出力バインド

重要

Azure Functions 用の Azure OpenAI 拡張機能は現在、プレビュー段階です。

Azure OpenAI アシスタント作成出力バインドを使用すると、関数コードの実行から新しいアシスタント チャット ボットを作成できます。

Azure OpenAI 拡張機能のセットアップと構成の詳細については、「Azure Functions 用の Azure OpenAI 拡張機能」を参照してください。 Azure OpenAI アシスタントの詳細については、「Azure OpenAI Assistants API」を参照してください。

リファレンスと例は、Node.js v4 モデルに対してのみ提供されています。

リファレンスと例は、Python v2 モデルに対してのみ提供されます。

両方の C# プロセス モデルがサポートされていますが、 isolated worker モデル 例のみが提供されます。

この例では、指定された ID を持つ新しいアシスタント チャット ボットを作成する HTTP PUT 関数の作成プロセスを示します。 プロンプトに対する応答は HTTP 応答で返されます。

/// <summary>
/// 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)
{
    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 = 201 },
        ChatBotCreateRequest = new AssistantCreateRequest(assistantId, instructions)
        {
            ChatStorageConnectionSetting = DefaultChatStorageConnectionSetting,
            CollectionName = DefaultCollectionName,
        },
    };
}

public class CreateChatBotOutput
{
    [AssistantCreateOutput()]
    public AssistantCreateRequest? ChatBotCreateRequest { get; set; }

    [HttpResult]
    public IActionResult? HttpResponse { get; set; }
}

この例では、指定された ID を持つ新しいアシスタント チャット ボットを作成する HTTP PUT 関数の作成プロセスを示します。 プロンプトに対する応答は HTTP 応答で返されます。

/**
 * The default storage account setting for the table storage account.
 * This constant is used to specify the connection string for the table storage
 * account
 * where chat data will be stored.
 */
final String DEFAULT_CHATSTORAGE = "AzureWebJobsStorage";

/**
 * The default collection name for the table storage account.
 * This constant is used to specify the collection name for the table storage
 * account
 * where chat data will be stored.
 */
final String DEFAULT_COLLECTION = "ChatState";

/*
 * HTTP PUT function that creates a new assistant chat bot with the specified ID.
 */
@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);
        assistantCreateRequest.setChatStorageConnectionSetting(DEFAULT_CHATSTORAGE);
        assistantCreateRequest.setCollectionName(DEFAULT_COLLECTION);

        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();    
}

この例では、指定された ID を持つ新しいアシスタント チャット ボットを作成する HTTP PUT 関数の作成プロセスを示します。 プロンプトに対する応答は HTTP 応答で返されます。

const { app, input, output } = require("@azure/functions");

const CHAT_STORAGE_CONNECTION_SETTING = "AzureWebJobsStorage";
const COLLECTION_NAME = "ChatState";

const chatBotCreateOutput = output.generic({
    type: 'assistantCreate'
})
app.http('CreateAssistant', {
    methods: ['PUT'],
    route: 'assistants/{assistantId}',
    authLevel: 'anonymous',
    extraOutputs: [chatBotCreateOutput],
    handler: async (request, context) => {
        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,
            chatStorageConnectionSetting: CHAT_STORAGE_CONNECTION_SETTING,
            collectionName: COLLECTION_NAME
        }
        context.extraOutputs.set(chatBotCreateOutput, createRequest)
        return { status: 202, jsonBody: { assistantId: assistantId } }
    }
})
import { HttpRequest, InvocationContext, app, input, output } from "@azure/functions"

const CHAT_STORAGE_CONNECTION_SETTING = "AzureWebJobsStorage";
const COLLECTION_NAME = "ChatState";

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,
            chatStorageConnectionSetting: CHAT_STORAGE_CONNECTION_SETTING,
            collectionName: COLLECTION_NAME
        }
        context.extraOutputs.set(chatBotCreateOutput, createRequest)
        return { status: 202, jsonBody: { assistantId: assistantId } }
    }
})

この例では、指定された ID を持つ新しいアシスタント チャット ボットを作成する HTTP PUT 関数の作成プロセスを示します。 プロンプトに対する応答は HTTP 応答で返されます。

Create Assistant の function.json ファイルを次に示します。

{
  "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"
    }
  ]
}

function.json ファイルのプロパティについて詳しくは、「構成」セクションをご覧ください。

{{これはコードコメントの例から来ています}}

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
    "chatStorageConnectionSetting" = "AzureWebJobsStorage"
    "collectionName" = "ChatState"
}

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"
    }
})

この例では、指定された ID を持つ新しいアシスタント チャット ボットを作成する HTTP PUT 関数の作成プロセスを示します。 プロンプトに対する応答は HTTP 応答で返されます。

DEFAULT_CHAT_STORAGE_SETTING = "AzureWebJobsStorage"
DEFAULT_CHAT_COLLECTION_NAME = "ChatState"


@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,
        "chatStorageConnectionSetting": DEFAULT_CHAT_STORAGE_SETTING,
        "collectionName": DEFAULT_CHAT_COLLECTION_NAME,
    }
    requests.set(json.dumps(create_request))
    response_json = {"assistantId": assistantId}
    return func.HttpResponse(
        json.dumps(response_json), status_code=202, mimetype="application/json"
    )

属性

CreateAssistant 属性を適用して、これらのパラメーターをサポートするアシスタント作成出力バインドを定義します。

パラメーター 内容
身分証明書 作成するアシスタントの識別子。
手順 省略可。 アシスタントに提供する従う手順。
ChatStorageConnectionSetting 省略可。 チャット ストレージのテーブル設定の構成セクション名。 既定値は AzureWebJobsStorage です。
CollectionName 省略可。 チャット ストレージのテーブル コレクション名。 既定値は ChatState です。

注釈

CreateAssistant 注釈を使用すると、これらのパラメーターをサポートするアシスタント作成出力バインドを定義できます。

要素 内容
名前 出力バインドの名前を取得または設定します。
ID 作成するアシスタントの識別子。
指示 省略可。 アシスタントに提供する従う手順。
chatStorageConnectionSetting 省略可。 チャット ストレージのテーブル設定の構成セクション名。 既定値は AzureWebJobsStorage です。
collectionName 省略可。 チャット ストレージのテーブル コレクション名。 既定値は ChatState です。

デコレーター

プレビュー中に、出力バインドをこれらのパラメーターをサポートする generic_output_binding 型の createAssistant バインドとして定義します。

パラメーター 内容
arg_name バインド パラメーターを表す変数の名前。
ID 作成するアシスタントの識別子。
指示 省略可。 アシスタントに提供する従う手順。
chat_storage_connection_setting 省略可。 チャット ストレージのテーブル設定の構成セクション名。 既定値は AzureWebJobsStorage です。
collection_name 省略可。 チャット ストレージのテーブル コレクション名。 既定値は ChatState です。

構成

このバインドでは、function.json ファイルで設定したこれらの構成プロパティをサポートします。

プロパティ 内容
タイプ CreateAssistantである必要があります。
方向 outである必要があります。
名前 出力バインドの名前。
ID 作成するアシスタントの識別子。
指示 省略可。 アシスタントに提供する従う手順。
chatStorageConnectionSetting 省略可。 チャット ストレージのテーブル設定の構成セクション名。 既定値は AzureWebJobsStorage です。
collectionName 省略可。 チャット ストレージのテーブル コレクション名。 既定値は ChatState です。

構成

このバインドでは、コードで定義されている、これらのプロパティをサポートします。

プロパティ 内容
ID 作成するアシスタントの識別子。
指示 省略可。 アシスタントに提供する従う手順。
chatStorageConnectionSetting 省略可。 チャット ストレージのテーブル設定の構成セクション名。 既定値は AzureWebJobsStorage です。
collectionName 省略可。 チャット ストレージのテーブル コレクション名。 既定値は ChatState です。

使用方法

完全な例については、セクションの例を参照してください。