Lesson 39 of 39 · Production
Project: Bike Shop Support Desk
Build a complete support desk with Microsoft Agent Framework: tools, sessions, staff approvals, a triage workflow and evaluations, ready for production.
- 10 min read
- Intermediate
- Reviewed
- Plan an agent system from a business brief
- Build tools with @tool, including one that needs a staff member's approval
- Run a multi-turn rental desk with an AgentSession
- Route questions to the right agent with a WorkflowBuilder triage workflow
- Test the desk with evaluations and plan the path to production
The brief
Velo rents e-bikes in Porto, and its support inbox is overflowing. The owner wants a support desk that:
- Answers prices and free bikes from real shop data, never from guesses.
- Books bikes, but only after a staff member approves each booking.
- Remembers the conversation, so customers don't repeat themselves.
- Sends repair and safety questions to a separate repair desk.
- Is tested before launch, and ready for the production checklist.
This project uses what you learned across the course: tools, approvals, sessions, workflows and evaluations. Here is its design in plain Python first:
# The support desk's design in plain Python: route, answer with tools, and ask a person before booking.
PRICES = {"City E": 35, "Trail X": 50}
log = []
def route(text):
return "repairs" if any(word in text.lower() for word in ("brake", "flat", "chain")) else "rentals"
def rentals(text, approve):
if "book" in text.lower():
return "Booked a City E." if approve("book_bike City E") else "No booking made."
model = next((model for model in PRICES if model in text), "City E")
return f"A {model} costs {PRICES[model]} EUR a day."
def repairs(text, approve):
return "Please don't ride it. Bring it in for a free check."
def desk(text, approve=lambda action: True):
team = route(text)
answer = {"rentals": rentals, "repairs": repairs}[team](text, approve)
log.append((team, text))
return f"{team}: {answer}"
print(desk("How much is a Trail X?"))
print(desk("My chain fell off."))
print(desk("Book a City E for tomorrow.", approve=lambda action: False))
print(len(log), "requests logged")Step 1: the shop's tools
Tools give the agent real data and real actions. Put them in their own file, shop.py, so every part of the project can share them:
from agent_framework import tool
PRICES = {"City E": 35, "Trail X": 50, "Kids 20": 15} # EUR a day
FREE = {"Ribeira": {"City E": 3, "Trail X": 0}, "Boavista": {"City E": 1, "Trail X": 2}}
BOOKINGS: list[dict] = []
@tool
def bike_price(model: str) -> str:
"""Daily rental price of one Velo bike model."""
if model not in PRICES:
return f"Unknown model {model}. Models: {', '.join(PRICES)}."
return f"{model}: {PRICES[model]} EUR a day."
@tool
def bikes_free(station: str) -> str:
"""Free bikes at one Velo station in Porto."""
if station not in FREE:
return f"Unknown station {station}. Stations: {', '.join(FREE)}."
return ", ".join(f"{model}: {count} free" for model, count in FREE[station].items())
@tool(approval_mode="always_require")
def book_bike(customer: str, model: str, station: str, day: str) -> str:
"""Book a bike for a customer. A staff member approves every booking."""
BOOKINGS.append({"customer": customer, "model": model, "station": station, "day": day})
return f"Booked a {model} at {station} for {customer}, {day}. Booking B-{1040 + len(BOOKINGS)}."@toolturns each function into a tool; the docstring tells the model when to use it.book_bikehasapproval_mode="always_require", so a booking never happens without a person (requirement 2).- Unknown models and stations return a helpful message instead of crashing, so the model can recover.
In a real shop, these functions would read your booking database; the dictionaries stand in for it.
Step 2: the rental desk
The desk is an Agent with the three tools. A AgentSession per customer keeps the conversation (requirement 3), and the chat() helper handles approval requests, as in the tool approval lesson:
import asyncio
from agent_framework import Agent, AgentSession, Message
from agent_framework.openai import OpenAIChatClient
from shop import bike_price, bikes_free, book_bike
INSTRUCTIONS = """You are Velo's rental desk in Porto. Be brief and friendly.
Use the tools for prices, free bikes and bookings. Never guess a price."""
async def chat(desk: Agent, session: AgentSession, text: str) -> str:
response = await desk.run(text, session=session)
while response.user_input_requests: # bookings wait for a staff member
answers = []
for request in response.user_input_requests:
call = request.function_call
print(f" [staff approves {call.name}: {call.parse_arguments()}]")
answers.append(request.to_function_approval_response(approved=True))
response = await desk.run(Message("user", answers), session=session)
return response.text
async def main():
desk = Agent(
client=OpenAIChatClient(model="MODEL_NAME"),
name="rental_desk",
instructions=INSTRUCTIONS,
tools=[bike_price, bikes_free, book_bike],
)
session = AgentSession(session_id="chat-asha") # one session per customer conversation
for text in ["Hi, I'm Asha. How much is a City E?",
"Are there free City E bikes at Ribeira?",
"Great, book one for me there tomorrow."]:
print("Asha:", text)
print("Desk:", await chat(desk, session, text))
asyncio.run(main())Asha: Hi, I'm Asha. How much is a City E?
Desk: A City E costs 35 EUR a day.
Asha: Are there free City E bikes at Ribeira?
Desk: Yes: Ribeira has 3 City E bikes free right now.
Asha: Great, book one for me there tomorrow.
[staff approves book_bike: {'customer': 'Asha', 'model': 'City E', 'station': 'Ribeira', 'day': 'tomorrow'}]
Desk: Done! Booked a City E at Ribeira for Asha, tomorrow. Booking B-1041. Have a great ride, Asha.The desk used bike_price and bikes_free for its facts, remembered Asha's name and bike across turns, and booked only after the staff approval. In your app, the approval is a button in a staff dashboard instead of the automatic approved=True used here.
Step 3: triage with a workflow
Repair and safety questions need different instructions, and later perhaps different tools. A WorkflowBuilder workflow routes each question with a switch-case edge group (requirement 4):
import asyncio
from agent_framework import Agent, Case, Default, WorkflowBuilder, WorkflowContext, executor
from agent_framework.openai import OpenAIChatClient
REPAIR_WORDS = ("brake", "flat", "chain", "broken", "repair")
@executor(id="triage")
async def triage(text: str, ctx: WorkflowContext[str]) -> None:
await ctx.send_message(text) # pass the question on, unchanged
def needs_repair(text: str) -> bool:
return any(word in text.lower() for word in REPAIR_WORDS)
async def main():
client = OpenAIChatClient(model="MODEL_NAME")
rentals = Agent(client=client, name="rentals",
instructions="You are Velo's rental desk in Porto. A City E costs 35 EUR a day.")
repairs = Agent(client=client, name="repairs",
instructions="You are Velo's repair desk. Give one safety tip, then offer a free check.")
workflow = (
WorkflowBuilder(start_executor=triage, output_from=[rentals, repairs])
.add_switch_case_edge_group(triage, [
Case(condition=needs_repair, target=repairs), # repairs first
Default(target=rentals), # everything else
])
.build()
)
for text in ["How much does a City E cost?", "The brake on my rental feels loose."]:
result = await workflow.run(text)
answer = result.get_outputs()[0]
print(f"{answer.messages[-1].author_name}: {answer.text}")
asyncio.run(main())rentals: A City E costs 35 EUR a day. repairs: Please don't ride with a loose brake. Bring the bike to any Velo station for a free check today.
The triage step here is a keyword check: fast, free and easy to test. When questions get harder to sort, replace it with a small classifier agent that returns a category with structured output, and keep the same edges.
Step 4: test before you ship
Requirement 1 says prices must come from the tool. An evaluation checks exactly that, with expected tool calls and a keyword check (requirement 5):
import asyncio
from agent_framework import Agent, ExpectedToolCall, LocalEvaluator, evaluate_agent, keyword_check, tool_calls_present
from agent_framework.openai import OpenAIChatClient
from shop import bike_price, bikes_free
async def main():
desk = Agent(
client=OpenAIChatClient(model="MODEL_NAME"),
name="rental_desk",
instructions="You are Velo's rental desk in Porto. Use the tools for prices. Never guess a price.",
tools=[bike_price, bikes_free],
)
results = await evaluate_agent(
agent=desk,
queries=["How much is a City E?", "How much is a Trail X?"],
expected_tool_calls=[
[ExpectedToolCall("bike_price", {"model": "City E"})],
[ExpectedToolCall("bike_price", {"model": "Trail X"})],
],
evaluators=LocalEvaluator(keyword_check("EUR"), tool_calls_present),
)
report = results[0]
print(f"{report.passed} of {report.total} passed")
for item in report.items:
print(f"{item.input_text} -> {item.status}")
asyncio.run(main())2 of 2 passed How much is a City E? -> pass How much is a Trail X? -> pass
Grow this list with every real question that once went wrong, and run it in CI with raise_for_status(), as in the evaluations lesson. A failing check then stops a bad prompt or model change before customers see it.
Step 5: make it production-ready
Go through the production checklist with the desk in mind:
| Need | Add | Lesson |
|---|---|---|
| Conversations that survive restarts | FileHistoryProvider or RedisHistoryProvider, and a session store | History Providers and Storage |
| A refund tool with a limit | function middleware that blocks large refunds | Middleware |
| Customer reviews or emails as input | SecureAgentConfig, so injected text can't trigger bookings | Security |
| Traces and costs | configure_otel_providers() and usage_details per request | Observability, Production Checklist |
| A web chat | an AG-UI endpoint, or ResponsesHostServer in a container | Hosting |
| Long jobs, such as weekly reports | a background agent or a durable orchestration | Background Agents, Hosting |
Your turn. Extend the project: add a refund tool with a refund-limit middleware, store sessions with FileSessionStore, and put the desk behind an AG-UI endpoint. Each step reuses a lesson you've done.
Common mistakes
Grow the desk's triage: route each message to the first matching team, so safety always comes before repairs and refunds.
RULES = [
("safety", ("accident", "hurt", "injured")),
("repairs", ("brake", "flat", "chain")),
("refunds", ("refund", "charged twice")),
]
def route(text):
# Check the RULES in order and return the first team with a matching word.
# Ignore upper and lower case. If nothing matches, return "rentals".
return "rentals"
for text in ["I had an accident and my brake is broken.", "Flat tyre at Ribeira.",
"I was charged twice, please refund me.", "How much is a City E?"]:
print(route(text), "<-", text)
Why does book_bike require a staff approval while bike_price doesn't?
Summary
- Start from requirements you can test, then build in small steps: tools, agent, workflow, evaluations.
@toolfunctions give the desk real data;approval_mode="always_require"keeps a person in charge of bookings.- An
AgentSessionper customer keeps the conversation, and approvals resume in the same session. - A
WorkflowBuildertriage routes repair questions to their ownAgent, with a default route for everything else. - Evaluations prove the requirements, and the production checklist tells you what to add before launch.
This is the last lesson of the course. Congratulations: you can now build, test and ship agents with Microsoft Agent Framework.
Finished reading? Tick it off to track your progress.