# LlamaIndex agents in depth: FunctionAgent, AgentWorkflow handoffs, memory and approvals

LlamaIndex reached 0.14.26 on 13 November 2026. Its agents now run on an event-driven workflow engine. This guide explains FunctionAgent, AgentWorkflow handoffs, shared state, the Memory class and human approval step by step, with code that runs offline on a scripted mock model.

LlamaIndex started as a library for connecting language models to your data, and it is still best known for retrieval-augmented generation. Its agent layer has grown into a full framework: agents are built on an event-driven workflow engine, they can hand work to each other, share state, remember long conversations and pause for a human. `llama-index-core` 0.14.26 was uploaded to PyPI on 13 November 2026, and the separate `llama-index-workflows` engine it depends on was at 2.26.1, released on 21 October 2026.

This article explains how those pieces work, one step at a time, and shows them in code. Every example ran on llama-index-core 0.14.26 with Python 3.13, without an API key, by using LlamaIndex's own `MockFunctionCallingLLM` with a scripted reply function. Replace the mock with a real model class, such as the OpenAI integration, and the same code runs against a live model.

If you need the background first, read [what an AI agent is](/articles/what-is-an-ai-agent-chatbot-workflow) and [RAG basics](/articles/rag-basics-retrieve-then-generate-pipeline). For a side-by-side with other frameworks, see [one agent built in seven frameworks](/articles/one-agent-seven-frameworks-compared).

## What happened

### llama-index-core 0.14.26 is released (13 November 2026)

PyPI lists `llama-index-core` 0.14.26 with an upload date of 13 November 2026. It requires Python 3.11 or newer and below 4.0. The detailed notes for this release were not available on the pages we could fetch, so this article describes the behaviour we observed by running it.

### 0.14.25 stops retrying failed function tools (21 September 2026)

The 0.14.25 release notes list core changes including "fix(core): avoid retrying failed function tools", "Fix: restore compact and refine streaming", "feat(core): add native async support to StructuredLLMRerank" and "Remove deprecated ipex-llm and optimum-intel IPEX integrations". The first one matters for agents: a tool that fails is not silently called again, so side effects are not repeated.

### 0.14.24 fixes structured output in multi-agent runs (19 August 2026)

The changelog for core 0.14.24 includes "fix: honor agent structured_output_fn/output_cls inside AgentWorkflow", "feat(core): allow Memory to accept any AsyncDBChatStore" and "fix: don't mark *args/**kwargs as required tool parameters". Together these make typed final answers and custom memory storage work across multi-agent workflows.

## How a LlamaIndex agent runs

### Agents are workflows

A LlamaIndex workflow is a set of steps that react to events. A step receives an event, does some work, and emits the next event. An agent is a prebuilt workflow whose steps are "set up the agent", "call the model", "run the tools" and "decide whether to continue". It is like a kitchen with order tickets: each station picks up a ticket, does its part and pins up a new ticket for the next station.

The docs describe the main agent classes briefly. `FunctionAgent` is "a simple function/tool calling agent". `AgentWorkflow` is "an agent capable of managing multiple agents". `ReActAgent` and `CodeActAgent` "use different prompting strategies to execute tools": ReAct writes its reasoning and tool calls as text, and CodeAct writes code that calls tools.

| Class | How it calls tools | Use it when |
|---|---|---|
| `FunctionAgent` | the model's native function calling | the model supports tool calls (most current models) |
| `ReActAgent` | text prompts with Thought, Action, Observation | the model has no native tool calling |
| `CodeActAgent` | writes code that calls tools | tasks need loops or arithmetic over tool results |
| `AgentWorkflow` | runs several agents with handoffs | work splits into specialist roles |

On 0.14.26 a `FunctionAgent` has these fields: `name`, `description`, `system_prompt`, `tools`, `tool_retriever`, `can_handoff_to`, `llm`, `initial_state`, `state_prompt`, `output_cls`, `structured_output_fn`, `streaming`, `early_stopping_method`, `scratchpad_key`, `initial_tool_choice` and `allow_parallel_tool_calls`. Plain Python functions become tools automatically: the type hints give the argument schema and the docstring gives the description.

