Skip to content

An image agent with a task

A Pydantic AI agent picks the keyframe for a video ad. It writes up to four prompts, and one task makes all the images in one GPU job on an H100. The job stops by itself. The agent looks at small previews and picks one.

It follows lessons 2.2 and 2.3 of the course Production AI agents for media generation ("keyframe options in one Job"), with ns.Task in place of the course's CLI wrappers.

View example files ↗ · Related reference: Tasks →

What this example does

  • tools.py has the task and the GPU tool. It uses the library only, with no agent framework.
  • agent.py has the model, view_image, the agent, and run_agent.

The task. generate_images(prompts) runs in the job on the course's worker image, which has Sana. It loads Sana once, writes image-<i>.png to $NS_OUTPUT_DIR, and returns the file names, the model load time, the time of each image, and a JPEG preview of each image, at most 512 px. The full PNGs stay in the run's folder in the task bucket, at run.output_uri.

Tool What it does Library calls
generate_keyframe_options(prompts) At most 4 prompts, capped in code. A bad call returns an error to the agent and starts nothing. A retried tool call with the same prompts returns the run it started instead of starting a second job. Waits for the job and returns the previews' paths. generate.submit(prompts).result()
view_image(path) Sends a preview to the model. none

Who decides what. The agent decides what to generate and when. Our code decides everything that costs money: the image, the GPU, and at most four prompts per job.

Retries. The tool keeps each call's run under a key made from the prompts. A retried tool call with the same prompts, in the same agent process, returns that run's images and starts no job. A run that failed is returned as it is, so the agent gets the same error: change the prompts to try again. After the agent restarts, the same prompts start a new job.

Cleanup. When the agent run breaks, run_agent cancels the task runs that haven't ended. A run that ended is left alone. The job id is printed at submit. After a crash, the job keeps running until it ends: find it with nebius ai job list.

Requirements

  • A Nebius profile that can create jobs: see Install and authenticate.
  • H100 quota in the project's region.
  • Object Storage credentials, to read results: AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY, or a profile in ~/.aws/credentials. The first task run creates the project's task bucket, ns-workspace-<project id>.
  • A Nebius Token Factory API key, for the agent's model, zai-org/GLM-5.3-Flash. It reads images, which view_image needs.

Runtime and compute

Machine gpu="h100", on-demand: the task default
Image docker.io/mnrozhkov/santa-worker:v0.1.0: the course's worker, with Sana and Wan2.2 in /app
Timeout 1 hour
Disk 500Gi

A job bills only while it runs. Most of it is the start and the model load, paid once for all the prompts in the call.

Run it

In this folder, in a virtual environment:

pip install -r requirements.txt
cp .env.example .env   # then set NEBIUS_API_KEY
python agent.py "a desk lamp, a person working from home, dusk"

Each tool call is printed:

TOOL CALL (tasks_image_agent): generate_keyframe_options({"prompts": ["...", "...", "...", "..."]})
TOOL CALL (tasks_image_agent): view_image({"path": "out/keyframes-.../preview-0.jpg"})
TOOL CALL (tasks_image_agent): view_image({"path": "out/keyframes-.../preview-1.jpg"})

Press Ctrl-C while the job runs: the run stops, and run_agent cancels the job.

Check that nothing is left

nebius ai job list

No job of the run should be RUNNING. The run folders stay in the task bucket, under tasks/generate-images/. Delete the ones you no longer need with an S3 client.

Licenses

  • Sana: [license placeholder]
  • Wan2.2, also in the worker image and not used here: [license placeholder]

Common failures

Symptom Cause Fix
KeyError: 'NEBIUS_API_KEY' No Token Factory key Set it in .env
AccessError about S3 credentials No Object Storage key on this machine Set AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY
TaskFailed with a traceback from the job The function failed in the job Read remote_traceback, or nebius ai job logs <job-id>

Source

tools.py
"""The GPU tool of the image agent: keyframe options in one task (E4b).

This file uses the library only, with no agent framework. ``agent.py``
turns the methods of ``TaskTools`` into Pydantic AI tools.

The agent writes up to four prompts. One task makes all the images in
one GPU job, which stops by itself: Sana loads once for all of them.
This code decides everything that costs money: the image, the GPU, and
the number of prompts. It also keeps each call's run, so a retried tool
call in the same process returns that run instead of starting a second
job.
"""

import base64
import hashlib
import json
import threading
from pathlib import Path
from typing import Any

import nebius_serverless as ns

# The course's worker image: Sana and Wan2.2, with their code in /app.
WORKER_IMAGE = "docker.io/mnrozhkov/santa-worker:v0.1.0"

# At most this many prompts per call: one job makes them all.
MAX_PROMPTS = 4


