Velamuvi AIAcademy

Lesson 19 of 39 · The Agent Harness

Background Agents and Long-Running Responses

Run slow work without blocking in Agent Framework: continuation tokens for background responses, BackgroundAgentsProvider and message injection.

  • 9 min read
  • Intermediate
  • Reviewed
In this lesson you will learn
  • Explain why long tasks need a token instead of an open connection
  • Start a background response and poll it with a ContinuationToken
  • Let an agent hand slow work to background agents with BackgroundAgentsProvider
  • Read a task's BackgroundTaskStatus, including lost tasks after a restart
  • Add messages to a running conversation with MessageInjectionMiddleware and enqueue_messages

Work that takes minutes

A normal run() waits until the model has finished. That's fine for a chat reply, but deep research or a long report can take minutes, and a web request or a phone connection may not stay open that long. The answer is to start the work, get a small token back, and ask again later with the token.

The token pattern in plain Python:

Try it yourselfPython
import itertools

# A slow "service": a job finishes after a few checks, and you hold a token in between.
jobs = {}
counter = itertools.count(1)


def start(task):
    job_id = f"job_{next(counter)}"
    jobs[job_id] = {"task": task, "checks_left": 2}
    return {"job_id": job_id}                         # the token: just enough to find the job again


def poll(token):
    job = jobs[token["job_id"]]
    if job["checks_left"] > 0:
        job["checks_left"] -= 1
        return None, token                            # not ready yet: keep the token
    return f"Report on {job['task']}: done.", None    # ready: no token any more


token = start("e-bike prices")
result = None
while token is not None:
    print("checking", token["job_id"])
    result, token = poll(token)
print(result)

Long-running responses with a ContinuationToken

OpenAIChatClient can ask OpenAI to run a response in the background with the option background=True. The run returns at once. While the work is in progress, response.continuation_token holds a token; when it's finished, the token is None and the response holds the answer.

import asyncio
import json

from agent_framework import Agent
from agent_framework.openai import OpenAIChatClient


async def main():
    agent = Agent(
        client=OpenAIChatClient(model="MODEL_NAME"),
        instructions="You write short market reports for Velo, a bike rental shop in Porto.",
    )
    session = agent.create_session()

    response = await agent.run(
        "Compare e-bike rental prices in Porto.",
        session=session,
        options={"background": True},                 # start the work and return at once
    )
    saved = json.dumps(response.continuation_token)    # store it anywhere: a database, a file
    print("started, token:", list(response.continuation_token))

    while response.continuation_token is not None:
        await asyncio.sleep(2)                          # come back later, even after a restart
        token = json.loads(saved)
        response = await agent.run(session=session, options={"continuation_token": token})
        if response.continuation_token is not None:
            saved = json.dumps(response.continuation_token)
            print("still working...")

    print(response.text)


asyncio.run(main())
Output
started, token: ['response_id']
still working...
E-bike day rentals in Porto cost 30 to 38 EUR. Velo's 35 EUR sits in the middle.

The token is a ContinuationToken: a plain dictionary you can store with json.dumps(). Each provider has its own kind; OpenAI's is an OpenAIContinuationToken with a single response_id. To check on the work, call agent.run() with no new message and options={"continuation_token": token}. With stream=True, the same option resumes a streamed response where it stopped, which helps when a connection drops halfway.

Background agents: hand off slow work

Sometimes the main agent should keep talking while helpers do slow research. BackgroundAgentsProvider is a context provider that gives an agent six tools to manage helper agents: start a task, wait for the first task to finish, get a task's result, list all tasks, continue a finished task, and clear a finished task. Each task runs in its own session, at the same time as the others.

import asyncio

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