### A single agent, traced event by event

```python
import asyncio
from llama_index.core.agent.workflow import FunctionAgent, ToolCall, ToolCallResult
from llama_index.core.llms import ChatMessage, MessageRole
from llama_index.core.llms.mock import MockFunctionCallingLLM
from llama_index.core.base.llms.types import ToolCallBlock
from llama_index.core.workflow import Context

def get_order(order_id: str) -> dict:
    """Look up an order by id."""
    return {"id": order_id, "total_eur": 120.0, "days_since_delivery": 9}

def refund_allowed(days_since_delivery: int) -> bool:
    """Refunds are allowed within 14 days of delivery."""
    return days_since_delivery <= 14

SCRIPT = [
    [ToolCallBlock(tool_call_id="t1", tool_name="get_order", tool_kwargs={"order_id": "A-1042"})],
    [ToolCallBlock(tool_call_id="t2", tool_name="refund_allowed",
                   tool_kwargs={"days_since_delivery": 9})],
    "Order A-1042 (120.00 EUR) was delivered 9 days ago, so the refund is approved.",
]
seen = []
def scripted(messages, **kwargs):
    seen.append(len(messages))
    step = SCRIPT[len(seen) - 1]
    if isinstance(step, str):
        return ChatMessage(role=MessageRole.ASSISTANT, content=step)
    return ChatMessage(role=MessageRole.ASSISTANT, blocks=step)

llm = MockFunctionCallingLLM(response_generator=scripted)
agent = FunctionAgent(name="refunds", description="Handles refunds.",
                      system_prompt="You handle refunds. Look up the order and the policy first.",
                      tools=[get_order, refund_allowed], llm=llm)

async def main():
    ctx = Context(agent)
    handler = agent.run("Refund order A-1042", ctx=ctx)
    async for ev in handler.stream_events():
        if isinstance(ev, ToolCallResult):
            print("ToolCallResult", ev.tool_name, ev.tool_output.content)
        elif isinstance(ev, ToolCall):
            print("ToolCall      ", ev.tool_name, ev.tool_kwargs)
    result = await handler
    print("final:", str(result))
    print("messages seen by LLM per call:", seen)

asyncio.run(main())
```

```text
ToolCall       get_order {'order_id': 'A-1042'}
ToolCallResult get_order {'id': 'A-1042', 'total_eur': 120.0, 'days_since_delivery': 9}
ToolCall       refund_allowed {'days_since_delivery': 9}
ToolCallResult refund_allowed True
final: Order A-1042 (120.00 EUR) was delivered 9 days ago, so the refund is approved.
messages seen by LLM per call: [2, 4, 6]
```

`agent.run()` returns a handler at once. You can stream its events while it works and then `await` it for the final answer. `ToolCall` is emitted when a tool is requested and `ToolCallResult` when it returns.

The last line shows how the loop grows. The first model call sees 2 messages: the system prompt and the user message. Each tool round adds 2 more: the assistant's tool call and the tool result. So call n sees 2 + 2 × (n − 1) messages, and the three calls together see 2 + 4 + 6 = 12 messages. A ten-call run would see 20 messages on its last call and 110 in total. That growth is why memory limits matter, as the next section shows. The [ReAct tool-calling simulation](/ai-simulations/react-tool-calling) animates the same cycle.

```chart
{"type": "line", "title": "Messages sent to the model per call, FunctionAgent", "x": ["1", "2", "3", "4", "5", "6"], "series": [{"name": "messages in this call", "data": [2, 4, 6, 8, 10, 12]}], "xlabel": "model call", "ylabel": "messages", "note": "Calls 1 to 3 measured on llama-index-core 0.14.26 with MockFunctionCallingLLM; calls 4 to 6 computed as 2 + 2 x (n - 1)."}
```

