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

使用 GPT-4 Turbo with Vision

GPT-4 Turbo with Vision 是 OpenAI 开发的一个大型多模态模型 (LMM),可以分析图像,并为有关图像的问题提供文本回应。 它结合了自然语言处理和视觉理解。

GPT-4 Turbo with Vision 可以回答一般图像相关问题。 如果使用视觉增强还可以出示视频。

提示

若要使用 GPT-4 Turbo with Vision,请在已部署的 GPT-4 Turbo with Vision 模型上调用会话补全 API。 如果不熟悉会话补全 API,请参阅 GPT-4 Turbo 和 GPT-4 操作指南

GPT-4 Turbo 模型升级

GPT-4 Turbo 的最新 GA 版本是:

  • gpt-4版本:turbo-2024-04-09

这是以下预览版模型的替代品:

  • gpt-4版本:1106-Preview
  • gpt-4版本:0125-Preview
  • gpt-4版本:vision-preview

OpenAI 与 Azure OpenAI GPT-4 Turbo GA 模型之间的差异

  • OpenAI 的最新 0409 turbo 模型的版本支持所有推理请求的 JSON 模式和函数调用。
  • Azure OpenAI 的最新 turbo-2024-04-09 的版本目前不支持在使用图像(视觉)输入发出推理请求时使用 JSON 模式和函数调用。 基于文本的输入请求(没有 image_url 和内联图像的请求)支持 JSON 模式和函数调用。

与 gpt-4 vision-preview 的差异

  • gpt-4 版本 turbo-2024-04-09 不支持将 Azure AI 的特定 Vision 增强功能与 GPT-4 Turbo with Vision 集成。 这包括光学字符识别 (OCR)、对象接地、视频提示以及改进的图像数据处理。

GPT-4 Turbo 预配的托管可用性

  • gpt-4版本:turbo-2024-04-09 可用于标准部署和预配部署。 目前,此模型的预配版本不支持图像/视觉推理请求。 此模型的预配部署仅接受文本输入。 标准模型部署同时接受文本和图像/视觉推理请求。

区域可用性

有关模型区域可用性的信息,请参阅标准预配部署的模型矩阵。

部署 GPT-4 Turbo with Vision GA

若要从 Studio UI 部署 GA 模型,请选择 GPT-4,然后从下拉菜单中选择 turbo-2024-04-09 版本。 gpt-4-turbo-2024-04-09 模型的默认配额将与 GPT-4-Turbo 的当前配额相同。 请参阅区域配额限制

调用会话补全 API

以下命令显示了通过代码使用 GPT-4 Turbo with Vision 模型的最基本方法。 如果这是首次以编程方式使用这些模型,建议先从 GPT-4 Turbo with Vision 快速入门开始。

将 POST 请求发送到 https://{RESOURCE_NAME}.openai.azure.com/openai/deployments/{DEPLOYMENT_NAME}/chat/completions?api-version=2023-12-01-preview

  • RESOURCE_NAME 是 OpenAI 资源的名称
  • DEPLOYMENT_NAME 是 GPT-4 Turbo with Vision 模型部署的名称

必需的标头

  • Content-Type:application/json
  • api-key: {API_KEY}

正文:下列为请求正文示例。 格式与 GPT-4 的聊天补全 API 相同,只是消息内容可以是包含文本和图像(图像的有效 HTTP 或 HTTPS URL 或者 base-64 编码的图像)的数组。

重要

切记设置 "max_tokens" 值,否则返回输出将被截断。

{
    "messages": [ 
        {
            "role": "system", 
            "content": "You are a helpful assistant." 
        },
        {
            "role": "user", 
            "content": [
	            {
	                "type": "text",
	                "text": "Describe this picture:"
	            },
	            {
	                "type": "image_url",
	                "image_url": {
                        "url": "<image URL>"
                    }
                } 
           ] 
        }
    ],
    "max_tokens": 100, 
    "stream": false 
} 

提示

使用本地图像