def generate_images(prompts: list[str], preview_px: int = 512) -> dict:
    """Make one image per prompt with Sana. Runs in the GPU job.

    Loads Sana once, then writes ``image-<i>.png`` to ``$NS_OUTPUT_DIR``,
    the run's folder in the task bucket. Returns the file names, the
    model load time, each image's time, and a small JPEG preview of each
    image as base64, for the agent to look at.
    """
    import base64
    import io
    import os
    import sys
    import time

    sys.path.insert(0, "/app")  # the worker's code: common.py, models.py
    import torch
    from common import load_pipeline
    from models import SANA

    spec = SANA.with_overrides(width=1024, height=1024)
    out = os.environ["NS_OUTPUT_DIR"]
    start = time.monotonic()
    pipe = load_pipeline(spec)
    load_s = time.monotonic() - start
    print(f"Sana loaded in {load_s:.1f} s", flush=True)

    images, latency_s, previews = [], [], []
    for i, prompt in enumerate(prompts):
        start = time.monotonic()
        # A seed per image, so two similar prompts give two options.
        seed = spec.seed + i
        generator = torch.Generator(device="cuda").manual_seed(seed)
        output = pipe(prompt=prompt, **spec.params, generator=generator)
        image = output.images[0]
        latency_s.append(round(time.monotonic() - start, 2))
        name = f"image-{i}.png"
        image.save(os.path.join(out, name))  # a PNG can go to the mount
        preview = image.convert("RGB")
        preview.thumbnail((preview_px, preview_px))
        buffer = io.BytesIO()
        preview.save(buffer, format="JPEG", quality=80)
        previews.append(base64.b64encode(buffer.getvalue()).decode())
        images.append(name)
        print(f"{name} in {latency_s[-1]:.1f} s", flush=True)
    return {
        "images": images,
        "load_s": round(load_s, 1),
        "latency_s": latency_s,
        "previews": previews,
    }


# One H100 job per call, on-demand: the task default. The job stops by
# itself, or at 1 hour.
GENERATE = ns.Task(
    generate_images,
    image=WORKER_IMAGE,
    gpu="h100",
    timeout="1h",
    disk="500Gi",
)


class ToolError(Exception):
    """A mistake the agent can fix, such as too many prompts.

    ``agent.py`` sends the message back to the model.
    """


def prompts_key(prompts: list[str]) -> str:
    """The key of a list of prompts.

    The same prompts give the same key, so a retried tool call in the
    same process returns the run it started. A run that failed is
    returned as it is: change the prompts to try again.
    """
    text = json.dumps(prompts, separators=(",", ":"))
    return "keyframes-" + hashlib.sha256(text.encode()).hexdigest()[:16]


class TaskTools:
    """The task runs of one agent run, and the tool that starts them."""

    def __init__(
        self, task: ns.Task = GENERATE, out_dir: str | Path = "out"
    ) -> None:
        self.task = task
        self.out_dir = Path(out_dir)
        self.runs: dict[str, Any] = {}
        self.ended: set[str] = set()
        self._lock = threading.Lock()

    def generate_keyframe_options(self, prompts: list[str]) -> list[str]:
        """Make one image per prompt in one GPU job; the previews' paths.

        Waits for the job. The full PNGs stay in the run's folder in the
        bucket, at ``run.output_uri``.
        """
        key, run = self.start(prompts)
        try:
            result = run.result()
        finally:
            with self._lock:
                self.ended.add(key)
        return self._previews(key, run, result)

    def start(self, prompts: list[str]) -> tuple[str, Any]:
        """Submit the call, or return the run of the same prompts.

        Returns the prompts' key and the run.
        """
        count = len(prompts) if isinstance(prompts, list) else 0
        if not 1 <= count <= MAX_PROMPTS:
            raise ToolError(f"Send between 1 and {MAX_PROMPTS} prompts.")
        if not all(isinstance(prompt, str) for prompt in prompts):
            raise ToolError("Each prompt must be a string.")
        key = prompts_key(prompts)
        with self._lock:
            if key in self.runs:
                return key, self.runs[key]
            try:
                # Checks the arguments before it creates the job.
                run = self.task.submit(prompts)
            except ns.ValidationError as exc:
                raise ToolError(
                    f"The call was refused before any GPU started: {exc}"
                ) from None
            self.runs[key] = run
        print(f"Job {run.job.id}: {key}")
        return key, run

    def cancel_unfinished(self) -> list[str]:
        """Cancel the runs that haven't ended. Returns their keys.

        ``run_agent`` calls this when the agent run breaks. A run that
        ended is left alone.
        """
        cancelled = []
        with self._lock:
            for key, run in self.runs.items():
                if key not in self.ended:
                    run.cancel()
                    cancelled.append(key)
        return cancelled

    def _previews(
        self, key: str, run: Any, result: dict[str, Any]
    ) -> list[str]:
        """Save the JPEG previews here; their paths."""
        folder = self.out_dir / key
        folder.mkdir(parents=True, exist_ok=True)
        paths = []
        for i, preview in enumerate(result["previews"]):
            path = folder / f"preview-{i}.jpg"
            path.write_bytes(base64.b64decode(preview))
            paths.append(str(path))
        print(f"Full images: {run.output_uri}")
        return paths
