Add samples for web search and image gen tools (#2155)

This commit is contained in:
Tao Chen
2025-11-12 15:58:23 -08:00
committed by GitHub
Unverified
parent e8243b7d11
commit 348ac764e6
3 changed files with 127 additions and 0 deletions
@@ -17,6 +17,8 @@ This folder contains examples demonstrating different ways to create and use age
| [`azure_ai_with_hosted_mcp.py`](azure_ai_with_hosted_mcp.py) | Shows how to integrate hosted Model Context Protocol (MCP) tools with Azure AI Agent. |
| [`azure_ai_with_response_format.py`](azure_ai_with_response_format.py) | Shows how to use structured outputs (response format) with Azure AI agents using Pydantic models to enforce specific response schemas. |
| [`azure_ai_with_thread.py`](azure_ai_with_thread.py) | Demonstrates thread management with Azure AI agents, including automatic thread creation for stateless conversations and explicit thread management for maintaining conversation context across multiple interactions. |
| [`azure_ai_with_image_generation.py`](azure_ai_with_image_generation.py) | Shows how to use the `ImageGenTool` with Azure AI agents to generate images based on text prompts. |
| [`azure_ai_with_web_search.py`](azure_ai_with_web_search.py) | Shows how to use the `HostedWebSearchTool` with Azure AI agents to perform web searches and retrieve up-to-date information from the internet. |
## Environment Variables
@@ -0,0 +1,77 @@
# Copyright (c) Microsoft. All rights reserved.
import asyncio
from pathlib import Path
import aiofiles
from agent_framework import DataContent
from agent_framework.azure import AzureAIClient
from azure.ai.projects.models import ImageGenTool
from azure.identity.aio import AzureCliCredential
"""
Azure AI Agent With Image Generation
This sample demonstrates basic usage of AzureAIClient to create an agent
that can generate images based on user requirements.
Pre-requisites:
- Make sure to set up the AZURE_AI_PROJECT_ENDPOINT and AZURE_AI_MODEL_DEPLOYMENT_NAME
environment variables before running this sample.
"""
async def main() -> None:
# Since no Agent ID is provided, the agent will be automatically created.
# For authentication, run `az login` command in terminal or replace AzureCliCredential with preferred
# authentication option.
async with (
AzureCliCredential() as credential,
AzureAIClient(async_credential=credential).create_agent(
name="ImageGenAgent",
instructions="Generate images based on user requirements.",
tools=[ImageGenTool(quality="low", size="1024x1024")],
) as agent,
):
query = "Generate an image of Microsoft logo."
print(f"User: {query}")
result = await agent.run(
query,
# These additional options are required for image generation
additional_chat_options={
"extra_headers": {"x-ms-oai-image-generation-deployment": "gpt-image-1"},
},
)
print(f"Agent: {result}\n")
# Save the image to a file
print("Downloading generated image...")
image_data = [
content
for content in result.messages[0].contents
if isinstance(content, DataContent) and content.media_type == "image/png"
]
if image_data and image_data[0]:
# Save to the same directory as this script
filename = "microsoft.png"
current_dir = Path(__file__).parent.resolve()
file_path = current_dir / filename
async with aiofiles.open(file_path, "wb") as f:
await f.write(image_data[0].get_data_bytes())
print(f"Image downloaded and saved to: {file_path}")
else:
print("No image data found in the agent response.")
"""
Sample output:
User: Generate an image of Microsoft logo.
Agent: Here is the Microsoft logo image featuring its iconic four quadrants.
Downloading generated image...
Image downloaded and saved to: .../microsoft.png
"""
if __name__ == "__main__":
asyncio.run(main())
@@ -0,0 +1,48 @@
# Copyright (c) Microsoft. All rights reserved.
import asyncio
from agent_framework import HostedWebSearchTool
from agent_framework.azure import AzureAIClient
from azure.identity.aio import AzureCliCredential
"""
Azure AI Agent With Web Search
This sample demonstrates basic usage of AzureAIClient to create an agent
that can perform web searches using the HostedWebSearchTool.
Pre-requisites:
- Make sure to set up the AZURE_AI_PROJECT_ENDPOINT and AZURE_AI_MODEL_DEPLOYMENT_NAME
environment variables before running this sample.
"""
async def main() -> None:
# Since no Agent ID is provided, the agent will be automatically created.
# For authentication, run `az login` command in terminal or replace AzureCliCredential with preferred
# authentication option.
async with (
AzureCliCredential() as credential,
AzureAIClient(async_credential=credential).create_agent(
name="WebsearchAgent",
instructions="You are a helpful assistant that can search the web",
tools=[HostedWebSearchTool()],
) as agent,
):
query = "What's the weather today in Seattle?"
print(f"User: {query}")
result = await agent.run(query)
print(f"Agent: {result}\n")
"""
Sample output:
User: What's the weather today in Seattle?
Agent: Here is the updated weather forecast for Seattle: The current temperature is approximately 57°F,
mostly cloudy conditions, with light winds and a chance of rain later tonight. Check out more details
at the [National Weather Service](https://forecast.weather.gov/zipcity.php?inputstring=Seattle%2CWA).
"""
if __name__ == "__main__":
asyncio.run(main())