適用於 Azure Functions 的 Azure OpenAI 內嵌輸入繫結

重要

適用於 Azure Functions 的 Azure OpenAI 延伸模組目前為預覽狀態。

Azure OpenAI 內嵌輸入繫結可讓您產生輸入的內嵌。 繫結可以從檔案或原始文字輸入產生內嵌。

如需 Azure OpenAI 延伸模組的安裝和設定詳細資訊,請參閱適用於 Azure Functions 的 Azure OpenAI 延伸模組。 若要深入了解 Azure OpenAI 服務中的內嵌,請參閱了解 Azure OpenAI 服務中的內嵌。

注意

參考和範例僅適用於 Node.js v4 模型。

注意

參考和範例僅適用於 Python v2 模型。

注意

雖然支援這兩個 C# 進程模型,但只會 提供隔離的背景工作模型 範例。

範例

目前這款綁定沒有 Go 支援。

此範例示範如何產生原始文字字串的內嵌。

internal class EmbeddingsRequest
{
    [JsonPropertyName("rawText")]
    public string? RawText { get; set; }

    [JsonPropertyName("fileName")]
    public string? FileName { get; set; }

    [JsonPropertyName("url")]
    public string? Url { get; set; }
}

/// <summary>
/// Example showing how to use the <see cref="EmbeddingsAttribute"/> input binding to generate embeddings 
/// for a raw text string.
/// </summary>
[Function(nameof(GenerateEmbeddings_Http_RequestAsync))]
public async Task GenerateEmbeddings_Http_RequestAsync(
    [HttpTrigger(AuthorizationLevel.Function, "post", Route = "embeddings")] HttpRequestData req,
    [EmbeddingsInput("{rawText}", InputType.RawText, EmbeddingsModel = "%EMBEDDING_MODEL_DEPLOYMENT_NAME%", AIConnectionName = "AzureOpenAI")] EmbeddingsContext embeddings)
{
    using StreamReader reader = new(req.Body);
    string request = await reader.ReadToEndAsync();

    EmbeddingsRequest? requestBody = JsonSerializer.Deserialize<EmbeddingsRequest>(request);

    this.logger.LogInformation(
        "Received {count} embedding(s) for input text containing {length} characters.",
        embeddings.Count,
        requestBody?.RawText?.Length);

    // TODO: Store the embeddings into a database or other storage.
}

這個範例示範如何擷取儲存在函式可存取之指定檔案的內嵌專案。

[Function(nameof(GetEmbeddings_Http_FilePath))]
public async Task GetEmbeddings_Http_FilePath(
    [HttpTrigger(AuthorizationLevel.Function, "post", Route = "embeddings-from-file")] HttpRequestData req,
    [EmbeddingsInput("{fileName}", InputType.FilePath, MaxChunkLength = 512, EmbeddingsModel = "%EMBEDDING_MODEL_DEPLOYMENT_NAME%", AIConnectionName = "AzureOpenAI")] EmbeddingsContext embeddings)
{
    using StreamReader reader = new(req.Body);
    string request = await reader.ReadToEndAsync();

    EmbeddingsRequest? requestBody = JsonSerializer.Deserialize<EmbeddingsRequest>(request);
    this.logger.LogInformation(
        "Received {count} embedding(s) for input file '{path}'.",
        embeddings.Count,
        requestBody?.FileName);

    // TODO: Store the embeddings into a database or other storage.
}

此範例示範如何產生原始文字字串的內嵌。

@FunctionName("GenerateEmbeddingsHttpRequest")
public HttpResponseMessage generateEmbeddingsHttpRequest(
        @HttpTrigger(
            name = "req", 
            methods = {HttpMethod.POST},
            authLevel = AuthorizationLevel.FUNCTION,
            route = "embeddings")
        HttpRequestMessage<EmbeddingsRequest> request,
        @EmbeddingsInput(name = "Embeddings", input = "{RawText}", inputType = InputType.RawText, embeddingsModel = "%EMBEDDING_MODEL_DEPLOYMENT_NAME%", aiConnectionName = "AzureOpenAI") String embeddingsContext,
        final ExecutionContext context) {

    if (request.getBody() == null) 
    {
        throw new IllegalArgumentException(
                "Invalid request body. Make sure that you pass in {\"rawText\": value } as the request body.");
    }

    JSONObject embeddingsContextJsonObject = new JSONObject(embeddingsContext);

    context.getLogger().info(String.format("Received %d embedding(s) for input text containing %s characters.",
            embeddingsContextJsonObject.get("count"),
            request.getBody().getRawText().length()));

    // TODO: Store the embeddings into a database or other storage.
    return request.createResponseBuilder(HttpStatus.ACCEPTED)
            .header("Content-Type", "application/json")
            .build();
}

