Routing and task execution can belong to agents with different tools and instructions. In LlamaIndex, AgentWorkflow connects those roles so an initial agent can hand a request to a specialist, which performs its task and returns the final answer. Both agents use a local Ollama model.

Each agent has its own instructions and tools, while the workflow controls the starting agent and the allowed handoff destinations. After a handoff, the specialist becomes the active agent and can complete the request with its own final response.

A local Ollama model provides function calling without a provider API key. The Python project needs an active virtual environment and a running Ollama server; the specialist receives only an arithmetic tool, with no shell, file, or external-service access.

Steps to build a multi-agent workflow with AgentWorkflow in LlamaIndex:

  1. Install the core framework and Ollama integration in the active project virtual environment.
    $ python -m pip install --upgrade llama-index-core llama-index-llms-ollama

    Python 3.14 supports llama-index-core 0.14.25 and llama-index-llms-ollama 0.11.0. A separate environment prevents an upgrade from changing dependencies in another application.
    Related: How to install Python 3 on Ubuntu or Debian
    Related: How to create a virtual environment in Python
    Related: How to activate a Python virtual environment
    Related: How to install LlamaIndex with pip

  2. Pull the tool-calling qwen3:8b model into the running Ollama server.
    $ ollama pull qwen3:8b

    The model download is about 5.2 GB, and inference needs additional working memory. A model without tool support cannot perform the handoff.
    Related: How to install Ollama on Linux
    Related: How to start the Ollama server
    Related: How to pull an Ollama model

  3. Create multi-agent.py in the project directory using your text editor with the imports and pricing tool.
    multi-agent.py
    import asyncio
    import os
     
    from llama_index.core.agent.workflow import (
        AgentInput,
        AgentWorkflow,
        FunctionAgent,
        ToolCall,
        ToolCallResult,
    )
    from llama_index.llms.ollama import Ollama
     
     
    def calculate_total(quantity: int, unit_price: int) -> int:
        """Return the total price in dollars for a quantity and whole-dollar unit price."""
        return quantity * unit_price

    The type hints and docstring describe the tool to the model. Both arguments are integers because the prices are whole dollars; the function calculates the result from the model's arguments.

  4. Append the Ollama connection after calculate_total() in multi-agent.py.
    llm = Ollama(
        model="qwen3:8b",
        base_url=os.getenv(
            "OLLAMA_BASE_URL", "http://localhost:11434"
        ),
        thinking=False,
        temperature=0.7,
        context_window=8192,
        request_timeout=300.0,
        additional_kwargs={
            "top_p": 0.8,
            "top_k": 20,
            "min_p": 0,
            "num_predict": 2048,
            "num_thread": 4,
        },
    )

    The default endpoint reaches Ollama on the same machine. OLLAMA_BASE_URL can point to your own reachable Ollama server when Python runs elsewhere. The 8,192-token context leaves room for tool descriptions and conversation history, while the 300-second request timeout allows slower local inference. thinking=False disables thinking for this tool-calling task; the qwen3:8b model supports that switch. The sampling values follow Qwen3's non-thinking recommendations. num_predict limits each model response to 2,048 tokens. num_thread bounds inference to four CPU threads. A different CPU allocation may need a different thread count.
    Related: How to connect LlamaIndex to Ollama

  5. Append the initial Triage agent after the Ollama connection.
    triage = FunctionAgent(
        name="Triage",
        description="Routes pricing requests to the pricing specialist.",
        system_prompt=(
            "You route requests. For price calculations, use the "
            "handoff tool to transfer the request to Pricing. "
            "Do not calculate prices yourself."
        ),
        llm=llm,
        can_handoff_to=["Pricing"],
    )

    AgentWorkflow supplies the handoff tool. The destination must match the specialist's name exactly.

  6. Append the Pricing specialist after triage.
    pricing = FunctionAgent(
        name="Pricing",
        description=(
            "Calculates totals from a quantity and a "
            "whole-dollar unit price."
        ),
        system_prompt=(
            "For every price calculation, call calculate_total "
            "before answering. Use the returned total instead "
            "of calculating it yourself. Then answer in one "
            "sentence with the quantity and total in dollars."
        ),
        tools=[calculate_total],
        llm=llm,
        can_handoff_to=[],
    )

    The specialist owns calculate_total. Its empty handoff list keeps it from sending control back to Triage; it can finish by generating the answer from the tool result.

  7. Append the workflow registration after pricing.
    workflow = AgentWorkflow(
        agents=[triage, pricing],
        root_agent="Triage",
        timeout=600,
    )

    Both agents must be registered before a handoff can reach Pricing. The root name selects Triage as the entry point, and the 600-second timeout bounds the complete workflow rather than one model request.

  8. Append the asynchronous request and event loop after workflow.
    async def main() -> None:
        handler = workflow.run(
            user_msg=(
                "What is the total price for 7 notebooks "
                "at 12 dollars each?"
            )
        )
     
        async for event in handler.stream_events():
            if isinstance(event, AgentInput):
                print(f"Agent: {event.current_agent_name}")
            elif isinstance(event, ToolCall):
                print(f"Tool: {event.tool_name} {event.tool_kwargs}")
            elif isinstance(event, ToolCallResult):
                print(
                    f"Result: {event.tool_name} -> "
                    f"{event.tool_output.content}"
                )
     
        result = await handler
        print(f"Final agent: {result.current_agent_name}")
        print(f"Final answer: {result.response.content}")
     
     
    if __name__ == "__main__":
        asyncio.run(main())

    run() returns a handler before completion. Iterating its events shows the selected agents, tool arguments, and returned values; awaiting the same handler then provides the final response.
    Related: How to stream events from a LlamaIndex agent

  9. Save multi-agent.py in the project directory.
  10. Run multi-agent.py to confirm the handoff to Pricing and its final answer. Example output:
    $ python multi-agent.py
    Agent: Triage
    Tool: handoff {'to_agent': 'Pricing', 'reason': 'Calculating total price for 7 notebooks at 12 dollars each.'}
    ##### snipped #####
    Agent: Pricing
    Tool: calculate_total {'quantity': 7, 'unit_price': 12}
    Result: calculate_total -> 84
    Agent: Pricing
    Final agent: Pricing
    Final answer: The total price for 7 notebooks at 12 dollars each is 84 dollars.

    The event stream must name Pricing in the handoff arguments, show Agent: Pricing and the calculation result 84, and finish with Final agent: Pricing and an answer using that total. A correct number alone does not show that the specialist handled the request. The model's wording and handoff reason can vary.

Share this guide