## Multi-agent handoffs and shared state

`AgentWorkflow` runs a team of agents. One is the `root_agent`. Each agent can be limited to certain targets with `can_handoff_to`. Reading the 0.14.26 source, handoff is a built-in tool named `handoff` with two arguments, `to_agent` and `reason`. If the target does not exist, or the current agent may not hand off to it, the tool returns an error message to the model instead of switching. In a multi-agent workflow every agent must have a name and a description, or the constructor raises an error.

The workflow also keeps a shared `state` dictionary. A tool that takes `ctx: Context` as its first parameter can read and change it. The docs show the pattern: `async with ctx.store.edit_state() as ctx_state: ctx_state["state"]["name"] = name`.

```python
import asyncio
from llama_index.core.agent.workflow import (FunctionAgent, AgentWorkflow,
                                             AgentInput, ToolCallResult)
from llama_index.core.llms import ChatMessage, MessageRole
from llama_index.core.llms.mock import MockFunctionCallingLLM
from llama_index.core.base.llms.types import ToolCallBlock
from llama_index.core.workflow import Context

def scripted(steps):
    it = iter(steps)
    def gen(messages, **kwargs):
        s = next(it)
        if isinstance(s, str):
            return ChatMessage(role=MessageRole.ASSISTANT, content=s)
        return ChatMessage(role=MessageRole.ASSISTANT, blocks=s)
    return MockFunctionCallingLLM(response_generator=gen)

async def record_refund(ctx: Context, order_id: str, amount_eur: float) -> str:
    """Record an approved refund in the shared state."""
    async with ctx.store.edit_state() as state:
        state["state"]["refunds"].append({"order_id": order_id, "amount_eur": amount_eur})
    return "recorded"

triage = FunctionAgent(name="triage", description="Routes customer requests.",
    system_prompt="Route requests to the right agent.", can_handoff_to=["refunds"],
    llm=scripted([[ToolCallBlock(tool_call_id="h1", tool_name="handoff",
                   tool_kwargs={"to_agent": "refunds", "reason": "refund request"})]]))
refunds = FunctionAgent(name="refunds", description="Approves and records refunds.",
    system_prompt="Approve refunds within 14 days and record them.", tools=[record_refund],
    llm=scripted([[ToolCallBlock(tool_call_id="r1", tool_name="record_refund",
                   tool_kwargs={"order_id": "A-1042", "amount_eur": 120.0})],
                  "Refund of 120.00 EUR recorded for A-1042."]))

wf = AgentWorkflow(agents=[triage, refunds], root_agent="triage",
                   initial_state={"refunds": []})

async def main():
    ctx = Context(wf)
    h = wf.run(user_msg="Refund A-1042, delivered 9 days ago", ctx=ctx)
    async for ev in h.stream_events():
        if isinstance(ev, AgentInput):
            print("AgentInput     ", ev.current_agent_name)
        elif isinstance(ev, ToolCallResult):
            print("ToolCallResult ", ev.tool_name, "->", str(ev.tool_output.content)[:70])
    print("final:", str(await h))
    print("shared state:", await ctx.store.get("state"))

asyncio.run(main())
```

```text
AgentInput      triage
ToolCallResult  handoff -> Agent refunds is now handling the request due to the following reason:
AgentInput      refunds
ToolCallResult  record_refund -> recorded
AgentInput      refunds
final: Refund of 120.00 EUR recorded for A-1042.
shared state: {'refunds': [{'order_id': 'A-1042', 'amount_eur': 120.0}]}
```

The trace has three model calls: one by triage and two by refunds. The handoff's tool result tells the next agent why it was called. The shared state now holds the refund record, which any agent or your own code can read with `ctx.store.get("state")`. This is a swarm-style design where agents pass control directly; for the supervisor alternative, see [multi-agent supervisors, handoffs and sub-agents](/articles/multi-agent-supervisor-handoffs-subagents) and the [multi-agent supervisor simulation](/ai-simulations/multi-agent-supervisor).