如果要使用本地图像,可以使用以下 Python 代码将其转换为 base64,以便将其传递给 API。 在线提供了其他文件转换工具。

import base64
from mimetypes import guess_type

# Function to encode a local image into data URL 
def local_image_to_data_url(image_path):
    # Guess the MIME type of the image based on the file extension
    mime_type, _ = guess_type(image_path)
    if mime_type is None:
        mime_type = 'application/octet-stream'  # Default MIME type if none is found

    # Read and encode the image file
    with open(image_path, "rb") as image_file:
        base64_encoded_data = base64.b64encode(image_file.read()).decode('utf-8')

    # Construct the data URL
    return f"data:{mime_type};base64,{base64_encoded_data}"

# Example usage
image_path = '<path_to_image>'
data_url = local_image_to_data_url(image_path)
print("Data URL:", data_url)

当你的 base64 图像数据准备就绪后,可以在请求正文中将其传递给 API,如下所示:

...
"type": "image_url",
"image_url": {
   "url": "data:image/jpeg;base64,<your_image_data>"
}
...

输出

API 响应应如下所示:

{
    "id": "chatcmpl-8VAVx58veW9RCm5K1ttmxU6Cm4XDX",
    "object": "chat.completion",
    "created": 1702439277,
    "model": "gpt-4",
    "prompt_filter_results": [
        {
            "prompt_index": 0,
            "content_filter_results": {
                "hate": {
                    "filtered": false,
                    "severity": "safe"
                },
                "self_harm": {
                    "filtered": false,
                    "severity": "safe"
                },
                "sexual": {
                    "filtered": false,
                    "severity": "safe"
                },
                "violence": {
                    "filtered": false,
                    "severity": "safe"
                }
            }
        }
    ],
    "choices": [
        {
            "finish_reason":"stop",
            "index": 0,
            "message": {
                "role": "assistant",
                "content": "The picture shows an individual dressed in formal attire, which includes a black tuxedo with a black bow tie. There is an American flag on the left lapel of the individual's jacket. The background is predominantly blue with white text that reads \"THE KENNEDY PROFILE IN COURAGE AWARD\" and there are also visible elements of the flag of the United States placed behind the individual."
            },
            "content_filter_results": {
                "hate": {
                    "filtered": false,
                    "severity": "safe"
                },
                "self_harm": {
                    "filtered": false,
                    "severity": "safe"
                },
                "sexual": {
                    "filtered": false,
                    "severity": "safe"
                },
                "violence": {
                    "filtered": false,
                    "severity": "safe"
                }
            }
        }
    ],
    "usage": {
        "prompt_tokens": 1156,
        "completion_tokens": 80,
        "total_tokens": 1236
    }
}

每个响应都包含 "finish_details" 字段。 它具有以下可能值:

  • stop:API 返回了完整的模型输出。
  • length:由于 max_tokens 输入参数或模型的标记限制,模型输出不完整。
  • content_filter:由于内容筛选器的标志,省略了内容。

图像处理中的详细信息参数设置:低、高、自动

模型中的 detail 参数提供三种选择:lowhighauto,用于调整模型解释和处理图像的方式。 默认设置为自动,其中模型将根据图像输入的大小在低或高之间做出决定。

  • low 设置:模型不会激活“高分辨率”模式,而是处理分辨率较低的 512x512 版本,从而加快响应速度,减少在细化细节并不重要的方案中的标记消耗。
  • high 设置:模型将激活“高分辨率”模式。 在此设置下,模型首先查看低分辨率图像,然后根据输入图像生成详细的 512x512 段。 每个段使用两倍的标记预算,从而获得对图像的更详细解释。”

有关图像参数如何影响使用的令牌和定价的详细信息,请参阅 - 什么是 OpenAI?具有 GPT-4 Turbo with Vision 的图像标记

对图像使用视觉增强

GPT-4 Turbo with Vision 提供对 Azure AI 服务定制增强功能的独占访问权限。 与 Azure AI 视觉结合使用时,它可以为聊天模型提供有关图像中可见文本和对象位置的更详细信息,从而增强聊天体验。

