How can I access AI Foundry Agents in Python application with API Key

Venkateswaran Mrithinjayan 20 Reputation points
2025-08-30T13:31:54.2166667+00:00

I have created an agent for Azure Bing search with grounding. How do I access the agent created in Azure Foundry with API Key in a python app

Screenshot 2025-08-30 185624

Screenshot 2025-08-30 184121

Screenshot 2025-08-30 183912

Azure AI services
Azure AI services
A group of Azure services, SDKs, and APIs designed to make apps more intelligent, engaging, and discoverable.
0 comments No comments
{count} votes

Answer accepted by question author
  1. Aryan Parashar 3,685 Reputation points Microsoft External Staff Moderator
    2025-09-01T05:13:46.8533333+00:00

    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:

    https://learn.microsoft.com/en-us/azure/ai-foundry/agents/how-to/tools/bing-code-samples?pivots=python

    Feel free to accept this as an answer.

    Thank you for reaching out to the Microsoft Q&A Portal.

    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.