Velamuvi AIAcademy

Lesson 11 of 39 · Tools

Agents as Tools

Turn agents into tools with as_tool in Microsoft Agent Framework: a manager agent that asks specialists, tool names, streaming and shared sessions.

  • 13 min read
  • Intermediate
  • Reviewed
In this lesson you will learn
  • Explain the manager and specialist pattern, and what as_tool builds
  • Give one agent another agent as a tool with as_tool
  • Control the tool's name, description and argument so the manager knows when to ask
  • Watch a specialist with stream_callback and share a session with propagate_session
  • Choose between agents as tools, handoffs, orchestrations and workflows

One agent asks another

So far your agents have called Python functions. An agent can also call another agent. A manager agent talks to the customer. Specialist agents each know one area well. When a question needs a specialist, the manager asks it, reads the answer and decides what to tell the customer.

To the manager's model, a specialist looks like any other tool: a name, a description and one text parameter. The specialist's instructions, tools and conversation stay hidden behind it. Here is the pattern in plain Python:

Try it yourselfPython
# Agents as tools in plain Python: the front desk's "model" picks specialists,
# your program runs them, and each answer comes back as a tool result.

def workshop(task):
    # A specialist: its own instructions and knowledge.
    prices = {"puncture repair": "15 EUR and takes 20 minutes", "brake service": "35 EUR and takes one hour"}
    for job, answer in prices.items():
        if job in task:
            return f"A {job} costs {answer}."
    return "The workshop can't answer that."

def bike_expert(task):
    return "For hills, the Commuter 3 (1299 EUR) is the best fit."

TOOLS = {"workshop": workshop, "bike_expert": bike_expert}

def front_desk_model(question, results):
    # Stands in for the manager's model: first it asks for tool calls, then it answers.
    if not results:
        calls = []
        if "repair" in question or "service" in question:
            calls.append(("workshop", question))
        if "which bike" in question:
            calls.append(("bike_expert", question))
        return calls
    return " ".join(results)

question = "How much is a brake service, and which bike is best for hills?"
results = []
for name, task in front_desk_model(question, []):
    print(f"front desk -> {name}: {task!r}")
    results.append(TOOLS[name](task))
print("Answer:", front_desk_model(question, results))

Your first agent tool

as_tool() turns any agent into a FunctionTool, the same type the @tool decorator makes. Give it to the manager in tools=[...], like a function tool.

import asyncio

from agent_framework import Agent
from agent_framework.openai import OpenAIChatClient


async def main():
    client = OpenAIChatClient(model="MODEL_NAME")
    workshop = Agent(
        client=client,
        name="workshop",
        description="Answers questions about repairs at Velo's workshop: prices and waiting times.",
        instructions="You run Velo's repair workshop. A puncture repair costs 15 EUR and takes 20 minutes. "
        "A brake service costs 35 EUR and takes one hour. Answer in one sentence.",
    )
    front_desk = Agent(
        client=client,
        name="front_desk",
        instructions="You are Velo's front desk. Ask the workshop about anything to do with repairs.",
        tools=[workshop.as_tool()],
    )

    response = await front_desk.run("How much is a brake service, and how long does it take?")
    for message in response.messages:
        for content in message.contents:
            if content.type == "function_call":
                print("call:  ", content.name, content.arguments)
            elif content.type == "function_result":
                print("result:", content.result)
    print(response.text)


asyncio.run(main())
Output
call:   workshop {"task": "How much does a brake service cost and how long does it take?"}
result: A brake service costs 35 EUR and takes one hour.
A brake service costs 35 EUR and takes about an hour. Would you like to book one?
  • The front desk's model wrote the task itself, in the argument called task. The workshop agent ran on that text, and its reply became the tool result.
  • The front desk then answered the customer in its own words. It stays in charge of the conversation the whole time.
  • By default, each call gives the specialist a new, private session, so the workshop doesn't remember earlier questions.

What the manager's model sees

The manager's model can't see the specialist's instructions. It only sees the tool's name, description and parameters, so those decide when it asks the specialist and what it writes in the task.

from agent_framework import Agent
from agent_framework.openai import OpenAIChatClient

workshop = Agent(
    client=OpenAIChatClient(model="MODEL_NAME"),
    name="Velo Workshop",
    description="Answers questions about repairs at Velo's workshop: prices and waiting times.",
)

default_tool = workshop.as_tool()
print(default_tool.name)
print(default_tool.description)
print(default_tool.parameters())