### Keeping state across runs

By default, the docs say, an `AgentWorkflow` does not remember earlier runs. You create `ctx = Context(workflow)` once and pass it to every run. To survive a restart, serialise it with `ctx.to_dict(serializer=JsonSerializer())` and load it with `Context.from_dict(workflow, ctx_dict, serializer=JsonSerializer())`. `JsonPickleSerializer` handles objects that JSON cannot. When we called `ctx.to_dict()` on 0.14.26, the workflows engine warned that it skipped the `memory` key as unserialisable and that it must be set again after loading, so test your restore path.

## Memory: short-term, long-term and token limits

Every agent run uses a `Memory` object. On 0.14.26, `Memory.from_defaults()` takes, among others, `session_id`, `token_limit=30000`, `chat_history_token_ratio=0.7`, `token_flush_size=3000`, `memory_blocks`, `chat_store` and `async_database_uri`. The docs explain the rules:

- `token_limit` caps short-term plus long-term memory together.
- Short-term chat history may use `chat_history_token_ratio` of that limit.
- When history passes that share, the oldest messages are flushed to long-term memory, `token_flush_size` tokens at a time, and each flushed batch goes to every memory block.
- If the merged result is still too long, blocks are cut in order of their `priority`; priority 0 is never removed.
- Storage is an in-memory SQLite database by default; set `async_database_uri` for a remote database.

Here is the arithmetic with the defaults. The short-term budget is 30,000 × 0.7 = 21,000 tokens, which leaves 9,000 tokens for long-term blocks. Suppose each turn adds 1,500 tokens. After 14 turns, history reaches 14 × 1,500 = 21,000 tokens. Turn 15 pushes it to 22,500, so the oldest 3,000 tokens are flushed and history drops to 19,500. From then on it swings between 19,500 and 21,000. This is a simplified model of the rule above, but it shows the shape: a sawtooth under a ceiling.

```chart
{"type": "line", "title": "Short-term history under default Memory limits", "x": ["2", "4", "6", "8", "10", "12", "13", "14", "15", "16", "17", "18"], "series": [{"name": "history tokens kept", "data": [3000, 6000, 9000, 12000, 15000, 18000, 19500, 21000, 19500, 21000, 19500, 21000]}], "xlabel": "turn", "ylabel": "tokens", "note": "Computed: 1,500 tokens per turn, 21,000-token short-term budget (30,000 x 0.7), oldest 3,000 tokens flushed when over."}
```

Long-term memory comes from blocks. The docs describe three:

| Block | What it keeps | Needs |
|---|---|---|
| `StaticMemoryBlock` | fixed text that is always included | nothing |
| `FactExtractionMemoryBlock` | facts an LLM pulls from flushed messages, summarised when over `max_facts` | an LLM |
| `VectorMemoryBlock` | flushed message batches, retrieved by similarity | `vector_store` and `embed_model` |

For a deeper look at these choices, read [agent memory: threads, stores and context engineering](/articles/agent-memory-threads-stores-context-engineering) and try the [context compaction simulation](/ai-simulations/context-compaction-agent-history).

## Human approval inside a tool

LlamaIndex pauses for a person with two built-in events, `InputRequiredEvent` and `HumanResponseEvent`. A tool calls `ctx.wait_for_event(...)`, which emits the request and waits. The caller watches the event stream, asks a person, and replies with `handler.ctx.send_event(...)`.

```python
from llama_index.core.workflow import Context, InputRequiredEvent, HumanResponseEvent

async def issue_refund(ctx: Context, order_id: str, amount_eur: float) -> str:
    """Send money back. Requires a human yes."""
    reply = await ctx.wait_for_event(
        HumanResponseEvent,
        waiter_id=f"refund-{order_id}",
        waiter_event=InputRequiredEvent(
            prefix=f"Approve {amount_eur:.2f} EUR on {order_id}? ", user_name="reviewer"),
        requirements={"user_name": "reviewer"},
    )
    if reply.response.strip().lower() == "yes":
        return f"refunded {amount_eur:.2f} EUR on {order_id}"
    return "refund rejected by reviewer"

# caller side
async def run(agent):
    h = agent.run("Refund A-1042")
    async for ev in h.stream_events():
        if isinstance(ev, InputRequiredEvent):
            print("asked:", ev.prefix)
            h.ctx.send_event(HumanResponseEvent(response="yes", user_name=ev.user_name))
    print("final:", str(await h))
```