“光学字符识别 (OCR)”集成使模型能够针对密集文本、转换后的图像和数字较多的财务文档生成更高质量的响应。 它还涵盖了更广泛的语言。

对象接地集成为数据分析和用户交互带来了新的层面,因为该功能可以在视觉上区分和突出显示其处理的图像中的重要元素。

重要

若要将视觉增强与 Azure OpenAI 资源配合使用,需要指定计算机视觉资源。 它必须位于付费 (S1) 层,并且位于具有视觉的 GPT-4 Turbo 资源所在的 Azure 区域。 如果使用 Azure AI 服务资源,则不需要额外的计算机视觉资源。

注意

GPT-4 Turbo with Vision 的 Azure AI 增强功能将与核心功能分开计费。 GPT-4 Turbo with Vision 的每个特定 Azure AI 增强功能都有其独特的费用。 有关详细信息,请参阅特殊定价信息

将 POST 请求发送到 https://{RESOURCE_NAME}.openai.azure.com/openai/deployments/{DEPLOYMENT_NAME}/extensions/chat/completions?api-version=2023-12-01-preview

  • RESOURCE_NAME 是 OpenAI 资源的名称
  • DEPLOYMENT_NAME 是 GPT-4 Turbo with Vision 模型部署的名称

必需的标头

  • Content-Type:application/json
  • api-key: {API_KEY}

正文:

格式与 GPT-4 的聊天补全 API 类似,但消息内容可以是包含字符串和图像(图像的有效 HTTP 或 HTTPS URL 或者 base-64 编码的图像)的数组。

还必须包括 enhancementsdataSources 对象。 enhancements 为会话中请求的视觉增强功能。 它具有 groundingocr 属性,这两个属性都有一个布尔 enabled 属性。 使用这些内容请求 OCR 服务和/或对象检测/定位服务。 dataSources 为视觉增强需要的计算机视觉资源数据。 它具有应为 "AzureComputerVision"type 属性和 parameters 属性。 将 endpointkey 设置为计算机视觉资源的终结点 URL 和访问密钥。

重要

切记设置 "max_tokens" 值,否则返回输出将被截断。

{
    "enhancements": {
            "ocr": {
              "enabled": true
            },
            "grounding": {
              "enabled": true
            }
    },
    "dataSources": [
    {
        "type": "AzureComputerVision",
        "parameters": {
            "endpoint": "<your_computer_vision_endpoint>",
            "key": "<your_computer_vision_key>"
        }
    }],
    "messages": [
        {
            "role": "system",
            "content": "You are a helpful assistant."
        },
        {
            "role": "user",
            "content": [
	            {
	                "type": "text",
	                "text": "Describe this picture:"
	            },
	            {
	                "type": "image_url",
	                "image_url": {
                        "url":"<image URL>" 
                    }
                }
           ] 
        }
    ],
    "max_tokens": 100, 
    "stream": false 
} 

输出

如此,从模型收到的聊天响应应包括有关图像的增强信息,例如对象标签和边界框以及 OCR 结果。 API 响应应如下所示:

{
    "id": "chatcmpl-8UyuhLfzwTj34zpevT3tWlVIgCpPg",
    "object": "chat.completion",
    "created": 1702394683,
    "model": "gpt-4",
    "choices":
    [
        {
            "finish_details": {
                "type": "stop",
                "stop": "<|fim_suffix|>"
            },
            "index": 0,
            "message":
            {
                "role": "assistant",
                "content": "The image shows a close-up of an individual with dark hair and what appears to be a short haircut. The person has visible ears and a bit of their neckline. The background is a neutral light color, providing a contrast to the dark hair."
            },
            "enhancements":
            {
                "grounding":
                {
                    "lines":
                    [
                        {
                            "text": "The image shows a close-up of an individual with dark hair and what appears to be a short haircut. The person has visible ears and a bit of their neckline. The background is a neutral light color, providing a contrast to the dark hair.",
                            "spans":
                            [
                                {
                                    "text": "the person",
                                    "length": 10,
                                    "offset": 99,
                                    "polygon": [{"x":0.11950000375509262,"y":0.4124999940395355},{"x":0.8034999370574951,"y":0.4124999940395355},{"x":0.8034999370574951,"y":0.6434999704360962},{"x":0.11950000375509262,"y":0.6434999704360962}]
                                }
                            ]
                        }
                    ],
                    "status": "Success"
                }
            }
        }
    ],
    "usage":
    {
        "prompt_tokens": 816,
        "completion_tokens": 49,
        "total_tokens": 865
    }
}

