Your profile

One profile for every MSDEVBUILD site. Only you can see it, and the site owner if you write in.

Lesson 20 of 30
❮Prev Next❯

Build a Client App for an Agent

Module 2: Microsoft Foundry ⏱ 9 min read Updated

Your note

My notes for this lesson

Select any text in the lesson to highlight it or add a note. Saved in this browser.

    No highlights yet. Select a sentence in the lesson, then pick a colour or add a note.

    All my bookmarks and notes

    Reading settings

    For every lesson, saved in this browser.

    Text size
    Line spacing
    Font

    With IaaS you rent the virtual machine. Microsoft looks after the building, power and hardware; you patch the operating system.

    30-second answer

    A client app for a Foundry agent connects to your project with AIProjectClient and DefaultAzureCredential, creates or reuses an agent with create_version and a PromptAgentDefinition, then gets an OpenAI client bound to the agent with get_openai_client(agent_name=...). It starts a conversation, sends each user message with responses.create, prints output_text, and loops for more turns. The conversation keeps the history, so follow-up questions just work.

    Simulate it » No Azure account needed

    Exam objective: 2.1.5 Create a lightweight client application for an agent. (Skills measured as of April 15, 2026)

    Simulations

    Feel it before you read it. No account needed, nothing leaves this page.

    Azure portal: Call an agent from a Python app Get the agent’s code and hold a two-turn conversation.
    </> Embed

    Embed this simulation

    Free for trainers, teachers and bloggers. Paste this into your page:

    Loading the portal…

    You can create agents in the portal or in code. <strong>create_version</strong> makes a new immutable version each time.

    👆 Click the glowing item in the portal to continue

    Read the steps as text
    1. You can create agents in the portal or in code. create_version makes a new immutable version each time.
    2. The client: get an OpenAI client bound to the agent, create a conversation, and send each turn into it.
    3. Run it. The follow-up works because both turns share one conversation.
    4. Every run appears in Tracing, so you can see which tools the agent used.

    🧪 Simulation for learning. Screens are simplified versions of the Azure portal; names, prices and IDs are examples. Nothing here touches real Azure.

    😟 THE PROBLEM

    Your agent works in the portal but the website can’t talk to it.

    😊 THE SOLUTION

    A small Python client that holds a conversation with the agent.

    • How to reach the agent?✓ get_openai_client(agent_name=…)
    • Follow-ups lose context✓ Conversations
    • Test runs pile up✓ Clean up conversations
    🛠️ Solved with: Agent client

    Start with a question

    Your agent works perfectly in the playground. How do your customers use it?

    Nobody’s going to log in to the Foundry portal to chat with your HR agent. Staff want it inside the intranet page, a Teams bot or a little command-line tool.

    That’s what a client app is for. It’s a few lines of Python that send the user’s message to the agent you built and print the reply, turn after turn.

    Explain it like I’m 10

    The technical explanation

    A client app needs four things: the project endpoint, a credential, the agent’s name, and a conversation to hold the chat history.

    1. Set up

    pip install "azure-ai-projects>=2.3.0" azure-identity
    az login
    # Project endpoint from the project's overview page in the Foundry portal
    export FOUNDRY_PROJECT_ENDPOINT="https://<resource-name>.services.ai.azure.com/api/projects/<project-name>"

    The project client only signs in with Microsoft Entra ID. Locally, DefaultAzureCredential picks up your az login. In Azure, give the app a managed identity with the Foundry User role on the project.

    2. Create (or update) the agent from code

    If you built the agent in the portal you can skip this and just use its name. Doing it in code is handy when you want the definition in source control.

    import os
    from azure.identity import DefaultAzureCredential
    from azure.ai.projects import AIProjectClient
    from azure.ai.projects.models import PromptAgentDefinition
    
    project = AIProjectClient(
        endpoint=os.environ["FOUNDRY_PROJECT_ENDPOINT"],
        credential=DefaultAzureCredential(),
    )
    
    # Each call creates a new, immutable version of "hr-helper"
    agent = project.agents.create_version(
        agent_name="hr-helper",
        definition=PromptAgentDefinition(
            model="gpt-4.1-mini",  # your deployment name, not the model family
            instructions="You are Contoso's HR helper. Answer only HR questions. "
                         "If you don't know, say so and suggest emailing HR.",
        ),
    )
    print(f"Agent {agent.name}, version {agent.version}")

    3. Chat in a loop

    # An OpenAI client that sends every request to the hr-helper agent
    openai = project.get_openai_client(agent_name="hr-helper")
    
    # One conversation = one chat with memory
    conversation = openai.conversations.create()
    
    while True:
        question = input("You: ").strip()
        if question.lower() in ("", "quit", "exit"):
            break
        response = openai.responses.create(
            conversation=conversation.id,
            input=question,
        )
        print("Agent:", response.output_text)
    
    # Clean up the conversation when the chat is over
    openai.conversations.delete(conversation_id=conversation.id)

    Ask “How many casual leave days do I get?” and then “Can I carry them forward?”. The second question only makes sense because the conversation already holds the first one. If you created a fresh conversation inside the loop, the agent would have no idea what “them” means.

    Conversation id

    • Create once with conversations.create()
    • Pass conversation=conversation.id each turn
    • History is stored by the service
    • Best for chat apps

    previous_response_id

    • Pass the id of the last response
    • Chains turns one after another
    • Handy for short, linear exchanges
    • You track the last id yourself
    Two ways to keep turns together

    4. Tidy up

    Test code tends to leave things behind. Delete conversations you don’t need, and if you created an agent version only for a test, delete it too (project.agents.delete_version(...) with the agent name and version). In a real app you’d keep the agent and create it from a deployment script, not every time the app starts.

    Architect level What about Agent Framework?

    For bigger code-first projects Microsoft recommends the Microsoft Agent Framework (agent-framework package), which adds orchestration across several agents, middleware and local tools. For AI-901 the Foundry SDK calls above are enough: a project client, an agent version, a conversation and responses.

    Real-world business scenario

    Logistics

    Fabrikam Logistics

    The problem
    Its shipment-help agent worked well in the Foundry playground, but drivers needed it inside the internal web app they already used on their phones.
    What they used
    A small Python backend that uses AIProjectClient with a managed identity, calls get_openai_client(agent_name='shipment-help'), and keeps one conversation per driver session.
    Why that choice
    No keys to store or rotate, the agent's instructions and tools stay managed in Foundry, and the conversation id gives drivers natural follow-up questions.
    The result
    Drivers asked follow-ups like 'and the one after that?' without repeating themselves, and the team updated instructions in Foundry without redeploying the app.

    When to use it and when not to

    ✓ Use it when…

    • You've tested an agent in the portal and need it inside your own app, bot or script.
    • You want the agent definition in source control and created by a script.
    • Users ask follow-up questions, so the chat needs memory.

    ✕ Think twice when…

    • You only need one-off answers with no tools. A plain responses call to a model deployment is simpler.
    • Creating a new agent version every time the app starts. Reference it by name instead.

    ↔ Alternatives to consider

    • Microsoft Agent Framework for multi-agent, code-first solutions.
    • Publishing the agent to Microsoft Teams or Microsoft 365 Copilot when users live there.
    Ready for more?The full lesson adds the technical explanation, when to use it, interview questions and revision notes.

    Test yourself with exercises

    5 original practice questions in the AI-901 style. Pick your answers, then check them. You will see why each option is right or wrong. Score 75% or more and this topic is marked complete.

    Question 1

    Question 1 of 5

    You are writing a Python client application for an agent in a Microsoft Foundry project. Which class should you use to connect to the project?

    Question 2

    Question 2 of 5

    A client application sends a user's first question to an agent. The user then asks a follow-up question that refers to the first answer, but the agent responds as if it has no context.

    What should you change in the application?

    Question 3

    Question 3 of 5 · Select 2

    Which TWO statements about authenticating AIProjectClient are true?

    Question 4

    Question 4 of 5

    Which method creates an agent, or a new version of an existing agent, from Python code by using the Foundry SDK?

    Question 5

    Question 5 of 5

    In a PromptAgentDefinition, what value should you provide for the model parameter?

    Interview preparation

    Say your answer out loud first, then open the model answer. Interviewers care more about your reasoning than the exact words.

    Beginner How does a Python app talk to an agent you built in the Foundry portal?

    Model answer

    It connects to the project endpoint with AIProjectClient and DefaultAzureCredential, then calls get_openai_client with the agent's name. From there it's a normal responses.create call, and the agent answers using its own instructions and tools.

    Interviewer follows up

    Do you need an API key?

    You

    No. The project client only supports Microsoft Entra ID. Locally I run az login; in Azure the app uses a managed identity with the Foundry User role.

    Intermediate How do you make the agent remember the previous question?

    Model answer

    I create a conversation once with conversations.create and pass its id to every responses.create call. The service stores the history, so I don't resend earlier messages myself. Passing previous_response_id is another way to chain turns.

    Experienced developer Should your app create the agent every time it starts?

    Model answer

    Usually not in production. The agent is a project resource, so I'd create or update it from a deployment script, and the app just references it by name. Creating a version on every start clutters the version history and makes it harder to know which instructions users actually got.

    Scenario The app works on your laptop but fails with an authorization error in Azure. What's wrong?

    Model answer

    Most likely the app's managed identity hasn't been given a role on the Foundry project. I'd assign it the Foundry User role on the project and make sure FOUNDRY_PROJECT_ENDPOINT is set in the app settings.

    Quick revision

    Key points

    • Install azure-ai-projects (2.x) and azure-identity, then sign in with az login.
    • Connect with AIProjectClient(endpoint=..., credential=DefaultAzureCredential()).
    • Create an agent version with project.agents.create_version and a PromptAgentDefinition.
    • Get an agent-bound client with project.get_openai_client(agent_name=...).
    • Create one conversation and pass its id to every responses.create call for multi-turn chat.

    Important terminology

    AIProjectClient
    The Foundry SDK client that connects to a project endpoint and gives you agents, deployments and an OpenAI client.
    PromptAgentDefinition
    The SDK object that describes a prompt agent, with its model deployment, instructions and tools.
    create_version
    The SDK method that creates an agent, or a new immutable version of an existing agent with the same name.
    Conversation
    A server-side thread that stores the messages and responses of one chat, so the agent remembers earlier turns.
    DefaultAzureCredential
    An Azure Identity credential that signs in with whatever is available, such as az login locally or a managed identity in Azure.

    Common mistakes

    • Starting a new conversation for every message, so the agent forgets the last turn.
    • Trying to authenticate the project client with an API key. It only supports Microsoft Entra ID.

    Exam tips

    • "Keep context across turns" = reuse the same conversation id.
    • "Connect to a Foundry project from code" = AIProjectClient with the project endpoint.
    • "Each update makes a new snapshot" = agent versions from create_version.

    Five quick revision questions

    1. 1.Which pip package holds AIProjectClient?Show

      azure-ai-projects

    2. 2.Which credential does the sample use?Show

      DefaultAzureCredential (Microsoft Entra ID).

    3. 3.Which method creates an agent or a new version of it?Show

      project.agents.create_version

    4. 4.What do you pass to keep a multi-turn chat together?Show

      The same conversation id on each responses.create call.

    5. 5.Which property holds the agent's reply text?Show

      response.output_text

    Official references

    Finished this lesson? Tick it off. Your progress is saved in this browser.

    Next up: Build a Text Analysis App

    Studying with a friend? Send them this lesson

    It's free and needs no sign-up. Their progress saves in their own browser.

    Lesson done? Make it stick with a quick gameSort It, Match the Pairs, Lightning Round and Who Am I? Earn XP and badges. Play ❯

    Install MSDEVBUILD Azure

    Free · no account · works offline

    Save the whole course for offline ›

    Hi, I’m your Nimbus

    Your study buddy. Pick what we do next.

    MSDEVBUILD · Multi-Stack Dev Build

    Sign in to MSDEVBUILD

    One account for Azure certifications and the blog: sign in here and you are signed in on both. Your XP, streak, practice deck and certificate stay in sync on every device. Optional: everything works without an account.