這個範例示範如何擷取儲存在函式可存取之指定檔案的內嵌專案。

@FunctionName("GenerateEmbeddingsHttpFilePath")
public HttpResponseMessage generateEmbeddingsHttpFilePath(
    @HttpTrigger(
        name = "req", 
        methods = {HttpMethod.POST},
        authLevel = AuthorizationLevel.FUNCTION,
        route = "embeddings-from-file")
    HttpRequestMessage<EmbeddingsRequest> request,
    @EmbeddingsInput(name = "Embeddings", input = "{FileName}", inputType = InputType.FilePath, maxChunkLength = 512, embeddingsModel = "%EMBEDDING_MODEL_DEPLOYMENT_NAME%", aiConnectionName = "AzureOpenAI") String embeddingsContext,
    final ExecutionContext context) {

    if (request.getBody() == null) 
    {
        throw new IllegalArgumentException(
                "Invalid request body. Make sure that you pass in {\"fileName\": value } as the request body.");
    }

    JSONObject embeddingsContextJsonObject = new JSONObject(embeddingsContext);

    context.getLogger().info(String.format("Received %d embedding(s) for input file %s.",
            embeddingsContextJsonObject.get("count"),
            request.getBody().getFileName()));

    // TODO: Store the embeddings into a database or other storage.
    return request.createResponseBuilder(HttpStatus.ACCEPTED)
            .header("Content-Type", "application/json")
            .build();
}

此範例示範如何產生原始文字字串的內嵌。

const embeddingsHttpInput = input.generic({
    input: '{rawText}',
    inputType: 'RawText',
    type: 'embeddings',
    embeddingsModel: '%EMBEDDING_MODEL_DEPLOYMENT_NAME%',
    aiConnectionName: 'AzureOpenAI',
})

app.http('generateEmbeddings', {
    methods: ['POST'],
    route: 'embeddings',
    authLevel: 'function',
    extraInputs: [embeddingsHttpInput],
    handler: async (request, context) => {
        let requestBody = await request.json();
        let response = context.extraInputs.get(embeddingsHttpInput);

        context.log(
            `Received ${response.count} embedding(s) for input text containing ${requestBody.rawText?.length ?? 0} characters.`
        );
        
        // TODO: Store the embeddings into a database or other storage.

        return {status: 202}
    }
});
interface EmbeddingsHttpRequest {
    rawText?: string;
}

const embeddingsHttpInput = input.generic({
    input: '{rawText}',
    inputType: 'RawText',
    type: 'embeddings',
    embeddingsModel: '%EMBEDDING_MODEL_DEPLOYMENT_NAME%',
    aiConnectionName: 'AzureOpenAI',
})

app.http('generateEmbeddings', {
    methods: ['POST'],
    route: 'embeddings',
    authLevel: 'function',
    extraInputs: [embeddingsHttpInput],
    handler: async (request, context) => {
        let requestBody: EmbeddingsHttpRequest = await request.json();
        let response: any = context.extraInputs.get(embeddingsHttpInput);

        context.log(
            `Received ${response.count} embedding(s) for input text containing ${requestBody.rawText?.length ?? 0} characters.`
        );
        
        // TODO: Store the embeddings into a database or other storage.

        return {status: 202}
    }
});

此範例示範如何產生原始文字字串的內嵌。


const embeddingsFilePathInput = input.generic({
    input: '{fileName}',
    inputType: 'FilePath',
    type: 'embeddings',
    maxChunkLength: 512,
    embeddingsModel: '%EMBEDDING_MODEL_DEPLOYMENT_NAME%',
    aiConnectionName: 'AzureOpenAI',
})

app.http('getEmbeddingsFilePath', {
    methods: ['POST'],
    route: 'embeddings-from-file',
    authLevel: 'function',
    extraInputs: [embeddingsFilePathInput],
    handler: async (request, context) => {
        let requestBody = await request.json();
        let response = context.extraInputs.get(embeddingsFilePathInput);

        context.log(
            `Received ${response.count} embedding(s) for input file ${requestBody.fileName}.`
        );
        
        // TODO: Store the embeddings into a database or other storage.

        return {status: 202}
    }
});

interface EmbeddingsFilePath {
    fileName?: string;
}