每个响应都包含 "finish_details" 字段。 它具有以下可能值:

  • stop:API 返回了完整的模型输出。
  • length:由于 max_tokens 输入参数或模型的标记限制,模型输出不完整。
  • content_filter:由于内容筛选器的标志,省略了内容。

对视频使用视觉增强

GPT-4 Turbo with Vision 提供对 Azure AI 服务定制增强功能的独占访问权限。 视频提示集成使用 Azure AI 视觉视频检索对视频中的一组帧进行采样,并创建视频中语音的转录。 它使 AI 模型能够给出有关视频内容的摘要和答案。

按照以下步骤设置视频检索系统并将其与 AI 聊天模型集成。

重要

若要将视觉增强与 Azure OpenAI 资源配合使用,需要指定计算机视觉资源。 它必须位于付费 (S1) 层,并且位于具有视觉的 GPT-4 Turbo 资源所在的 Azure 区域。 如果使用 Azure AI 服务资源,则不需要额外的计算机视觉资源。

注意

GPT-4 Turbo with Vision 的 Azure AI 增强功能将与核心功能分开计费。 GPT-4 Turbo with Vision 的每个特定 Azure AI 增强功能都有其独特的费用。 有关详细信息,请参阅特殊定价信息

提示

如果愿意,可转而使用 Jupyter 笔记本执行以下步骤:视频聊天完成笔记本

将视频上传到 Azure Blob 存储

需要将视频上传到 Azure Blob 存储容器。 创建一个新的存储帐户存储帐户(如果没有)。

上传视频后,可以获取其 SAS URL,可在后续步骤中访问这些 URL。

确保适当的读取访问权限

根据身份验证方法,可能需要执行一些额外的步骤来授予对 Azure Blob 存储容器的访问权限。 如果使用的是 Azure AI 服务资源而不是 Azure OpenAI 资源,需要使用托管标识向它授予 Azure Blob 存储的读取访问权限:

按照以下步骤在 Azure AI 服务资源上启用系统分配的标识:

  1. 在 Azure 门户中的 AI 服务资源中,选择“资源管理”->标识”,并将状态切换为“开”。
  2. 向 AI 服务资源分配“存储 Blob 数据读取”访问权限:从“标识”页中,选择“Azure 角色分配”,然后按照以下设置添加角色分配:
    • 范围:存储
    • 订阅:{你的订阅}
    • 资源:{选择 Azure Blob 存储资源}
    • 角色:存储 Blob 数据读取者
  3. 保存设置。