With a `FunctionAgent` that has `issue_refund` as a tool and the same scripted mock, the run printed `asked: Approve 120.00 EUR on A-1042?` and then the final answer. The `waiter_id` names this particular wait, and `requirements` makes sure only a reply from `reviewer` is accepted. For slow approvals, the docs suggest serialising the context and resuming later. See [human in the loop](/tools/human-in-the-loop) for the general pattern.

## Use cases and examples

**Document assistant over company files.** A legal team indexes contracts in a vector index and gives a `FunctionAgent` a `QueryEngineTool` built with `QueryEngineTool.from_defaults(query_engine, name, description)`. The agent decides when to search, which is [agentic RAG](/articles/agentic-rag-retrieval-decisions-deep-research); the [agentic RAG simulation](/ai-simulations/rag-agentic) shows the decision points.

**Support desk with specialists.** A retailer runs triage, refunds and shipping agents in one `AgentWorkflow`, with `can_handoff_to` limiting who may call whom. As in the trace above, a refund costs three model calls, and every refund is written to shared state that the reporting job reads.

**Long-running customer chats.** A telecom bot keeps conversations for weeks. With default memory, short-term history is capped at 21,000 tokens and older turns flow into a `FactExtractionMemoryBlock`, so the agent remembers the customer's plan and device without re-reading every message.

**Approval-gated payments.** A finance team wraps payouts in a tool that waits for a `HumanResponseEvent` from a named reviewer. Pending runs are serialised with `JsonSerializer` and resumed when the reviewer answers in a separate web app.

**Offline tests in CI.** A platform team scripts `MockFunctionCallingLLM` replies for its main flows and asserts on the event stream: which tools ran, with which arguments, and which agent finished. These tests run with no API key and caught a broken handoff name before release.

## What it means in practice

LlamaIndex's strength is still data: loaders, indexes, retrievers and query engines. The agent layer lets you put that data behind tools and combine it with other tools, handoffs and memory, all in one library. The workflow engine underneath means every agent is inspectable as a stream of typed events, which makes tracing and testing straightforward.

The trade-off is that state lives in a `Context` object you must pass and persist yourself. Frameworks built around checkpointed graphs, such as [LangGraph](/tools/langgraph), save state at every step by design. In LlamaIndex you decide when to serialise, and you must check that everything you need, including memory, survives the round trip.

## What to do now

1. **Pin both packages.** Install `llama-index-core==0.14.26` and pin `llama-index-workflows`, since the agent runtime lives there.
2. **Prefer FunctionAgent.** Use native tool calling when the model supports it; fall back to `ReActAgent` only for models without it.
3. **Limit handoffs.** Set `can_handoff_to` on every agent in an `AgentWorkflow` so routing stays predictable.
4. **Put shared facts in state.** Write records with `ctx.store.edit_state()` instead of asking the model to repeat them.
5. **Size memory on purpose.** Check the 30,000-token default against your model's context window and set `token_limit` and the ratio to fit.
6. **Add long-term blocks.** Use `FactExtractionMemoryBlock` or `VectorMemoryBlock` for chats that run longer than the short-term budget.
7. **Gate risky tools.** Wrap payments and deletions in a tool that waits for a `HumanResponseEvent` with `requirements` set.
8. **Test the restore path.** Serialise and restore the `Context` in a test and confirm memory and state are intact afterwards.
9. **Script your tests.** Use `MockFunctionCallingLLM` with a `response_generator` to check tool calls and handoffs offline.