custom_tool = workshop.as_tool(
    name="ask_workshop",
    arg_name="question",
    arg_description="The customer's repair question, in full",
)
print(custom_tool.name)
print(custom_tool.parameters())
Output
Velo_Workshop
Answers questions about repairs at Velo's workshop: prices and waiting times.
{'additionalProperties': False, 'properties': {'task': {'description': 'Task for Velo_Workshop', 'type': 'string'}}, 'required': ['task'], 'type': 'object'}
ask_workshop
{'additionalProperties': False, 'properties': {'question': {'description': "The customer's repair question, in full", 'type': 'string'}}, 'required': ['question'], 'type': 'object'}
  • Name: the agent's name, with every character except letters, digits and _ replaced by _. An agent without a name needs name=.
  • Description: the agent's description, or an empty string if it has none.
  • Argument: one required string called task, described as "Task for" plus the tool name. Change it with arg_name= and arg_description=.

A team of specialists

Give the manager several agent tools and it picks the right ones for each question. This is the manager pattern: one agent talks to the customer and delegates the expert work.

import asyncio

from agent_framework import Agent
from agent_framework.openai import OpenAIChatClient


async def main():
    client = OpenAIChatClient(model="MODEL_NAME")
    workshop = Agent(
        client=client,
        name="workshop",
        description="Answers questions about repairs at Velo's workshop: prices and waiting times.",
        instructions="You run Velo's repair workshop. A puncture repair costs 15 EUR and takes 20 minutes. "
        "A brake service costs 35 EUR and takes one hour. Answer in one sentence.",
    )
    bike_expert = Agent(
        client=client,
        name="bike_expert",
        description="Recommends which Velo bike to buy for a rider's trips, budget and terrain.",
        instructions="You know every bike Velo sells: Commuter 3 (1299 EUR, light, good on hills), "
        "Gravel X (1890 EUR, for gravel roads) and City Kid 20 (349 EUR, for children). Answer in one sentence.",
    )
    front_desk = Agent(
        client=client,
        name="front_desk",
        instructions="You are Velo's front desk. Ask the specialists, then give the customer one short answer.",
        tools=[workshop.as_tool(), bike_expert.as_tool()],
    )

    response = await front_desk.run(
        "My old bike has a flat tyre. How much is a puncture repair, and which new bike suits my 6 km commute with hills?"
    )
    for message in response.messages:
        for content in message.contents:
            if content.type == "function_call":
                print("call:  ", content.name, content.arguments)
            elif content.type == "function_result":
                print("result:", content.result)
    print(response.text)


asyncio.run(main())
Output
call:   workshop {"task": "How much does a puncture repair cost and how long does it take?"}
call:   bike_expert {"task": "Which bike suits a 6 km commute with hills?"}
result: A puncture repair costs 15 EUR and takes 20 minutes.
result: For a 6 km commute with hills, the Commuter 3 (1299 EUR) is the best fit.
A puncture repair costs 15 EUR and takes 20 minutes. For your hilly 6 km commute, we recommend the Commuter 3 (1299 EUR).

The question needed both specialists, so the model asked both in one turn. Each specialist ran on its own task, with its own instructions, and the front desk combined the two answers. You can test and improve each specialist separately, and give each one only the tools it needs.

Watching a specialist work

Inside the tool, the specialist always runs in streaming mode. Pass stream_callback= to see each AgentResponseUpdate as it arrives, for example to show "the workshop is typing" in a chat window. The callback can be a normal function or an async one.

import asyncio

from agent_framework import Agent, AgentResponseUpdate
from agent_framework.openai import OpenAIChatClient


def show_workshop(update: AgentResponseUpdate) -> None:
    print(update.text, end="", flush=True)


async def main():
    client = OpenAIChatClient(model="MODEL_NAME")
    workshop = Agent(
        client=client,
        name="workshop",
        description="Answers questions about repairs at Velo's workshop: prices and waiting times.",
        instructions="You run Velo's repair workshop. A puncture repair costs 15 EUR and takes 20 minutes. "
        "A brake service costs 35 EUR and takes one hour. Answer in one sentence.",
    )
    front_desk = Agent(
        client=client,
        name="front_desk",
        instructions="You are Velo's front desk. Ask the workshop about anything to do with repairs.",
        tools=[workshop.as_tool(stream_callback=show_workshop)],
    )

    print("workshop: ", end="")
    response = await front_desk.run("I have a flat tyre. How much is a puncture repair?")
    print()
    print("front desk:", response.text)