创建视频检索索引

  1. 获取与正在使用的 Azure OpenAI 资源位于同一区域中的 Azure AI 视觉资源。

  2. 创建索引来存储和组织视频文件及其元数据。 下面的示例命令演示如何使用创建索引 API 创建名为 my-video-index 的索引。 将索引名称保存到临时位置;稍后的步骤需要用到它。

    提示

    有关创建视频索引的更详细说明,请参阅使用矢量化执行视频检索

    curl.exe -v -X PUT "https://<YOUR_ENDPOINT_URL>/computervision/retrieval/indexes/my-video-index?api-version=2023-05-01-preview" -H "Ocp-Apim-Subscription-Key: <YOUR_SUBSCRIPTION_KEY>" -H "Content-Type: application/json" --data-ascii "
    {
      'metadataSchema': {
        'fields': [
          {
            'name': 'cameraId',
            'searchable': false,
            'filterable': true,
            'type': 'string'
          },
          {
            'name': 'timestamp',
            'searchable': false,
            'filterable': true,
            'type': 'datetime'
          }
        ]
      },
      'features': [
        {
          'name': 'vision',
          'domain': 'surveillance'
        },
        {
          'name': 'speech'
        }
      ]
    }"
    
  3. 使用视频文件关联的元数据将这些文件添加到索引。 下面的示例演示如何通过创建引入 API 使用 SAS URL 向索引添加两个视频文件以提供访问权限。 将 SAS URL 和 documentId 值保存到临时位置;稍后的步骤需要用到它们。

    curl.exe -v -X PUT "https://<YOUR_ENDPOINT_URL>/computervision/retrieval/indexes/my-video-index/ingestions/my-ingestion?api-version=2023-05-01-preview" -H "Ocp-Apim-Subscription-Key: <YOUR_SUBSCRIPTION_KEY>" -H "Content-Type: application/json" --data-ascii "
    {
      'videos': [
        {
          'mode': 'add',
          'documentId': '02a504c9cd28296a8b74394ed7488045',
          'documentUrl': 'https://example.blob.core.windows.net/videos/02a504c9cd28296a8b74394ed7488045.mp4?sas_token_here',
          'metadata': {
            'cameraId': 'camera1',
            'timestamp': '2023-06-30 17:40:33'
          }
        },
        {
          'mode': 'add',
          'documentId': '043ad56daad86cdaa6e493aa11ebdab3',
          'documentUrl': '[https://example.blob.core.windows.net/videos/043ad56daad86cdaa6e493aa11ebdab3.mp4?sas_token_here',
          'metadata': {
            'cameraId': 'camera2'
          }
        }
      ]
    }"
    
  4. 将视频文件添加到索引后,引入过程将启动。 可能需要一些时间,具体取决于文件的大小和数量。 若要在执行搜索之前确保引入已完成,可以使用获取引入 API 来检查状态。 等待此调用返回 "state" = "Completed",然后再继续下一步。

    curl.exe -v -X GET "https://<YOUR_ENDPOINT_URL>/computervision/retrieval/indexes/my-video-index/ingestions?api-version=2023-05-01-preview&$top=20" -H "ocp-apim-subscription-key: <YOUR_SUBSCRIPTION_KEY>"
    

将视频索引与 GPT-4 Turbo with Vision 集成

  1. 将 POST 请求准备到 https://{RESOURCE_NAME}.openai.azure.com/openai/deployments/{DEPLOYMENT_NAME}/extensions/chat/completions?api-version=2023-12-01-preview

    • RESOURCE_NAME 是 OpenAI 资源的名称
    • DEPLOYMENT_NAME 是 GPT-4 视觉模型部署的名称

    必需的标头

    • Content-Type:application/json
    • api-key: {API_KEY}
  2. 将以下 JSON 结构添加到请求正文中:

    {
        "enhancements": {
                "video": {
                  "enabled": true
                }
        },
        "dataSources": [
        {
            "type": "AzureComputerVisionVideoIndex",
            "parameters": {
                "computerVisionBaseUrl": "<your_computer_vision_endpoint>",
                "computerVisionApiKey": "<your_computer_vision_key>",
                "indexName": "<name_of_your_index>",
                "videoUrls": ["<your_video_SAS_URL>"]
            }
        }],
        "messages": [ 
            {
                "role": "system", 
                "content": "You are a helpful assistant." 
            },
            {
                "role": "user",
                "content": [
                        {
                            "type": "acv_document_id",
                            "acv_document_id": "<your_video_ID>"
                        },
                        {
                            "type": "text",
                            "text": "Describe this video:"
                        }
                    ]
            }
        ],
        "max_tokens": 100, 
    } 
    

    请求包括 enhancementsdataSources 对象。 enhancements 为会话中请求的视觉增强功能。 dataSources 为视觉增强需要的计算机视觉资源数据。 它具有应为 "AzureComputerVisionVideoIndex"type 属性,以及包含 AI 视觉和视频信息的 parameters 属性。

  3. 将自己的信息填写在上述所有 <placeholder> 字段中:按需输入 OpenAI 和 AI 视觉资源的终结点 URL 和密钥,并按照之前的步骤检索视频索引信息。

  4. 将 POST 请求发送到 API 终结点。 它应包含 OpenAI 和 AI 视觉凭据、视频索引的名称以及单个视频的 ID 和 SAS URL。