## Risks and open questions

**Release notes can lag.** The 0.14.26 notes were not available where we looked, and the documentation changelog lagged behind PyPI. Read the diff or test before upgrading.

**Context serialisation is partial by default.** On 0.14.26 the engine skips the `memory` key when serialising and asks you to set it again, which is easy to miss.

**Shared state is trusted state.** Any agent with a `ctx` tool can change it. A prompt-injected agent could write bad records unless your tools validate what they store.

**Fact extraction can be wrong.** `FactExtractionMemoryBlock` relies on an LLM to pick facts. A wrong fact will be repeated in every later turn until it is removed.

**Two packages move together.** The agent layer depends on the separate workflows engine, so a version mismatch can break runs.

**Watch next:** how the workflows engine's durability features develop, whether more agent defaults move into `llama-index-workflows`, and how the 0.14 line handles structured output and memory in multi-agent runs.

## Frequently asked questions

### What is the difference between FunctionAgent and ReActAgent in LlamaIndex?

`FunctionAgent` uses the model's native function-calling API to request tools. `ReActAgent` writes its reasoning and tool requests as text in a Thought, Action, Observation format, so it works with models that lack native tool calling. Use `FunctionAgent` when your model supports tools.

### How do LlamaIndex agents hand off to each other?

Inside an `AgentWorkflow`, each agent gets a built-in `handoff` tool with `to_agent` and `reason` arguments. When the model calls it, control moves to that agent, provided it exists and is listed in the caller's `can_handoff_to`. The reason is passed on as the tool result.

### How does LlamaIndex remember earlier conversations?

Pass the same `Context` to each run, and the agent's `Memory` keeps the chat. Short-term history is capped at a share of `token_limit` (70% of 30,000 tokens by default), and older messages flow to long-term memory blocks. To survive a restart, serialise the context with `ctx.to_dict()` and restore it with `Context.from_dict()`.

### Can a LlamaIndex agent wait for human approval?

Yes. A tool calls `ctx.wait_for_event(HumanResponseEvent, waiter_event=InputRequiredEvent(...))`, and the run pauses. Your code sees the `InputRequiredEvent` in the event stream and answers with `handler.ctx.send_event(HumanResponseEvent(...))`.

### Can I test LlamaIndex agents without an API key?

Yes. `MockFunctionCallingLLM` accepts a `response_generator` function that returns scripted messages, including tool calls as `ToolCallBlock` objects. All the examples in this article ran this way on llama-index-core 0.14.26.

## Summary

LlamaIndex 0.14.26, released on 13 November 2026, runs agents as event-driven workflows. A `FunctionAgent` calls tools through native function calling, and our trace showed the messages sent per call growing by two with each tool round. `AgentWorkflow` adds multi-agent handoffs through a built-in `handoff` tool and a shared state dictionary. `Memory` caps short-term history at 21,000 tokens by default and flushes older turns to long-term blocks, and tools can pause for a person with `InputRequiredEvent` and `HumanResponseEvent`. Pin the core and workflows packages together, test your context restore path, and use the scripted mock model to test agents offline.

## Sources

- [LlamaIndex: Building an agent](https://developers.llamaindex.ai/python/framework/understanding/agent/)
- [LlamaIndex: Maintaining state](https://developers.llamaindex.ai/python/framework/understanding/agent/state/)
- [LlamaIndex: Human in the loop](https://developers.llamaindex.ai/python/framework/understanding/agent/human_in_the_loop/)
- [LlamaIndex: Memory](https://developers.llamaindex.ai/python/framework/module_guides/deploying/agents/memory/)
- [LlamaIndex: Changelog](https://developers.llamaindex.ai/python/framework/changelog/)
- [GitHub: run-llama/llama_index releases](https://github.com/run-llama/llama_index/releases)
- [PyPI: llama-index-core](https://pypi.org/project/llama-index-core/)
- [PyPI: llama-index-workflows](https://pypi.org/project/llama-index-workflows/)
