Skip to content

Commit d552798

Browse files
authored
Python: Azure AI Agent with Bing Grounding Citations Sample (#2892)
* bing grounding sample with citations * small fix * fix
1 parent ec1c5e9 commit d552798

2 files changed

Lines changed: 87 additions & 0 deletions

File tree

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ This folder contains examples demonstrating different ways to create and use age
99
| [`azure_ai_basic.py`](azure_ai_basic.py) | The simplest way to create an agent using `ChatAgent` with `AzureAIAgentClient`. It automatically handles all configuration using environment variables. |
1010
| [`azure_ai_with_bing_custom_search.py`](azure_ai_with_bing_custom_search.py) | Shows how to use Bing Custom Search with Azure AI agents to find real-time information from the web using custom search configurations. Demonstrates how to set up and use HostedWebSearchTool with custom search instances. |
1111
| [`azure_ai_with_bing_grounding.py`](azure_ai_with_bing_grounding.py) | Shows how to use Bing Grounding search with Azure AI agents to find real-time information from the web. Demonstrates web search capabilities with proper source citations and comprehensive error handling. |
12+
| [`azure_ai_with_bing_grounding_citations.py`](azure_ai_with_bing_grounding_citations.py) | Demonstrates how to extract and display citations from Bing Grounding search responses. Shows how to collect citation annotations (title, URL, snippet) during streaming responses, enabling users to verify sources and access referenced content. |
1213
| [`azure_ai_with_code_interpreter_file_generation.py`](azure_ai_with_code_interpreter_file_generation.py) | Shows how to retrieve file IDs from code interpreter generated files using both streaming and non-streaming approaches. |
1314
| [`azure_ai_with_code_interpreter.py`](azure_ai_with_code_interpreter.py) | Shows how to use the HostedCodeInterpreterTool with Azure AI agents to write and execute Python code. Includes helper methods for accessing code interpreter data from response chunks. |
1415
| [`azure_ai_with_existing_agent.py`](azure_ai_with_existing_agent.py) | Shows how to work with a pre-existing agent by providing the agent ID to the Azure AI chat client. This example also demonstrates proper cleanup of manually created agents. |
Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
# Copyright (c) Microsoft. All rights reserved.
2+
3+
import asyncio
4+
5+
from agent_framework import ChatAgent, CitationAnnotation, HostedWebSearchTool
6+
from agent_framework.azure import AzureAIAgentClient
7+
from azure.identity.aio import AzureCliCredential
8+
9+
"""
10+
This sample demonstrates how to create an Azure AI agent that uses Bing Grounding
11+
search to find real-time information from the web with comprehensive citation support.
12+
It shows how to extract and display citations (title, URL, and snippet) from Bing
13+
Grounding responses, enabling users to verify sources and explore referenced content.
14+
15+
Prerequisites:
16+
1. A connected Grounding with Bing Search resource in your Azure AI project
17+
2. Set BING_CONNECTION_ID environment variable
18+
Example: BING_CONNECTION_ID="your-bing-connection-id"
19+
20+
To set up Bing Grounding:
21+
1. Go to Azure AI Foundry portal (https://ai.azure.com)
22+
2. Navigate to your project's "Connected resources" section
23+
3. Add a new connection for "Grounding with Bing Search"
24+
4. Copy the connection ID and set the BING_CONNECTION_ID environment variable
25+
"""
26+
27+
28+
async def main() -> None:
29+
"""Main function demonstrating Azure AI agent with Bing Grounding search."""
30+
# 1. Create Bing Grounding search tool using HostedWebSearchTool
31+
# The connection ID will be automatically picked up from environment variable
32+
bing_search_tool = HostedWebSearchTool(
33+
name="Bing Grounding Search",
34+
description="Search the web for current information using Bing",
35+
)
36+
37+
# 2. Use AzureAIAgentClient as async context manager for automatic cleanup
38+
async with (
39+
AzureAIAgentClient(credential=AzureCliCredential()) as client,
40+
ChatAgent(
41+
chat_client=client,
42+
name="BingSearchAgent",
43+
instructions=(
44+
"You are a helpful assistant that can search the web for current information. "
45+
"Use the Bing search tool to find up-to-date information and provide accurate, "
46+
"well-sourced answers. Always cite your sources when possible."
47+
),
48+
tools=bing_search_tool,
49+
) as agent,
50+
):
51+
# 3. Demonstrate agent capabilities with web search
52+
print("=== Azure AI Agent with Bing Grounding Search ===\n")
53+
54+
user_input = "What is the most popular programming language?"
55+
print(f"User: {user_input}")
56+
print("Agent: ", end="", flush=True)
57+
58+
# Stream the response and collect citations
59+
citations: list[CitationAnnotation] = []
60+
async for chunk in agent.run_stream(user_input):
61+
if chunk.text:
62+
print(chunk.text, end="", flush=True)
63+
64+
# Collect citations from Bing Grounding responses
65+
for content in getattr(chunk, "contents", []):
66+
annotations = getattr(content, "annotations", [])
67+
if annotations:
68+
citations.extend(annotations)
69+
70+
print()
71+
72+
# Display collected citations
73+
if citations:
74+
print("\n\nCitations:")
75+
for i, citation in enumerate(citations, 1):
76+
print(f"[{i}] {citation.title}: {citation.url}")
77+
if citation.snippet:
78+
print(f" Snippet: {citation.snippet}")
79+
else:
80+
print("\nNo citations found in the response.")
81+
82+
print()
83+
84+
85+
if __name__ == "__main__":
86+
asyncio.run(main())

0 commit comments

Comments
 (0)