1# pylint: disable=line-too-long,useless-suppression
2# ------------------------------------
3# Copyright (c) Microsoft Corporation.
4# Licensed under the MIT License.
5# ------------------------------------
6
7"""
8DESCRIPTION:
9 This sample demonstrates how to use agent operations with the Bing grounding tool from
10 the Azure Agents service using a synchronous client.
11
12USAGE:
13 python sample_agents_bing_grounding.py
14
15 Before running the sample:
16
17 pip install azure-ai-projects azure-ai-agents azure-identity
18
19 Set these environment variables with your own values:
20 1) PROJECT_ENDPOINT - The Azure AI Project endpoint, as found in the Overview
21 page of your Azure AI Foundry portal.
22 2) MODEL_DEPLOYMENT_NAME - The deployment name of the AI model, as found under the "Name" column in
23 the "Models + endpoints" tab in your Azure AI Foundry project.
24 3) BING_CONNECTION_NAME - The name of a connection to the Bing resource as it is
25 listed in Azure AI Foundry connected resources.
26"""
27
28import os
29from azure.ai.projects import AIProjectClient
30from azure.ai.agents.models import MessageRole, BingGroundingTool
31from azure.identity import DefaultAzureCredential
32
33project_client = AIProjectClient(
34 endpoint=os.environ["PROJECT_ENDPOINT"],
35 credential=DefaultAzureCredential(),
36)
37
38# [START create_agent_with_bing_grounding_tool]
39conn_id = project_client.connections.get(os.environ["BING_CONNECTION_NAME"]).id
40
41# Initialize agent bing tool and add the connection id
42bing = BingGroundingTool(connection_id=conn_id)
43
44# Create agent with the bing tool and process agent run
45with project_client:
46 agents_client = project_client.agents
47 agent = agents_client.create_agent(
48 model=os.environ["MODEL_DEPLOYMENT_NAME"],
49 name="my-agent",
50 instructions="You are a helpful agent",
51 tools=bing.definitions,
52 )
53 # [END create_agent_with_bing_grounding_tool]
54
55 print(f"Created agent, ID: {agent.id}")
56
57 # Create thread for communication
58 thread = agents_client.threads.create()
59 print(f"Created thread, ID: {thread.id}")
60
61 # Create message to thread
62 message = agents_client.messages.create(
63 thread_id=thread.id,
64 role=MessageRole.USER,
65 content="How does wikipedia explain Euler's Identity?",
66 )
67 print(f"Created message, ID: {message.id}")
68
69 # Create and process agent run in thread with tools
70 run = agents_client.runs.create_and_process(thread_id=thread.id, agent_id=agent.id)
71 print(f"Run finished with status: {run.status}")
72
73 if run.status == "failed":
74 print(f"Run failed: {run.last_error}")
75
76 # Fetch run steps to get the details of the agent run
77 run_steps = agents_client.run_steps.list(thread_id=thread.id, run_id=run.id)
78 for step in run_steps:
79 print(f"Step {step['id']} status: {step['status']}")
80 step_details = step.get("step_details", {})
81 tool_calls = step_details.get("tool_calls", [])
82
83 if tool_calls:
84 print(" Tool calls:")
85 for call in tool_calls:
86 print(f" Tool Call ID: {call.get('id')}")
87 print(f" Type: {call.get('type')}")
88
89 bing_grounding_details = call.get("bing_grounding", {})
90 if bing_grounding_details:
91 print(f" Bing Grounding ID: {bing_grounding_details.get('requesturl')}")
92
93 print() # add an extra newline between steps
94
95 # Delete the agent when done
96 agents_client.delete_agent(agent.id)
97 print("Deleted agent")
98
99 # Print the Agent's response message with optional citation
100 response_message = agents_client.messages.get_last_message_by_role(thread_id=thread.id, role=MessageRole.AGENT)
101 if response_message:
102 responses = []
103 for text_message in response_message.text_messages:
104 responses.append(text_message.text.value)
105 message = " ".join(responses)
106 for annotation in response_message.url_citation_annotations:
107 message = message.replace(
108 annotation.text, f" [{annotation.url_citation.title}]({annotation.url_citation.url})"
109 )
110 print(f"Agent response: {message}")