共用方式為


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

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

將映像傳遞至代理

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

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

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

警告

DefaultAzureCredential 開發方便,但在生產過程中需謹慎考量。 在生產環境中,建議使用特定的憑證(例如 ManagedIdentityCredential),以避免延遲問題、意外的憑證探測,以及備援機制帶來的安全風險。

接下來,建立一個同時包含文字提示和影像 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));

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

將映像傳遞至代理

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

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

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

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

接下來,建立一個同時包含文字提示和影像 URL 的Message。 使用 Content.from_text() 來表示文字,使用 Content.from_uri() 來表示影像。

from agent_framework import Message, Content

message = Message(
    role="user",
    contents=[
        Content.from_text(text="What do you see in this image?"),
        Content.from_uri(
            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"
        )
    ]
)

您也可以使用以下方式從 Content.from_data()本機檔案系統載入映像:

from agent_framework import Message, Content

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

message = Message(
    role="user",
    contents=[
        Content.from_text(text="What do you see in this image?"),
        Content.from_data(
            data=image_bytes,
            media_type="image/jpeg"
        )
    ]
)

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

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

asyncio.run(main())

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

後續步驟