agent.py
"""An image agent that makes keyframe options in one GPU task (example E4b).

Run it from this folder:

    python agent.py "a desk lamp, a person working from home, dusk"

The agent calls generate_keyframe_options once with up to four prompts,
then view_image on each preview. When the run breaks, run_agent cancels
the task runs that haven't ended. A run that ended is left alone.
"""

import asyncio
import os
import sys
from collections.abc import Callable
from pathlib import Path
from typing import Any

from pydantic_ai import Agent, BinaryContent, ModelRetry, ToolReturn
from pydantic_ai.messages import FunctionToolCallEvent
from pydantic_ai.models import Model
from pydantic_ai.models.openai import OpenAIChatModel
from pydantic_ai.providers.openai import OpenAIProvider
from tools import TaskTools, ToolError

INSTRUCTIONS = """
You pick the keyframe for a video advertisement, from the idea the user gives
you.

Write 4 different prompts for the idea and generate them with one call to
generate_keyframe_options. Every call runs a GPU job that takes several minutes
and costs money. Look at each image and pick the one that fits the idea best.
If none fits, call generate_keyframe_options once more with better prompts.
Never call it more than twice.

Answer with the path of the image you picked and one sentence on why.
""".strip()

MEDIA_TYPES = {
    ".png": "image/png",
    ".jpg": "image/jpeg",
    ".jpeg": "image/jpeg",
}


def nebius_model() -> OpenAIChatModel:
    """GLM-5.3-Flash on Nebius Token Factory. It reads images too."""
    return OpenAIChatModel(
        model_name="zai-org/GLM-5.3-Flash",
        provider=OpenAIProvider(
            base_url="https://api.tokenfactory.nebius.com/v1/",
            api_key=os.environ["NEBIUS_API_KEY"],
        ),
    )


def view_image(path: str) -> ToolReturn:
    """Look at an image. Use it to check a generated image."""
    media_type = MEDIA_TYPES.get(Path(path).suffix.lower(), "image/png")
    return ToolReturn(
        return_value=f"Image {path} is attached",
        content=[
            BinaryContent(data=Path(path).read_bytes(), media_type=media_type)
        ],
    )


def _tool(function: Callable[..., Any], *args: Any) -> Any:
    """Call a tool; a mistake the agent can fix goes back to the model."""
    try:
        return function(*args)
    except ToolError as exc:
        raise ModelRetry(str(exc)) from None


def build_agent(tools: TaskTools, model: Model | None = None) -> Agent:
    """The agent, with the tools of one run."""

    def generate_keyframe_options(prompts: list[str]) -> list[str]:
        """Generate one image per prompt with sana, all in one GPU job.

        Send 2 to 4 different prompts for the same idea, then look at the
        images and pick one. Returns the paths of small previews. It takes
        several minutes.
        """
        return _tool(tools.generate_keyframe_options, prompts)

    return Agent(
        name="tasks_image_agent",
        model=model or nebius_model(),
        tools=[generate_keyframe_options, view_image],
        instructions=INSTRUCTIONS,
    )


class NamedCallback:
    """Prints every tool call the agent makes (course lesson 2.2)."""

    def __init__(self, agent: Agent) -> None:
        self.agent_name = agent.name

    async def print_function_calls(self, ctx: Any, event: Any) -> None:
        if hasattr(event, "__aiter__"):
            async for sub in event:
                await self.print_function_calls(ctx, sub)
            return
        if isinstance(event, FunctionToolCallEvent):
            tool_name = event.part.tool_name
            args = event.part.args
            print(f"TOOL CALL ({self.agent_name}): {tool_name}({args})")

    async def __call__(self, ctx: Any, event: Any) -> None:
        await self.print_function_calls(ctx, event)


async def run_agent(agent: Agent, tools: TaskTools, prompt: str) -> Any:
    """Run the agent. When the run breaks, cancel the unfinished runs.

    A run that ended normally is left alone. The handler is around the
    whole run, not inside the tool: an interrupt stops the run, but not
    the thread the tool runs in.
    """
    try:
        return await agent.run(
            prompt, event_stream_handler=NamedCallback(agent)
        )
    except BaseException:
        cancelled = tools.cancel_unfinished()
        if cancelled:
            print(f"Cancelled runs: {', '.join(cancelled)}")
        raise


def main() -> None:
    from dotenv import load_dotenv

    load_dotenv()
    prompt = " ".join(sys.argv[1:]) or (
        "a desk lamp, a person working from home, dusk"
    )
    tools = TaskTools()
    result = asyncio.run(run_agent(build_agent(tools), tools, prompt))
    print(result.output)


if __name__ == "__main__":
    main()