你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn

如何使用 Azure AI 模型推理生成图像嵌入

重要

本文中标记了“(预览版)”的项目目前为公共预览版。 此预览版未提供服务级别协议,不建议将其用于生产工作负载。 某些功能可能不受支持或者受限。 有关详细信息,请参阅 Microsoft Azure 预览版补充使用条款

本文介绍如何在 Azure AI Foundry 中将图像嵌入 API 与部署到 Azure AI 模型推理的模型配合使用。

先决条件

若要在应用程序中使用嵌入模型,你需要:

使用嵌入

首先,创建客户端以使用模型。 以下代码使用存储在环境变量中的终结点 URL 和密钥。

import os
from azure.ai.inference import ImageEmbeddingsClient
from azure.core.credentials import AzureKeyCredential

model = ImageEmbeddingsClient(
    endpoint=os.environ["AZURE_INFERENCE_ENDPOINT"],
    credential=AzureKeyCredential(os.environ["AZURE_INFERENCE_CREDENTIAL"]),
    model="Cohere-embed-v3-english"
)

如果将资源配置为具有 Microsoft Entra ID 支持,则可以使用以下代码片段创建客户端。

import os
from azure.ai.inference import ImageEmbeddingsClient
from azure.identity import DefaultAzureCredential

model = ImageEmbeddingsClient(
    endpoint=os.environ["AZURE_INFERENCE_ENDPOINT"],
    credential=DefaultAzureCredential(),
    model="Cohere-embed-v3-english"
)

创建嵌入

若要创建图像嵌入,则需要将图像数据作为请求的一部分传递。 图像数据应采用 PNG 格式,并编码为 base64。

from azure.ai.inference.models import ImageEmbeddingInput

image_input= ImageEmbeddingInput.load(image_file="sample1.png", image_format="png")
response = model.embed(
    input=[ image_input ],
)

提示

创建请求时,请考虑模型的标记输入限制。 如果需要嵌入较大的文本,则需要分块策略。

响应如下所示,可从中查看模型的使用统计信息:

import numpy as np

for embed in response.data:
    print("Embeding of size:", np.asarray(embed.embedding).shape)

print("Model:", response.model)
print("Usage:", response.usage)

重要

可能并非所有模型都支持按批计算嵌入内容。 例如,对于 cohere-embed-v3 模型,你需要一次发送一个图像。

嵌入图像和文本对

某些模型可以通过图像和文本对生成嵌入内容。 在这种情况下,可以使用请求中的 imagetext 字段将图像和文本传递给模型。 以下示例演示如何为图像和文本对创建嵌入内容:

text_image_input= ImageEmbeddingInput.load(image_file="sample1.png", image_format="png")
text_image_input.text = "A cute baby sea otter"
response = model.embed(
    input=[ text_image_input ],
)

创建不同类型的嵌入

某些模型可以为同一输入生成多个嵌入,具体取决于你计划如何使用它们。 此功能允许检索 RAG 模式的更准确的嵌入。

以下示例演示如何创建嵌入,这些嵌入用于为要存储在矢量数据库中的文档创建嵌入:

from azure.ai.inference.models import EmbeddingInputType

response = model.embed(
    input=[ image_input ],
    input_type=EmbeddingInputType.DOCUMENT,
)

处理查询以检索此类文档时,可以使用以下代码片段为查询创建嵌入,并最大程度地提高检索性能。

from azure.ai.inference.models import EmbeddingInputType

response = model.embed(
    input=[ image_input ],
    input_type=EmbeddingInputType.QUERY,
)

请注意,并非所有嵌入模型都支持在请求中指示输入类型,在这些情况下会返回 422 错误。

重要

本文中标记了“(预览版)”的项目目前为公共预览版。 此预览版未提供服务级别协议,不建议将其用于生产工作负载。 某些功能可能不受支持或者受限。 有关详细信息,请参阅 Microsoft Azure 预览版补充使用条款

本文介绍如何在 Azure AI Foundry 中将图像嵌入 API 与部署到 Azure AI 模型推理的模型配合使用。

先决条件

若要在应用程序中使用嵌入模型,你需要:

使用嵌入

首先,创建客户端以使用模型。 以下代码使用存储在环境变量中的终结点 URL 和密钥。

import ModelClient from "@azure-rest/ai-inference";
import { isUnexpected } from "@azure-rest/ai-inference";
import { AzureKeyCredential } from "@azure/core-auth";

const client = new ModelClient(
    process.env.AZURE_INFERENCE_ENDPOINT,
    new AzureKeyCredential(process.env.AZURE_INFERENCE_CREDENTIAL),
    "Cohere-embed-v3-english"
);

如果将资源配置为具有 Microsoft Entra ID 支持,则可以使用以下代码片段创建客户端。

import ModelClient from "@azure-rest/ai-inference";
import { isUnexpected } from "@azure-rest/ai-inference";
import { DefaultAzureCredential } from "@azure/identity";

const client = new ModelClient(
    process.env.AZURE_INFERENCE_ENDPOINT,
    new DefaultAzureCredential(),
    "Cohere-embed-v3-english"
);

创建嵌入

若要创建图像嵌入,则需要将图像数据作为请求的一部分传递。 图像数据应采用 PNG 格式,并编码为 base64。

var image_path = "sample1.png";
var image_data = fs.readFileSync(image_path);
var image_data_base64 = Buffer.from(image_data).toString("base64");

var response = await client.path("/images/embeddings").post({
    body: {
        input: [ { image: image_data_base64 } ],
    }
});

提示

创建请求时,请考虑模型的标记输入限制。 如果需要嵌入较大的文本,则需要分块策略。

