Skip to content

Commit 348ac76

Browse files
authored
Add samples for web search and image gen tools (#2155)
1 parent e8243b7 commit 348ac76

File tree

3 files changed

+127
-0
lines changed

3 files changed

+127
-0
lines changed

python/samples/getting_started/agents/azure_ai/README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,8 @@ This folder contains examples demonstrating different ways to create and use age
1717
| [`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. |
1818
| [`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. |
1919
| [`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. |
20+
| [`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. |
21+
| [`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. |
2022

2123
## Environment Variables
2224

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
# Copyright (c) Microsoft. All rights reserved.
2+
3+
import asyncio
4+
from pathlib import Path
5+
6+
import aiofiles
7+
from agent_framework import DataContent
8+
from agent_framework.azure import AzureAIClient
9+
from azure.ai.projects.models import ImageGenTool
10+
from azure.identity.aio import AzureCliCredential
11+
12+
"""
13+
Azure AI Agent With Image Generation
14+
15+
This sample demonstrates basic usage of AzureAIClient to create an agent
16+
that can generate images based on user requirements.
17+
18+
Pre-requisites:
19+
- Make sure to set up the AZURE_AI_PROJECT_ENDPOINT and AZURE_AI_MODEL_DEPLOYMENT_NAME
20+
environment variables before running this sample.
21+
"""
22+
23+
24+
async def main() -> None:
25+
# Since no Agent ID is provided, the agent will be automatically created.
26+
# For authentication, run `az login` command in terminal or replace AzureCliCredential with preferred
27+
# authentication option.
28+
async with (
29+
AzureCliCredential() as credential,
30+
AzureAIClient(async_credential=credential).create_agent(
31+
name="ImageGenAgent",
32+
instructions="Generate images based on user requirements.",
33+
tools=[ImageGenTool(quality="low", size="1024x1024")],
34+
) as agent,
35+
):
36+
query = "Generate an image of Microsoft logo."
37+
print(f"User: {query}")
38+
result = await agent.run(
39+
query,
40+
# These additional options are required for image generation
41+
additional_chat_options={
42+
"extra_headers": {"x-ms-oai-image-generation-deployment": "gpt-image-1"},
43+
},
44+
)
45+
print(f"Agent: {result}\n")
46+
47+
# Save the image to a file
48+
print("Downloading generated image...")
49+
image_data = [
50+
content
51+
for content in result.messages[0].contents
52+
if isinstance(content, DataContent) and content.media_type == "image/png"
53+
]
54+
if image_data and image_data[0]:
55+
# Save to the same directory as this script
56+
filename = "microsoft.png"
57+
current_dir = Path(__file__).parent.resolve()
58+
file_path = current_dir / filename
59+
async with aiofiles.open(file_path, "wb") as f:
60+
await f.write(image_data[0].get_data_bytes())
61+
62+
print(f"Image downloaded and saved to: {file_path}")
63+
else:
64+
print("No image data found in the agent response.")
65+
66+
"""
67+
Sample output:
68+
User: Generate an image of Microsoft logo.
69+
Agent: Here is the Microsoft logo image featuring its iconic four quadrants.
70+
71+
Downloading generated image...
72+
Image downloaded and saved to: .../microsoft.png
73+
"""
74+
75+
76+
if __name__ == "__main__":
77+
asyncio.run(main())
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
# Copyright (c) Microsoft. All rights reserved.
2+
3+
import asyncio
4+
5+
from agent_framework import HostedWebSearchTool
6+
from agent_framework.azure import AzureAIClient
7+
from azure.identity.aio import AzureCliCredential
8+
9+
"""
10+
Azure AI Agent With Web Search
11+
12+
This sample demonstrates basic usage of AzureAIClient to create an agent
13+
that can perform web searches using the HostedWebSearchTool.
14+
15+
Pre-requisites:
16+
- Make sure to set up the AZURE_AI_PROJECT_ENDPOINT and AZURE_AI_MODEL_DEPLOYMENT_NAME
17+
environment variables before running this sample.
18+
"""
19+
20+
21+
async def main() -> None:
22+
# Since no Agent ID is provided, the agent will be automatically created.
23+
# For authentication, run `az login` command in terminal or replace AzureCliCredential with preferred
24+
# authentication option.
25+
async with (
26+
AzureCliCredential() as credential,
27+
AzureAIClient(async_credential=credential).create_agent(
28+
name="WebsearchAgent",
29+
instructions="You are a helpful assistant that can search the web",
30+
tools=[HostedWebSearchTool()],
31+
) as agent,
32+
):
33+
query = "What's the weather today in Seattle?"
34+
print(f"User: {query}")
35+
result = await agent.run(query)
36+
print(f"Agent: {result}\n")
37+
38+
"""
39+
Sample output:
40+
User: What's the weather today in Seattle?
41+
Agent: Here is the updated weather forecast for Seattle: The current temperature is approximately 57°F,
42+
mostly cloudy conditions, with light winds and a chance of rain later tonight. Check out more details
43+
at the [National Weather Service](https://forecast.weather.gov/zipcity.php?inputstring=Seattle%2CWA).
44+
"""
45+
46+
47+
if __name__ == "__main__":
48+
asyncio.run(main())

0 commit comments

Comments
 (0)