Azure Functions 用の Azure OpenAI 埋め込みストアの出力バインド

重要

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

Azure OpenAI 埋め込みストアの出力バインドを使ってファイルをセマンティック ドキュメント ストアに書き込み、セマンティック検索で後で参照できるようにすることができます。

Azure OpenAI 拡張機能のセットアップと構成の詳細については、「Azure Functions 用の Azure OpenAI 拡張機能」を参照してください。 Azure AI 検索でのセマンティック ランク付けの詳細については、「Azure AI 検索 でのセマンティック ランク付け」を参照してください。

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

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

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

このバインドに関しては現在、Goのサポートは利用できません。

この例では、指定された URL のセマンティック ドキュメント ストアに HTTP 入力ストリームを書き込みます。

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

この例では、指定された URL のセマンティック ドキュメント ストアに HTTP 入力ストリームを書き込みます。

@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%", aiConnectionName = "AzureOpenAI") 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;
    }

}

この例では、指定された URL のセマンティック ドキュメント ストアに HTTP 入力ストリームを書き込みます。

const embeddingsStoreOutput = output.generic({
    type: "embeddingsStore",
    input: "{url}", 
    inputType: "url", 
    storeConnectionName: "AISearchEndpoint", 
    collection: "openai-index", 
    embeddingsModel: "%EMBEDDING_MODEL_DEPLOYMENT_NAME%",
    aiConnectionName: 'AzureOpenAI',
});

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%",
    aiConnectionName: 'AzureOpenAI',
});

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

この例では、指定された URL のセマンティック ドキュメント ストアに HTTP 入力ストリームを書き込みます。

ファイルを取り込むための function.json ファイルを次に示します。

{
  "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%",
      "aiConnectionName": "AzureOpenAI"
    }
  ]
}

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

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

この例では、指定された URL のセマンティック ドキュメント ストアに HTTP 入力ストリームを書き込みます。

@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%",
    ai_connection_name="AzureOpenAI",
)
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"
    )

属性

EmbeddingsStoreOutput 属性を適用して、これらのパラメーターをサポートする埋め込みストア出力バインドを定義します。

パラメーター 説明
入力 埋め込みを生成する入力文字列。
AIConnectionName 省略可。 AI サービス接続設定の構成セクションの名前を取得または設定します。 Azure OpenAI の場合: 指定した場合は、この構成セクションで "Endpoint" と "Key" の値を探します。 指定されていない場合、またはセクションが存在しない場合は、環境変数 (AZURE_OPENAI_ENDPOINTとAZURE_OPENAI_KEY) にフォールバックします。 ユーザー割り当てマネージド ID 認証の場合、このプロパティは必須です。 OpenAI サービス (Azure 以外) の場合は、OPENAI_API_KEY環境変数を設定します。
EmbeddingsModel 省略可。 使用するモデルの ID。既定値は text-embedding-ada-002 です。 既存のデータベースのモデルは変更しないでください。 詳細については、「使用」を参照してください。
MaxChunkLength 省略可。 入力のチャンキングに使用される文字の最大数。 詳細については、「使用」を参照してください。
MaxOverlap 省略可。 チャンク間で重複する文字の最大数を取得または設定します。
InputType 省略可。 入力の型を取得します。
StoreConnectionName 接続文字列の値を含むアプリ設定または環境変数の名前。 このプロパティは、バインド式をサポートしています。
コレクション 検索するコレクション、テーブル、またはインデックスの名前。 このプロパティは、バインド式をサポートしています。

注釈

EmbeddingsStoreOutput注釈を使用すると、次のパラメーターをサポートする埋め込みストア出力バインドを定義できます。

要素 説明
名前 出力バインドの名前を取得または設定します。
インプット 埋め込みを生成する入力文字列。
aiConnectionName 省略可。 AI サービス接続設定の構成セクションの名前を取得または設定します。 Azure OpenAI の場合: 指定した場合は、この構成セクションで "Endpoint" と "Key" の値を探します。 指定されていない場合、またはセクションが存在しない場合は、環境変数 (AZURE_OPENAI_ENDPOINTとAZURE_OPENAI_KEY) にフォールバックします。 ユーザー割り当てマネージド ID 認証の場合、このプロパティは必須です。 OpenAI サービス (Azure 以外) の場合は、OPENAI_API_KEY環境変数を設定します。
embeddingsModel 省略可。 使用するモデルの ID。既定値は text-embedding-ada-002 です。 既存のデータベースのモデルは変更しないでください。 詳細については、「使用」を参照してください。
maxChunkLength 省略可。 入力のチャンキングに使用される文字の最大数。 詳細については、「使用」を参照してください。
maxOverlap 省略可。 チャンク間で重複する文字の最大数を取得または設定します。
inputType 省略可。 入力の型を取得します。
storeConnectionName 接続文字列の値を含むアプリ設定または環境変数の名前。 このプロパティは、バインド式をサポートしています。
コレクション 検索するコレクション、テーブル、またはインデックスの名前。 このプロパティは、バインド式をサポートしています。

