搭配視覺使用 GPT-4 Turbo

GPT-4 Turbo with Vision 是 OpenAI 開發的大型多模式模型(LMM),可分析影像並提供文字回應,以回答有關影像的問題。 它同時包含自然語言處理和視覺理解。

GPT-4 Turbo 與視覺模型回答影像中存在的一般問題。 如果您使用視覺增強功能,也可以顯示影片

提示

若要搭配視覺使用 GPT-4 Turbo,請在已部署的 GPT-4 Turbo 與視覺模型上呼叫聊天完成 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 渦輪增壓模型版本支援所有推斷要求的 JSON 模式和函式呼叫。
  • Azure OpenAI 的最新版本 turbo-2024-04-09 目前不支援使用 JSON 模式和函式呼叫,以影像(視覺)輸入提出推斷要求。 以文字為基礎的輸入要求(沒有 image_url 和內嵌影像的要求)支援 JSON 模式和函式呼叫。

gpt-4 視覺預覽的差異

  • 版本不支援 gpt-4turbo-2024-04-09Azure AI 特定視覺增強功能與 GPT-4 Turbo with Vision 整合。 這包括光學字元辨識 (OCR)、物件地面、視訊提示,以及使用影像改善數據的處理。

GPT-4 Turbo 布建的受控可用性

  • gpt-4版本:turbo-2024-04-09 適用於標準和布建的部署。 此模型的 布建版本目前不支援影像/視覺推斷要求。 此模型的布建部署只接受文字輸入。 標準模型部署同時接受文字和影像/視覺推斷要求。

區域可用性

如需模型區域可用性的資訊,請參閱標準與布建部署的模型矩陣

使用視覺 GA 部署 GPT-4 Turbo

若要從 Studio UI 部署 GA 模型,請從下拉功能表中選取 GPT-4 並選擇 turbo-2024-04-09 版本。 模型的預設配額 gpt-4-turbo-2024-04-09 會與 GPT-4-Turbo 目前的配額相同。 請參閱區域配額限制。

呼叫聊天完成 API

下列命令顯示搭配程序代碼使用 GPT-4 Turbo 與視覺模型的最基本方式。 如果這是您第一次以程序設計方式使用這些模型,建議您從 GPT-4 Turbo 搭配視覺快速入門開始

將POST要求傳送至 https://{RESOURCE_NAME}.openai.azure.com/openai/deployments/{DEPLOYMENT_NAME}/chat/completions?api-version=2023-12-01-preview 其中

  • RESOURCE_NAME是您 Azure OpenAI 資源的名稱
  • DEPLOYMENT_NAME是具有視覺模型部署的 GPT-4 Turbo 名稱

必要標頭

  • 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:由於內容篩選條件的旗標而省略內容。

影像處理中的詳細參數設定:低、高、自動

模型中的詳細數據參數提供三個選項:lowhighauto,以調整模型解譯和處理影像的方式。 默認設定為 auto,其中模型會根據影像輸入的大小來決定低或高。

  • low 設定:模型不會啟用「高解析度」模式,而是處理解析度較低的 512x512 版本,進而針對詳細數據並不重要的案例,產生更快速的回應和降低的令牌耗用量。
  • high 設定:模型會啟動「高 res」模式。 在此,模型一開始會檢視低解析度影像,然後從輸入影像產生詳細的 512x512 區段。 每個區段都會使用兩倍的令牌預算,以更詳細的解譯影像。''

如需映像參數如何影響使用令牌和定價的詳細資訊,請參閱 - 什麼是OpenAI?使用 GPT-4 Turbo 搭配視覺的影像令牌

搭配影像使用視覺增強功能

GPT-4 Turbo with Vision 提供對 Azure AI Services 量身打造增強功能的獨佔存取權。 與 Azure AI 視覺結合時,它會提供聊天模型,以提供影像中可見文字和物件位置的更詳細資訊,藉此增強您的聊天體驗。

光學字元辨識(OCR)整合可讓模型針對密集文字、轉換的圖像和大量財務檔產生更高的質量回應。 它也涵蓋更廣泛的語言。

物件地面整合為數據分析和用戶互動帶來了一個新的圖層,因為此功能可以可視化地區分並醒目提示它處理之影像中的重要元素。

重要

若要搭配 Azure OpenAI 資源使用視覺增強功能,您必須指定 電腦視覺 資源。 它必須位於付費 (S1) 層,且位於與具有視覺資源的 GPT-4 Turbo 相同的 Azure 區域中。 如果您使用 Azure AI Services 資源,則不需要額外的 電腦視覺 資源。

警告

適用於 GPT-4 Turbo with Vision 的 Azure AI 增強功能將會與核心功能分開計費。 GPT-4 Turbo 搭配視覺的每個特定 Azure AI 增強功能都有自己的不同費用。 如需詳細資訊,請參閱 特殊定價資訊

