Hi Venkateswaran,
AI Foundry Agents cannot be accessed by API keys.
You can use Entra ID authentication to access them in your python application.
Here is the supported documentation:
https://learn.microsoft.com/en-us/python/api/overview/azure/ai-agents-readme?view=azure-python
Below is a example code snippet for creating and using an agent with a Bing grounding resource:
import asyncio
import os
from azure.identity.aio import DefaultAzureCredential
from semantic_kernel.agents import AzureAIAgent, AzureAIAgentThread
from azure.ai.agents.models import BingGroundingTool
from azure.core.exceptions import ResourceNotFoundError
AGENT_NAME = "MyAgent"
ENDPOINT = "<YOUR_PROJECT_ENDPOINT>"
DEPLOYMENT_NAME = "<YOUR_MODEL_DEPLOYMENT_NAME>"
GROUNDING_CONNECTION_NAME = "<YOUR_GROUNDING_CONNECTION_NAME>"
os.environ["AZURE_AI_AGENT_ENDPOINT"] = ENDPOINT
os.environ["AZURE_AI_AGENT_MODEL_DEPLOYMENT_NAME"] = DEPLOYMENT_NAME
async def run_agent_by_name():
try:
async with (
DefaultAzureCredential() as creds,
AzureAIAgent.create_client(credential=creds) as client,
):
print("Client initialized.")
found_agent = None
print(f"Looking for agent with name: {AGENT_NAME}")
async for agent in client.agents.list_agents():
if agent.name == AGENT_NAME:
found_agent = agent
break
if not found_agent:
print(f"No agent found with name '{AGENT_NAME}', creating a new one...")
grounding_connection = await client.connections.get(
name=GROUNDING_CONNECTION_NAME
)
conn_id = grounding_connection.id
bing_tool = BingGroundingTool(connection_id=conn_id)
new_agent_def = {
"name": AGENT_NAME,
"model": DEPLOYMENT_NAME,
"instructions": "You are a helpful AI agent. Use Bing Search grounding to fetch real-time information.",
"tools": bing_tool.definitions,
}
found_agent = await client.agents.create_agent(new_agent_def)
print(f"Created new agent '{AGENT_NAME}' with ID: {found_agent.id}")
else:
print(f"Found agent '{AGENT_NAME}' with ID: {found_agent.id}")
agent_definition = await client.agents.get_agent(found_agent.id)
agent = AzureAIAgent(client=client, definition=agent_definition)
print("Azure AI Agent initialized successfully. New conversation thread created. Conversation started.")
thread = AzureAIAgentThread(client=client)
user_input = "What is the temperature and time in Seattle now?"
print(f"Sending message: {user_input}")
try:
response = await asyncio.wait_for(
agent.get_response(messages=user_input, thread=thread),
timeout=60,
)
print("\nAgent response raw:")
print(response)
if hasattr(response, "message"):
print("\nAgent response content:")
print(response.message.content)
except asyncio.TimeoutError:
print("Error: The request to the agent timed out.")
except Exception as e:
import traceback
print("An unexpected error occurred:", str(e))
print("Message:", str(e))
traceback.print_exc()
finally:
pass
if __name__ == "__main__":
asyncio.run(run_agent_by_name())
Documentation to use Grounding with Bing Search:
Feel free to accept this as an answer.
Thank you for reaching out to the Microsoft Q&A Portal.