响应如下所示,可从中查看模型的使用统计信息:

if (isUnexpected(response)) {
    throw response.body.error;
}

console.log(response.embedding);
console.log(response.body.model);
console.log(response.body.usage);

重要

可能并非所有模型都支持按批计算嵌入内容。 例如,对于 cohere-embed-v3 模型,你需要一次发送一个图像。

嵌入图像和文本对

某些模型可以通过图像和文本对生成嵌入内容。 在这种情况下,可以使用请求中的 imagetext 字段将图像和文本传递给模型。 以下示例演示如何为图像和文本对创建嵌入内容:

var image_path = "sample1.png";
var image_data = fs.readFileSync(image_path);
var image_data_base64 = Buffer.from(image_data).toString("base64");

var response = await client.path("images/embeddings").post({
    body: {
        input: [
            {
                text: "A cute baby sea otter",
                image: image_data_base64
            }
        ]
    }
});

创建不同类型的嵌入

某些模型可以为同一输入生成多个嵌入,具体取决于你计划如何使用它们。 此功能允许检索 RAG 模式的更准确的嵌入。

以下示例演示如何创建嵌入,这些嵌入用于为要存储在矢量数据库中的文档创建嵌入:

var response = await client.path("/embeddings").post({
    body: {
        input: [ { image: image_data_base64 } ],
        input_type: "document",
    }
});

处理查询以检索此类文档时,可以使用以下代码片段为查询创建嵌入,并最大程度地提高检索性能。

var response = await client.path("/embeddings").post({
    body: {
        input: [ { image: image_data_base64 } ],
        input_type: "query",
    }
});

请注意,并非所有嵌入模型都支持在请求中指示输入类型,在这些情况下会返回 422 错误。

注意

只有在使用 Python、JavaScript 或 REST 请求时支持使用图像嵌入。

注意

只有在使用 Python、JavaScript 或 REST 请求时支持使用图像嵌入。

重要

本文中标记了“(预览版)”的项目目前为公共预览版。 此预览版未提供服务级别协议,不建议将其用于生产工作负载。 某些功能可能不受支持或者受限。 有关详细信息,请参阅 Microsoft Azure 预览版补充使用条款

本文介绍如何在 Azure AI Foundry 中将图像嵌入 API 与部署到 Azure AI 模型推理的模型配合使用。

先决条件

若要在应用程序中使用嵌入模型,你需要:

使用嵌入

若要使用文本嵌入,请使用追加到基 URL 的路由 /images/embeddings 以及 api-key 中指示的凭据。 Bearer <key> 格式也支持 Authorization 标头。

POST https://<resource>.services.ai.azure.com/models/images/embeddings?api-version=2024-05-01-preview
Content-Type: application/json
api-key: <key>

如果已将资源配置为具有 Microsoft Entra ID 支持,请在 Authorization 标头中传递令牌:

POST https://<resource>.services.ai.azure.com/models/images/embeddings?api-version=2024-05-01-preview
Content-Type: application/json
Authorization: Bearer <token>

创建嵌入

若要创建图像嵌入,则需要将图像数据作为请求的一部分传递。 图像数据应采用 PNG 格式,并编码为 base64。

{
    "model": "Cohere-embed-v3-english",
    "input": [
        {
            "image": "data:image/png;base64,iVBORw0KGgoAAAANSUh..."
        }
    ]
}

提示

创建请求时,请考虑模型的标记输入限制。 如果需要嵌入较大的文本,则需要分块策略。

响应如下所示,可从中查看模型的使用统计信息:

{
    "id": "0ab1234c-d5e6-7fgh-i890-j1234k123456",
    "object": "list",
    "data": [
        {
            "index": 0,
            "object": "embedding",
            "embedding": [
                0.017196655,
                // ...
                -0.000687122,
                -0.025054932,
                -0.015777588
            ]
        }
    ],
    "model": "Cohere-embed-v3-english",
    "usage": {
        "prompt_tokens": 9,
        "completion_tokens": 0,
        "total_tokens": 9
    }
}

重要

可能并非所有模型都支持按批计算嵌入内容。 例如,对于 cohere-embed-v3 模型,你需要一次发送一个图像。

嵌入图像和文本对

某些模型可以通过图像和文本对生成嵌入内容。 在这种情况下,可以使用请求中的 imagetext 字段将图像和文本传递给模型。 以下示例演示如何为图像和文本对创建嵌入内容:

{
    "model": "Cohere-embed-v3-english",
    "input": [
        {
            "image": "data:image/png;base64,iVBORw0KGgoAAAANSUh...",
            "text": "A photo of a cat"
        }
    ]
}

创建不同类型的嵌入

某些模型可以为同一输入生成多个嵌入,具体取决于你计划如何使用它们。 此功能允许检索 RAG 模式的更准确的嵌入。

以下示例演示如何创建嵌入,这些嵌入用于为要存储在矢量数据库中的文档创建嵌入:

{
    "model": "Cohere-embed-v3-english",
    "input": [
        {
            "image": "data:image/png;base64,iVBORw0KGgoAAAANSUh..."
        }
    ],
    "input_type": "document"
}

处理查询以检索此类文档时,可以使用以下代码片段为查询创建嵌入,并最大程度地提高检索性能。

{
    "model": "Cohere-embed-v3-english",
    "input": [
        {
            "image": "data:image/png;base64,iVBORw0KGgoAAAANSUh..."
        }
    ],
    "input_type": "query"
}

请注意,并非所有嵌入模型都支持在请求中指示输入类型,在这些情况下会返回 422 错误。