Lesson 7 of 39 · Tools
Tool Approval and User Input
Make Agent Framework tools wait for a person: approval_mode, approving or rejecting calls, resuming the run, auto-approval rules and ToolApprovalMiddleware.
- 13 min read
- Intermediate
- Reviewed
- Make a tool wait for a person's approval with approval_mode
- Read the approval requests in a response, approve or reject them, and resume the run
- Approve safe calls automatically with ToolApprovalMiddleware and approval rules
- Let users answer “always allow” for a tool, or for one exact call
- Handle other requests for the user, including UserInputRequiredException
Why some tools need a person
In the last lesson, the model called tools whenever it liked. That's fine for looking up a price, but not for refunding money, sending emails or deleting files. The model can misunderstand a request, or a cleverly written message can trick it into calling a tool it shouldn't (prompt injection, covered in the lesson Security: Prompt Injection and Governance).
The idea in plain Python:
# Tool approval in plain Python: calls to a risky tool wait until a person decides.
pending = [
{"tool": "refund_order", "args": {"order_id": "1042", "amount_eur": 35.0}},
{"tool": "refund_order", "args": {"order_id": "2001", "amount_eur": 480.0}},
]
decisions = {"1042": True, "2001": False} # the person's answers: approve or reject
def refund_order(order_id, amount_eur):
return f"Refunded {amount_eur} EUR for order {order_id}."
for call in pending:
if decisions[call["args"]["order_id"]]:
result = refund_order(**call["args"]) # the tool runs only after a yes
else:
result = "Error: Tool call invocation was rejected by user." # what the model is told
print(f"{call['tool']} {call['args']['order_id']}: {result}")The rejected call never runs. The model is told it was rejected, so it can explain that to the customer instead of pretending it worked.
Requiring approval: approval_mode
Add approval_mode="always_require" to the tool. The default is "never_require".
import asyncio
from agent_framework import Agent, tool
from agent_framework.openai import OpenAIChatClient
@tool(approval_mode="always_require") # a person must approve every call
def refund_order(order_id: str, amount_eur: float) -> str:
"""Refund a customer's order. Use only when the customer asks for a refund."""
return f"Refunded {amount_eur} EUR for order {order_id}."
async def main():
agent = Agent(client=OpenAIChatClient(model="MODEL_NAME"), instructions="You are Velo's support assistant.",
tools=[refund_order])
session = agent.create_session() # keeps the waiting call between runs
response = await agent.run("Please refund order 1042, the 35 EUR helmet.", session=session)
print("text:", repr(response.text))
for request in response.user_input_requests:
call = request.function_call # the call that is waiting
print(request.type, "->", call.name, call.parse_arguments())
asyncio.run(main())text: ''
function_approval_request -> refund_order {'order_id': '1042', 'amount_eur': 35.0}- The run stops before the tool runs. There's no answer text yet.
response.user_input_requestslists everything that waits for a person. Here it holds onefunction_approval_requestcontent.request.function_callis the planned call:name,arguments(JSON text) andparse_arguments()(a dictionary). Show these to the person, so they know exactly what they approve.- A session (
AgentSession) keeps a conversation's state between runs;agent.create_session()makes one. Approvals need it, because the waiting call is stored there. The lesson Sessions and Multi-Turn Chat covers sessions in full.
Approving or rejecting, then resuming
To continue, turn each request into a response with request.to_function_approval_response(approved=...) and send the responses back in a user message, in the same session:
import asyncio
from agent_framework import Agent, Message, tool
from agent_framework.openai import OpenAIChatClient
@tool(approval_mode="always_require")
def refund_order(order_id: str, amount_eur: float) -> str:
"""Refund a customer's order. Use only when the customer asks for a refund."""
return f"Refunded {amount_eur} EUR for order {order_id}."
async def main():
agent = Agent(client=OpenAIChatClient(model="MODEL_NAME"), instructions="You are Velo's support assistant.",
tools=[refund_order])
session = agent.create_session()
response = await agent.run("Please refund order 1042, the 35 EUR helmet.", session=session)
while response.user_input_requests: # the model may ask for more calls later
answers = []
for request in response.user_input_requests:
call = request.function_call
ok = input(f"Allow {call.name} {call.arguments}? (y/n) ") == "y"
answers.append(request.to_function_approval_response(approved=ok))
response = await agent.run(Message("user", answers), session=session) # the SAME session
print(response.text)
asyncio.run(main())Allow refund_order {"order_id": "1042", "amount_eur": 35.0}? (y/n) y
Done: order 1042 is refunded, 35 EUR. The money reaches your account in 3 to 5 working days.With a n, the tool doesn't run. The model receives Error: Tool call invocation was rejected by user. as the tool's result and answers accordingly:
Allow refund_order {"order_id": "1042", "amount_eur": 35.0}? (y/n) n
I'm sorry, I couldn't refund order 1042. A colleague will review your request and contact you.approved=Trueruns the tool with the arguments shown in the request;approved=Falseskips it.- After the tool has run, the model continues. It may call another tool that needs approval, so the code checks
user_input_requestsin a loop. - If the model asks for several calls in one turn, each call that needs approval gets its own request. Answer them all in one message. Calls in the same turn that need no approval wait, and run when you resume.
- With
stream=True, the request arrives as an update; readuser_input_requestsfromawait stream.get_final_response().
Approval rules with ToolApprovalMiddleware
Asking a person for every call is safe but slow. ToolApprovalMiddleware adds rules that approve some calls automatically. Middleware is code that runs around every agent run; the lesson Middleware explains it in detail.
import asyncio
from agent_framework import Agent, Content, ToolApprovalMiddleware, tool
from agent_framework.openai import OpenAIChatClient
@tool(approval_mode="always_require")
def refund_order(order_id: str, amount_eur: float) -> str:
"""Refund a customer's order. Use only when the customer asks for a refund."""
return f"Refunded {amount_eur} EUR for order {order_id}."
def small_refund(function_call: Content) -> bool:
"""An approval rule: refunds of 20 EUR or less need no person."""
arguments = function_call.parse_arguments()
return function_call.name == "refund_order" and arguments["amount_eur"] <= 20
async def main():
agent = Agent(
client=OpenAIChatClient(model="MODEL_NAME"),
instructions="You are Velo's support assistant.",
tools=[refund_order],
middleware=[ToolApprovalMiddleware(auto_approval_rules=[small_refund])],
)
session = agent.create_session() # the middleware needs a session
small = await agent.run("Refund order 1042, the 12 EUR bottle cage.", session=session)
print(small.text, "| waiting:", len(small.user_input_requests))
big = await agent.run("Also refund order 2001, the 480 EUR wheel set.", session=session)
print(repr(big.text), "| waiting:", len(big.user_input_requests))
asyncio.run(main())Done: order 1042 is refunded (12 EUR). | waiting: 0 '' | waiting: 1
auto_approval_rulesis a list of functions (aToolApprovalRuleCallback, which may also beasync). Each receives the plannedfunction_calland returnsTrueto approve it without asking.- A call that no rule approves goes to the person as before, so the 480 EUR refund waits.
- The middleware keeps its data in the session, so it needs one. Without a session, the run fails.
- When several calls wait at once, the middleware shows them one at a time: you answer one request, and the next run returns the next one.
“Always allow”
People get tired of approving the same harmless call. With the middleware, a person can answer “yes, and don't ask again”:
import asyncio
from agent_framework import (DEFAULT_TOOL_APPROVAL_SOURCE_ID, Agent, Message, ToolApprovalMiddleware,
ToolApprovalState, create_always_approve_tool_response, tool)
from agent_framework.openai import OpenAIChatClient
@tool(approval_mode="always_require")
def book_repair(day: str, time: str) -> str:
"""Book a slot in Velo's repair workshop."""
return f"Repair booked for {day} at {time}."
async def main():
agent = Agent(client=OpenAIChatClient(model="MODEL_NAME"), instructions="You book repairs at Velo.",
tools=[book_repair], middleware=[ToolApprovalMiddleware()])
session = agent.create_session()
response = await agent.run("Book a repair on Thursday at 10:00.", session=session)
request = response.user_input_requests[0]
always = create_always_approve_tool_response(request) # yes, and don't ask again
response = await agent.run(Message("user", [always]), session=session)
print(response.text)
state = ToolApprovalState.from_dict(session.state[DEFAULT_TOOL_APPROVAL_SOURCE_ID])
print("rules:", [(rule.tool_name, rule.arguments) for rule in state.rules])
response = await agent.run("Book another one on Friday at 15:00.", session=session)
print(response.text, "| waiting:", len(response.user_input_requests))
asyncio.run(main())Booked: Thursday at 10:00. See you at the workshop!
rules: [('book_repair', None)]
Booked: Friday at 15:00 as well. | waiting: 0create_always_approve_tool_response(request)approves this call and stores a standing rule: every laterbook_repaircall in this session is approved.create_always_approve_tool_with_arguments_response(request)approves the call and stores a rule for exactly these arguments only.- The rules are a
ToolApprovalRulelist inside aToolApprovalState, stored insession.stateunderDEFAULT_TOOL_APPROVAL_SOURCE_ID(the text"tool_approval"). The state also holds the queue of requests still waiting.
You can also give a session rules up front, for example for a trusted staff member:
import asyncio
from agent_framework import (DEFAULT_TOOL_APPROVAL_SOURCE_ID, Agent, Message, ToolApprovalMiddleware,
ToolApprovalRule, ToolApprovalState, create_always_approve_tool_with_arguments_response, tool)
from agent_framework.openai import OpenAIChatClient
@tool(approval_mode="always_require")
def book_repair(day: str, time: str) -> str:
"""Book a slot in Velo's repair workshop."""
return f"Repair booked for {day} at {time}."
@tool(approval_mode="always_require")
def send_sms(phone: str, text: str) -> str:
"""Send a text message to a customer."""
return f"SMS sent to {phone}."
async def main():
agent = Agent(client=OpenAIChatClient(model="MODEL_NAME"), instructions="You book repairs at Velo.",
tools=[book_repair, send_sms], middleware=[ToolApprovalMiddleware()])
session = agent.create_session()
session.state[DEFAULT_TOOL_APPROVAL_SOURCE_ID] = ToolApprovalState(rules=[
ToolApprovalRule("book_repair"), # every call to book_repair
])
response = await agent.run("Book Thursday 10:00 and text +351 900 000 000 to confirm.", session=session)
request = response.user_input_requests[0] # only send_sms asks: book_repair has a rule
print("waiting:", request.function_call.name, "| requests:", len(response.user_input_requests))
answer = create_always_approve_tool_with_arguments_response(request) # yes, for these exact arguments
response = await agent.run(Message("user", [answer]), session=session)
print(response.text)
state = ToolApprovalState.from_dict(session.state[DEFAULT_TOOL_APPROVAL_SOURCE_ID])
for rule in state.rules:
print(rule.tool_name, rule.arguments)
asyncio.run(main())waiting: send_sms | requests: 1
Your repair is booked for Thursday at 10:00, and I've sent you a confirmation by SMS.
book_repair None
send_sms {'phone': '"+351 900 000 000"', 'text': '"Your repair is booked for Thursday at 10:00."'}ToolApprovalRule("book_repair")approves every call to that tool.ToolApprovalRule(name, arguments)approves only calls with these exact arguments, each stored as JSON text, which is why the strings keep their quotes.ToolApprovalMiddleware(source_id="...")stores its state under another key. Two approval middlewares that share one session, such as a manager agent and an agent it uses as a tool, each need their ownsource_id.
Other requests for the user
user_input_requests collects every content that needs the user or your app, not only approvals:
type | What your app should do |
|---|---|
function_approval_request | Ask a person to approve or reject the call |
oauth_consent_request | Show the consent_link, a sign-in page, for example for a tool in Microsoft Foundry that acts in the user's account |
computer_tool_call | Check the safety warnings of a computer-use action (lesson Hosted Tools: Code, Web, Files and Images) |
function_call | A call to a declaration-only tool, which your app runs itself (lesson Function Tools) |
Your own tools can create such a request by raising UserInputRequiredException with the request contents. The run stops and the contents appear in user_input_requests:
import asyncio
from agent_framework import Agent, Content, UserInputRequiredException, tool
from agent_framework.openai import OpenAIChatClient
calendar_token = None # set once the mechanic has signed in
@tool
def read_calendar(day: str) -> str:
"""Show the mechanic's free repair slots for a day."""
if calendar_token is None: # the app must get permission first
raise UserInputRequiredException(
[Content.from_oauth_consent_request("https://login.example.com/consent?app=velo")],
message="Calendar sign-in needed.",
)
return f"{day}: free at 10:00 and 15:00"
async def main():
agent = Agent(client=OpenAIChatClient(model="MODEL_NAME"), instructions="You book repairs at Velo.",
tools=[read_calendar])
session = agent.create_session()
response = await agent.run("When is the mechanic free on Thursday?", session=session)
for request in response.user_input_requests:
if request.type == "function_approval_request":
print("approve?", request.function_call.name)
elif request.type == "oauth_consent_request":
print("please sign in:", request.consent_link)
else:
print("needs the app:", request.type)
asyncio.run(main())please sign in: https://login.example.com/consent?app=velo
UserInputRequiredException is a ToolException, but the tool loop doesn't turn it into an error result: it passes the requests on to your app. Your app handles them, here by showing the sign-in link, and starts a new run once the user is done. The framework uses the same exception when an agent used as a tool needs something from the user (lesson Agents as Tools).
Common mistakes
Write the approval policy of a support agent: which calls may run without a person, and which must wait for one.
requests = [
{"tool": "refund_order", "args": {"order_id": "1042", "amount_eur": 12.0}},
{"tool": "refund_order", "args": {"order_id": "2001", "amount_eur": 480.0}},
{"tool": "book_repair", "args": {"day": "Thursday", "time": "10:00"}},
]
always_allowed = {"book_repair"} # tools with a standing "always allow" rule
def decide(request):
# Return "auto" if the tool is always allowed, or if it is a refund of 20 EUR or less.
# Otherwise return "ask", because a person must decide.
pass
for request in requests:
print(request["tool"], decide(request))
An agent's response has empty text and one function_approval_request. How do you let the tool run?
Summary
@tool(approval_mode="always_require")makes the run stop before the tool runs; the waiting calls are inresponse.user_input_requests.- Answer with
request.to_function_approval_response(approved=True or False)in a user message, in the same session; a rejected call tells the model it was rejected. ToolApprovalMiddlewareadds automatic rules (auto_approval_rules) and asks for one request at a time.create_always_approve_tool_responseandcreate_always_approve_tool_with_arguments_responsestore standingToolApprovalRules in the session'sToolApprovalState.- Other requests, such as sign-in links, also arrive in
user_input_requests; tools raiseUserInputRequiredExceptionto create them.
Next: Hosted Tools: Code, Web, Files and Images.
Finished reading? Tick it off to track your progress.