共用方式為


將影像與代理程式搭配使用

本教學課程說明如何將影像與代理程式搭配使用,讓代理程式能夠分析和回應影像內容。

先決條件

如需必要條件和安裝 NuGet 套件,請參閱本教學課程中的 建立並執行簡單代理程式 步驟。

將映像傳遞至代理

您可以透過建立包含文字和影像內容的影像 ChatMessage 來將影像傳送給客服專員。 然後,代理可以分析圖像並做出相應的回應。

首先,創建一個能夠分析圖像的 AIAgent

AIAgent agent = new AzureOpenAIClient(
    new Uri("https://<myresource>.openai.azure.com"),
    new AzureCliCredential())
    .GetChatClient("gpt-4o")
    .CreateAIAgent(
        name: "VisionAgent",
        instructions: "You are a helpful agent that can analyze images");

接下來,建立一個同時包含文字提示和影像 URL 的ChatMessage。 使用 TextContent 來表示文字,使用 UriContent 來表示影像。

ChatMessage message = new(ChatRole.User, [
    new TextContent("What do you see in this image?"),
    new UriContent("https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg", "image/jpeg")
]);

執行具有訊息的代理程式。 您可以使用串流來接收產生的回應。

Console.WriteLine(await agent.RunAsync(message));

這會將代理程式對映像的分析列印到控制台。

將映像傳遞至代理

您可以透過建立包含文字和影像內容的影像 ChatMessage 來將影像傳送給客服專員。 然後,代理可以分析圖像並做出相應的回應。

首先,建立能夠分析影像的代理程式。

import asyncio
from agent_framework.azure import AzureOpenAIChatClient
from azure.identity import AzureCliCredential

agent = AzureOpenAIChatClient(credential=AzureCliCredential()).create_agent(
    name="VisionAgent",
    instructions="You are a helpful agent that can analyze images"
)

接下來,建立一個同時包含文字提示和影像 URL 的ChatMessage。 使用 TextContent 來表示文字,使用 UriContent 來表示影像。

from agent_framework import ChatMessage, TextContent, UriContent, Role

message = ChatMessage(
    role=Role.USER,
    contents=[
        TextContent(text="What do you see in this image?"),
        UriContent(
            uri="https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg",
            media_type="image/jpeg"
        )
    ]
)

您也可以使用以下方式從 DataContent本機檔案系統載入映像:

from agent_framework import ChatMessage, TextContent, DataContent, Role

# Load image from local file
with open("path/to/your/image.jpg", "rb") as f:
    image_bytes = f.read()

message = ChatMessage(
    role=Role.USER,
    contents=[
        TextContent(text="What do you see in this image?"),
        DataContent(
            data=image_bytes,
            media_type="image/jpeg"
        )
    ]
)

執行具有訊息的代理程式。 您可以使用串流來接收產生的回應。

async def main():
    result = await agent.run(message)
    print(result.text)

asyncio.run(main())

這會將代理程式對映像的分析列印到控制台。

後續步驟