asyncio.run(main())
Output
workshop: A puncture repair costs 15 EUR and takes 20 minutes.
front desk: A puncture repair costs 15 EUR, and you can wait for it: it takes about 20 minutes.

The callback printed the workshop's words while it answered. The front desk's own answer comes later, after the tool returns.

Sharing a session

You'll learn sessions properly in the next lesson. For now: a session holds a conversation's state, and session.state is a dictionary your tools can read and write through FunctionInvocationContext, as in Function Tools.

By default the specialist gets a private session, so anything it saves is lost after the call. With propagate_session=True, it works on a copy of the manager's session state, and its changes flow back into the manager's session when it finishes.

import asyncio

from agent_framework import Agent, FunctionInvocationContext, tool
from agent_framework.openai import OpenAIChatClient


@tool
def book_repair(job: str, ctx: FunctionInvocationContext) -> str:
    """Book a repair job at Velo's workshop."""
    ctx.session.state.setdefault("bookings", []).append(job)
    return f"Booked: {job}."


async def main():
    client = OpenAIChatClient(model="MODEL_NAME")
    workshop = Agent(client=client, name="workshop", tools=[book_repair],
                     instructions="You run Velo's repair workshop. Book repairs with book_repair.")

    for propagate in (False, True):
        front_desk = Agent(client=client, name="front_desk",
                           instructions="You are Velo's front desk. Ask the workshop about anything to do with repairs.",
                           tools=[workshop.as_tool(propagate_session=propagate)])
        session = front_desk.create_session()
        response = await front_desk.run("Please book a brake service for my bike.", session=session)
        print(f"propagate_session={propagate}: {response.text}")
        print("  bookings in the front desk's session:", session.state.get("bookings"))


asyncio.run(main())
Output
propagate_session=False: Your brake service is booked. See you at the workshop!
  bookings in the front desk's session: None
propagate_session=True: Your brake service is booked. See you at the workshop!
  bookings in the front desk's session: ['brake service']

Only application state is shared. Approval state and each provider's own conversation ids stay with their own agent.

Approvals and specialists

You can require approval for the whole specialist: workshop.as_tool(approval_mode="always_require"). The manager's run then stops with a function_approval_request for the workshop call, and you approve or reject it as in Tool Approval and User Input.

An approval inside the specialist is different: it never reaches the manager or your app, so the delegated call fails (see the mistakes below). Give the specialist a ToolApprovalMiddleware with auto_approval_rules for decisions a rule can make, or use a workflow when a person must decide.

Agents as tools, handoffs or workflows?

PatternWho talks to the customerUse it when
Agents as tools (as_tool)The manager, alwaysOne agent stays in charge and asks experts for answers
HandoffWhichever agent has the conversation nowA specialist should take over the conversation
Sequential, concurrent, group chat, MagenticSeveral agents in one shared conversationAgents build on each other's work
WorkflowsExecutors you connect yourselfFixed steps, typed messages, checkpoints and approvals that wait

A WorkflowAgent (a workflow wrapped with as_agent()) is the exception. as_tool() on it runs without an error, but the framework doesn't support it, because every caller of the tool would share one workflow and its state.

Common mistakes

Practice exercise

Write the rule that as_tool uses to turn an agent's name into a tool name. Your output must match the names the framework makes for these five agents.

Your solutionPython
import re


def to_tool_name(agent_name):
    # 1. Replace every character that is not a letter, digit or underscore with "_".
    # 2. Replace each run of "_" with a single "_".
    # 3. Remove "_" from both ends.
    # 4. If nothing is left, return "agent".
    # 5. If the name starts with a digit, put "_" in front of it.
    return agent_name


for name in ["workshop", "Velo Workshop", "repair-desk (EU)", "2nd opinion", "@@@"]:
    print(to_tool_name(name))
Knowledge check

The front desk's model calls the workshop agent tool. What does it get back as the tool result?

Summary

  • agent.as_tool() wraps an agent in a FunctionTool with a name, a description and one text argument, task.
  • A manager agent with specialist tools stays in charge: each specialist answers one task and returns text.
  • Write a clear description, and use name, arg_name and arg_description when the defaults don't fit. Agent names are cleaned into valid tool names.
  • stream_callback shows a specialist's answer as it streams, and propagate_session=True shares the manager's session state with the specialist.
  • Approvals inside a specialist don't reach the manager: require approval on the agent tool itself, or use a workflow.

Next: Sessions and Multi-Turn Chat.

Finished reading? Tick it off to track your progress.