デコレーター

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

パラメーター 説明
arg_name バインド パラメーターを表す変数の名前。
インプット 埋め込みを生成する入力文字列。
ai_connection_name 省略可。 AI サービス接続設定の構成セクションの名前を取得または設定します。 Azure OpenAI の場合: 指定した場合は、この構成セクションで "Endpoint" と "Key" の値を探します。 指定されていない場合、またはセクションが存在しない場合は、環境変数 (AZURE_OPENAI_ENDPOINTとAZURE_OPENAI_KEY) にフォールバックします。 ユーザー割り当てマネージド ID 認証の場合、このプロパティは必須です。 OpenAI サービス (Azure 以外) の場合は、OPENAI_API_KEY環境変数を設定します。
embeddings_model 省略可。 使用するモデルの ID。既定値は text-embedding-ada-002 です。 既存のデータベースのモデルは変更しないでください。 詳細については、「使用」を参照してください。
maxChunkLength 省略可。 入力のチャンキングに使用される文字の最大数。 詳細については、「使用」を参照してください。
max_overlap 省略可。 チャンク間で重複する文字の最大数を取得または設定します。
input_type 入力の型を取得します。
store_connection_name 接続文字列の値を含むアプリ設定または環境変数の名前。 このプロパティは、バインド式をサポートしています。
コレクション 検索するコレクション、テーブル、またはインデックスの名前。 このプロパティは、バインド式をサポートしています。

構成

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

プロパティ 説明
タイプ embeddingsStoreである必要があります。
方向 outである必要があります。
名前 出力バインドの名前。
インプット 埋め込みを生成する入力文字列。
aiConnectionName 省略可。 AI サービス接続設定の構成セクションの名前を取得または設定します。 Azure OpenAI の場合: 指定した場合は、この構成セクションで "Endpoint" と "Key" の値を探します。 指定されていない場合、またはセクションが存在しない場合は、環境変数 (AZURE_OPENAI_ENDPOINTとAZURE_OPENAI_KEY) にフォールバックします。 ユーザー割り当てマネージド ID 認証の場合、このプロパティは必須です。 OpenAI サービス (Azure 以外) の場合は、OPENAI_API_KEY環境変数を設定します。
embeddingsModel 省略可。 使用するモデルの ID。既定値は text-embedding-ada-002 です。 既存のデータベースのモデルは変更しないでください。 詳細については、「使用」を参照してください。
maxChunkLength 省略可。 入力のチャンキングに使用される文字の最大数。 詳細については、「使用」を参照してください。
maxOverlap 省略可。 チャンク間で重複する文字の最大数を取得または設定します。
inputType 省略可。 入力の型を取得します。
storeConnectionName 接続文字列の値を含むアプリ設定または環境変数の名前。 このプロパティは、バインド式をサポートしています。
コレクション 検索するコレクション、テーブル、またはインデックスの名前。 このプロパティは、バインド式をサポートしています。

構成

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

プロパティ 説明
インプット 埋め込みを生成する入力文字列。
aiConnectionName 省略可。 AI サービス接続設定の構成セクションの名前を取得または設定します。 Azure OpenAI の場合: 指定した場合は、この構成セクションで "Endpoint" と "Key" の値を探します。 指定されていない場合、またはセクションが存在しない場合は、環境変数 (AZURE_OPENAI_ENDPOINTとAZURE_OPENAI_KEY) にフォールバックします。 ユーザー割り当てマネージド ID 認証の場合、このプロパティは必須です。 OpenAI サービス (Azure 以外) の場合は、OPENAI_API_KEY環境変数を設定します。
embeddingsModel 省略可。 使用するモデルの ID。既定値は text-embedding-ada-002 です。 既存のデータベースのモデルは変更しないでください。 詳細については、「使用」を参照してください。
maxChunkLength 省略可。 入力のチャンキングに使用される文字の最大数。 詳細については、「使用」を参照してください。
maxOverlap 省略可。 チャンク間で重複する文字の最大数を取得または設定します。
inputType 省略可。 入力の型を取得します。
storeConnectionName 接続文字列の値を含むアプリ設定または環境変数の名前。 このプロパティは、バインド式をサポートしています。
コレクション 検索するコレクション、テーブル、またはインデックスの名前。 このプロパティは、バインド式をサポートしています。

使用方法

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

接続

