Azure OpenAI 嵌入存储 Azure Functions 的输出绑定

重要

适用于 Azure Functions 的 Azure OpenAI 扩展目前为预览版。

Azure OpenAI 嵌入存储输出绑定允许将文件写入语义文档存储,稍后可以在语义搜索中引用。

如需了解有关 Azure OpenAI 扩展的设置和配置详细信息,请参阅适用于 Azure Functions 的 Azure OpenAI 扩展。 若要详细了解 Azure AI 搜索中的语义排名,请参阅 Azure AI 搜索中的语义排名

注意

仅提供了适用于 Node.js v4 模型的参考和示例。

注意

仅提供了适用于 Python v2 模型的参考和示例。

注意

虽然支持这两个 C# 进程模型,但仅 提供了独立的辅助角色模型 示例。

示例

此示例将 HTTP 输入流写入提供的 URL 上的语义文档存储。

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

此示例将 HTTP 输入流写入提供的 URL 上的语义文档存储。

@FunctionName("IngestFile")
public HttpResponseMessage ingestFile(
    @HttpTrigger(
        name = "req", 
        methods = {HttpMethod.POST},
        authLevel = AuthorizationLevel.ANONYMOUS)
        HttpRequestMessage<EmbeddingsRequest> request,
    @EmbeddingsStoreOutput(name="EmbeddingsStoreOutput", input = "{url}", inputType = InputType.Url,
            storeConnectionName = "AISearchEndpoint", collection = "openai-index",
            embeddingsModel = "%EMBEDDING_MODEL_DEPLOYMENT_NAME%") 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;
    }

}

此示例将 HTTP 输入流写入提供的 URL 上的语义文档存储。

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

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", 
    connectionName: "AISearchEndpoint", 
    collection: "openai-index", 
    embeddingsModel: "%EMBEDDING_MODEL_DEPLOYMENT_NAME%"
});

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

此示例将 HTTP 输入流写入提供的 URL 上的语义文档存储。

下面是 用于引入文件的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",
      "connectionName": "AISearchEndpoint",
      "collection": "openai-index",
      "embeddingsModel": "%EMBEDDING_MODEL_DEPLOYMENT_NAME%"
    }
  ]
}

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

此示例将 HTTP 输入流写入提供的 URL 上的语义文档存储。

@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%",
)
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:如果已指定,请在此配置部分查找“终结点”和“密钥”值。 如果未指定或节不存在,请回退到环境变量:AZURE_OPENAI_ENDPOINT和AZURE_OPENAI_KEY。 对于用户分配的托管标识身份验证,此属性是必需的。 对于 OpenAI 服务(非 Azure),请设置OPENAI_API_KEY环境变量。
EmbeddingsModel 可选。 要使用的模型的 ID,默认为 text-embedding-ada-002。 不应更改现有数据库的模型。 有关详细信息,请参阅用法
MaxChunkLength 可选。 用于对输入进行分块的最大字符数。 有关详细信息,请参阅用法
MaxOverlap 可选。 获取或设置区块之间重叠的最大字符数。
InputType 可选。 获取输入的类型。
StoreConnectionName 包含连接字符串值的应用设置或环境变量的名称。 此属性支持绑定表达式。
集合 要搜索的集合、表或索引的名称。 此属性支持绑定表达式。

批注

通过 EmbeddingsStoreOutput 批注可以定义嵌入存储输出绑定,该绑定支持以下参数:

元素 说明
名字 获取或设置输出绑定的名称。
输入 要为其生成嵌入的输入字符串。
aiConnectionName 可选。 获取或设置 AI 服务连接设置的配置节的名称。 对于 Azure OpenAI:如果已指定,请在此配置部分查找“终结点”和“密钥”值。 如果未指定或节不存在,请回退到环境变量:AZURE_OPENAI_ENDPOINT和AZURE_OPENAI_KEY。 对于用户分配的托管标识身份验证,此属性是必需的。 对于 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:如果已指定,请在此配置部分查找“终结点”和“密钥”值。 如果未指定或节不存在,请回退到环境变量:AZURE_OPENAI_ENDPOINT和AZURE_OPENAI_KEY。 对于用户分配的托管标识身份验证,此属性是必需的。 对于 OpenAI 服务(非 Azure),请设置OPENAI_API_KEY环境变量。
embeddings_model 可选。 要使用的模型的 ID,默认为 text-embedding-ada-002。 不应更改现有数据库的模型。 有关详细信息,请参阅用法
maxChunkLength 可选。 用于对输入进行分块的最大字符数。 有关详细信息,请参阅用法
max_overlap 可选。 获取或设置区块之间重叠的最大字符数。
input_type 获取输入的类型。
store_connection_name 包含连接字符串值的应用设置或环境变量的名称。 此属性支持绑定表达式。
集合 要搜索的集合、表或索引的名称。 此属性支持绑定表达式。

配置

绑定支持在 function.json 文件中设置的这些配置属性。

properties 说明
type 必须是 embeddingsStore
方向 必须是 out
名字 输出绑定的名称。
输入 要为其生成嵌入的输入字符串。
aiConnectionName 可选。 获取或设置 AI 服务连接设置的配置节的名称。 对于 Azure OpenAI:如果已指定,请在此配置部分查找“终结点”和“密钥”值。 如果未指定或节不存在,请回退到环境变量:AZURE_OPENAI_ENDPOINT和AZURE_OPENAI_KEY。 对于用户分配的托管标识身份验证,此属性是必需的。 对于 OpenAI 服务(非 Azure),请设置OPENAI_API_KEY环境变量。
embeddingsModel 可选。 要使用的模型的 ID,默认为 text-embedding-ada-002。 不应更改现有数据库的模型。 有关详细信息,请参阅用法
maxChunkLength 可选。 用于对输入进行分块的最大字符数。 有关详细信息,请参阅用法
maxOverlap 可选。 获取或设置区块之间重叠的最大字符数。
inputType 可选。 获取输入的类型。
storeConnectionName 包含连接字符串值的应用设置或环境变量的名称。 此属性支持绑定表达式。
集合 要搜索的集合、表或索引的名称。 此属性支持绑定表达式。

配置

绑定支持以下属性,这些属性在代码中定义:

properties 说明
输入 要为其生成嵌入的输入字符串。
aiConnectionName 可选。 获取或设置 AI 服务连接设置的配置节的名称。 对于 Azure OpenAI:如果已指定,请在此配置部分查找“终结点”和“密钥”值。 如果未指定或节不存在,请回退到环境变量:AZURE_OPENAI_ENDPOINT和AZURE_OPENAI_KEY。 对于用户分配的托管标识身份验证,此属性是必需的。 对于 OpenAI 服务(非 Azure),请设置OPENAI_API_KEY环境变量。
embeddingsModel 可选。 要使用的模型的 ID,默认为 text-embedding-ada-002。 不应更改现有数据库的模型。 有关详细信息,请参阅用法
maxChunkLength 可选。 用于对输入进行分块的最大字符数。 有关详细信息,请参阅用法
maxOverlap 可选。 获取或设置区块之间重叠的最大字符数。
inputType 可选。 获取输入的类型。
storeConnectionName 包含连接字符串值的应用设置或环境变量的名称。 此属性支持绑定表达式。
集合 要搜索的集合、表或索引的名称。 此属性支持绑定表达式。

使用情况

有关完整示例,请参阅示例部分