重要

"data_sources" 对象的内容因所使用的 Azure 资源类型和身份验证方法而异。 请查看以下参考文章:

"data_sources": [
{
    "type": "AzureComputerVisionVideoIndex",
    "parameters": {
    "endpoint": "<your_computer_vision_endpoint>",
    "computerVisionApiKey": "<your_computer_vision_key>",
    "indexName": "<name_of_your_index>",
    "videoUrls": ["<your_video_SAS_URL>"]
    }
}],

输出

从模型收到的聊天响应应包含有关视频的信息。 API 响应应如下所示:

{
    "id": "chatcmpl-8V4J2cFo7TWO7rIfs47XuDzTKvbct",
    "object": "chat.completion",
    "created": 1702415412,
    "model": "gpt-4",
    "choices":
    [
        {
            "finish_reason":"stop",
            "index": 0,
            "message":
            {
                "role": "assistant",
                "content": "The advertisement video opens with a blurred background that suggests a serene and aesthetically pleasing environment, possibly a workspace with a nature view. As the video progresses, a series of frames showcase a digital interface with search bars and prompts like \"Inspire new ideas,\" \"Research a topic,\" and \"Organize my plans,\" suggesting features of a software or application designed to assist with productivity and creativity.\n\nThe color palette is soft and varied, featuring pastel blues, pinks, and purples, creating a calm and inviting atmosphere. The backgrounds of some frames are adorned with abstract, organically shaped elements and animations, adding to the sense of innovation and modernity.\n\nMidway through the video, the focus shifts to what appears to be a browser or software interface with the phrase \"Screens simulated, subject to change; feature availability and timing may vary,\" indicating the product is in development and that the visuals are illustrative of its capabilities.\n\nThe use of text prompts continues with \"Help me relax,\" followed by a demonstration of a 'dark mode' feature, providing a glimpse into the software's versatility and user-friendly design.\n\nThe video concludes by revealing the product name, \"Copilot,\" and positioning it as \"Your everyday AI companion,\" implying the use of artificial intelligence to enhance daily tasks. The final frames feature the Microsoft logo, associating the product with the well-known technology company.\n\nIn summary, the advertisement video is for a Microsoft product named \"Copilot,\" which seems to be an AI-powered software tool aimed at improving productivity, creativity, and organization for its users. The video conveys a message of innovation, ease, and support in daily digital interactions through a visually appealing and calming presentation."
            }
        }
    ],
    "usage":
    {
        "prompt_tokens": 2068,
        "completion_tokens": 341,
        "total_tokens": 2409
    }
}

每个响应都包含 "finish_details" 字段。 它具有以下可能值:

  • stop:API 返回了完整的模型输出。
  • length:由于 max_tokens 输入参数或模型的标记限制,模型输出不完整。
  • content_filter:由于内容筛选器的标志,省略了内容。

视频提示的定价示例

GPT-4 Turbo with Vision 的定价是动态的,取决于使用的特定功能和输入。 有关 Azure OpenAI 定价的全面视图,请参阅Azure OpenAI 定价

基本费用和附加功能如下所述:

GPT-4 Turbo with Vision 的基本定价为:

  • 输入:每 1000 个令牌 0.01 USDX
  • 输出:每 1000 个令牌 0.03 USDX

视频提示与视频检索加载项集成:

  • 引入:每分钟视频 0.05 USDX
  • 事务:视频检索的每 1000 个查询 $0.25

后续步骤