Azure OpenAIのバインディング拡張を使うには、OpenAIモデル定義への接続を指定する必要があります。 以下のいずれかの方法を使って、バインディング内でOpenAIモデル接続を設定します。

  • AIConnectionName bindingプロパティ(OpenAI Azure推奨)を使いましょう。
  • OpenAI Azureのアプリ設定でAZURE_OPENAI_ENDPOINTAZURE_OPENAI_KEYを設定してください。
  • アプリの設定で Open_API_Key だけに設定してください( https://api.openai.com用)。

接続の設定方法は、モデルAPIと認証方法の両方に依存し、以下の表に示されています:

認証/モデルAPI Azure OpenAI OpenAI(https://api.openai.com)
マネージド・アイデンティティ接続 AIConnectionName サポートしていません
Key Vault 参照 AZURE_OPENAI_ENDPOINT
AZURE_OPENAI_KEY
Open_API_Key
アプリ設定リファレンス AZURE_OPENAI_ENDPOINT
AZURE_OPENAI_KEY
Open_API_Key
共有シークレット AZURE_OPENAI_ENDPOINT
AZURE_OPENAI_KEY
Open_API_Key

管理型アイデンティティベースの接続と AIConnectionName プロパティを活用してください。

AIConnectionNameを使う場合、このプロパティ設定の値は接続の種類によって異なります。

  • マネージド・アイデンティティ接続:AIConnectionNameプロパティ<CONNECTION_NAME_PREFIX>は、複数の設定群が共有するものであり、これらが共同でOpenAIへのアイデンティティベースの接続を定義しますAzure。 詳細については、「 同一性接続の定義」を参照してください。
  • Key Vault参照:AIConnectionNameプロパティ設定は、APIキーが中央管理されている場所へのAzure Key Vault参照を返します。 詳細については、「Key Vault connectionsの定義」をご覧ください。
  • App Configuration reference:AIConnectionNameプロパティ設定はAPIキーまたはKey Vault参照を返すAzure App Configuration参照を返します。 詳細については、接続記事のAzure App Configurationをご覧ください。
  • APIキー: AIConnectionName プロパティ設定はエンドポイントとキーを含むアプリ設定に解決されます。 共有鍵は漏洩する可能性があるため、可能な限り管理型ID接続を使用してください。 詳細については、「 接続の定義」を参照してください。

バインディング接続について詳しく知りたい方は、「Azure Functionsの接続管理」をご覧ください。

OpenAIのバインディングには、OpenAIとの接続を定義するアプリ設定群のAIConnectionNameを指定するための<ConnectionNamePrefix>プロパティAzure含まれています。

設定名 説明
<CONNECTION_NAME_PREFIX>__endpoint Azure OpenAIサービスのURIエンドポイントを設定します。 この設定は常に必須です。
<CONNECTION_NAME_PREFIX>__clientId アクセス トークンを取得するときに使用する特定のユーザー割り当て ID を設定します。 <CONNECTION_NAME_PREFIX>__credentialmanagedidentity に設定する必要があります。 このプロパティは、アプリケーションに割り当てられたユーザー割り当て ID に相当するクライアント ID を受け取ります。 リソース ID とクライアント ID の両方を指定することは無効です。 このプロパティを指定しない場合は、システムが割り当てたアイデンティティが使われます。 このプロパティは、 を設定しないとき、credentialで異なる方法で使用されます。
<CONNECTION_NAME_PREFIX>__credential 接続のaccess トークンを取得する方法を定義します。 マネージド ID 認証には managedidentity を使用します。 この値は、ホスティング環境でマネージド ID が使用できる場合にのみ有効です。
<CONNECTION_NAME_PREFIX>__managedIdentityResourceId credentialmanagedidentityに設定されている場合、このプロパティでトークンを取得する際に使用するリソース識別子を指定します。 プロパティは、ユーザー定義マネージド ID のリソース ID に対応するリソース識別子を受け取ります。 リソース ID とクライアント ID の両方を指定することは無効です。 どちらかを指定しなければ、システムが割り当てたアイデンティティが使われます。 このプロパティは、 を設定しないとき、credentialで異なる方法で使用されます。
<CONNECTION_NAME_PREFIX>__key 鍵ベースの認証を用いて、Azure OpenAIサービスのエンドポイントにアクセスするために必要な共有秘密鍵を設定します。 セキュリティのベストプラクティスとして、認証には必ず管理されたIDと共にMicrosoft Entra IDを使用してください。

AIConnectionNameプロパティをmyAzureOpenAIに設定する際は、以下の管理されたID接続設定を考慮してください。

  • myAzureOpenAI__endpoint=https://contoso.openai.azure.com/
  • myAzureOpenAI__credential=managedidentity
  • myAzureOpenAI__clientId=aaaaaaaa-bbbb-cccc-1111-222222222222

実行時には、ホストはこれらの設定を単一の myAzureOpenAI 設定として解釈します。

"myAzureOpenAI":
{
    "endpoint": "https://contoso.openai.azure.com/",
    "credential": "managedidentity",
    "clientId": "aaaaaaaa-bbbb-cccc-1111-222222222222"
}

マネージドIDを使う場合は、必ず Cognitive Services OpenAIユーザー ロールに自分のIDを追加してください。

ローカルで動作する場合は、これらの設定を local.settings.json プロジェクトファイルに追加してください。 詳細については、「 ID ベースの接続を使用したローカル開発」を参照してください。

詳細については、アプリケーション設定の操作に関する記事を参照してください。