const embeddingsFilePathInput = input.generic({
    input: '{fileName}',
    inputType: 'FilePath',
    type: 'embeddings',
    maxChunkLength: 512,
    embeddingsModel: '%EMBEDDING_MODEL_DEPLOYMENT_NAME%',
    aiConnectionName: 'AzureOpenAI',
})

app.http('getEmbeddingsFilePath', {
    methods: ['POST'],
    route: 'embeddings-from-file',
    authLevel: 'function',
    extraInputs: [embeddingsFilePathInput],
    handler: async (request, context) => {
        let requestBody: EmbeddingsFilePath = await request.json();
        let response: any = context.extraInputs.get(embeddingsFilePathInput);

        context.log(
            `Received ${response.count} embedding(s) for input file ${requestBody.fileName}.`
        );
        
        // TODO: Store the embeddings into a database or other storage.

        return {status: 202}
    }
});

此範例示範如何產生原始文字字串的內嵌。

以下是用來產生內嵌function.json檔案:

{
  "bindings": [
    {
      "authLevel": "function",
      "type": "httpTrigger",
      "direction": "in",
      "name": "Request",
      "route": "embeddings",
      "methods": [
        "post"
      ]
    },
    {
      "type": "http",
      "direction": "out",
      "name": "Response"
    },
    {
      "name": "Embeddings",
      "type": "embeddings",
      "direction": "in",
      "inputType": "RawText",
      "input": "{rawText}",
      "embeddingsModel": "%EMBEDDING_MODEL_DEPLOYMENT_NAME%",
      "aiConnectionName": "AzureOpenAI"
    }
  ]
}

如需 function.json 檔案屬性的詳細資訊,請參閱設定一節。

using namespace System.Net

param($Request, $TriggerMetadata, $Embeddings)

$input = $Request.Body.RawText

Write-Host "Received $($Embeddings.Count) embedding(s) for input text containing $($input.Length) characters."

Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{
        StatusCode = [HttpStatusCode]::Accepted
})

此範例示範如何產生原始文字字串的內嵌。

@app.function_name("GenerateEmbeddingsHttpRequest")
@app.route(route="embeddings", methods=["POST"])
@app.embeddings_input(
    arg_name="embeddings",
    input="{rawText}",
    input_type="rawText",
    embeddings_model="%EMBEDDING_MODEL_DEPLOYMENT_NAME%",
    ai_connection_name="AzureOpenAI",
)
def generate_embeddings_http_request(
    req: func.HttpRequest, embeddings: str
) -> func.HttpResponse:
    user_message = req.get_json()
    embeddings_json = json.loads(embeddings)
    embeddings_request = {"raw_text": user_message.get("rawText")}
    logging.info(
        f'Received {embeddings_json.get("count")} embedding(s) for input text '
        f'containing {len(embeddings_request.get("raw_text"))} characters.'
    )
    # TODO: Store the embeddings into a database or other storage.
    return func.HttpResponse(status_code=200)

屬性

套用 EmbeddingsInput 屬性來定義內嵌儲存輸入繫結,其支援下列參數:

參數 描述
輸入 要為其產生內嵌的輸入字串。
AIConnectionName 選擇性。 取得或設定 AI 服務連線設定的組態區段名稱。 針對 Azure OpenAI:如果指定,請在此組態區段中尋找「端點」和「金鑰」值。 如果未指定或區段不存在,請回復為環境變數:AZURE_OPENAI_ENDPOINT和AZURE_OPENAI_KEY。 針對使用者指派的受控識別驗證,需要此屬性。 針對OpenAI服務 (非 Azure),請設定OPENAI_API_KEY環境變數。
EmbeddingsModel 選擇性。 要使用的模型識別碼,預設為 text-embedding-ada-002。 您不應該變更現有資料庫的模型。 如需詳細資訊,請參閱使用方式。
MaxChunkLength 選擇性。 用於區塊化輸入的字元數目上限。 如需詳細資訊,請參閱使用方式。
MaxOverlap 選擇性。 取得或設定區塊之間重疊的最大字元數目。
InputType 選擇性。 取得輸入的類型。

註釋

EmbeddingsInput 註釋可讓您定義內嵌輸入繫結,其支援下列參數:

元素 描述
名字 取得或設定輸入繫結的名稱。
輸入 要為其產生內嵌的輸入字串。
aiConnectionName 選擇性。 取得或設定 AI 服務連線設定的組態區段名稱。 針對 Azure OpenAI:如果指定,請在此組態區段中尋找「端點」和「金鑰」值。 如果未指定或區段不存在,請回復為環境變數:AZURE_OPENAI_ENDPOINT和AZURE_OPENAI_KEY。 針對使用者指派的受控識別驗證,需要此屬性。 針對OpenAI服務 (非 Azure),請設定OPENAI_API_KEY環境變數。
embeddingsModel 選擇性。 要使用的模型識別碼,預設為 text-embedding-ada-002。 您不應該變更現有資料庫的模型。 如需詳細資訊,請參閱使用方式。
maxChunkLength 選擇性。 用於區塊化輸入的字元數目上限。 如需詳細資訊,請參閱使用方式。
maxOverlap 選擇性。 取得或設定區塊之間重疊的最大字元數目。
inputType 選擇性。 取得輸入的類型。

裝飾項目

在預覽期間,將輸入繫結定義為 generic_input_binding 類型的 embeddings 繫結,其支援下列參數:embeddings 裝飾項目支援這些參數:

參數 描述
arg_name 代表繫結參數的變數名稱。
輸入 要為其產生內嵌的輸入字串。
ai_connection_name 選擇性。 取得或設定 AI 服務連線設定的組態區段名稱。 針對 Azure OpenAI:如果指定,請在此組態區段中尋找「端點」和「金鑰」值。 如果未指定或區段不存在,請回復為環境變數:AZURE_OPENAI_ENDPOINT和AZURE_OPENAI_KEY。 針對使用者指派的受控識別驗證,需要此屬性。 針對OpenAI服務 (非 Azure),請設定OPENAI_API_KEY環境變數。
embeddings_model 選擇性。 要使用的模型識別碼,預設為 text-embedding-ada-002。 您不應該變更現有資料庫的模型。 如需詳細資訊,請參閱使用方式。
maxChunkLength 選擇性。 用於區塊化輸入的字元數目上限。 如需詳細資訊,請參閱使用方式。
max_overlap 選擇性。 取得或設定區塊之間重疊的最大字元數目。
input_type 取得輸入的類型。

組態

繫結支援您在 function.json 檔案中設定的下列組態屬性。

屬性 描述
類型 必須是 EmbeddingsInput。
方向 必須是 in。
名字 輸入繫結的名稱。
輸入 要為其產生內嵌的輸入字串。
aiConnectionName 選擇性。 取得或設定 AI 服務連線設定的組態區段名稱。 針對 Azure OpenAI:如果指定,請在此組態區段中尋找「端點」和「金鑰」值。 如果未指定或區段不存在,請回復為環境變數:AZURE_OPENAI_ENDPOINT和AZURE_OPENAI_KEY。 針對使用者指派的受控識別驗證,需要此屬性。 針對OpenAI服務 (非 Azure),請設定OPENAI_API_KEY環境變數。
embeddingsModel 選擇性。 要使用的模型識別碼,預設為 text-embedding-ada-002。 您不應該變更現有資料庫的模型。 如需詳細資訊,請參閱使用方式。
maxChunkLength 選擇性。 用於區塊化輸入的字元數目上限。 如需詳細資訊,請參閱使用方式。
maxOverlap 選擇性。 取得或設定區塊之間重疊的最大字元數目。
inputType 選擇性。 取得輸入的類型。

組態

繫結支援您在程式碼中定義的下列屬性:

屬性 描述
輸入 要為其產生內嵌的輸入字串。
aiConnectionName 選擇性。 取得或設定 AI 服務連線設定的組態區段名稱。 針對 Azure OpenAI:如果指定,請在此組態區段中尋找「端點」和「金鑰」值。 如果未指定或區段不存在,請回復為環境變數:AZURE_OPENAI_ENDPOINT和AZURE_OPENAI_KEY。 針對使用者指派的受控識別驗證,需要此屬性。 針對OpenAI服務 (非 Azure),請設定OPENAI_API_KEY環境變數。
embeddingsModel 選擇性。 要使用的模型識別碼,預設為 text-embedding-ada-002。 您不應該變更現有資料庫的模型。 如需詳細資訊,請參閱使用方式。
maxChunkLength 選擇性。 用於區塊化輸入的字元數目上限。 如需詳細資訊,請參閱使用方式。
maxOverlap 選擇性。 取得或設定區塊之間重疊的最大字元數目。
inputType 選擇性。 取得輸入的類型。

如需完整範例,請參閱範例一節。

使用方式