將POST要求傳送至 https://{RESOURCE_NAME}.openai.azure.com/openai/deployments/{DEPLOYMENT_NAME}/extensions/chat/completions?api-version=2023-12-01-preview 其中

  • RESOURCE_NAME是您 Azure OpenAI 資源的名稱
  • DEPLOYMENT_NAME是具有視覺模型部署的 GPT-4 Turbo 名稱

必要標頭

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

本文

格式類似於 GPT-4 的聊天完成 API,但訊息內容可以是包含字串和影像的陣列(有效的 HTTP 或影像 HTTPS URL,或 base-64 編碼的影像)。

您也必須包含 enhancementsdataSources 物件。 enhancements 代表聊天中要求的特定視覺增強功能。 grounding它有 和 ocr 屬性,兩者都有布爾enabled屬性。 使用這些來要求 OCR 服務和/或對象偵測/地面服務。 dataSources代表視覺增強所需的 電腦視覺 資源數據。 type它有應"AzureComputerVision"為 和 parameters 屬性的屬性。 endpoint將和 key 設定為 電腦視覺 資源的端點 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 Services 量身打造增強功能的獨佔存取權。 影片 提示 整合會使用 Azure AI 視覺影片擷取來取樣影片中的一組畫面,並在影片中建立語音記錄。 它可讓 AI 模型提供影片內容的摘要和解答。

請遵循下列步驟來設定影片擷取系統,並將其與您的 AI 聊天模型整合。

重要

若要搭配 Azure OpenAI 資源使用視覺增強功能,您必須指定 電腦視覺 資源。 它必須位於付費 (S1) 層,且位於與具有視覺資源的 GPT-4 Turbo 相同的 Azure 區域中。 如果您使用 Azure AI Services 資源,則不需要額外的 電腦視覺 資源。

警告

適用於 GPT-4 Turbo with Vision 的 Azure AI 增強功能將會與核心功能分開計費。 GPT-4 Turbo 搭配視覺的每個特定 Azure AI 增強功能都有自己的不同費用。 如需詳細資訊,請參閱 特殊定價資訊

提示

如果您想要的話,您可以改為使用 Jupyter Notebook 來執行下列步驟: 視訊聊天完成筆記本

將影片上傳至 Azure Blob 儲存體

您必須將影片上傳至 Azure Blob 儲存體 容器。 如果您還沒有記憶體帳戶,請建立新的記憶體帳戶

上傳影片之後,您可以取得其 SAS URL,您可以在稍後的步驟中用來存取這些 URL。

確定適當的讀取許可權

根據您的驗證方法,您可能需要執行一些額外的步驟,以授與 Azure Blob 儲存體 容器的存取權。 如果您使用 Azure AI Services 資源,而不是 Azure OpenAI 資源,您必須使用受控識別來授與讀取許可權給 Azure Blob 儲存體:

遵循下列步驟,在 Azure AI Services 資源上啟用系統指派的身分識別:

  1. 從您的 AI Services 資源 Azure 入口網站 選取 [資源管理 -> 身分識別],並將狀態切換為 [開啟]。
  2. 將 [Blob 數據讀取] 指派給 AI Services 資源 儲存體:從 [身分識別] 頁面中,選取 [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. 使用其相關聯的元數據,將影片檔案新增至索引。 下列範例示範如何使用 SAS URL 搭配 建立擷取 API,將兩個影片檔案新增至索引。 將 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 與 Vision 整合

  1. 準備POST要求到 https://{RESOURCE_NAME}.openai.azure.com/openai/deployments/{DEPLOYMENT_NAME}/extensions/chat/completions?api-version=2023-12-01-preview 何處

    • RESOURCE_NAME是您 Azure 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代表視覺增強所需的 電腦視覺 資源數據。 其屬性 type"AzureComputerVisionVideoIndex" 為 ,以及 parameters 包含 AI 視覺和視訊資訊的屬性。

  3. 在上述所有 <placeholder> 欄位中填入您自己的資訊:視需要輸入 OpenAI 和 AI 視覺資源的端點 URL 和密鑰,並從先前的步驟擷取影片索引資訊。

  4. 將 POST 要求傳送至 API 端點。 它應該包含 OpenAI 和 AI Vision 認證、影片索引的名稱,以及單一影片的標識碼和 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 定價是動態的,取決於所使用的特定功能和輸入。 如需 Azure OpenAI 定價的完整檢視,請參閱 Azure OpenAI 定價

基本費用和其他功能如下所述:

具有視覺功能的 GPT-4 Turbo 基本定價為:

  • 輸入:每 1000 個令牌 $0.01
  • 輸出:每 1000 個令牌 $0.03

影片提示與影片擷取附加元件整合:

  • 擷取:每分鐘視訊 $0.05
  • 交易:每 1000 個影片擷取查詢 $0.25

下一步