Velamuvi AIAcademy

Lesson 3 of 39 · Getting Started

Your First Agent

Build your first Microsoft Agent Framework agent: instructions, name and description, agent.run in async Python, reading AgentResponse, token usage and options.

  • 10 min read
  • Intermediate
  • Reviewed
In this lesson you will learn
  • Create an Agent from a chat client, with a name, description and instructions
  • Run it with await agent.run() inside an async program
  • Read the AgentResponse: text, messages, finish reason and token usage
  • Set default options for every run and override them for one run
  • Explain why separate runs don't remember each other, and what SupportsAgentRun is

An agent is a client plus a job description

In the last lesson you sent messages to a model through a chat client. An agent wraps a chat client and adds everything that makes the model behave like a dedicated helper: its instructions (the job description), its tools, its memory and its middleware.

This lesson builds a shop assistant for Velo, a small bike shop in Porto, which you'll extend throughout the course.

The smallest agent

import asyncio
from agent_framework import Agent
from agent_framework.openai import OpenAIChatClient

async def main():
    agent = Agent(
        client=OpenAIChatClient(model="MODEL_NAME"),
        name="velo_assistant",
        description="Answers questions about the Velo bike shop.",
        instructions=(
            "You work at Velo, a small bike shop in Porto. "
            "Opening hours: Monday to Saturday, 9:00 to 18:00. "
            "Answer in at most two sentences."
        ),
    )
    response = await agent.run("Are you open on Sunday?")
    print(response)                     # printing a response prints its text

asyncio.run(main())
Output
Sorry, we're closed on Sundays. We're open Monday to Saturday from 9:00 to 18:00.

What each argument does:

ArgumentMeaning
clientThe chat client: which provider and model answers
instructionsThe job description, sent with every run. The most important text you'll write for an agent
nameA short identifier, used in logs, traces and multi-agent systems. Letters, digits and underscores are safest
descriptionOne sentence saying what the agent is for. Other agents and orchestrators read it to decide when to call this one
idA unique ID. If you don't give one, a random one is created

Good instructions say who the agent is, what it knows (opening hours, prices, rules), what it must not do, and how to answer (length, tone, language). The model sees them before every question.

Async in two minutes

Calling a model takes time, often a few seconds. Agent Framework is asynchronous so that your program can do other work, or run several agents at once, while it waits:

  • async def main(): defines a function that can wait for slow work.
  • await agent.run(...) starts the call and pauses main until the answer arrives.
  • asyncio.run(main()) starts the whole thing from normal Python code.

The rule to remember: you can only use await inside an async def function. In a Jupyter notebook, which already runs an event loop, write await agent.run(...) directly in a cell instead of using asyncio.run.

What happens inside run()

Here is the core of agent.run() in plain Python, with a pretend client:

Try it yourselfPython
# What agent.run() does, in plain Python: wrap your text in a message, send it to the chat
# client together with the agent's instructions and options, and wrap the reply in a response.
class FakeChatClient:                               # stands in for OpenAIChatClient and friends
    def get_response(self, messages, options):
        question = messages[-1]["text"]
        reply = f"({options['instructions']}) Short answer to: {question}"
        return {"role": "assistant", "text": reply, "input_tokens": 12, "output_tokens": len(reply.split())}

class TinyAgent:
    def __init__(self, client, name, instructions, default_options=None):
        self.client, self.name = client, name
        self.instructions = instructions
        self.default_options = default_options or {}

    def run(self, text, options=None):
        messages = [{"role": "user", "text": text}]                       # 1. your text becomes a message
        merged = {**self.default_options, **(options or {}), "instructions": self.instructions}  # 2. options
        reply = self.client.get_response(messages, merged)                 # 3. one call to the model
        return {"text": reply["text"], "messages": [reply],                # 4. a response object
                "usage": reply["input_tokens"] + reply["output_tokens"]}

agent = TinyAgent(FakeChatClient(), "velo_assistant", "Be brief", {"temperature": 0.9})
response = agent.run("Are you open on Sunday?")
print(response["text"])
print("tokens used:", response["usage"])

The real Agent does the same four steps, plus much more around them: tools, memory, middleware and telemetry, which later lessons add one at a time. The instructions aren't added to your messages; they travel alongside them as the instructions option, and each chat client puts them where its provider expects them.

Reading the response

agent.run() returns an AgentResponse:

import asyncio
from agent_framework import Agent, AgentResponse, UsageDetails
from agent_framework.openai import OpenAIChatClient

async def main():
    agent = Agent(client=OpenAIChatClient(model="MODEL_NAME"), name="velo_assistant",
                  instructions="You work at Velo, a bike shop in Porto. Be brief.")
    print("agent:", agent.name, "| id:", agent.id[:8] + "...")

    response: AgentResponse = await agent.run("Do you rent e-bikes?")
    print("text:", response.text)
    print("messages:", [(message.role, message.author_name) for message in response.messages])
    print("finish reason:", response.finish_reason, "| response id:", response.response_id)
    usage: UsageDetails = response.usage_details
    print("tokens:", usage["input_token_count"], "in +", usage["output_token_count"], "out =", usage["total_token_count"])