async def main():
    client = OpenAIChatClient(model="MODEL_NAME")
    researcher = Agent(
        client=client,
        name="researcher",                          # background agents need a unique name
        description="Researches prices of bike rental shops",
        instructions="You research prices for Velo, a bike rental shop in Porto. Answer briefly.",
    )
    manager = Agent(
        client=client,
        instructions="You help Velo's owner. Hand slow research to background agents.",
        context_providers=[BackgroundAgentsProvider([researcher])],
    )

    session = manager.create_session()
    response = await manager.run("Compare our e-bike price with other shops in Porto.", session=session)
    for message in response.messages:
        for content in message.contents:
            if content.type == "function_call":
                print("tool:", content.name)
    print(response.text)


asyncio.run(main())
Output
tool: background_agents_start_task
tool: background_agents_wait_for_first_completion
tool: background_agents_get_task_results
Here is what the researcher found: Bike Porto: 30 EUR a day. Ride Douro: 38 EUR a day. Velo: 35 EUR a day.

The manager started a task on the researcher, waited for it, and collected the result, all through tools. The provider is part of the experimental harness, so its first use prints an ExperimentalWarning.

Each task is saved as a BackgroundTaskInfo with its id, agent_name, description and a BackgroundTaskStatus: RUNNING, COMPLETED, FAILED or LOST. The task list is saved in the session, but the running work itself lives only in your process. If the process restarts, tasks that were still running can never finish, and the provider marks them LOST.

Only add agents you trust as background agents: they receive text from the main agent, and their answers flow back into its context.

Adding messages while the agent works

Customers don't wait politely. While the agent is busy with a tool, they may type another message. MessageInjectionMiddleware handles that: messages you add with enqueue_messages(session, ...) wait in the session and are added to the next model call, even in the middle of a run.

import asyncio

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


@tool
def book_bike(model: str, day: str, ctx: FunctionInvocationContext) -> str:
    """Book a bike for a day."""
    # While the booking runs, the customer types another message in the chat window.
    enqueue_messages(ctx.session, "Oh, and please add a child seat.")
    return f"Booked one {model} for {day}."


async def main():
    injector = MessageInjectionMiddleware()
    agent = Agent(
        client=OpenAIChatClient(model="MODEL_NAME"),
        instructions="You are Velo's rental desk in Porto. Use book_bike() for bookings.",
        tools=[book_bike],
        middleware=[injector],
    )
    session = agent.create_session()
    response = await agent.run("I'd like to rent a City E tomorrow.", session=session)
    print(response.text)
    print("still queued:", len(injector.get_pending_messages(session)))


asyncio.run(main())
Output
Booked one City E for tomorrow. I've added a child seat too.
still queued: 0

The extra message arrived while book_bike() was running, and the model saw it in its next call, so the reply covers both wishes. The tool got the session through its ctx: FunctionInvocationContext parameter. Your web app can call enqueue_messages() in the same way when a new chat message arrives.

Common mistakes

Practice exercise

After a restart, background tasks that were running are gone. Write refresh(), which marks them as lost the way BackgroundAgentsProvider does, and counts the tasks per status.

Your solutionPython
tasks = [
    {"id": 1, "agent": "researcher", "status": "completed"},
    {"id": 2, "agent": "researcher", "status": "running"},
    {"id": 3, "agent": "writer", "status": "running"},
    {"id": 4, "agent": "writer", "status": "failed"},
]
still_running = {3}   # after a restart, only task 3 is really still running


def refresh(tasks, still_running):
    # A task marked "running" whose id is not in still_running can never finish:
    # change its status to "lost". Then return a dict that counts the tasks per status.
    return {}


print(refresh(tasks, still_running))
print([task["status"] for task in tasks])
Knowledge check

A background response is still running. What does the response you got back contain?

Summary

  • Slow work returns a ContinuationToken instead of an answer; store it and call run() again with options={"continuation_token": token} until it's None.
  • With OpenAIChatClient, start background responses with options={"background": True}; the token is an OpenAIContinuationToken.
  • BackgroundAgentsProvider gives an agent tools to start, wait for and collect tasks on named helper agents; each task has a BackgroundTaskStatus.
  • MessageInjectionMiddleware and enqueue_messages() add messages to the next model call of a running conversation.

Next: Structured Output.

Finished reading? Tick it off to track your progress.