xonecas.ioDon't click! Sean Caetano Martin Sign in

skills / commits / 127d498

An openrouter skill makes images and runs one-shot prompts on other model families

Co-Authored-By: Claude Opus 5.5

sacenox2 days ago127d498d5b1f1b68e62cebe8121fe46e68f7fb11parent 770d60b3 files changed

README.md+1-0
@@ -11,6 +11,7 @@ How I work, written down for coding agents. Agent skills that follow the [Agent
1111 | [prose](skills/prose/SKILL.md) | Anything a person reads: the voice, the sentence rules, the tells to cut, and the formats for READMEs, commits, tickets, and replies |
1212 | [linux-computer-use](skills/linux-computer-use/SKILL.md) | Driving a real desktop window on KDE Wayland or XFCE X11: keys, clicks, screenshots, kitty, sound |
1313 | [cast](skills/cast/SKILL.md) | `/cast <prompt>`: plan the prompt as a workflow, review it in a local page, run it with subagents |
14+| [openrouter](skills/openrouter/SKILL.md) | Images, image edits, and one-shot prompts to other model families through OpenRouter |
1415
1516 ## Install
1617
skills/openrouter/SKILL.md+57-0
@@ -0,0 +1,57 @@
1+---
2+name: openrouter
3+description: Call OpenRouter with the user's OPENROUTER_API_KEY to generate or edit images, or to run a one-shot prompt on a non-Claude model such as Gemini, GPT, DeepSeek, or Qwen. Use when the user asks for an image, an asset, a second opinion from another model family, or anything that names OpenRouter.
4+---
5+
6+# Call OpenRouter with one script
7+
8+`scripts/openrouter.py` covers the whole job with the standard library: list models, ask a model, and make or edit images. Use it instead of writing `curl` calls. It reads `OPENROUTER_API_KEY` from the environment. Never print the key, and never pass it as an argument.
9+
10+Set `S` to the script in this skill's folder, such as `S=~/.claude/skills/openrouter/scripts/openrouter.py`.
11+
12+## Pick the model from the live list
13+
14+Model ids change every few weeks. Don't guess one. List them, filtered by a substring of the id:
15+
16+```bash
17+python3 -I $S models text gemini
18+python3 -I $S models image flux
19+```
20+
21+- `models text` prints the id, the context length, and the price in dollars per million input and output tokens.
22+- `models image` prints the id, the inputs it takes, and every parameter it accepts with the allowed values, such as `aspect_ratio=1:1,16:9 n=1-1 resolution=1K,2K`. A model with `image` in its inputs can edit.
23+
24+Pick the cheapest model that does the job, unless the user names one. In late 2026, `google/gemini-3.1-flash-lite` is a cheap text model and `black-forest-labs/flux-3-image-klein` makes an image for about $0.009.
25+
26+## Ask a model
27+
28+```bash
29+python3 -I $S ask google/gemini-3.1-flash-lite --system "Answer tersely." "What is a monad?"
30+python3 -I $S ask MODEL --ref shot.png "What is wrong with this layout?"
31+python3 -I $S ask MODEL < prompt.md
32+```
33+
34+The reply goes to stdout. The prompt comes from the arguments, or from stdin when there are none. Use stdin for long prompts.
35+
36+## Make or edit an image
37+
38+```bash
39+python3 -I $S image black-forest-labs/flux-3-image-klein assets/mushroom --json '{"aspect_ratio":"16:9"}' "a red pixel-art mushroom on white"
40+python3 -I $S image MODEL assets/mushroom-blue --ref assets/mushroom.jpg "make the mushroom blue"
41+```
42+
43+- The second argument is the output path without an extension. The script adds the extension from the returned type and prints each path it wrote. With `n` above 1, the files are `NAME-1.ext`, `NAME-2.ext`, and so on.
44+- `--ref FILE` sends an input image. Repeat it for several references.
45+- Open the file with the Read tool to check the result before you show it to the user.
46+
47+## Pass any other field with `--json`
48+
49+`--json` merges a JSON object into the request body. Use it for everything the flags don't cover.
50+
51+- Images go to `POST /api/v1/images`. Common fields are `aspect_ratio`, `resolution`, `n`, `seed`, `quality`, `output_format`, and `background` (`transparent` needs png or webp). Use only the values `models image` lists for that model.
52+- Text goes to `POST /api/v1/chat/completions`. Common fields are `temperature`, `max_tokens`, `reasoning`, and `response_format`.
53+
54+## Read the cost and the errors
55+
56+- The script prints `cost $0.009000` to stderr after each call.
57+- On failure it prints the provider's error as is and exits 1. A 400 such as `n: must be exactly 1` names the parameter to fix. Fix it and run again.
skills/openrouter/scripts/openrouter.py+99-0
@@ -0,0 +1,99 @@
1+import argparse
2+import base64
3+import json
4+import mimetypes
5+import os
6+import pathlib
7+import sys
8+import urllib.error
9+import urllib.request
10+
11+api = "https://openrouter.ai/api/v1"
12+
13+
14+def call(path, body=None):
15+ req = urllib.request.Request(api + path, json.dumps(body).encode() if body else None)
16+ key = os.environ.get("OPENROUTER_API_KEY") or sys.exit("OPENROUTER_API_KEY is not set")
17+ req.add_header("Authorization", "Bearer " + key)
18+ req.add_header("Content-Type", "application/json")
19+ try:
20+ with urllib.request.urlopen(req, timeout=600) as res:
21+ data = json.load(res)
22+ except urllib.error.HTTPError as e:
23+ sys.exit(f"openrouter {path}: HTTP {e.code}: {e.read().decode()}")
24+ if "error" in data:
25+ sys.exit(f"openrouter {path}: {json.dumps(data['error'])}")
26+ if "usage" in data:
27+ print(f"cost ${data['usage'].get('cost', 0):.6f}", file=sys.stderr)
28+ return data
29+
30+
31+def prompt(words):
32+ text = " ".join(words) or sys.stdin.read()
33+ return text.strip() or sys.exit("empty prompt: pass it as arguments or on stdin")
34+
35+
36+def data_url(file):
37+ kind = mimetypes.guess_type(file)[0] or sys.exit(f"{file}: unknown image type")
38+ return f"data:{kind};base64,{base64.b64encode(pathlib.Path(file).read_bytes()).decode()}"
39+
40+
41+def values(p):
42+ return {"enum": lambda: "=" + ",".join(p["values"]), "range": lambda: f"={p['min']}-{p['max']}"}.get(p["type"], str)()
43+
44+
45+def models(a):
46+ if a.kind == "image":
47+ for m in call("/images/models")["data"]:
48+ if a.filter in m["id"]:
49+ params = " ".join(k + values(p) for k, p in sorted(m["supported_parameters"].items()))
50+ print(f"{m['id']}\t{','.join(m['architecture']['input_modalities'])}\t{params}")
51+ return
52+ for m in call("/models?output_modalities=text")["data"]:
53+ if a.filter in m["id"]:
54+ p = m["pricing"]
55+ per_m = [f"{float(p[k]) * 1e6:g}" for k in ("prompt", "completion")]
56+ print(f"{m['id']}\t{m['context_length']}\t${per_m[0]}/${per_m[1]} per M")
57+
58+
59+def ask(a):
60+ content = [{"type": "text", "text": prompt(a.prompt)}]
61+ content += [{"type": "image_url", "image_url": {"url": data_url(f)}} for f in a.ref]
62+ messages = [{"role": "system", "content": a.system}] if a.system else []
63+ body = {"model": a.model, "messages": messages + [{"role": "user", "content": content}]}
64+ print(call("/chat/completions", body | json.loads(a.json))["choices"][0]["message"]["content"])
65+
66+
67+def image(a):
68+ body = {"model": a.model, "prompt": prompt(a.prompt)}
69+ if a.ref:
70+ body["input_references"] = [{"type": "image_url", "image_url": {"url": data_url(f)}} for f in a.ref]
71+ out = pathlib.Path(a.out)
72+ out.parent.mkdir(parents=True, exist_ok=True)
73+ items = call("/images", body | json.loads(a.json))["data"]
74+ for i, d in enumerate(items):
75+ ext = mimetypes.guess_extension(d.get("media_type", "image/png")) or ".png"
76+ path = out.with_name(out.name + (f"-{i + 1}" if len(items) > 1 else "") + ext)
77+ path.write_bytes(base64.b64decode(d["b64_json"]))
78+ print(path)
79+
80+
81+cli = argparse.ArgumentParser(prog="openrouter.py")
82+sub = cli.add_subparsers(required=True)
83+m = sub.add_parser("models", help="list models: id, context, $ per M tokens in/out; image: id, inputs, params")
84+m.add_argument("kind", choices=["text", "image"])
85+m.add_argument("filter", nargs="?", default="")
86+m.set_defaults(run=models)
87+for name, run in (("ask", ask), ("image", image)):
88+ p = sub.add_parser(name)
89+ p.add_argument("model")
90+ if name == "image":
91+ p.add_argument("out", help="output path without extension")
92+ else:
93+ p.add_argument("--system", default="")
94+ p.add_argument("--ref", action="append", default=[], help="input image file, repeatable")
95+ p.add_argument("--json", default="{}", help="extra request body fields as a JSON object")
96+ p.add_argument("prompt", nargs="*", help="prompt words, or stdin when absent")
97+ p.set_defaults(run=run)
98+args = cli.parse_args()
99+args.run(args)