An image agent with an endpoint¶
A Pydantic AI agent makes the keyframe for a video ad. It starts a Sana endpoint on an H100, generates an image, looks at it, and stops the endpoint. Our code deletes every endpoint the run created, however the run ends.
It follows lessons 2.2 and 2.3 of the course Production AI agents for media generation, with ns.Endpoint in place of the course's CLI wrappers.
View example files ↗ · Related reference: Endpoints →
What this example does¶
tools.pyhas the GPU tools. It uses the library only, with no agent framework.agent.pyhas the model,view_image, the agent, andrun_agent.
| Tool | What it does | Library calls |
|---|---|---|
start_endpoint(model) |
Creates the endpoint on first use, or starts it again if this run stopped it. Waits until the model answers on /v1/models. Reuses a running one: one endpoint per model. |
ns.Endpoint(spec).create(), endpoint.start(), endpoint.wait(probe="/v1/models") |
generate_image(prompt) |
Calls the endpoint with the token held in code, saves the PNG in out/, and returns its path. Without a running endpoint, it tells the agent to call start_endpoint first. |
endpoint.url, endpoint.token |
view_image(path) |
Sends the image to the model, so the agent checks what it generated. | none |
stop_endpoint(model) |
Stops the endpoint. It can start again in the same run. | endpoint.stop() |
Who decides what. The agent decides when it needs a GPU: it starts and stops the endpoint. Our code decides everything that costs money or touches credentials: the container image, the GPU, the disk, the token, and at most one endpoint per model. The agent sees only the model's name, sana. The models it may start are in MODELS in tools.py, as ns.EndpointSpec values: an allow-list is data our code fixes and the agent can't change, which is what specs are for.
Cleanup. run_agent runs the agent inside try/finally, and the finally deletes every endpoint the run created, stopped or not. It is around the whole run, not inside a tool: an interrupt stops the agent run, but not the thread a tool runs in. The endpoint id is printed as soon as create() returns it, before the long wait. If the process dies, delete it with ns.endpoints.get("<id>").delete().
Requirements¶
- A Nebius profile that can create endpoints: see Install and authenticate.
- H100 quota in the project's region.
- A Nebius Token Factory API key, for the agent's model,
zai-org/GLM-5.3-Flash. It reads images, whichview_imageneeds.
Runtime and compute¶
| Machine | gpu="h100", on-demand, set in code: a preempted spot endpoint would stop while the agent waits on it |
| Image | cr.eu-north1.nebius.cloud/e00gw2b7v3pxetvpy7/sana-serve:d315ae1: Sana 1.6B behind an OpenAI-style images API |
| Model | Efficient-Large-Model/Sana_1600M_1024px_diffusers, 1024×1024 |
| Port | 8000, token auth |
| Disk | 500Gi |
An endpoint bills from create until it is stopped or deleted. Most of its life is the start: a VM, the image pull and the model load take minutes.
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 (endpoints_image_agent): start_endpoint({"model": "sana"})
TOOL CALL (endpoints_image_agent): generate_image({"prompt": "..."})
TOOL CALL (endpoints_image_agent): view_image({"path": "out/sana-....png"})
TOOL CALL (endpoints_image_agent): stop_endpoint({"model": "sana"})
Press Ctrl-C while the endpoint starts: the run stops, and run_agent deletes the endpoint.
Check that nothing is left¶
No agent-sana-... endpoint should be there. To delete one by hand:
Licenses¶
- Sana: [license placeholder]
Common failures¶
| Symptom | Cause | Fix |
|---|---|---|
KeyError: 'NEBIUS_API_KEY' |
No Token Factory key | Set it in .env |
RuntimeError: The sana endpoint ... is ERROR |
No free GPU, or the container failed | See the endpoint's logs in the console. run_agent deletes it |
WaitTimeout from start_endpoint |
The model didn't answer within 30 minutes | See the endpoint's logs. run_agent deletes it |
An agent-sana-... endpoint exists after the run |
The process died, or an interrupt landed during create() |
Delete it with nebius ai endpoint delete --id <endpoint-id> |
Source¶
"""The GPU tools of the image agent: a Sana endpoint that it starts and stops.
This file uses the library only, with no agent framework. ``agent.py``
turns these methods into Pydantic AI tools.
The agent decides when it needs a GPU: it starts the endpoint, generates
images, and stops it. This code decides everything that costs money or
touches credentials: the container image, the GPU, the disk, the token,
and at most one endpoint per model. Whatever happens to the agent run,
``cleanup()`` deletes every endpoint the run created.
"""
import base64
import json
import threading
import urllib.request
from dataclasses import dataclass
from datetime import datetime
from pathlib import Path
from typing import Any
import nebius_serverless as ns
# A server for Sana 1.6B with an OpenAI-style images API on port 8000.
SANA_IMAGE = "cr.eu-north1.nebius.cloud/e00gw2b7v3pxetvpy7/sana-serve:d315ae1"
@dataclass(frozen=True)
class Model:
"""How to serve one model, and the model id its requests name."""
spec: ns.EndpointSpec
model_id: str
# The models the agent may start, by name. The agent sees only the name.
# Adding a model means adding one entry here, not changing the tools.
MODELS = {
"sana": Model(
spec=ns.EndpointSpec(
image=SANA_IMAGE,
port=8000,
gpu="h100",
# On-demand: a preempted spot endpoint would stop while the
# agent waits on it, and the run would fail.
pricing="on-demand",
disk="500Gi",
shm="16Gi",
),
model_id="Efficient-Large-Model/Sana_1600M_1024px_diffusers",
),
}
# Every endpoint created here is named agent-<model>-<time>, so a
# leftover one is easy to find with `nebius ai endpoint list`.
NAME_PREFIX = "agent-"
# A new endpoint starts a VM, pulls the image and loads the model.
READY_TIMEOUT = "30m"
class ToolError(Exception):
"""A mistake the agent can fix, such as generating before starting.
``agent.py`` sends the message back to the model.
"""
def post_json(url: str, body: dict[str, Any], token: str) -> Any:
"""POST ``body`` as JSON with the bearer token; the JSON answer.
Tests replace this function.
"""
request = urllib.request.Request(
url,
data=json.dumps(body).encode(),
headers={
"Authorization": f"Bearer {token}",
"Content-Type": "application/json",
},
method="POST",
)
with urllib.request.urlopen(request, timeout=300) as response:
return json.loads(response.read())
class EndpointTools:
"""The endpoints of one agent run, and the tools that use them.
``transport`` is for tests. ``None`` uses Nebius.
"""
def __init__(
self, out_dir: str | Path = "out", transport: Any = None
) -> None:
self.out_dir = Path(out_dir)
self.transport = transport
self.endpoints: dict[str, ns.Endpoint] = {}
self.stopped: set[str] = set()
self.created: list[ns.Endpoint] = []
# The model may call tools in parallel; one endpoint per model.
self._lock = threading.Lock()
def start_endpoint(self, model: str) -> str:
"""Start a GPU endpoint for the model and wait until it answers.
Creates it on first use, starts it again if this run stopped it,
and reuses it while it runs.
"""
if model not in MODELS:
raise ToolError(
f"Unknown model {model!r}. Use one of: {', '.join(MODELS)}."
)
with self._lock:
endpoint = self.endpoints.get(model)
if endpoint is None:
name = f"{NAME_PREFIX}{model}-{datetime.now():%Y%m%d-%H%M%S}"
spec = MODELS[model].spec.clone(name=name)
endpoint = ns.Endpoint(spec).create(transport=self.transport)
# Kept before the long wait: cleanup() deletes it even if
# the run breaks while the model loads.
self.endpoints[model] = endpoint
self.created.append(endpoint)
print(
f"Created endpoint {endpoint.id} ({name}). If this "
"process dies, delete it: "
f"ns.endpoints.get({endpoint.id!r}).delete()"
)
elif model in self.stopped:
endpoint.start()
self.stopped.discard(model)
# RUNNING means the container started; the model answers later.
endpoint.wait(READY_TIMEOUT, probe="/v1/models")
if endpoint.status != "RUNNING":
raise RuntimeError(
f"The {model} endpoint {endpoint.id} is {endpoint.status}. "
"See its logs in the console."
)
return f"The {model} endpoint is ready."
def generate_image(self, prompt: str) -> str:
"""Generate one image with the sana endpoint; the PNG's path."""
endpoint = self._running("sana")
answer = post_json(
f"{endpoint.url}/v1/images/generations",
{
"model": MODELS["sana"].model_id,
"prompt": prompt,
"size": "1024x1024",
"seed": 7,
"response_format": "b64_json",
"num_inference_steps": 20,
},
str(endpoint.token),
)
png = base64.b64decode(answer["data"][0]["b64_json"])
self.out_dir.mkdir(parents=True, exist_ok=True)
path = self.out_dir / f"sana-{datetime.now():%Y%m%d-%H%M%S-%f}.png"
path.write_bytes(png)
return str(path)
def stop_endpoint(self, model: str) -> str:
"""Stop the model's endpoint. It can start again in this run."""
with self._lock:
endpoint = self.endpoints.get(model)
if endpoint is None or model in self.stopped:
return f"The {model} endpoint isn't running."
endpoint.stop()
self.stopped.add(model)
return (
f"The {model} endpoint is stopped. start_endpoint('{model}') "
"starts it again."
)
def cleanup(self) -> list[str]:
"""Delete every endpoint this run created, stopped or not.
``run_agent`` calls this in its ``finally``. Returns the ids.
"""
deleted = []
with self._lock:
for endpoint in self.created:
try:
endpoint.delete(quiet=True)
deleted.append(str(endpoint.id))
except ns.Error as exc:
print(
f"Could not delete endpoint {endpoint.id}: {exc} "
f"Delete it: nebius ai endpoint delete --id "
f"{endpoint.id}"
)
self.created.clear()
self.endpoints.clear()
self.stopped.clear()
return deleted
def _running(self, model: str) -> ns.Endpoint:
endpoint = self.endpoints.get(model)
if endpoint is None or model in self.stopped:
raise ToolError(
f"The {model} endpoint isn't running. Call "
f"start_endpoint('{model}') first."
)
return endpoint
"""An image agent that starts and stops its own Sana endpoint (example E4a).
Run it from this folder:
python agent.py "a desk lamp, a person working from home, dusk"
The agent calls start_endpoint, generate_image, view_image and
stop_endpoint. run_agent deletes every endpoint the run created, however
the run ends, including Ctrl-C.
"""
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 EndpointTools, ToolError
INSTRUCTIONS = """
You make the keyframe for a video advertisement, from the idea the user gives
you.
You run the image model on a GPU endpoint. It costs money while it runs. Start
the sana endpoint, generate the image, and stop the endpoint as soon as the
image is good.
Look at every image before you accept it. If it doesn't show what you expect,
generate it again with a better prompt.
Answer with the path of the keyframe.
""".strip()
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."""
return ToolReturn(
return_value=f"Image {path} is attached",
content=[
BinaryContent(data=Path(path).read_bytes(), media_type="image/png")
],
)
def _tool(function: Callable[..., str], *args: Any) -> str:
"""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: EndpointTools, model: Model | None = None) -> Agent:
"""The agent, with the tools of one run."""
def start_endpoint(model: str) -> str:
"""Start a GPU endpoint for the model and wait until it's ready.
sana generates images. The first start takes several minutes. A
running endpoint is reused.
"""
return _tool(tools.start_endpoint, model)
def generate_image(prompt: str) -> str:
"""Generate an image with the sana endpoint; return its path."""
return _tool(tools.generate_image, prompt)
def stop_endpoint(model: str) -> str:
"""Stop the model's GPU endpoint. Call it as soon as you are done."""
return _tool(tools.stop_endpoint, model)
return Agent(
name="endpoints_image_agent",
model=model or nebius_model(),
tools=[start_endpoint, generate_image, view_image, stop_endpoint],
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: EndpointTools, prompt: str) -> Any:
"""Run the agent. However the run ends, delete its endpoints.
The ``finally`` is around the whole run, not inside a tool: an
interrupt stops the run, but not the thread a tool runs in.
"""
try:
return await agent.run(
prompt, event_stream_handler=NamedCallback(agent)
)
finally:
deleted = tools.cleanup()
if deleted:
print(f"Deleted endpoints: {', '.join(deleted)}")
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 = EndpointTools()
result = asyncio.run(run_agent(build_agent(tools), tools, prompt))
print(result.output)
if __name__ == "__main__":
main()