變更預設內嵌 model 會變更內嵌在向量資料庫的儲存方式。 變更預設模型可能會導致查閱與先前內嵌至向量資料庫的其他資料不相符,從而導致錯誤行為。 內嵌的預設模型是 text-embedding-ada-002。

計算輸入區塊的最大字元長度時,請考慮允許第二代輸入內嵌模型 (例如 text-embedding-ada-002) 的最大輸入權杖為 8191。 單一權杖長度約為 4 個字元 (英文),轉譯為單一區塊可容納的輸入字元為 32,000 個字元 (英文)。

連結

要使用 Azure OpenAI 綁定擴充功能,你需要指定一個連接到 OpenAI 模型定義的連結。 請使用以下其中一種方法在綁定中設定 OpenAI 模型連線:

  • 使用 AIConnectionName binding 屬性(Azure OpenAI 偏好)。
  • 在應用程式內設定並設定AZURE_OPENAI_ENDPOINTAZURE_OPENAI_KEY(針對 Azure OpenAI)。
  • 只 Open_API_Key 在應用程式設定中設定(針對 https://api.openai.com)。

連線的設定方式取決於模型 API 與認證方法,如下表所示:

認證/模型 API Azure OpenAI OpenAI (https://api.openai.com)
管理身份連線 AIConnectionName 不支援
金鑰保存庫 參考 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>一組設定共享,這些設定共同定義了與 Azure OpenAI 的身份基礎連線。 欲了解更多資訊,請參閱定義身份連結。
  • 金鑰保存庫 參考:AIConnectionName屬性設定回傳一個 Azure Key Vault 參考,指向 API 金鑰集中維護的位置。 欲了解更多資訊,請參閱定義 金鑰保存庫 連接。
  • App Configuration 參考:AIConnectionName屬性設定會回傳一個 Azure 應用程式組態 參考,該參考會回傳 API 金鑰或 金鑰保存庫 參考。 欲了解更多資訊,請參閱連接條目中的 Azure 應用程式組態。
  • API 金鑰: AIConnectionName 屬性設定會解析成包含端點與金鑰的應用程式設定。 由於共享金鑰可能被入侵,請盡可能使用受管理身份連線。 欲了解更多資訊,請參閱定義連結。

想了解更多關於綁定連接的資訊,請參閱 Azure Functions 中的 Manage connections 。

OpenAI 綁定包含一個AIConnectionName屬性,你可以用來指定定義與 Azure OpenAI 連結的應用程式設定群組:<ConnectionNamePrefix>

設定名稱 描述
<CONNECTION_NAME_PREFIX>__endpoint 設定 Azure OpenAI 服務的 URI 端點。 這項設定一律為必要。
<CONNECTION_NAME_PREFIX>__clientId 設定取得存取令牌時要使用的特定使用者指派身分識別。 需要將 <CONNECTION_NAME_PREFIX>__credential 設定為 managedidentity。 屬性接受的用戶端識別碼,對應至指派給應用程式的使用者指派身分識別。 指定資源識別碼和用戶端識別碼無效。 如果你沒有指定這個屬性,則會使用系統指定的身份。 不應該設定 時,這個屬性會以不同的方式用於credential。
<CONNECTION_NAME_PREFIX>__credential 定義連線中取得 access token 的方式。 為受控識別驗證使用 managedidentity。 僅在裝載環境中有受控識別可用時,這個值才有效。
<CONNECTION_NAME_PREFIX>__managedIdentityResourceId 當 credential 設定為 managedidentity時,設定此屬性以指定取得標記時使用的資源識別碼。 屬性會接受的資源識別碼是對應至使用者定義受控識別的資源識別碼。 指定資源識別碼和用戶端識別碼無效。 如果你沒有指定任何一個,系統會用指定的身份。 不應該設定 時,這個屬性會以不同的方式用於credential。
<CONNECTION_NAME_PREFIX>__key 透過基於金鑰的認證,設定存取 Azure OpenAI 服務端點所需的共享秘密金鑰。 作為安全最佳實務,請務必使用 Microsoft Entra ID 搭配受管理身份來進行驗證。

當你將屬性設定 AIConnectionName 為 myAzureOpenAI:

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

使用受管理身份時,務必將你的身份加入認知 服務 OpenAI 使用者 角色。

本地執行時,請將這些設定加入 local.settings.json 專案檔案。 如需詳細資訊,請參閱 使用身分識別型連線進行本機開發。

如需詳細資訊,請參閱使用應用程式設定。