Guides
Agent guides
Teach coding agents and agent frameworks to use ImgSearch: an AGENTS snippet, setups and two small programs.
https://imgsearch.com/llms.txt
An agent can use ImgSearch in two ways: through the MCP server, signed in as the person, or by calling the API with a key you give it. Either way it should follow the same four steps. The snippet below teaches them; https://imgsearch.com/llms.txt says the same at more length.
The AGENTS snippet #
Paste this into the instructions file your coding agent reads (such as AGENTS.md or CLAUDE.md). It is also served as Markdown at https://imgsearch.com/developers/AGENTS-snippet.md.
## ImgSearch
ImgSearch is a library of photos, SVG illustrations and packs, brand logos, sound effects, 3D models and videos, with an AI Generator for what the library lacks.
### Calling the API
- Base URL: https://imgsearch.com/api/v2
- Send `Authorization: Bearer $IMGSEARCH_API_KEY`. Read the key from the environment; never put it in client-side code or commit it.
- JSON in and out, except uploads (multipart), files and redirects. Reference: https://imgsearch.com/developers/reference.md. Errors: https://imgsearch.com/developers/errors.md.
### The order
Follow these four steps for every need:
1. Search first. For any need for an image, illustration, icon, video, sound, music, voice or 3D model, search once per distinct need, in the user’s own generations and the ImgSearch library. Searching is free.
2. Inspect. Read each result’s description, size and license, and its band where one is given: strong usually fits when the description shows what was asked for; possible needs a closer look. Prefer results the user made or already owns, which cost nothing. If a search says it is incomplete, search again before deciding.
3. Reuse if one fits. Download only the items you chose.
4. Generate only if nothing fits, and only where generating is offered. Check the estimate first and stay within the most the user allowed; ask the user before going higher. If a request is refused for its content, tell the user; do not rephrase or retry it.
### Rules for every call
- Send an `Idempotency-Key` header and `max_usd` (the most it may cost, in US dollars) with `POST /generations` and `POST /generations/{id}/upscale`. The same key with the same body charges nothing twice.
- If a call answers `price_above_max`, ask the user before sending a higher `max_usd`.
- If a request is refused with `content_refused`, tell the user; do not rephrase or retry it.
- On `429 rate_limited`, `too_many_active` or `checks_busy`, wait `retry_after_seconds` (also sent as `Retry-After`) before the next call.
- On `429 fair_use_reached`, stop new downloads and tell the user: they work again at `details.resets_at`, and files the account already owns stay free.
- If a search answers `complete: false`, search again before generating.
- Read an unfinished generation again after `poll_after_seconds`, or receive its events by webhook.
### More
- What ImgSearch is, for agents: https://imgsearch.com/llms.txt
- The API reference: https://imgsearch.com/developers/reference.md
The commands to connect each tool to the MCP server:
Server URL:
https://imgsearch.com/mcp
Claude Code
claude mcp add --transport http imgsearch --scope user https://imgsearch.com/mcp
Codex
codex mcp add imgsearch --url https://imgsearch.com/mcp
codex mcp login imgsearch
Cursor (in mcpServers of .cursor/mcp.json)
"imgsearch": {
"url": "https://imgsearch.com/mcp"
}
Claude Code #
- Through MCP: run the Claude Code command above, then type
/mcpin a session and approve the connection in your browser. Claude Code then has ImgSearch’s tools and their instructions. - Through the API: put the key in
IMGSEARCH_API_KEYin the environment Claude Code runs in, and the snippet in your project’s instructions. The agent can then call the API with curl or a script, such as the plain loop below.
Codex #
- Through MCP: run the Codex commands above. The login command opens the sign-in in your browser.
- Through the API: put the key in
IMGSEARCH_API_KEYin the environment Codex runs in, and the snippet in your project’sAGENTS.md.
Cursor #
- Through MCP: add the entry above to
.cursor/mcp.json, then select "Needs login" next to ImgSearch and approve in your browser. - Through the API: put the key in
IMGSEARCH_API_KEYin the environment Cursor’s agent runs in, and the snippet in your project’s instructions.
OpenAI Agents SDK #
An agent built with the OpenAI Agents SDK gets ImgSearch as function tools. This one takes its instructions from llms.txt, and its generate tool always sends max_usd (the user’s limit in US dollars, from MAX_USD) and an Idempotency-Key made from the request, so a repeated call never charges twice.
"""An OpenAI Agents SDK agent that uses ImgSearch through function tools: search, a download link, estimate, generate
and reading a generation.
pip install openai-agents httpx. Needs OPENAI_API_KEY (for the agent's model) and IMGSEARCH_API_KEY.
MAX_USD is the most the user allows one generation to cost, in US dollars; generate() never sends more.
"""
import os
import uuid
import httpx
from agents import Agent, Runner, function_tool
BASE = os.environ.get("IMGSEARCH_API_BASE", "https://imgsearch.com/api/v2")
SITE = BASE.removesuffix("/api/v2")
MAX_USD = float(os.environ.get("MAX_USD", "0"))
api = httpx.Client(base_url=BASE, headers={"Authorization": f"Bearer {os.environ['IMGSEARCH_API_KEY']}"}, timeout=60)
def answer(r):
"""The JSON of an answer, errors included: the agent reads error.code and error.message."""
return r.json()
@function_tool
def search(query: str, kind: str = "image") -> dict:
"""Search the user's own generations and the ImgSearch library for one need. Searching is free."""
return answer(api.post("/search", json={"query": query, "kind": kind, "limit": 10}))
@function_tool
def download_link(item_type: str, item_id: str) -> dict:
"""A 10-minute download link for one search result you chose (its type and id), for the user to open."""
return answer(api.post("/downloads", json={"items": [{"type": item_type, "id": item_id}]}))
@function_tool
def estimate(kind: str, prompt: str) -> dict:
"""What generating this would cost in US dollars with the default model, and whether it can start now."""
return answer(api.post("/generations/estimate", json={"kind": kind, "prompt": prompt}))
@function_tool
def generate(kind: str, prompt: str) -> dict:
"""Start a generation, only after search found nothing that fits. Spends at most the user's limit."""
if MAX_USD <= 0:
return {"refused": "The user has not allowed any spending (MAX_USD)."}
key = str(uuid.uuid5(uuid.NAMESPACE_URL, f"imgsearch-agent:{kind}:{prompt}")) # the same request never charges twice
body = {"kind": kind, "prompt": prompt, "max_usd": MAX_USD}
return answer(api.post("/generations", json=body, headers={"Idempotency-Key": key}))
@function_tool
def get_generation(generation_id: str) -> dict:
"""A generation's status and, once it succeeded, its 10-minute file links. Wait poll_after_seconds between reads."""
return answer(api.get(f"/generations/{generation_id}"))
agent = Agent(
name="Asset finder",
# ImgSearch's own guide for agents: the four steps and the rules for every call.
instructions=httpx.get(f"{SITE}/llms.txt", timeout=30).text,
tools=[search, download_link, estimate, generate, get_generation],
)
if __name__ == "__main__":
result = Runner.run_sync(agent, "Find a 16:9 hero image of a red fox in fresh snow at sunrise for a blog post.")
print(result.final_output)
A plain Python loop #
No framework: search, inspect, reuse or generate, wait, save. Run it with a need as its argument; it generates only when nothing fits and the price is within MAX_USD, stops with the reason on content_refused or price_above_max, and uses an Idempotency-Key made from the need, so running it twice never pays twice.
"""Gets one picture for a need from ImgSearch: search first, reuse what fits, generate only when nothing does.
Usage: python3 plain_loop.py "a red fox in fresh snow at sunrise, space on the left for a headline"
Needs IMGSEARCH_API_KEY. MAX_USD is the most the user allows a generation to cost, in US dollars (0, the default, never
generates).
"""
import os
import re
import sys
import time
import uuid
import httpx
BASE = os.environ.get("IMGSEARCH_API_BASE", "https://imgsearch.com/api/v2")
MAX_USD = float(os.environ.get("MAX_USD", "0"))
api = httpx.Client(base_url=BASE, headers={"Authorization": f"Bearer {os.environ['IMGSEARCH_API_KEY']}"}, timeout=60)
def call(method, path, **kwargs):
"""One API call; waits out a 429 once when it says how long (fair use does not), and stops with the error's message
on any other error."""
r = api.request(method, path, **kwargs)
if r.status_code == 429 and "Retry-After" in r.headers:
time.sleep(int(r.headers["Retry-After"]))
r = api.request(method, path, **kwargs)
if r.status_code >= 400:
error = r.json()["error"]
sys.exit(f"{error['code']}: {error['message']}")
return r
def save(response, fallback):
match = re.search(r'filename="?([^";]+)', response.headers.get("content-disposition", ""))
name = match.group(1) if match else fallback
with open(name, "wb") as file:
file.write(response.content)
return name
need = sys.argv[1]
# 1. Search first: the user's own generations and the library together. Search again if a source failed just now.
for attempt in range(2):
found = call("POST", "/search", json={"query": need, "kind": "image", "filters": {"orientation": "landscape"}, "limit": 10}).json()
if found["complete"]:
break
# 2. Inspect: read each description; strong usually fits, and owned or own items cost nothing.
for card in found["results"]:
print(card["band"], card["owned"], card["made_by_you"], card["type"], card["id"], "-", card["description"][:100])
fits = [card for card in found["results"] if card["band"] == "strong" and card["type"] in ("photo", "generation")]
fits.sort(key=lambda card: not (card["owned"] or card["made_by_you"]))
# 3. Reuse if one fits: download only the item chosen.
if fits:
card = fits[0]
if card["type"] == "generation":
generation_id, n = card["id"].split(":")
file = call("GET", f"/generations/{generation_id}/outputs/{n}", params={"download": 1})
else:
link = call("POST", "/downloads", json={"items": [{"type": card["type"], "id": card["id"]}]}).json()["data"][0]
if link["status"] != "ready":
sys.exit(link["error"]["message"])
file = httpx.get(link["url"], timeout=60) # a signed link: it needs no key
print("Reused", card["type"], card["id"], "saved as", save(file, card["id"]))
sys.exit(0)
# 4. Generate only if nothing fits, within what the user allowed.
estimate = found["generation_estimate"]
if estimate is None or not estimate["can_generate"]:
sys.exit("Nothing fits, and generating is not possible now: " + str(estimate and estimate["reason"]))
if estimate["per_output_usd"] > MAX_USD:
sys.exit(f"Nothing fits. Generating costs ${estimate['per_output_usd']}, more than the ${MAX_USD} allowed: ask the user.")
# The same need gives the same Idempotency-Key, so running this again never charges twice.
key = str(uuid.uuid5(uuid.NAMESPACE_URL, "imgsearch-plain-loop:" + need))
body = {"kind": "image", "model": estimate["model"]["id"], "prompt": need, "options": {"aspect_ratio": "16:9"}, "max_usd": MAX_USD}
r = api.post("/generations", json=body, headers={"Idempotency-Key": key})
if r.status_code >= 400:
error = r.json()["error"]
# content_refused: tell the user; never rephrase or retry. price_above_max: ask before raising max_usd.
sys.exit(f"Not generated ({error['code']}): {error['message']}")
generation = r.json()
while generation["status"] in ("queued", "running"):
time.sleep(generation["poll_after_seconds"] or 5)
generation = call("GET", f"/generations/{generation['id']}").json()
if generation["status"] != "succeeded":
sys.exit(f"The generation {generation['status']}: {generation['error']['message']}")
output = generation["outputs"][0]
print("Generated", generation["id"], "for", f"${generation['charged_usd']},", "saved as",
save(httpx.get(output["download_url"], timeout=60), generation["id"] + ".png"))