asyncio.run(main())
Output
agent: velo_assistant | id: 3f2b9c1e...
text: Yes: e-bikes are 35 EUR a day, and booking a day ahead is a good idea.
messages: [('assistant', 'velo_assistant')]
finish reason: stop | response id: resp_68a1f0c2
tokens: 41 in + 19 out = 60
FieldWhat it holds
textAll the text of the reply. print(response) prints this too
messagesThe messages the agent produced in this run: the final answer, and with tools also the tool calls and results. Each has a role and an author_name (the agent's name)
finish_reasonWhy the model stopped: stop (finished normally), length (hit max_tokens), tool_calls or content_filter
usage_detailsToken counts as a UsageDetails dictionary: input_token_count, output_token_count, total_token_count, and when the provider reports them, cached and reasoning tokens
response_idThe provider's ID for this response, useful when reporting a problem
valueThe parsed result when you ask for structured output (lesson Structured Output)

Token counts are how providers bill you, so usage_details is the first place to look when a bill is higher than expected.

Default options and per-run options

import asyncio
from agent_framework import Agent
from agent_framework.openai import OpenAIChatClient

async def main():
    agent = Agent(
        client=OpenAIChatClient(model="MODEL_NAME"),
        instructions="You write short, catchy slogans for a bike shop.",
        default_options={"temperature": 0.9, "max_tokens": 40},    # used by every run
    )
    playful = await agent.run("A slogan for our e-bike rentals")
    steady = await agent.run("A slogan for our e-bike rentals", options={"temperature": 0.0})  # this run only
    print("temperature 0.9:", playful.text)
    print("temperature 0.0:", steady.text)

asyncio.run(main())
Output
temperature 0.9: Hills? What hills? Rent an e-bike at Velo.
temperature 0.0: Ride further with less effort: rent an e-bike at Velo.
  • default_options is a ChatOptions dictionary used by every run of this agent.
  • options= on run() applies to one run. Its keys replace the defaults with the same name and keep the rest, so the second run used temperature 0.0 and still max_tokens 40.
  • options={"instructions": "..."} adds extra instructions for one run, after the agent's own.

Every run starts fresh

import asyncio
from agent_framework import Agent
from agent_framework.openai import OpenAIChatClient

async def main():
    agent = Agent(client=OpenAIChatClient(model="MODEL_NAME"), instructions="You are a friendly assistant.")
    print((await agent.run("Hi! My name is Ana.")).text)
    print((await agent.run("What's my name?")).text)      # a separate run: the agent has forgotten

asyncio.run(main())
Output
Nice to meet you, Ana!
I'm sorry, I don't know your name. Could you tell me?

Each agent.run() call without a session is a separate conversation: the model only sees that run's messages and the instructions. To hold a conversation, you pass the same session to each run, which is the subject of the lesson Sessions and Multi-Turn Chat.

Any agent works the same way

import asyncio
from agent_framework import Agent, SupportsAgentRun
from agent_framework.openai import OpenAIChatClient

async def ask(agent: SupportsAgentRun, question: str) -> str:
    """Works with any agent: Agent, a remote agent, or your own class."""
    response = await agent.run(question)
    return f"{agent.name}: {response.text}"

async def main():
    client = OpenAIChatClient(model="MODEL_NAME")              # one client, shared by two agents
    mechanic = Agent(client=client, name="mechanic", instructions="You fix bikes. One sentence.")
    guide = Agent(client=client, name="guide", instructions="You suggest bike routes in Porto. One sentence.")
    print(isinstance(mechanic, SupportsAgentRun))
    for agent in [mechanic, guide]:
        print(await ask(agent, "What should I do this weekend?"))

asyncio.run(main())
Output
True
mechanic: Give your bike a quick check: tyre pressure, brakes and a drop of chain oil.
guide: Ride the riverside path from Ribeira to Foz and stop for lunch by the sea.

SupportsAgentRun is the protocol for agents: anything with an id, name, description and the methods run, create_session and get_session qualifies, without inheriting from a framework class. Write your helper functions against SupportsAgentRun and they'll work with Agent, with the hosted and remote agents in the lesson Other Agent Types, and with workflows turned into agents.

One client can serve many agents: create it once and share it, as above.

Common mistakes

Practice exercise

Work out which options a run really uses.

Your solutionPython
default_options = {"temperature": 0.9, "max_tokens": 40}    # given to Agent(...)
run_options = {"temperature": 0.0, "seed": 7}                # given to agent.run(...)

# Combine them like Agent Framework does: start from the defaults, and let the run's
# options replace or add keys. Print each key and value as "key=value", sorted by key.
Knowledge check

An agent has default_options={'temperature': 0.9, 'max_tokens': 40}. You call agent.run('Hi', options={'temperature': 0.2}). Which options does that run use?

Summary

  • An Agent is a chat client plus instructions, a name, a description and an id; tools, memory and middleware come later.
  • Run it with await agent.run(...) inside async def main(), started by asyncio.run(main()).
  • An AgentResponse has the text, the messages, the finish_reason and the token counts in usage_details.
  • default_options apply to every run; options= on run() overrides them for one run.
  • Runs without a session don't remember each other. SupportsAgentRun describes every kind of agent.

Next: Messages, Content and Streaming.

Finished reading? Tick it off to track your progress.