diff --git a/docs/images/generate-image.png b/docs/images/generate-image.png index a9fa3854..2f9d2ffd 100644 Binary files a/docs/images/generate-image.png and b/docs/images/generate-image.png differ diff --git a/docs/images/scientific-schematics.png b/docs/images/scientific-schematics.png index c2415229..ceb391c3 100644 Binary files a/docs/images/scientific-schematics.png and b/docs/images/scientific-schematics.png differ diff --git a/skills/arbor/references/arbor-upstream.md b/skills/arbor/references/arbor-upstream.md index c5646f7a..f6ae76a2 100644 --- a/skills/arbor/references/arbor-upstream.md +++ b/skills/arbor/references/arbor-upstream.md @@ -19,7 +19,7 @@ Requires Python ≥ 3.10 and Git. git clone https://github.com/RUC-NLPIR/Arbor.git cd Arbor python -m venv .venv && source .venv/bin/activate -pip install -e . +uv pip install -e . arbor doctor # verify install, PATH, git, API keys ``` diff --git a/skills/citation-management/SKILL.md b/skills/citation-management/SKILL.md index f31b793a..838bc66c 100644 --- a/skills/citation-management/SKILL.md +++ b/skills/citation-management/SKILL.md @@ -4,7 +4,7 @@ description: Comprehensive citation management for academic research. Search Goo allowed-tools: Read Write Edit Bash license: MIT License metadata: - version: "1.6" + version: "1.7" skill-author: K-Dense Inc. openclaw: primaryEnv: OPENROUTER_API_KEY @@ -276,22 +276,22 @@ literature-review and Zotero/pyzotero export paths — are in ```bash # Core dependencies -pip install requests # HTTP requests for APIs -pip install bibtexparser # BibTeX parsing and formatting -pip install biopython # PubMed E-utilities access +uv pip install requests # HTTP requests for APIs +uv pip install bibtexparser # BibTeX parsing and formatting +uv pip install biopython # PubMed E-utilities access # Optional (for Google Scholar) -pip install scholarly # Google Scholar API wrapper +uv pip install scholarly # Google Scholar API wrapper # or -pip install selenium # For more robust Scholar scraping +uv pip install selenium # For more robust Scholar scraping ``` ### Optional Tools ```bash # For advanced validation -pip install crossref-commons # Enhanced CrossRef API access -pip install pylatexenc # LaTeX special character handling +uv pip install crossref-commons # Enhanced CrossRef API access +uv pip install pylatexenc # LaTeX special character handling ``` ### Where credentials are sent diff --git a/skills/citation-management/scripts/generate_schematic.py b/skills/citation-management/scripts/generate_schematic.py index 64246559..6392aebf 100644 --- a/skills/citation-management/scripts/generate_schematic.py +++ b/skills/citation-management/scripts/generate_schematic.py @@ -147,7 +147,12 @@ Environment Variables: help="Verbose output") args = parser.parse_args() - + + # Validated here rather than clamped silently, and before the credential + # lookup so an out-of-range value reports itself rather than an absent key. + if not 1 <= args.iterations <= 2: + parser.error("--iterations must be 1 or 2") + # Check for API key — resolves --api-key, the environment, then any .env file api_key = resolve_api_key(args.api_key) if not api_key: @@ -173,12 +178,9 @@ Environment Variables: if args.doc_type != "default": cmd.extend(["--doc-type", args.doc_type]) - - # Enforce max 2 iterations - iterations = min(args.iterations, 2) - if iterations != 2: - cmd.extend(["--iterations", str(iterations)]) - + + cmd.extend(["--iterations", str(args.iterations)]) + if args.verbose: cmd.append("-v") diff --git a/skills/citation-management/scripts/generate_schematic_ai.py b/skills/citation-management/scripts/generate_schematic_ai.py index 3e3e475f..85c4fd29 100644 --- a/skills/citation-management/scripts/generate_schematic_ai.py +++ b/skills/citation-management/scripts/generate_schematic_ai.py @@ -22,17 +22,94 @@ import argparse import base64 import json import os +import re import sys import time from pathlib import Path -from typing import Optional, Dict, Any, List, Tuple +from typing import Optional, Dict, Any, List, NamedTuple try: import requests except ImportError: - print("Error: requests library not found. Install with: pip install requests") + print("Error: requests library not found. Install with: uv pip install requests") sys.exit(1) + +class ReviewResult(NamedTuple): + """The outcome of one quality review. + + A named tuple rather than a bare tuple because the review has several + failure modes -- the model returns no choices, the request raises, the + answer arrives in an unexpected shape -- and each of them used to be a + chance to return the wrong number of values to the caller. + + `score` is None whenever no usable number was parsed, and `reviewed` is + False whenever the review never produced an answer at all. Neither case + invents a score: a diagram whose quality was not measured is reported as + unmeasured, not as passing. + """ + + critique: str + score: Optional[float] + needs_improvement: bool + reviewed: bool + error: Optional[str] = None + + +# Markdown decoration the reviewer routinely wraps its answer in. Gemini writes +# "**SCORE:** 8.5" far more often than the bare "SCORE: 8.5" the rubric asks +# for, and a pattern that does not allow for it silently scores every diagram +# at whatever the default happens to be. +_MARKUP = re.compile(r"[*_`#]") + +_SCORE_PATTERN = re.compile(r"\bSCORE\s*:?\s*(\d+(?:\.\d+)?)", re.IGNORECASE) +_LOOSE_SCORE_PATTERN = re.compile( + r"(?:score|rating|quality)\s*[:\s]\s*(\d+(?:\.\d+)?)\s*(?:/\s*10)?", re.IGNORECASE +) +# The underscore is optional because normalization strips it out of +# NEEDS_IMPROVEMENT along with the surrounding markdown. +_VERDICT_PATTERN = re.compile( + r"^\s*VERDICT\s*:?\s*(ACCEPTABLE|NEEDS[_ ]?IMPROVEMENT)", re.IGNORECASE | re.MULTILINE +) + + +def _normalize_review_text(text: str) -> str: + """Strip markdown decoration so the rubric's fields can be found.""" + return _MARKUP.sub("", text or "") + + +def _parse_score(text: str) -> Optional[float]: + """Return the reviewer's 0-10 score, or None when there isn't a usable one. + + None rather than a default: a fabricated score is indistinguishable from a + real one once it reaches the review log, and a default near the middle of + the range quietly passes lenient document types while failing strict ones. + """ + normalized = _normalize_review_text(text) + match = _SCORE_PATTERN.search(normalized) or _LOOSE_SCORE_PATTERN.search(normalized) + if not match: + return None + score = float(match.group(1)) + # A number outside the rubric's range means something other than the score + # was matched -- a figure count, a percentage, an iteration number. + return score if 0.0 <= score <= 10.0 else None + + +def _parse_verdict(text: str) -> Optional[str]: + """Return ACCEPTABLE / NEEDS_IMPROVEMENT from the verdict line, or None. + + Anchored to the start of a line. The rubric prompt spells out both tokens + when it explains the response format, so a reviewer that echoes those + instructions back would fail a perfectly good diagram under a plain + substring search. + """ + match = _VERDICT_PATTERN.search(_normalize_review_text(text)) + if not match: + return None + verdict = match.group(1).upper().replace(" ", "").replace("_", "") + return "NEEDS_IMPROVEMENT" if verdict == "NEEDSIMPROVEMENT" else "ACCEPTABLE" + + def _resolve_api_key(explicit: Optional[str] = None) -> Optional[str]: """Resolve the OpenRouter key from --api-key, the environment, then any .env file. @@ -282,7 +359,6 @@ IMPORTANT - NO FIGURE NUMBERS: # Handle string content if isinstance(content, str) and "data:image" in content: - import re match = re.search(r'data:image/[^;]+;base64,([A-Za-z0-9+/=\n\r]+)', content, re.DOTALL) if match: base64_str = match.group(1).replace('\n', '').replace('\r', '').replace(' ', '') @@ -417,24 +493,24 @@ IMPORTANT - NO FIGURE NUMBERS: def review_image(self, image_path: str, original_prompt: str, iteration: int, doc_type: str = "default", - max_iterations: int = 2) -> Tuple[str, float, bool]: + max_iterations: int = 2) -> ReviewResult: """ - Review generated image using Gemini 3.6 Flash for quality analysis. - - Uses Gemini 3.6 Flash's superior vision and reasoning capabilities to - evaluate the schematic quality and determine if regeneration is needed. - + Review the generated image for quality, using the vision review model. + Args: image_path: Path to the generated image original_prompt: Original user prompt iteration: Current iteration number doc_type: Document type (journal, poster, presentation, etc.) max_iterations: Maximum iterations allowed - + Returns: - Tuple of (critique text, quality score 0-10, needs_improvement bool) + A ReviewResult. When the review cannot be completed -- the request + fails, or the model answers with nothing usable -- `reviewed` is + False and `score` is None rather than a stand-in number, and + `needs_improvement` is False: the fault is in the reviewer, not in + the diagram, so regenerating would not help. """ - # Use Gemini 3.6 Flash for review - excellent vision and analysis image_data_url = self._image_to_base64(image_path) # Get quality threshold for this document type @@ -510,25 +586,32 @@ If score < {threshold}, mark as NEEDS_IMPROVEMENT with specific suggestions.""" ] try: - # Use Gemini 3.6 Flash for high-quality review response = self._make_request( model=self.review_model, messages=messages ) - + # Extract text response choices = response.get("choices", []) if not choices: - return "Image generated successfully", 8.0 - + # A normal enough outcome -- a rate limit, a content filter, a + # provider hiccup. The diagram itself is fine; only its review + # is missing, and saying so beats inventing a score. + reason = "the review model returned no choices" + self._log(f"⚠ Review unavailable: {reason}") + return ReviewResult( + f"Review unavailable: {reason}.", + None, False, reviewed=False, error=reason, + ) + message = choices[0].get("message", {}) content = message.get("content", "") - - # Check reasoning field (Nano Banana 2 puts analysis here) + + # Some models put their analysis in a separate reasoning field reasoning = message.get("reasoning", "") if reasoning and not content: content = reasoning - + if isinstance(content, list): # Extract text from content blocks text_parts = [] @@ -536,38 +619,41 @@ If score < {threshold}, mark as NEEDS_IMPROVEMENT with specific suggestions.""" if isinstance(block, dict) and block.get("type") == "text": text_parts.append(block.get("text", "")) content = "\n".join(text_parts) - - # Try to extract score - score = 7.5 # Default score if extraction fails - import re - - # Look for SCORE: X or SCORE: X/10 format - score_match = re.search(r'SCORE:\s*(\d+(?:\.\d+)?)', content, re.IGNORECASE) - if score_match: - score = float(score_match.group(1)) - else: - # Fallback: look for any score pattern - score_match = re.search(r'(?:score|rating|quality)[:\s]+(\d+(?:\.\d+)?)\s*(?:/\s*10)?', content, re.IGNORECASE) - if score_match: - score = float(score_match.group(1)) - - # Determine if improvement is needed based on verdict or score - needs_improvement = False - if "NEEDS_IMPROVEMENT" in content.upper(): - needs_improvement = True - elif score < threshold: - needs_improvement = True - - self._log(f"✓ Review complete (Score: {score}/10, Threshold: {threshold}/10)") + + score = _parse_score(content) + verdict = _parse_verdict(content) + + if score is None and verdict is None: + reason = "no score or verdict found in the review" + self._log(f"⚠ Review unusable: {reason}") + return ReviewResult( + content if content else f"Review unusable: {reason}.", + None, False, reviewed=True, error=reason, + ) + + needs_improvement = verdict == "NEEDS_IMPROVEMENT" or ( + score is not None and score < threshold + ) + + shown = f"{score}/10" if score is not None else "not stated" + self._log(f"✓ Review complete (Score: {shown}, Threshold: {threshold}/10)") self._log(f" Verdict: {'Needs improvement' if needs_improvement else 'Acceptable'}") - - return (content if content else "Image generated successfully", - score, - needs_improvement) + + return ReviewResult( + content if content else "Review returned no text", + score, + needs_improvement, + reviewed=True, + error=None if score is not None else "no score found in the review", + ) except Exception as e: - self._log(f"Review skipped: {str(e)}") - # Don't fail the whole process if review fails - assume acceptable - return "Image generated successfully (review skipped)", 7.5, False + # A failed review must not fail the run -- the image is already + # generated and saved -- but it must not read as a pass either. + self._log(f"⚠ Review failed: {str(e)}") + return ReviewResult( + f"Review failed: {str(e)}", + None, False, reviewed=False, error=str(e), + ) def improve_prompt(self, original_prompt: str, critique: str, iteration: int) -> str: @@ -629,7 +715,10 @@ Generate an improved version that addresses all the critique points while mainta "quality_threshold": threshold, "iterations": [], "final_image": None, - "final_score": 0.0, + # None, not 0.0 -- a run whose review never completed has no score, + # and a number here would be read as one the reviewer gave. + "final_score": None, + "final_reviewed": False, "success": False, "early_stop": False, "early_stop_reason": None @@ -675,48 +764,63 @@ Generate a publication-quality scientific diagram that meets all the guidelines f.write(image_data) print(f"✓ Saved: {iter_path}") - # Review image using Gemini 3.6 Flash - print(f"Reviewing image with Gemini 3.6 Flash...") - critique, score, needs_improvement = self.review_image( + # Review the image with the vision review model + print(f"Reviewing image with {self.review_model}...") + review = self.review_image( str(iter_path), user_prompt, i, doc_type, iterations ) - print(f"✓ Score: {score}/10 (threshold: {threshold}/10)") - + if review.score is not None: + print(f"✓ Score: {review.score}/10 (threshold: {threshold}/10)") + else: + print(f"⚠ Review unavailable — image kept, quality not verified") + print(f" Reason: {review.error}") + # Save iteration results iteration_result = { "iteration": i, "image_path": str(iter_path), "prompt": current_prompt, - "critique": critique, - "score": score, - "needs_improvement": needs_improvement, + "critique": review.critique, + "score": review.score, + "reviewed": review.reviewed, + "review_error": review.error, + "needs_improvement": review.needs_improvement, "success": True } results["iterations"].append(iteration_result) - + # Check if quality is acceptable - STOP EARLY if so - if not needs_improvement: - print(f"\n✓ Quality meets {doc_type} threshold ({score} >= {threshold})") - print(f" No further iterations needed!") + if not review.needs_improvement: + if review.score is not None: + print(f"\n✓ Quality meets {doc_type} threshold ({review.score} >= {threshold})") + print(f" No further iterations needed!") + reason = (f"Quality score {review.score} meets threshold " + f"{threshold} for {doc_type}") + else: + # Regenerating cannot fix a reviewer that did not answer. + print(f"\n⚠ Stopping without a verified score — review the image yourself") + reason = f"Review did not produce a score: {review.error}" results["final_image"] = str(iter_path) - results["final_score"] = score + results["final_score"] = review.score + results["final_reviewed"] = review.reviewed and review.score is not None results["success"] = True results["early_stop"] = True - results["early_stop_reason"] = f"Quality score {score} meets threshold {threshold} for {doc_type}" + results["early_stop_reason"] = reason break - + # If this is the last iteration, we're done regardless if i == iterations: print(f"\n⚠ Maximum iterations reached") results["final_image"] = str(iter_path) - results["final_score"] = score + results["final_score"] = review.score + results["final_reviewed"] = review.reviewed and review.score is not None results["success"] = True break - + # Quality below threshold - improve prompt for next iteration - print(f"\n⚠ Quality below threshold ({score} < {threshold})") + print(f"\n⚠ Quality below threshold ({review.score} < {threshold})") print(f"Improving prompt based on feedback...") - current_prompt = self.improve_prompt(user_prompt, critique, i + 1) + current_prompt = self.improve_prompt(user_prompt, review.critique, i + 1) # Copy final version to output path if results["success"] and results["final_image"]: @@ -734,7 +838,10 @@ Generate a publication-quality scientific diagram that meets all the guidelines print(f"\n{'='*60}") print(f"Generation Complete!") - print(f"Final Score: {results['final_score']}/10") + if results["final_score"] is not None: + print(f"Final Score: {results['final_score']}/10") + else: + print(f"Final Score: unavailable (the review did not produce one)") if results["early_stop"]: print(f"Iterations Used: {len([r for r in results['iterations'] if r.get('success')])}/{iterations} (early stop)") print(f"{'='*60}\n") @@ -821,8 +928,14 @@ Environment: if results["success"]: print(f"\n✓ Success! Image saved to: {args.output}") - if results.get("early_stop"): - print(f" (Completed in {len([r for r in results['iterations'] if r.get('success')])} iteration(s) - quality threshold met)") + used = len([r for r in results['iterations'] if r.get('success')]) + if results.get("final_reviewed"): + if results.get("early_stop"): + print(f" (Completed in {used} iteration(s) - quality threshold met)") + else: + # The image is real; the quality claim is not. Say which. + print(f" (Completed in {used} iteration(s) - quality NOT verified," + f" the review produced no score. Check the image yourself.)") sys.exit(0) else: print(f"\n✗ Generation failed. Check review log for details.") diff --git a/skills/citation-management/scripts/search_google_scholar.py b/skills/citation-management/scripts/search_google_scholar.py index 94a4e02b..95dc3823 100755 --- a/skills/citation-management/scripts/search_google_scholar.py +++ b/skills/citation-management/scripts/search_google_scholar.py @@ -4,7 +4,7 @@ Google Scholar Search Tool Search Google Scholar and export results. Note: This script requires the 'scholarly' library. -Install with: pip install scholarly +Install with: uv pip install scholarly """ import sys @@ -19,7 +19,7 @@ try: SCHOLARLY_AVAILABLE = True except ImportError: SCHOLARLY_AVAILABLE = False - print('Warning: scholarly library not installed. Install with: pip install scholarly', file=sys.stderr) + print('Warning: scholarly library not installed. Install with: uv pip install scholarly', file=sys.stderr) class GoogleScholarSearcher: """Search Google Scholar using scholarly library.""" @@ -32,7 +32,7 @@ class GoogleScholarSearcher: use_proxy: Use free proxy (helps avoid rate limiting) """ if not SCHOLARLY_AVAILABLE: - raise ImportError('scholarly library required. Install with: pip install scholarly') + raise ImportError('scholarly library required. Install with: uv pip install scholarly') # Setup proxy if requested if use_proxy: @@ -236,7 +236,7 @@ def main(): if not SCHOLARLY_AVAILABLE: print('\nError: scholarly library not installed', file=sys.stderr) - print('Install with: pip install scholarly', file=sys.stderr) + print('Install with: uv pip install scholarly', file=sys.stderr) print('\nAlternatively, use PubMed search for biomedical literature:', file=sys.stderr) print(' python search_pubmed.py "your query"', file=sys.stderr) sys.exit(1) diff --git a/skills/exa-search/SKILL.md b/skills/exa-search/SKILL.md index 35364378..5efcd305 100644 --- a/skills/exa-search/SKILL.md +++ b/skills/exa-search/SKILL.md @@ -77,7 +77,7 @@ First, check if a `.env` file exists in the project root and contains `EXA_API_K dotenv -f .env run -- uv run --with exa-py python "$SKILL_PATH/scripts/exa_search.py" "your query" ``` -If `dotenv` isn't available, install it: `pip install python-dotenv[cli]` or `uv pip install python-dotenv[cli]`. +If `dotenv` isn't available, install it: `uv pip install python-dotenv[cli]`. If there's no `.env`, export the key for the session: diff --git a/skills/generate-image/SKILL.md b/skills/generate-image/SKILL.md index 0f8c3486..67aef140 100644 --- a/skills/generate-image/SKILL.md +++ b/skills/generate-image/SKILL.md @@ -1,13 +1,13 @@ --- name: generate-image -description: Generate or edit images with AI models through the OpenRouter Image API (Gemini, FLUX, Seedream, Recraft, GPT-Image). Use for photos, illustrations, artwork, concept art, visual assets, logos, and image editing or compositing from reference images. For flowcharts, circuits, pathways, and other technical diagrams, use the scientific-schematics skill instead. +description: Generate or edit images with AI models through the OpenRouter Image API (Gemini, Seedream, Recraft, GPT-Image, Riverflow). Use for photos, illustrations, artwork, concept art, visual assets, logos, and image editing or compositing from reference images. For flowcharts, circuits, pathways, and other technical diagrams, use the scientific-schematics skill instead. license: MIT -compatibility: Requires Python 3.9+ and network access to openrouter.ai. The bundled script uses only the standard library. Image generation requires the OPENROUTER_API_KEY credential and bills per request; listing models does not. Targets the OpenRouter Image API (POST /api/v1/images) as documented on 2026-07-26. +compatibility: Requires Python 3.9+ and network access to openrouter.ai. The bundled script uses only the standard library. Image generation requires the OPENROUTER_API_KEY credential and bills per request; listing models, inspecting a model, and --dry-run do not. Targets the OpenRouter Image API (POST /api/v1/images) as verified on 2026-07-31. allowed-tools: Read Write Edit Bash metadata: - version: "2.0" + version: "3.0" skill-author: K-Dense Inc. - last-reviewed: "2026-07-26" + last-reviewed: "2026-07-31" openclaw: primaryEnv: OPENROUTER_API_KEY envVars: @@ -18,8 +18,8 @@ metadata: # Generate Image -Generate and edit images through OpenRouter's Image API, which reaches Gemini, FLUX, Seedream, -Recraft, GPT-Image, and roughly thirty other models behind one request shape. +Generate and edit images through OpenRouter's Image API, which reaches Gemini, Seedream, Recraft, +GPT-Image, Riverflow, and roughly thirty other models behind one request shape. ## When to use @@ -36,11 +36,12 @@ Generation requires an OpenRouter key. The script resolves it in this order: 1. `--api-key` 2. the `OPENROUTER_API_KEY` environment variable -3. `OPENROUTER_API_KEY=` in a `.env` file, searching the working directory upward +3. `OPENROUTER_API_KEY=` in a `.env` file, searching the working directory upward, then the + script's own directory If none is present the script exits with setup instructions. Keys: https://openrouter.ai/keys -`--list-models` needs no key. +`--list-models`, `--model-info`, and `--dry-run` need no key. ## Quick start @@ -52,8 +53,11 @@ python scripts/generate_image.py "A beautiful sunset over mountains" python scripts/generate_image.py "Make the sky purple" -i photo.jpg -o edited.png ``` -Output defaults to `generated_image.`, where the extension follows the media type the model -returned. The per-request cost is printed from `usage.cost`. +Paths are relative to this skill's directory. Output defaults to `generated_image.`, where the +extension follows the media type the model returned. The per-request cost is printed after the run. + +**Then look at the image.** Read the file back and check it before using it anywhere: composition, +aspect ratio, and any text are all things models get wrong silently. ## Choosing a model @@ -63,33 +67,71 @@ Default: `google/gemini-3.1-flash-image`. | --- | --- | | General quality, prompt adherence | `google/gemini-3.1-flash-image` | | Highest Gemini tier | `google/gemini-3-pro-image` | -| Photoreal control, reproducible seeds | `black-forest-labs/flux.2-pro` | -| Cheap iteration | `black-forest-labs/flux.2-klein-4b` | -| Several images per request | `bytedance-seed/seedream-4.5`, `openai/gpt-image-2` | -| Vector / SVG output | `recraft/recraft-v4-vector` | -| Transparent background | `openai/gpt-image-2` with `--background transparent` | +| Cheap iteration | `google/gemini-3.1-flash-lite-image` (1K only), `openai/gpt-image-1-mini` | +| Photoreal control, reproducible seeds | `bytedance-seed/seedream-4.5` | +| Several images per request | `bytedance-seed/seedream-4.5`, `openai/gpt-image-2` (up to 10) | +| Vector / SVG output | `recraft/recraft-v4.1-vector` | +| Transparent background | `openai/gpt-image-1` with `--background transparent` | +| Legible text inside the image | `recraft/recraft-v4.1`, `sourceful/riverflow-v2.5-pro` — see the caveat below | -`references/models.md` carries the full catalogue with per-model parameter support. The live -listing is authoritative: +`references/models.md` carries the full catalogue with per-model parameters, allowed values, and +prices. The live listing is authoritative and free: ```bash -python scripts/generate_image.py --list-models +python scripts/generate_image.py --list-models # every model and its allowed values +python scripts/generate_image.py --list-models gemini # filtered by substring +python scripts/generate_image.py --model-info openai/gpt-image-1 # one model, plus pricing ``` ## Parameter support varies by model -This is the main thing to get right. Models advertise different parameter sets, and **sending a -parameter a model does not support is rejected, not ignored**. The script omits every flag you do -not pass, so pass only what the target model accepts. +This is the main thing to get right. Models advertise different parameter sets **and different +allowed values**, and sending something a model does not support is rejected, not ignored. -- `--resolution` (`512`, `1K`, `2K`, `4K`) — Gemini, Seedream, Riverflow, Krea, Grok. **Not FLUX.** -- `--output-format` — FLUX and Riverflow 2.5. **Not Gemini.** -- `--quality`, `--background`, `--output-compression` — the OpenAI family. -- `--seed` — FLUX, Seedream, Krea. **Not Gemini, not OpenAI.** -- `--aspect-ratio` — nearly all models, but the allowed enum differs. -- `--n` — capped per model: 1 for Gemini and FLUX, 6 for Recraft, 10 for Seedream and OpenAI. +The script checks the request against the live catalogue before spending anything, so a bad +parameter fails locally in under a second with the legal values printed: -On an HTTP 400 the script prints OpenRouter's message and points at `--list-models`. +```console +$ python scripts/generate_image.py "abstract pattern" -m openai/gpt-image-2 --background transparent +Error: Request rejected before billing (1 problem): + - background=transparent is not allowed; this model accepts: auto, opaque +``` + +Rough guide — but let the check be the authority, since the catalogue moves: + +- `--resolution` — Gemini, Seedream, Riverflow, Krea, Grok. The tiers differ: `512` only on Gemini + 3.1 Flash, `4K` on Gemini 3 Pro / Seedream / Riverflow, and **`1K` only** on + `gemini-3.1-flash-lite-image` and the Krea models. +- `--output-format` — Riverflow 2.5 only (`png`, `jpeg`, `webp`; the `fast` variant takes `jpeg` + alone). Gemini, OpenAI, Seedream, and Recraft all choose their own container. +- `--quality`, `--background`, `--output-compression` — the OpenAI family, plus `--background` on + Riverflow 2.5. **`--background transparent` is not available on `gpt-image-2` or + `gpt-5.4-image-2`** — use `gpt-image-1`, `gpt-image-1-mini`, `gpt-5-image`, or `gpt-5-image-mini`. +- `--seed` — Seedream and Krea. Not Gemini, not OpenAI. +- `--aspect-ratio` — nearly all models, but the enum differs sharply: `gpt-image-1` accepts only + `1:1`, `3:2`, `2:3`, `auto`, and `gpt-5-image*` does not accept it at all. +- `--n` — capped per model: 1 for Gemini, Riverflow, MAI and Grok, 6 for Recraft, 10 for Seedream + and OpenAI. The Krea models reject it outright. + +Pass `--dry-run` to validate and print the exact request body without generating or billing. +`--no-preflight` skips the check when you want the API itself to arbitrate. + +## Writing the prompt + +Prompt quality decides output quality more than model choice does. Name, in one sentence each: + +1. **Subject** — what is in frame, and how much of it. "A single pipette tip above a 96-well plate." +2. **Medium and style** — photograph, watercolour, 3D render, flat vector, scientific illustration. +3. **Lighting and palette** — "soft diffuse lighting, cool blue and white palette." +4. **Composition** — "wide shot, subject left of centre, empty space on the right for a title." +5. **What to avoid** — "no text, no labels, no watermark." + +Asking for empty space where a caption or title will go is the single most useful compositional +instruction for posters and slides. + +Iterate cheaply: draft on `gemini-3.1-flash-lite-image`, then regenerate the wording you settled on +with the model you actually want. To refine rather than restart, feed the last output back as a +reference (`-i out.png`) and describe only the change. ## Editing and reference images @@ -107,31 +149,36 @@ python scripts/generate_image.py "Blend these two styles" -i style_a.png -i styl python scripts/generate_image.py "Restyle as a watercolor" -i https://example.com/photo.jpg ``` -Reference limits differ: 16 for OpenAI, 14 for Gemini and Seedream, 8 for FLUX, 1 for Recraft and -MAI. Accepted local formats: PNG, JPEG, GIF, WebP. +Reference limits differ: 16 for OpenAI, 14 for Gemini and Seedream, 10 for `riverflow-v2*-pro`, +3 for `gemini-2.5-flash-image` and Grok, 1 for Recraft, MAI, and Krea. Accepted local formats: PNG, +JPEG, GIF, WebP. Riverflow v2 bills $0.20 per reference image on top of the output. ## Worked examples -```bash -# Wide hero image for a poster -python scripts/generate_image.py \ - "Laboratory with modern equipment, photorealistic, well-lit" \ - -m black-forest-labs/flux.2-pro --aspect-ratio 21:9 -o poster/hero.png +The `-o` paths are destinations the script creates, not files bundled with the skill. -# Conceptual figure for a manuscript +```bash +# Wide hero image for a poster, with space reserved for the title python scripts/generate_image.py \ - "Microscopic view of cancer cells attacked by immunotherapy agents, scientific illustration" \ + "Laboratory with modern equipment, photorealistic, well-lit, wide shot, \ + equipment on the left, empty wall on the right, no text" \ + --aspect-ratio 21:9 --resolution 2K -o poster/hero.png + +# Conceptual illustration for a manuscript — illustrative, never presented as data +python scripts/generate_image.py \ + "Stylised illustration of immune cells surrounding a tumour cell, scientific illustration, \ + cool palette, no text" \ --resolution 2K -o figures/immunotherapy_concept.png # Vector logo python scripts/generate_image.py \ "Minimal geometric fox logo, two colors" \ - -m recraft/recraft-v4-vector -o assets/logo.svg + -m recraft/recraft-v4.1-vector -o assets/logo.svg # Slide background with a transparent alpha channel python scripts/generate_image.py \ - "Abstract molecular pattern, subtle, blue and white" \ - -m openai/gpt-image-2 --background transparent -o slides/bg.png + "Abstract molecular pattern, subtle, blue and white, no text" \ + -m openai/gpt-image-1 --background transparent -o slides/bg.png # Four variations in one request python scripts/generate_image.py \ @@ -141,29 +188,38 @@ python scripts/generate_image.py \ # Reproducible output python scripts/generate_image.py "A cat astronaut" \ - -m black-forest-labs/flux.2-pro --seed 42 + -m bytedance-seed/seedream-4.5 --seed 42 + +# Check a request costs nothing to get wrong +python scripts/generate_image.py "A cat astronaut" --resolution 4K --dry-run ``` ## Script parameters | Flag | Purpose | | --- | --- | -| `prompt` | Image description, or the edit to apply (required unless `--list-models`) | +| `prompt` | Image description, or the edit to apply (required unless `--list-models` / `--model-info`) | | `-m`, `--model` | Model slug (default `google/gemini-3.1-flash-image`) | | `-o`, `--output` | Output path; extension defaults to the returned media type | | `-i`, `--input` | Reference image — path, URL, or data URL. Repeatable | | `--n` | Images per request, model-capped | -| `--aspect-ratio` | `1:1`, `16:9`, `9:16`, `4:3`, `3:2`, `21:9`, … | -| `--resolution` | `512`, `1K`, `2K`, `4K` | -| `--size` | Explicit pixels, e.g. `2048x2048` | -| `--quality` | `auto`, `low`, `medium`, `high` | -| `--output-format` | `png`, `jpeg`, `webp`, `svg` | +| `--aspect-ratio` | `1:1`, `16:9`, `9:16`, `4:3`, `3:2`, `21:9`, … — enum differs per model | +| `--resolution` | `512`, `1K`, `2K`, `4K` — tiers differ per model | +| `--quality` | `auto`, `low`, `medium`, `high` (OpenAI) | +| `--output-format` | `png`, `jpeg`, `webp` (Riverflow 2.5) | | `--background` | `auto`, `transparent`, `opaque` | -| `--output-compression` | 0–100, for WebP/JPEG | +| `--output-compression` | 0–100, OpenAI models | | `--seed` | Deterministic output where supported | | `--api-key` | Overrides the environment and `.env` | | `--timeout` | Request timeout, seconds (default 300) | -| `--list-models` | Print the catalogue with parameter support, then exit | +| `--retries` | Retries for rate limits and 5xx responses (default 2) | +| `--no-preflight` | Skip the free capability check before the billed request | +| `--dry-run` | Validate and print the request, then exit without generating | +| `--list-models` | Print the catalogue with allowed values, optionally filtered, then exit | +| `--model-info` | Print one model's allowed values and pricing, then exit | + +There is no `--size`: no model in the catalogue accepts a `size` parameter. Shape output with +`--aspect-ratio` and `--resolution`. ## API shape @@ -186,27 +242,60 @@ Response: { "created": 1748372400, "data": [{ "b64_json": "", "media_type": "image/png" }], - "usage": { "prompt_tokens": 0, "completion_tokens": 4175, "total_tokens": 4175, "cost": 0.04 } + "usage": { + "prompt_tokens": 4, + "completion_tokens": 1120, + "total_tokens": 1124, + "cost": 0.0672, + "completion_tokens_details": { "image_tokens": 1120 } + } } ``` `b64_json` is raw base64, **not** a data URL. `media_type` reflects the real format, so honour it -when naming files — vector models return `image/svg+xml`. +when naming files — vector models return `image/svg+xml`, and `gemini-3.1-flash-lite-image` returns +JPEG rather than PNG. Streaming (`"stream": true`) emits `image_generation.partial_image`, `image_generation.completed`, and `error` events, terminating with `data: [DONE]`. Only the OpenAI models support it, and the bundled script does not use it. Billing is all-or-nothing: a generation is either completed and billed in full, or it fails and is -not billed. Streaming preview frames are not charged separately. +not billed — so a rejected parameter costs nothing but time. Streaming preview frames are not +charged separately. On a bring-your-own-key account `usage.cost` reads `0` and the real amount is +in `cost_details.upstream_inference_cost`; the script reports that figure rather than claiming the +run was free. + +## Cost + +Per-image models are predictable: Seedream $0.04, Recraft v4.1 $0.035 (vector $0.08, pro $0.21), +Riverflow 2.5 fast $0.019 and pro $0.13–0.17, Grok $0.05–0.07. + +Gemini, OpenAI, and MAI bill per output token, which scales with resolution — a 4K image costs +roughly sixteen times a 1K one. Measured: one 1K `gemini-3.1-flash-lite-image` render is 1120 +output tokens, $0.034. At the same size `gemini-3.1-flash-image` is double that and +`gemini-3-pro-image` four times. Draft at low resolution on a cheap model; pay for size once. ## Notes and caveats -- Generation is a paid API call. Prefer a cheap model while iterating on a prompt. +- **Models cannot be trusted with text.** Words inside a generated image come back misspelled, + garbled, or invented. Ask for "no text" and overlay real type in LaTeX, PowerPoint, or HTML — or + use `scientific-schematics` when labels are the point. +- **A generated image is an illustration, never evidence.** It shows nothing that was measured. + Never present one as microscopy, imaging, gel, or instrument output, never let it stand in for a + figure that reports results, and label it as an illustration in captions. Nature and Science both + require disclosure of generative-AI imagery, and several journals prohibit it outside + clearly-marked concept art — check the target venue before submitting. +- Generation is a paid API call. Prefer a cheap model and low resolution while iterating on wording. - Generation takes roughly 5–60 seconds depending on model and resolution. -- Reference images are uploaded to OpenRouter. Do not send unpublished or sensitive data. +- Reference images are uploaded to OpenRouter. Do not send unpublished or sensitive data, patient + images, or anything under embargo. - Never hardcode the API key. Keep it in the environment or an ignored `.env`. - Prompt specifically when editing: "change the sky to sunset colours" beats "edit the sky". +- A refusal arrives as an HTTP 400 or 403 mentioning content policy, not as a bad image. Rephrase — + clinical and anatomical subjects trip moderation more often than the request warrants. +- Rate limits and 5xx responses are retried automatically; a 4xx is final, because the request + itself is what needs changing. ## Related skills diff --git a/skills/generate-image/references/models.md b/skills/generate-image/references/models.md index 2d9d4ddf..ef0c57e7 100644 --- a/skills/generate-image/references/models.md +++ b/skills/generate-image/references/models.md @@ -1,90 +1,158 @@ # OpenRouter image model reference -Snapshot of `GET https://openrouter.ai/api/v1/images/models`, taken 2026-07-26 (38 models). -The catalogue moves; re-read it rather than trusting this table: +Snapshot of `GET https://openrouter.ai/api/v1/images/models`, verified 2026-07-31. The catalogue +moves and this table will drift, so treat the live listing as authoritative: ```bash -python scripts/generate_image.py --list-models +python scripts/generate_image.py --list-models # every model, with allowed values +python scripts/generate_image.py --list-models gemini # filtered by substring +python scripts/generate_image.py --model-info MODEL # one model, plus pricing ``` -No API key is needed to list models. +No API key is needed for any of those, and nothing is billed. The script validates every request +against this same metadata before spending money, so an unsupported parameter or an out-of-enum +value fails locally rather than as an HTTP 400 — you do not have to memorise the tables below. -## Capability table +## Which parameters each model accepts -`refs` is the maximum number of `input_references` accepted; `n` is images per request. +`n` is images per request; `refs` is the maximum number of `input_references`. Prices are the +output-image rate the API reports; token-billed models scale with output resolution, so a 4K image +costs roughly sixteen times a 1K one. -| Model | n | refs | stream | Parameters | -| --- | --- | --- | --- | --- | -| `google/gemini-3.1-flash-image` | 1 | 14 | no | aspect_ratio, resolution, n, input_references | -| `google/gemini-3.1-flash-image-preview` | 1 | 14 | no | aspect_ratio, resolution, n, input_references | -| `google/gemini-3.1-flash-lite-image` | 1 | 14 | no | aspect_ratio, resolution, n, input_references | -| `google/gemini-3-pro-image` | 1 | 14 | no | aspect_ratio, resolution, n, input_references | -| `google/gemini-3-pro-image-preview` | 1 | 14 | no | aspect_ratio, resolution, n, input_references | -| `google/gemini-2.5-flash-image` | 1 | 3 | no | aspect_ratio, n, input_references | -| `black-forest-labs/flux.2-pro` | 1 | 8 | no | aspect_ratio, output_format, seed, n, input_references | -| `black-forest-labs/flux.2-max` | 1 | 8 | no | aspect_ratio, output_format, seed, n, input_references | -| `black-forest-labs/flux.2-flex` | 1 | 8 | no | aspect_ratio, output_format, seed, n, input_references | -| `black-forest-labs/flux.2-klein-4b` | 1 | 4 | no | aspect_ratio, output_format, seed, n, input_references | -| `bytedance-seed/seedream-4.5` | 10 | 14 | no | aspect_ratio, resolution, seed, n, input_references | -| `openai/gpt-image-2` | 10 | 16 | yes | aspect_ratio, background, quality, output_compression, n, input_references | -| `openai/gpt-image-1` | 10 | 16 | yes | aspect_ratio, background, quality, output_compression, n, input_references | -| `openai/gpt-image-1-mini` | 10 | 16 | yes | aspect_ratio, background, quality, output_compression, n, input_references | -| `openai/gpt-5.4-image-2` | 10 | 16 | yes | background, quality, output_compression, n, input_references | -| `openai/gpt-5-image` | 10 | 16 | yes | background, quality, output_compression, n, input_references | -| `openai/gpt-5-image-mini` | 10 | 16 | yes | background, quality, output_compression, n, input_references | -| `recraft/recraft-v4.1-pro` | 6 | 1 | no | aspect_ratio, n, input_references | -| `recraft/recraft-v4.1` | 6 | 1 | no | aspect_ratio, n, input_references | -| `recraft/recraft-v4.1-vector` | 6 | 1 | no | aspect_ratio, n, input_references | -| `recraft/recraft-v4.1-pro-vector` | 6 | 1 | no | aspect_ratio, n, input_references | -| `recraft/recraft-v4.1-utility` | 6 | 1 | no | aspect_ratio, n, input_references | -| `recraft/recraft-v4.1-utility-pro` | 6 | 1 | no | aspect_ratio, n, input_references | -| `recraft/recraft-v4-pro` | 6 | 1 | no | aspect_ratio, n, input_references | -| `recraft/recraft-v4` | 6 | 1 | no | aspect_ratio, n, input_references | -| `recraft/recraft-v4-vector` | 6 | 1 | no | aspect_ratio, n, input_references | -| `recraft/recraft-v4-pro-vector` | 6 | 1 | no | aspect_ratio, n, input_references | -| `recraft/recraft-v3` | 6 | 1 | no | aspect_ratio, n, input_references | -| `sourceful/riverflow-v2.5-pro` | 1 | 10 | no | aspect_ratio, background, output_format, resolution, n, input_references | -| `sourceful/riverflow-v2.5-fast` | 1 | 4 | no | aspect_ratio, background, output_format, resolution, n, input_references | -| `sourceful/riverflow-v2-pro` | 1 | 10 | no | aspect_ratio, resolution, n, input_references | -| `sourceful/riverflow-v2-fast` | 1 | 4 | no | aspect_ratio, resolution, n, input_references | -| `microsoft/mai-image-2.5-pro` | 1 | 1 | no | aspect_ratio, n, input_references | -| `microsoft/mai-image-2.5` | 1 | 1 | no | aspect_ratio, n, input_references | -| `krea/krea-2-large` | — | 1 | no | aspect_ratio, resolution, seed, input_references | -| `krea/krea-2-medium` | — | 1 | no | aspect_ratio, resolution, seed, input_references | -| `krea/krea-2-medium-turbo` | — | 1 | no | aspect_ratio, resolution, seed, input_references | -| `x-ai/grok-imagine-image-quality` | 1 | 3 | no | aspect_ratio, resolution, n, input_references | +| Model | n | refs | stream | Parameters | Output price | +| --- | --- | --- | --- | --- | --- | +| `google/gemini-3.1-flash-image` | 1 | 14 | no | aspect_ratio, input_references, n, resolution | $0.00006/token | +| `google/gemini-3.1-flash-image-preview` | 1 | 14 | no | aspect_ratio, input_references, n, resolution | $0.00006/token | +| `google/gemini-3-pro-image` | 1 | 14 | no | aspect_ratio, input_references, n, resolution | $0.00012/token | +| `google/gemini-3-pro-image-preview` | 1 | 14 | no | aspect_ratio, input_references, n, resolution | $0.00012/token | +| `google/gemini-3.1-flash-lite-image` | 1 | 14 | no | aspect_ratio, input_references, n, resolution | $0.00003/token | +| `google/gemini-2.5-flash-image` | 1 | 3 | no | aspect_ratio, input_references, n | $0.00003/token | +| `bytedance-seed/seedream-4.5` | 10 | 14 | no | aspect_ratio, input_references, n, resolution, seed | $0.04/image | +| `openai/gpt-image-2` | 10 | 16 | yes | aspect_ratio, background, input_references, n, output_compression, quality | $0.00003/token | +| `openai/gpt-image-1` | 10 | 16 | yes | aspect_ratio, background, input_references, n, output_compression, quality | $0.00004/token | +| `openai/gpt-image-1-mini` | 10 | 16 | yes | aspect_ratio, background, input_references, n, output_compression, quality | $0.000008/token | +| `openai/gpt-5.4-image-2` | 10 | 16 | yes | background, input_references, n, output_compression, quality | $0.00003/token | +| `openai/gpt-5-image` | 10 | 16 | yes | background, input_references, n, output_compression, quality | $0.00004/token | +| `openai/gpt-5-image-mini` | 10 | 16 | yes | background, input_references, n, output_compression, quality | $0.000008/token | +| `krea/krea-2-large` | — | 1 | no | aspect_ratio, input_references, resolution, seed | not published | +| `krea/krea-2-medium` | — | 1 | no | aspect_ratio, input_references, resolution, seed | not published | +| `krea/krea-2-medium-turbo` | — | 1 | no | aspect_ratio, input_references, resolution, seed | not published | +| `microsoft/mai-image-2.5` | 1 | 1 | no | aspect_ratio, input_references, n | $0.000047/token | +| `microsoft/mai-image-2.5-pro` | 1 | 1 | no | aspect_ratio, input_references, n | $0.000108/token | +| `recraft/recraft-v4.1` | 6 | 1 | no | aspect_ratio, input_references, n | $0.035/image | +| `recraft/recraft-v4.1-pro` | 6 | 1 | no | aspect_ratio, input_references, n | $0.21/image | +| `recraft/recraft-v4.1-vector` | 6 | 1 | no | aspect_ratio, input_references, n | $0.08/image | +| `recraft/recraft-v4.1-pro-vector` | 6 | 1 | no | aspect_ratio, input_references, n | $0.30/image | +| `recraft/recraft-v4.1-utility` | 6 | 1 | no | aspect_ratio, input_references, n | $0.035/image | +| `recraft/recraft-v4.1-utility-pro` | 6 | 1 | no | aspect_ratio, input_references, n | $0.21/image | +| `recraft/recraft-v4` | 6 | 1 | no | aspect_ratio, input_references, n | $0.04/image | +| `recraft/recraft-v4-pro` | 6 | 1 | no | aspect_ratio, input_references, n | $0.25/image | +| `recraft/recraft-v4-vector` | 6 | 1 | no | aspect_ratio, input_references, n | $0.08/image | +| `recraft/recraft-v4-pro-vector` | 6 | 1 | no | aspect_ratio, input_references, n | $0.30/image | +| `recraft/recraft-v3` | 6 | 1 | no | aspect_ratio, input_references, n | $0.04/image | +| `sourceful/riverflow-v2.5-pro` | 1 | 10 | no | aspect_ratio, background, input_references, n, output_format, resolution | $0.13/image; $0.15 at 2K; $0.17 at 4K | +| `sourceful/riverflow-v2.5-fast` | 1 | 4 | no | aspect_ratio, background, input_references, n, output_format, resolution | $0.019/image; $0.021 at 2K | +| `sourceful/riverflow-v2-pro` | 1 | 10 | no | aspect_ratio, input_references, n, resolution | $0.15/image; $0.33 at 4K | +| `sourceful/riverflow-v2-fast` | 1 | 4 | no | aspect_ratio, input_references, n, resolution | $0.02/image; $0.04 at 2K | +| `x-ai/grok-imagine-image-quality` | 1 | 3 | no | aspect_ratio, input_references, n, resolution | $0.05/image at 1K; $0.07 at 2K | -## Reading the parameter columns +Riverflow also bills reference images: v2 charges $0.20 per `input_reference` and $0.03 per input +font. The Krea models publish no price through the API — check the cost the script reports after a +run before using them at volume. -Parameters are not universal, and an unsupported one is **rejected, not ignored**: +## Which values each parameter accepts -- `resolution` (`512`, `1K`, `2K`, `4K`) — Gemini, Seedream, Riverflow, Krea, Grok. Not FLUX. -- `output_format` — FLUX (`png`, `jpeg`) and Riverflow 2.5. Gemini does not take it. -- `quality`, `background`, `output_compression` — the OpenAI family (`background` also on Riverflow 2.5). -- `seed` — FLUX, Seedream, Krea. Not Gemini, not OpenAI. -- `aspect_ratio` — nearly everything, but the enum differs. FLUX 2 Pro accepts - `1:1, 4:3, 3:4, 3:2, 2:3, 16:9, 9:16, 21:9, auto`. +Support is not enough: the allowed **values** differ per model too, and an out-of-enum value is +rejected the same way an unsupported parameter is. A dash means the model does not accept the +parameter at all. -Per-model detail, including provider-specific passthrough parameters and pricing: +| Model | resolution | output_format | background | quality | seed | +| --- | --- | --- | --- | --- | --- | +| `google/gemini-3.1-flash-image` | 512, 1K, 2K, 4K | — | — | — | — | +| `google/gemini-3.1-flash-image-preview` | 512, 1K, 2K, 4K | — | — | — | — | +| `google/gemini-3-pro-image` | 1K, 2K, 4K | — | — | — | — | +| `google/gemini-3-pro-image-preview` | 1K, 2K, 4K | — | — | — | — | +| `google/gemini-3.1-flash-lite-image` | **1K only** | — | — | — | — | +| `google/gemini-2.5-flash-image` | — | — | — | — | — | +| `bytedance-seed/seedream-4.5` | 1K, 2K, 4K | — | — | — | yes | +| `openai/gpt-image-2` | — | — | **auto, opaque** | auto, low, medium, high | — | +| `openai/gpt-image-1` | — | — | auto, transparent, opaque | auto, low, medium, high | — | +| `openai/gpt-image-1-mini` | — | — | auto, transparent, opaque | auto, low, medium, high | — | +| `openai/gpt-5.4-image-2` | — | — | **auto, opaque** | auto, low, medium, high | — | +| `openai/gpt-5-image` | — | — | auto, transparent, opaque | auto, low, medium, high | — | +| `openai/gpt-5-image-mini` | — | — | auto, transparent, opaque | auto, low, medium, high | — | +| `krea/krea-2-*` | **1K only** | — | — | — | yes | +| `microsoft/mai-image-2.5`, `-pro` | — | — | — | — | — | +| `recraft/*` | — | — | — | — | — | +| `sourceful/riverflow-v2.5-pro` | 1K, 2K, 4K | png, jpeg, webp | auto, transparent, opaque | — | — | +| `sourceful/riverflow-v2.5-fast` | 1K, 2K | **jpeg only** | auto, transparent, opaque | — | — | +| `sourceful/riverflow-v2-pro`, `-fast` | 1K, 2K, 4K | — | — | — | — | +| `x-ai/grok-imagine-image-quality` | 1K, 2K | — | — | — | — | -```bash -curl -s https://openrouter.ai/api/v1/images/models/black-forest-labs/flux.2-pro/endpoints -``` +Traps worth knowing, because each one is a wasted round trip: -FLUX 2 Pro, for example, allows `steps`, `guidance`, and `safety_tolerance` as passthrough -parameters and bills $0.03 per output megapixel. +- `transparent` is **not** available on `gpt-image-2` or `gpt-5.4-image-2`, the newest OpenAI + models. Use `gpt-image-1`, `gpt-image-1-mini`, `gpt-5-image`, `gpt-5-image-mini`, or Riverflow 2.5. +- `512` exists only on Gemini 3.1 Flash. `flash-lite` and the Krea models take `1K` and nothing else. +- `output_compression` is offered only by the OpenAI models, and none of them accept + `output_format` — the container is theirs to choose. +- **No model accepts `size`.** Shape the output with `aspect_ratio` and `resolution`. +- **No model accepts `output_format: svg`.** SVG comes from the Recraft vector models, which return + `media_type: image/svg+xml` regardless of that parameter. + +### Aspect ratio enums + +`aspect_ratio` is the most varied parameter, and three OpenAI models do not accept it at all. + +| Models | Allowed | +| --- | --- | +| `gemini-3.1-flash-image`, `-preview`, `flash-lite` | 1:1, 1:4, 1:8, 2:3, 3:2, 3:4, 4:1, 4:3, 4:5, 5:4, 8:1, 9:16, 16:9, 21:9 | +| `gemini-3-pro-image`, `-preview`, `gemini-2.5-flash-image` | 1:1, 2:3, 3:2, 3:4, 4:3, 4:5, 5:4, 9:16, 16:9, 21:9 | +| `seedream-4.5` | 1:1, 1:2, 2:1, 2:3, 3:2, 3:4, 4:3, 4:5, 5:4, 9:16, 16:9, 9:19.5, 19.5:9, 9:20, 20:9, 9:21, 21:9, auto | +| `gpt-image-2` | 1:1, 3:2, 2:3, 4:3, 3:4, 16:9, 9:16, 21:9, auto | +| `gpt-image-1`, `gpt-image-1-mini` | **1:1, 3:2, 2:3, auto only — no 16:9** | +| `gpt-5-image`, `gpt-5-image-mini`, `gpt-5.4-image-2` | **not accepted at all** | +| `recraft/*` | 1:1, 4:3, 3:4, 16:9, 9:16, auto | +| `riverflow-*` | 1:1, 4:3, 3:4, 3:2, 2:3, 16:9, 9:16, 21:9, auto | +| `mai-image-2.5`, `-pro` | 1:1, 4:3, 3:4, 16:9, 9:16, 3:2, 2:3, auto | +| `krea/krea-2-*` | 1:1, 4:3, 3:2, 16:9, 4:5, 2:3, 9:16 | +| `grok-imagine-image-quality` | 1:1, 3:4, 4:3, 9:16, 16:9, 2:3, 3:2, 9:19.5, 19.5:9, 9:20, 20:9, 1:2, 2:1, auto | ## Choosing a model -- **General quality, prompt adherence** — `google/gemini-3.1-flash-image` (skill default), or - `google/gemini-3-pro-image` for the higher tier. -- **Photoreal and artistic control, seeded reproducibility** — `black-forest-labs/flux.2-pro`. -- **Cheap iteration** — `black-forest-labs/flux.2-klein-4b`, `google/gemini-3.1-flash-lite-image`. -- **Batches** — `bytedance-seed/seedream-4.5` or the OpenAI family (up to 10 per request). -- **True vector output (SVG)** — `recraft/recraft-v4-vector`, `recraft/recraft-v4.1-vector`, and - the `-pro-vector` variants. These return `media_type: image/svg+xml`. -- **Transparent backgrounds** — the OpenAI family via `--background transparent`. -- **Heavy multi-reference compositing** — OpenAI (16 references), Gemini and Seedream (14). +- **General quality and prompt adherence** — `google/gemini-3.1-flash-image` (skill default), or + `google/gemini-3-pro-image` for the higher tier at double the token rate. +- **Cheap iteration** — `google/gemini-3.1-flash-lite-image` (half the flash rate, but 1K only) or + `openai/gpt-image-1-mini`. Measured: one 1K `flash-lite` image is 1120 output tokens, $0.034. +- **Photoreal and artistic control** — `bytedance-seed/seedream-4.5` (flat $0.04/image, seeded) or + `microsoft/mai-image-2.5-pro`. +- **Reproducible output from a seed** — `bytedance-seed/seedream-4.5` and the Krea models. The + Gemini and OpenAI families do not accept `seed`. +- **Batches** — `bytedance-seed/seedream-4.5` or the OpenAI family, up to 10 per request. Gemini, + Riverflow, MAI, and Grok cap at 1; Recraft at 6. +- **True vector output (SVG)** — `recraft/recraft-v4.1-vector`, `recraft/recraft-v4-vector`, and the + `-pro-vector` variants. These return `media_type: image/svg+xml`. +- **Text rendered legibly inside the image** — Recraft (which takes `text_layout` as a passthrough + parameter) and Riverflow are the strongest, but no model is dependable. Prefer overlaying text in + LaTeX, PowerPoint, or HTML. +- **Transparent backgrounds** — `gpt-image-1`, `gpt-image-1-mini`, `gpt-5-image`, + `gpt-5-image-mini`, or `riverflow-v2.5-*`. +- **Heavy multi-reference compositing** — OpenAI (16 references), Gemini and Seedream (14), + `riverflow-v2*-pro` (10). Recraft, MAI, and Krea accept exactly 1. + +## Passthrough parameters + +`GET /api/v1/images/models//endpoints` lists `allowed_passthrough_parameters` — provider +options the Image API forwards but the bundled script does not expose. Notable sets: + +- Recraft: `style`, `controls`, `text_layout` +- Krea: `styles`, `moodboards`, `image_style_references`, `creativity`, `intensity`, `complexity`, + `movement`, `strength` +- OpenAI: `moderation` +- Gemini: `cachedContent` +- Riverflow: `font_inputs` + +Send a direct request when you need one of these. `--model-info MODEL` prints the list. ## Provider routing @@ -96,5 +164,10 @@ routing control matters. ## Billing Image billing is all-or-nothing: a generation either completes and is billed in full, or fails and -is not billed. Partial preview frames delivered during streaming are not charged separately. -Per-request cost comes back in `usage.cost`, which the script prints. +is not billed. A rejected parameter therefore costs nothing but time. Partial preview frames +delivered during streaming are not charged separately. + +Per-request cost comes back in `usage.cost`, which the script prints. On a bring-your-own-key +account `usage.cost` is `0` and the real figure is in `cost_details.upstream_inference_cost`, where +the upstream provider bills you directly — the script reports that instead of claiming the +generation was free. diff --git a/skills/generate-image/scripts/generate_image.py b/skills/generate-image/scripts/generate_image.py index 9477995b..07ac0919 100755 --- a/skills/generate-image/scripts/generate_image.py +++ b/skills/generate-image/scripts/generate_image.py @@ -2,25 +2,30 @@ """ Generate and edit images through the OpenRouter Image API (POST /api/v1/images). -The Image API is model-agnostic: the same request shape reaches Gemini, FLUX, -Seedream, Recraft, GPT-Image, and the rest of the image catalogue. Responses -carry base64 payloads in ``data[].b64_json`` alongside the concrete +The Image API is model-agnostic: the same request shape reaches Gemini, +Seedream, Recraft, GPT-Image, Riverflow, and the rest of the image catalogue. +Responses carry base64 payloads in ``data[].b64_json`` alongside the concrete ``media_type``, so the output extension follows what the model actually returned rather than an assumption. Reference images (image-to-image and editing) go in ``input_references`` as HTTP(S) URLs or base64 data URLs. -Only the standard library is required. +Parameter support is per-model and an unsupported parameter is rejected rather +than ignored, so every generation is preceded by a free metadata lookup that +validates the request locally before anything is billed (``--no-preflight`` +skips it). Only the standard library is required. """ from __future__ import annotations import argparse import base64 +import difflib import json import os import sys +import time import urllib.error import urllib.request from pathlib import Path @@ -42,6 +47,14 @@ EXTENSIONS = { "image/svg+xml": ".svg", } +# Suffixes that name the same format, so `-o out.jpeg` for an image/jpeg +# response is not reported as a mismatch. +SUFFIX_ALIASES = { + ".jpg": {".jpg", ".jpeg"}, + ".jpeg": {".jpg", ".jpeg"}, + ".svg": {".svg", ".svgz"}, +} + # Local file extension -> MIME type, for encoding reference images. INPUT_MIME = { ".png": "image/png", @@ -51,13 +64,48 @@ INPUT_MIME = { ".webp": "image/webp", } +# Request parameters that carry a per-model capability spec. `model`, `prompt`, +# and `input_references` are handled separately. +VALIDATED_PARAMETERS = ( + "n", + "aspect_ratio", + "resolution", + "quality", + "output_format", + "background", + "output_compression", + "seed", +) + +RETRY_STATUS = frozenset({429, 500, 502, 503, 504}) + +# Ceiling for an image the response asks us to download rather than inlining. +# A 4K PNG is a few tens of megabytes; anything past this is not an image we want. +MAX_DOWNLOAD_BYTES = 64 * 1024 * 1024 + +# Families outside this skill's documented set. They stay visible in +# --list-models and --model-info, which mirror the live catalogue, but are not +# offered as suggestions when a parameter is unsupported. +UNSUGGESTED_PREFIXES = ("black-forest-labs/",) + class ApiError(RuntimeError): """An error surfaced by the OpenRouter API or the transport beneath it.""" +class RequestRejected(ApiError): + """The request cannot succeed as built, caught before it is billed.""" + + def find_api_key(explicit: str | None = None) -> str: - """Resolve the API key from --api-key, the environment, then any .env file.""" + """Resolve the API key from --api-key, the environment, then any .env file. + + The .env scan walks up from the working directory and finally checks the + script's own directory, so running from anywhere inside a project picks up + the key at its root. Only the standard library is used: python-dotenv is a + common omission, and a missing optional dependency should not read as a + missing credential. + """ if explicit: return explicit @@ -66,7 +114,7 @@ def find_api_key(explicit: str | None = None) -> str: return from_env cwd = Path.cwd() - for directory in [cwd, *cwd.parents]: + for directory in [cwd, *cwd.parents, Path(__file__).resolve().parent]: env_file = directory / ".env" if not env_file.is_file(): continue @@ -76,6 +124,8 @@ def find_api_key(explicit: str | None = None) -> str: continue for raw in content.splitlines(): line = raw.strip() + if line.startswith("export "): + line = line[len("export "):].strip() if line.startswith("#") or "=" not in line: continue name, _, value = line.partition("=") @@ -118,9 +168,22 @@ def encode_reference(source: str) -> str: return f"data:{mime};base64,{encoded}" -def request_json(url: str, api_key: str | None, payload: dict | None, timeout: float) -> Any: - """POST (or GET when payload is None) and decode the JSON response.""" - headers = {"Accept": "application/json"} +def request_bytes( + url: str, + api_key: str | None, + payload: dict | None, + timeout: float, + retries: int = 2, + accept: str = "application/json", + max_bytes: int | None = None, +) -> bytes: + """POST (or GET when payload is None), retrying transient failures. + + Rate limits and 5xx responses are retried with exponential backoff, honouring + Retry-After when the server sends it. A 4xx other than 429 is final: the + request itself is wrong, so repeating it only wastes time. + """ + headers = {"Accept": accept} if api_key: headers["Authorization"] = f"Bearer {api_key}" @@ -129,31 +192,197 @@ def request_json(url: str, api_key: str | None, payload: dict | None, timeout: f data = json.dumps(payload).encode("utf-8") headers["Content-Type"] = "application/json" - req = urllib.request.Request(url, data=data, headers=headers) - try: - with urllib.request.urlopen(req, timeout=timeout) as resp: - return json.loads(resp.read().decode("utf-8")) - except urllib.error.HTTPError as exc: - body = exc.read().decode("utf-8", errors="replace") - detail = body + attempt = 0 + while True: + req = urllib.request.Request(url, data=data, headers=headers) try: - parsed = json.loads(body) - detail = parsed.get("error", {}).get("message") or body - except (json.JSONDecodeError, AttributeError): + with urllib.request.urlopen(req, timeout=timeout) as resp: + if max_bytes is None: + return resp.read() + body = resp.read(max_bytes + 1) + if len(body) > max_bytes: + raise ApiError(f"Refusing a response larger than {max_bytes} bytes: {url}") + return body + except urllib.error.HTTPError as exc: + body = exc.read().decode("utf-8", errors="replace") + retryable = exc.code in RETRY_STATUS + if retryable and attempt < retries: + delay = retry_delay(exc.headers.get("Retry-After"), attempt) + print( + f"HTTP {exc.code} from OpenRouter; retrying in {delay:.0f}s " + f"({attempt + 1}/{retries})", + file=sys.stderr, + ) + time.sleep(delay) + attempt += 1 + continue + raise ApiError(f"OpenRouter returned HTTP {exc.code}: {error_detail(exc.code, body)}") from exc + except urllib.error.URLError as exc: + if attempt < retries: + delay = retry_delay(None, attempt) + print( + f"Could not reach OpenRouter ({exc.reason}); retrying in {delay:.0f}s " + f"({attempt + 1}/{retries})", + file=sys.stderr, + ) + time.sleep(delay) + attempt += 1 + continue + raise ApiError(f"Could not reach OpenRouter: {exc.reason}") from exc + + +def retry_delay(retry_after: str | None, attempt: int) -> float: + """Seconds to wait before the next attempt: Retry-After, else backoff.""" + if retry_after: + try: + return max(1.0, min(60.0, float(retry_after))) + except ValueError: pass - hint = "" - if exc.code == 400: - hint = ( - "\nParameter support varies by model. Check what this model accepts:\n" - " python generate_image.py --list-models" - ) - raise ApiError(f"OpenRouter returned HTTP {exc.code}: {detail}{hint}") from exc - except urllib.error.URLError as exc: - raise ApiError(f"Could not reach OpenRouter: {exc.reason}") from exc - except json.JSONDecodeError as exc: + return float(2 ** attempt) + + +def error_detail(status: int, body: str) -> str: + """Extract the API's error message and add a hint for the usual causes.""" + detail = body + try: + parsed = json.loads(body) + detail = parsed.get("error", {}).get("message") or body + except (json.JSONDecodeError, AttributeError): + pass + + hint = "" + if status == 400: + hint = ( + "\nParameter support and allowed values are per-model. Inspect this model:\n" + " python generate_image.py --model-info MODEL" + ) + elif status in (401, 403): + hint = ( + "\nCheck the key and its credit balance: https://openrouter.ai/keys\n" + "A 403 can also be a content-policy refusal — rephrase the prompt." + ) + return f"{detail}{hint}" + + +def request_json(url: str, api_key: str | None, payload: dict | None, timeout: float, + retries: int = 2) -> Any: + """POST or GET and decode the JSON response.""" + raw = request_bytes(url, api_key, payload, timeout, retries) + try: + return json.loads(raw.decode("utf-8")) + except (json.JSONDecodeError, UnicodeDecodeError) as exc: raise ApiError(f"OpenRouter returned a non-JSON response: {exc}") from exc +def fetch_catalogue(timeout: float, retries: int = 2) -> dict[str, dict]: + """Return the image catalogue keyed by model id. Needs no API key.""" + result = request_json(MODELS_URL, None, None, timeout, retries) + return {m["id"]: m for m in result.get("data", []) if m.get("id")} + + +def describe_spec(spec: dict) -> str: + """Render one capability spec as the values or range it permits.""" + if not isinstance(spec, dict): + return "supported" + if spec.get("type") == "enum": + return ", ".join(str(v) for v in spec.get("values", [])) + if spec.get("type") == "range": + return f"{spec.get('min', '?')}-{spec.get('max', '?')}" + return "supported" + + +def spec_problem(name: str, value: Any, spec: dict) -> str | None: + """Return a message if `value` violates `spec`, else None.""" + if not isinstance(spec, dict): + return None + kind = spec.get("type") + if kind == "enum": + allowed = [str(v) for v in spec.get("values", [])] + if allowed and str(value) not in allowed: + return f"{name}={value} is not allowed; this model accepts: {', '.join(allowed)}" + elif kind == "range": + low, high = spec.get("min"), spec.get("max") + if isinstance(value, (int, float)): + if low is not None and value < low: + return f"{name}={value} is below this model's minimum of {low}" + if high is not None and value > high: + return f"{name}={value} exceeds this model's maximum of {high}" + return None + + +def models_supporting(catalogue: dict[str, dict], parameter: str, value: Any = None) -> list[str]: + """Model ids that accept `parameter`, and `value` for it when given.""" + matches = [] + for model_id, model in catalogue.items(): + spec = (model.get("supported_parameters") or {}).get(parameter) + if spec is None: + continue + if value is not None and spec_problem(parameter, value, spec): + continue + matches.append(model_id) + suggestable = [m for m in matches if not m.startswith(UNSUGGESTED_PREFIXES)] + return sorted(suggestable or matches) + + +def preflight(payload: dict, catalogue: dict[str, dict]) -> None: + """Validate the request against the model's advertised capabilities. + + Every problem found here would otherwise be an HTTP 400 after the round + trip, or -- worse -- a silently wrong request. Errors are collected so one + run reports all of them. + """ + model_id = payload["model"] + model = catalogue.get(model_id) + if model is None: + close = difflib.get_close_matches(model_id, sorted(catalogue), n=3, cutoff=0.4) + suggestion = f" Did you mean: {', '.join(close)}?" if close else "" + raise RequestRejected( + f"'{model_id}' is not in the OpenRouter image catalogue.{suggestion}\n" + " python generate_image.py --list-models" + ) + + supported = model.get("supported_parameters") or {} + problems: list[str] = [] + + for name in VALIDATED_PARAMETERS: + if name not in payload: + continue + spec = supported.get(name) + if spec is None: + others = models_supporting(catalogue, name, payload[name]) + alternatives = f"\n Models that accept it: {', '.join(others[:6])}" if others else "" + problems.append( + f"{name} is not supported by {model_id}" + f" (it accepts: {', '.join(sorted(supported)) or 'nothing but model and prompt'})" + f"{alternatives}" + ) + continue + issue = spec_problem(name, payload[name], spec) + if issue: + problems.append(issue) + + references = payload.get("input_references") or [] + if references: + spec = supported.get("input_references") + if spec is None: + problems.append(f"{model_id} does not accept reference images") + else: + maximum = spec.get("max", 0) if isinstance(spec, dict) else 0 + if maximum and len(references) > maximum: + problems.append( + f"{len(references)} reference images given; {model_id} accepts at most {maximum}" + ) + + if problems: + listed = "\n - ".join(problems) + raise RequestRejected( + f"Request rejected before billing ({len(problems)} problem" + f"{'s' if len(problems) > 1 else ''}):\n - {listed}\n" + f"Inspect the model: python generate_image.py --model-info {model_id}\n" + "Bypass this check with --no-preflight." + ) + + def build_payload(args: argparse.Namespace) -> dict: """Assemble the request body, omitting every parameter the caller left unset. @@ -166,7 +395,6 @@ def build_payload(args: argparse.Namespace) -> dict: "n": args.n, "aspect_ratio": args.aspect_ratio, "resolution": args.resolution, - "size": args.size, "quality": args.quality, "output_format": args.output_format, "background": args.background, @@ -184,20 +412,48 @@ def build_payload(args: argparse.Namespace) -> dict: return payload +def redacted_payload(payload: dict) -> dict: + """Copy the payload with base64 reference blobs shortened, for printing.""" + shown = dict(payload) + references = shown.get("input_references") + if references: + trimmed = [] + for ref in references: + url = ((ref.get("image_url") or {}).get("url")) or "" + if url.startswith("data:") and len(url) > 80: + head = url.split(",", 1)[0] + url = f"{head},<{len(url)} chars of base64>" + trimmed.append({"type": ref.get("type"), "image_url": {"url": url}}) + shown["input_references"] = trimmed + return shown + + +def acceptable_suffixes(media_type: str) -> set[str]: + """Suffixes that correctly name `media_type`, including spelling variants.""" + extension = EXTENSIONS.get(normalise_media_type(media_type), ".png") + return SUFFIX_ALIASES.get(extension, {extension}) + + +def normalise_media_type(media_type: str) -> str: + """Strip parameters and case from a media type: 'IMAGE/PNG; x=1' -> 'image/png'.""" + return media_type.split(";", 1)[0].strip().lower() + + def output_paths(requested: str | None, media_type: str, count: int) -> list[Path]: """Choose filenames for the returned images. The extension follows the model's media_type unless the caller named a file - explicitly, in which case their choice is kept and a mismatch is reported. + explicitly, in which case their choice is kept and a real mismatch -- not a + mere spelling variant -- is reported. """ - extension = EXTENSIONS.get(media_type, ".png") + extension = EXTENSIONS.get(normalise_media_type(media_type), ".png") if requested is None: stem, suffix = Path("generated_image"), extension else: given = Path(requested) stem, suffix = given.with_suffix(""), given.suffix or extension - if given.suffix and given.suffix.lower() != extension: + if given.suffix and given.suffix.lower() not in acceptable_suffixes(media_type): print( f"Note: model returned {media_type} but --output ends in " f"'{given.suffix}'; writing the returned bytes under that name.", @@ -209,8 +465,30 @@ def output_paths(requested: str | None, media_type: str, count: int) -> list[Pat return [stem.parent / f"{stem.name}_{i + 1}{suffix}" for i in range(count)] -def save_images(result: dict, requested_output: str | None) -> list[Path]: - """Decode data[].b64_json into files and return the paths written.""" +def image_bytes(item: dict, timeout: float) -> bytes | None: + """Decode one response entry, downloading it if it arrived as a URL.""" + payload = item.get("b64_json") + if payload: + if payload.startswith("data:") and "," in payload: + payload = payload.split(",", 1)[1] + return base64.b64decode(payload) + + url = item.get("url") + if not url: + return None + + # The documented response inlines base64, so this branch only runs if a + # provider hands back a link instead. The URL comes from the response rather + # than from the caller, so require HTTPS and cap what we are willing to read. + if not url.startswith("https://"): + raise ApiError(f"Refusing to fetch a non-HTTPS image URL from the response: {url}") + return request_bytes( + url, None, None, timeout, retries=1, accept="image/*", max_bytes=MAX_DOWNLOAD_BYTES + ) + + +def save_images(result: dict, requested_output: str | None, timeout: float = 60.0) -> list[Path]: + """Decode data[] into files and return the paths written.""" items = result.get("data") if not items: raise ApiError( @@ -218,48 +496,133 @@ def save_images(result: dict, requested_output: str | None) -> list[Path]: f"Raw response: {json.dumps(result, indent=2)[:800]}" ) - first_media = items[0].get("media_type", "image/png") - paths = output_paths(requested_output, first_media, len(items)) + decoded: list[tuple[dict, bytes]] = [] + for item in items: + content = image_bytes(item, timeout) + if content is None: + print(f"Skipping an entry with no image data: {list(item)}", file=sys.stderr) + continue + decoded.append((item, content)) + + if not decoded: + raise ApiError("Response carried image entries but none contained data.") + + # Numbering is assigned after skipping empty entries so the written files + # are always _1.._n with no gaps. + first_media = decoded[0][0].get("media_type", "image/png") + paths = output_paths(requested_output, first_media, len(decoded)) written: list[Path] = [] - for item, path in zip(items, paths): - payload = item.get("b64_json") - if not payload: - print(f"Skipping an entry with no b64_json: {list(item)}", file=sys.stderr) - continue - if "," in payload and payload.startswith("data:"): - payload = payload.split(",", 1)[1] + for (_, content), path in zip(decoded, paths): if str(path.parent) not in ("", "."): path.parent.mkdir(parents=True, exist_ok=True) - path.write_bytes(base64.b64decode(payload)) + path.write_bytes(content) written.append(path) - if not written: - raise ApiError("Response carried image entries but none contained data.") return written -def list_models(timeout: float) -> int: - """Print the image catalogue with each model's supported parameters.""" - result = request_json(MODELS_URL, None, None, timeout) - models = result.get("data", []) - if not models: +def format_cost(cost: Any) -> str: + """Render a USD amount in decimal, never scientific notation.""" + if not isinstance(cost, (int, float)): + return str(cost) + return f"{cost:.8f}".rstrip("0").rstrip(".") or "0" + + +def format_pricing(pricing: list[dict] | None) -> list[str]: + """Render an endpoint's pricing entries as readable lines.""" + if not pricing: + return [" pricing: not published for this model"] + lines = [] + for entry in pricing: + variant = f" ({entry['variant']})" if entry.get("variant") else "" + lines.append( + f" pricing: ${format_cost(entry.get('cost_usd'))} per {entry.get('unit', '?')}" + f" of {entry.get('billable', '?')}{variant}" + ) + return lines + + +def cost_lines(usage: dict) -> list[str]: + """Report what the request cost, including the BYOK case. + + On a bring-your-own-key account OpenRouter reports ``usage.cost`` as 0 + because the upstream provider bills directly; the real figure is in + ``cost_details.upstream_inference_cost``. Printing only ``cost`` there would + claim a paid generation was free. + """ + cost = usage.get("cost") + upstream = (usage.get("cost_details") or {}).get("upstream_inference_cost") + + lines = [] + if cost: + lines.append(f"Cost: ${format_cost(cost)}") + elif upstream: + lines.append(f"Cost: ${format_cost(upstream)} billed upstream (BYOK key)") + elif cost is not None: + lines.append("Cost: $0 reported") + + image_tokens = (usage.get("completion_tokens_details") or {}).get("image_tokens") + if image_tokens: + lines.append(f"Image tokens: {image_tokens}") + return lines + + +def print_model(model: dict) -> None: + """Print one catalogue entry with its per-parameter allowed values.""" + params = model.get("supported_parameters") or {} + n_spec = params.get("n") or {} + refs = params.get("input_references") or {} + print(model.get("id", "?")) + per_request = f"up to {n_spec.get('max', 1)}" if n_spec else "1 (n not accepted)" + print( + f" images/request: {per_request}" + f" | reference images: up to {refs.get('max', 0)}" + f" | streaming: {'yes' if model.get('supports_streaming') else 'no'}" + ) + for name in sorted(params): + if name in ("n", "input_references"): + continue + print(f" {name}: {describe_spec(params[name])}") + + +def list_models(timeout: float, substring: str = "") -> int: + """Print the image catalogue with each model's parameters and their values.""" + catalogue = fetch_catalogue(timeout) + if not catalogue: print("No models returned.", file=sys.stderr) return 1 - print(f"{len(models)} image models available\n") - for model in sorted(models, key=lambda m: m.get("id", "")): - params = model.get("supported_parameters") or {} - n_spec = params.get("n") or {} - refs = params.get("input_references") or {} - print(f"{model.get('id', '?')}") - print( - f" images/request: up to {n_spec.get('max', 1)}" - f" | reference images: up to {refs.get('max', 0)}" - f" | streaming: {'yes' if model.get('supports_streaming') else 'no'}" - ) - if params: - print(f" parameters: {', '.join(sorted(params))}") + selected = [m for mid, m in sorted(catalogue.items()) if substring.lower() in mid.lower()] + if not selected: + print(f"No image model id contains '{substring}'.", file=sys.stderr) + return 1 + + scope = f" matching '{substring}'" if substring else "" + print(f"{len(selected)} image models available{scope}\n") + for model in selected: + print_model(model) + return 0 + + +def model_info(model_id: str, timeout: float) -> int: + """Print one model's allowed values, passthrough parameters, and pricing.""" + catalogue = fetch_catalogue(timeout) + if model_id not in catalogue: + close = difflib.get_close_matches(model_id, sorted(catalogue), n=3, cutoff=0.4) + hint = f" Did you mean: {', '.join(close)}?" if close else "" + print(f"'{model_id}' is not in the image catalogue.{hint}", file=sys.stderr) + return 1 + + print_model(catalogue[model_id]) + result = request_json(f"{MODELS_URL}/{model_id}/endpoints", None, None, timeout) + for endpoint in result.get("endpoints", []): + print(f" provider: {endpoint.get('provider_name', '?')}") + for line in format_pricing(endpoint.get("pricing")): + print(line) + passthrough = endpoint.get("allowed_passthrough_parameters") or [] + if passthrough: + print(f" passthrough (direct API only): {', '.join(passthrough)}") return 0 @@ -273,7 +636,7 @@ Examples: python generate_image.py "A beautiful sunset over mountains" # Pick a model and shape - python generate_image.py "A cat in space" -m black-forest-labs/flux.2-pro --aspect-ratio 16:9 + python generate_image.py "A cat in space" -m google/gemini-3-pro-image --aspect-ratio 16:9 # Edit an existing image python generate_image.py "Make the sky purple" -i photo.jpg -o edited.png @@ -284,8 +647,12 @@ Examples: # Vector output python generate_image.py "Minimal fox logo" -m recraft/recraft-v4-vector -o logo.svg - # Inspect the catalogue and per-model parameter support - python generate_image.py --list-models + # Validate the request and print the payload without generating or billing + python generate_image.py "A cat astronaut" --resolution 4K --dry-run + + # Inspect the catalogue, or one model's allowed values and pricing + python generate_image.py --list-models gemini + python generate_image.py --model-info openai/gpt-image-1 """, ) @@ -297,11 +664,10 @@ Examples: parser.add_argument("--input", "-i", action="append", metavar="IMAGE", help="Reference image: local path, HTTP(S) URL, or data URL. Repeatable.") parser.add_argument("--n", type=int, help="Number of images (model-dependent maximum)") - parser.add_argument("--aspect-ratio", help="e.g. 1:1, 16:9, 9:16, 4:3, 3:2, 21:9") - parser.add_argument("--resolution", help="Tier: 512, 1K, 2K, 4K") - parser.add_argument("--size", help='Explicit pixels, e.g. "2048x2048"') + parser.add_argument("--aspect-ratio", help="e.g. 1:1, 16:9, 9:16, 4:3 (enum differs per model)") + parser.add_argument("--resolution", help="Tier: 512, 1K, 2K, 4K (support differs per model)") parser.add_argument("--quality", choices=["auto", "low", "medium", "high"]) - parser.add_argument("--output-format", choices=["png", "jpeg", "webp", "svg"]) + parser.add_argument("--output-format", choices=["png", "jpeg", "webp"]) parser.add_argument("--background", choices=["auto", "transparent", "opaque"]) parser.add_argument("--output-compression", type=int, metavar="0-100", help="Compression for webp/jpeg output") @@ -309,20 +675,53 @@ Examples: parser.add_argument("--api-key", help="Overrides OPENROUTER_API_KEY and any .env file") parser.add_argument("--timeout", type=float, default=300.0, help="Request timeout in seconds (default: 300)") - parser.add_argument("--list-models", action="store_true", - help="List image models and their supported parameters, then exit") + parser.add_argument("--retries", type=int, default=2, metavar="N", + help="Retries for rate limits and 5xx responses (default: 2)") + parser.add_argument("--no-preflight", action="store_true", + help="Skip the free capability check before the billed request") + parser.add_argument("--dry-run", action="store_true", + help="Validate and print the request, then exit without generating") + parser.add_argument("--list-models", nargs="?", const="", metavar="SUBSTRING", + help="List image models and their allowed values, then exit") + parser.add_argument("--model-info", metavar="MODEL", + help="Print one model's allowed values and pricing, then exit") args = parser.parse_args(argv) try: - if args.list_models: - return list_models(args.timeout) + if args.list_models is not None: + return list_models(args.timeout, args.list_models) + + if args.model_info: + return model_info(args.model_info, args.timeout) if not args.prompt: - parser.error("a prompt is required unless --list-models is given") + parser.error("a prompt is required unless --list-models or --model-info is given") + + if args.output_compression is not None and not 0 <= args.output_compression <= 100: + parser.error("--output-compression must be between 0 and 100") + if args.n is not None and args.n < 1: + parser.error("--n must be at least 1") + + payload = build_payload(args) + + if not args.no_preflight: + try: + catalogue = fetch_catalogue(args.timeout, args.retries) + except ApiError as exc: + # Fail open: an unreachable metadata endpoint should not block a + # request the API itself may well accept. + print(f"Skipping the capability check ({exc}).", file=sys.stderr) + else: + preflight(payload, catalogue) + + if args.dry_run: + print(f"POST {IMAGES_URL}") + print(json.dumps(redacted_payload(payload), indent=2)) + print("Dry run: nothing generated, nothing billed.") + return 0 api_key = find_api_key(args.api_key) - payload = build_payload(args) action = "Editing" if args.input else "Generating" print(f"{action} with {args.model}") @@ -330,15 +729,15 @@ Examples: if args.input: print(f"References: {', '.join(args.input)}") - result = request_json(IMAGES_URL, api_key, payload, args.timeout) - written = save_images(result, args.output) + result = request_json(IMAGES_URL, api_key, payload, args.timeout, args.retries) + written = save_images(result, args.output, args.timeout) for path in written: print(f"Saved {path}") - cost = (result.get("usage") or {}).get("cost") - if cost is not None: - print(f"Cost: ${cost}") + for line in cost_lines(result.get("usage") or {}): + print(line) + print("Open the image and check it before using it.") return 0 except ApiError as exc: diff --git a/skills/geomaster/README.md b/skills/geomaster/README.md index 3ab61e2d..1690e9cc 100644 --- a/skills/geomaster/README.md +++ b/skills/geomaster/README.md @@ -66,7 +66,7 @@ conda install -c conda-forge gdal rasterio fiona shapely pyproj geopandas ### Remote Sensing ```bash -pip install rsgislib torchgeo earthengine-api +uv pip install rsgislib torchgeo earthengine-api ``` ## Quick Examples diff --git a/skills/geomaster/references/troubleshooting.md b/skills/geomaster/references/troubleshooting.md index 29e63ba6..9fda07ab 100644 --- a/skills/geomaster/references/troubleshooting.md +++ b/skills/geomaster/references/troubleshooting.md @@ -16,10 +16,10 @@ conda install -c conda-forge gdal rasterio sudo apt-get install gdal-bin libgdal-dev export CPLUS_INCLUDE_PATH=/usr/include/gdal export C_INCLUDE_PATH=/usr/include/gdal -pip install rasterio +uv pip install rasterio # Solution 3: Wheel files -pip install rasterio --find-links=https://gis.wheelwrights.com/ +uv pip install rasterio --find-links=https://gis.wheelwrights.com/ # Verify installation python -c "from osgeo import gdal; print(gdal.__version__)" @@ -36,11 +36,11 @@ conda install -c conda-forge --force-reinstall gdal rasterio fiona # Problem: "Symbol not found" on macOS # Solution: Rebuild from source or use conda brew install gdal -pip install rasterio --no-binary rasterio +uv pip install rasterio --no-binary rasterio # Problem: GEOS errors brew install geos -pip install shapely --no-binary shapely +uv pip install shapely --no-binary shapely ``` ## Runtime Errors diff --git a/skills/gget/references/module_catalog.md b/skills/gget/references/module_catalog.md index f0863087..e7b63abe 100644 --- a/skills/gget/references/module_catalog.md +++ b/skills/gget/references/module_catalog.md @@ -706,7 +706,7 @@ gget.gpt("Explain CRISPR", api_key=os.environ["OPENAI_API_KEY"]) Install/download third-party dependencies for specific modules. -As of gget 0.29.2, `gget setup` tries `uv pip install` first for Python dependencies and falls back to `pip install` if uv is unavailable or fails. +As of gget 0.29.2, `gget setup` tries `uv pip install` first for Python dependencies and falls back to plain `pip install` if uv is unavailable or fails. **Parameters**: - `module`: Module name requiring dependency installation diff --git a/skills/glycoengineering/SKILL.md b/skills/glycoengineering/SKILL.md index 06676565..8ae53445 100644 --- a/skills/glycoengineering/SKILL.md +++ b/skills/glycoengineering/SKILL.md @@ -231,7 +231,7 @@ GlycoShield-MD analyzes how glycans shield protein surfaces during MD simulation ```bash # Installation -pip install glycoshield +uv pip install glycoshield # Basic usage: analyze glycan shielding from glycosylated protein MD trajectory glycoshield \ diff --git a/skills/imaging-data-commons/references/bigquery_guide.md b/skills/imaging-data-commons/references/bigquery_guide.md index e4923f1c..6e2fe7d4 100644 --- a/skills/imaging-data-commons/references/bigquery_guide.md +++ b/skills/imaging-data-commons/references/bigquery_guide.md @@ -660,7 +660,7 @@ from google.cloud import bigquery from idc_index import IDCClient # Initialize BigQuery client -# Requires: pip install google-cloud-bigquery +# Requires: uv pip install google-cloud-bigquery # Auth: gcloud auth application-default login # Project: needed for billing even on public datasets (free tier applies) bq_client = bigquery.Client(project="your-gcp-project-id") diff --git a/skills/imaging-data-commons/references/parquet_access_guide.md b/skills/imaging-data-commons/references/parquet_access_guide.md index 99e3fd9b..a6b11a20 100644 --- a/skills/imaging-data-commons/references/parquet_access_guide.md +++ b/skills/imaging-data-commons/references/parquet_access_guide.md @@ -2,7 +2,7 @@ **Tested with:** idc-index-data 23.10.1, DuckDB 1.x -All idc-index metadata tables are published as Parquet files to a public GCS bucket with unrestricted CORS access. This enables metadata queries with DuckDB or pandas without installing idc-index — useful for quick exploration or environments where pip install is unavailable. +All idc-index metadata tables are published as Parquet files to a public GCS bucket with unrestricted CORS access. This enables metadata queries with DuckDB or pandas without installing idc-index — useful for quick exploration or environments where package installation is unavailable. **Limitation:** download helpers (`download_from_selection()`), viewer URLs (`get_viewer_URL()`), and citation generation require the idc-index client and are not available from raw Parquet files. @@ -45,7 +45,7 @@ https://storage.googleapis.com/idc-index-data-artifacts/current/release_artifact ## Prerequisites ```bash -pip install duckdb +uv pip install duckdb # or: uv add duckdb ``` diff --git a/skills/infographics/SKILL.md b/skills/infographics/SKILL.md index b80a7097..7730067f 100644 --- a/skills/infographics/SKILL.md +++ b/skills/infographics/SKILL.md @@ -3,7 +3,7 @@ name: infographics description: "Create professional infographics using Nano Banana Pro AI with smart iterative refinement. Uses Gemini 3.6 Flash for quality review. Integrates research-lookup and web search for accurate data. Supports 10 infographic types, 8 industry styles, and colorblind-safe palettes." allowed-tools: Read Write Edit Bash metadata: - version: "1.4" + version: "1.5" openclaw: primaryEnv: OPENROUTER_API_KEY envVars: diff --git a/skills/infographics/scripts/generate_infographic_ai.py b/skills/infographics/scripts/generate_infographic_ai.py index 3c5d2f5f..88f96f85 100644 --- a/skills/infographics/scripts/generate_infographic_ai.py +++ b/skills/infographics/scripts/generate_infographic_ai.py @@ -27,15 +27,90 @@ import re import sys import time from pathlib import Path -from typing import Optional, Dict, Any, List, Tuple +from typing import Optional, Dict, Any, List, NamedTuple try: import requests except ImportError: - print("Error: requests library not found. Install with: pip install requests") + print("Error: requests library not found. Install with: uv pip install requests") sys.exit(1) +class ReviewResult(NamedTuple): + """The outcome of one quality review. + + A named tuple rather than a bare tuple because the review has several + failure modes -- the model returns no choices, the request raises, the + answer arrives in an unexpected shape -- and each of them used to be a + chance to return the wrong number of values to the caller. + + `score` is None whenever no usable number was parsed, and `reviewed` is + False whenever the review never produced an answer at all. Neither case + invents a score: an infographic whose quality was not measured is reported + as unmeasured, not as passing. + """ + + critique: str + score: Optional[float] + needs_improvement: bool + reviewed: bool + error: Optional[str] = None + + +# Markdown decoration the reviewer routinely wraps its answer in. Gemini writes +# "**SCORE:** 8.5" far more often than the bare "SCORE: 8.5" the rubric asks +# for, and a pattern that does not allow for it silently scores every image +# at whatever the default happens to be. +_MARKUP = re.compile(r"[*_`#]") + +_SCORE_PATTERN = re.compile(r"\bSCORE\s*:?\s*(\d+(?:\.\d+)?)", re.IGNORECASE) +_LOOSE_SCORE_PATTERN = re.compile( + r"(?:score|rating|quality)\s*[:\s]\s*(\d+(?:\.\d+)?)\s*(?:/\s*10)?", re.IGNORECASE +) +# The underscore is optional because normalization strips it out of +# NEEDS_IMPROVEMENT along with the surrounding markdown. +_VERDICT_PATTERN = re.compile( + r"^\s*VERDICT\s*:?\s*(ACCEPTABLE|NEEDS[_ ]?IMPROVEMENT)", re.IGNORECASE | re.MULTILINE +) + + +def _normalize_review_text(text: str) -> str: + """Strip markdown decoration so the rubric's fields can be found.""" + return _MARKUP.sub("", text or "") + + +def _parse_score(text: str) -> Optional[float]: + """Return the reviewer's 0-10 score, or None when there isn't a usable one. + + None rather than a default: a fabricated score is indistinguishable from a + real one once it reaches the review log, and a default near the middle of + the range quietly passes lenient document types while failing strict ones. + """ + normalized = _normalize_review_text(text) + match = _SCORE_PATTERN.search(normalized) or _LOOSE_SCORE_PATTERN.search(normalized) + if not match: + return None + score = float(match.group(1)) + # A number outside the rubric's range means something other than the score + # was matched -- a figure count, a percentage, an iteration number. + return score if 0.0 <= score <= 10.0 else None + + +def _parse_verdict(text: str) -> Optional[str]: + """Return ACCEPTABLE / NEEDS_IMPROVEMENT from the verdict line, or None. + + Anchored to the start of a line. The rubric prompt spells out both tokens + when it explains the response format, so a reviewer that echoes those + instructions back would fail a perfectly good image under a plain + substring search. + """ + match = _VERDICT_PATTERN.search(_normalize_review_text(text)) + if not match: + return None + verdict = match.group(1).upper().replace(" ", "").replace("_", "") + return "NEEDS_IMPROVEMENT" if verdict == "NEEDSIMPROVEMENT" else "ACCEPTABLE" + + def _resolve_api_key(explicit: Optional[str] = None) -> Optional[str]: """Resolve the OpenRouter key from --api-key, the environment, then any .env file. @@ -807,7 +882,7 @@ Incorporate specific numbers, percentages, and dates from the research.""" def review_image(self, image_path: str, original_prompt: str, infographic_type: Optional[str], iteration: int, doc_type: str = "default", - max_iterations: int = 3) -> Tuple[str, Optional[float], bool]: + max_iterations: int = 3) -> ReviewResult: """ Review generated infographic using Gemini 3.6 Flash for quality analysis. @@ -909,50 +984,64 @@ If score < {threshold}, mark as NEEDS_IMPROVEMENT with specific suggestions.""" choices = response.get("choices", []) if not choices: - return "Image generated successfully", 7.5, False - + # A normal enough outcome -- a rate limit, a content filter, a + # provider hiccup. The image itself is fine; only its review is + # missing, and saying so beats inventing a score. + reason = "the review model returned no choices" + self._log(f"⚠ Review unavailable: {reason}") + return ReviewResult( + f"Review unavailable: {reason}.", + None, False, reviewed=False, error=reason, + ) + message = choices[0].get("message", {}) content = message.get("content", "") - + reasoning = message.get("reasoning", "") if reasoning and not content: content = reasoning - + if isinstance(content, list): text_parts = [] for block in content: if isinstance(block, dict) and block.get("type") == "text": text_parts.append(block.get("text", "")) content = "\n".join(text_parts) - - # Extract score - score = 7.5 - import re - - score_match = re.search(r'SCORE:\s*(\d+(?:\.\d+)?)', content, re.IGNORECASE) - if score_match: - score = float(score_match.group(1)) - else: - score_match = re.search(r'(?:score|rating|quality)[:\s]+(\d+(?:\.\d+)?)\s*(?:/\s*10)?', content, re.IGNORECASE) - if score_match: - score = float(score_match.group(1)) - - # Determine if improvement is needed - needs_improvement = False - if "NEEDS_IMPROVEMENT" in content.upper(): - needs_improvement = True - elif score < threshold: - needs_improvement = True - - self._log(f"✓ Review complete (Score: {score}/10, Threshold: {threshold}/10)") + + score = _parse_score(content) + verdict = _parse_verdict(content) + + if score is None and verdict is None: + reason = "no score or verdict found in the review" + self._log(f"⚠ Review unusable: {reason}") + return ReviewResult( + content if content else f"Review unusable: {reason}.", + None, False, reviewed=True, error=reason, + ) + + needs_improvement = verdict == "NEEDS_IMPROVEMENT" or ( + score is not None and score < threshold + ) + + shown = f"{score}/10" if score is not None else "not stated" + self._log(f"✓ Review complete (Score: {shown}, Threshold: {threshold}/10)") self._log(f" Verdict: {'Needs improvement' if needs_improvement else 'Acceptable'}") - - return (content if content else "Image generated successfully", - score, - needs_improvement) + + return ReviewResult( + content if content else "Review returned no text", + score, + needs_improvement, + reviewed=True, + error=None if score is not None else "no score found in the review", + ) except Exception as e: - self._log(f"Review failed: {str(e)}") - return "Review failed", None, True + # A failed review must not fail the run -- the image is already + # generated and saved -- but it must not read as a pass either. + self._log(f"⚠ Review failed: {str(e)}") + return ReviewResult( + f"Review failed: {str(e)}", + None, False, reviewed=False, error=str(e), + ) def improve_prompt(self, original_prompt: str, critique: str, infographic_type: Optional[str], @@ -1066,7 +1155,10 @@ Generate an improved version that: "context_images": context_images, "iterations": [], "final_image": None, - "final_score": 0.0, + # None, not 0.0 -- a run whose review never completed has no score, + # and a number here would be read as one the reviewer gave. + "final_score": None, + "final_reviewed": False, "success": False, "early_stop": False, "early_stop_reason": None @@ -1139,55 +1231,63 @@ Generate an improved version that: f.write(image_data) print(f"✓ Saved: {iter_path}") - # Review image using Gemini 3.6 Flash - print(f"Reviewing with Gemini 3.6 Flash...") - critique, score, needs_improvement = self.review_image( + # Review the image with the vision review model + print(f"Reviewing with {self.review_model}...") + review = self.review_image( str(iter_path), user_prompt, infographic_type, i, doc_type, iterations ) - if score is None: - print(f"✗ Review failed (threshold: {threshold}/10)") + if review.score is not None: + print(f"✓ Score: {review.score}/10 (threshold: {threshold}/10)") else: - print(f"✓ Score: {score}/10 (threshold: {threshold}/10)") - + print(f"⚠ Review unavailable — image kept, quality not verified") + print(f" Reason: {review.error}") + # Save iteration results iteration_result = { "iteration": i, "image_path": str(iter_path), "prompt_length": len(current_prompt), - "critique": critique, - "score": score, - "needs_improvement": needs_improvement, + "critique": review.critique, + "score": review.score, + "reviewed": review.reviewed, + "review_error": review.error, + "needs_improvement": review.needs_improvement, "success": True } results["iterations"].append(iteration_result) - + # Check if quality is acceptable - if score is not None and score >= threshold and not needs_improvement: - print(f"\n✓ Quality meets threshold ({score} >= {threshold})") - print(f" No further iterations needed!") + if not review.needs_improvement: + if review.score is not None: + print(f"\n✓ Quality meets threshold ({review.score} >= {threshold})") + print(f" No further iterations needed!") + reason = f"Quality score {review.score} meets threshold {threshold}" + else: + # Regenerating cannot fix a reviewer that did not answer. + print(f"\n⚠ Stopping without a verified score — review the image yourself") + reason = f"Review did not produce a score: {review.error}" results["final_image"] = str(iter_path) - results["final_score"] = score + results["final_score"] = review.score + results["final_reviewed"] = review.reviewed and review.score is not None results["success"] = True results["early_stop"] = True - results["early_stop_reason"] = f"Quality score {score} meets threshold {threshold}" + results["early_stop_reason"] = reason break - + # If this is the last iteration, we're done if i == iterations: print(f"\n⚠ Maximum iterations reached") results["final_image"] = str(iter_path) - results["final_score"] = score + results["final_score"] = review.score + results["final_reviewed"] = review.reviewed and review.score is not None results["success"] = True break - + # Quality below threshold - improve prompt - if score is None: - print(f"\n⚠ Review failed; regenerating with review feedback if available") - else: - print(f"\n⚠ Quality below threshold ({score} < {threshold})") + print(f"\n⚠ Quality below threshold ({review.score} < {threshold})") print(f"Improving prompt based on feedback...") current_prompt = self.improve_prompt( - user_prompt, critique, infographic_type, style, palette, background, i + 1, + user_prompt, review.critique, infographic_type, style, palette, background, i + 1, len(context_images) ) @@ -1207,7 +1307,10 @@ Generate an improved version that: print(f"\n{'='*60}") print(f"Generation Complete!") - print(f"Final Score: {results['final_score']}/10") + if results["final_score"] is not None: + print(f"Final Score: {results['final_score']}/10") + else: + print(f"Final Score: unavailable (the review did not produce one)") if results["early_stop"]: iterations_used = len([r for r in results['iterations'] if r.get('success')]) print(f"Iterations Used: {iterations_used}/{iterations} (early stop)") diff --git a/skills/latex-posters/SKILL.md b/skills/latex-posters/SKILL.md index 30804e5b..e2e379d2 100644 --- a/skills/latex-posters/SKILL.md +++ b/skills/latex-posters/SKILL.md @@ -3,7 +3,7 @@ name: latex-posters description: "Create professional research posters in LaTeX using beamerposter, tikzposter, or baposter. Support for conference presentations, academic posters, and scientific communication. Includes layout design, color schemes, multi-column formats, figure integration, and poster-specific best practices for visual communication." allowed-tools: Read Write Edit Bash metadata: - version: "1.4" + version: "1.5" openclaw: primaryEnv: OPENROUTER_API_KEY envVars: diff --git a/skills/latex-posters/scripts/generate_schematic.py b/skills/latex-posters/scripts/generate_schematic.py index 64246559..6392aebf 100644 --- a/skills/latex-posters/scripts/generate_schematic.py +++ b/skills/latex-posters/scripts/generate_schematic.py @@ -147,7 +147,12 @@ Environment Variables: help="Verbose output") args = parser.parse_args() - + + # Validated here rather than clamped silently, and before the credential + # lookup so an out-of-range value reports itself rather than an absent key. + if not 1 <= args.iterations <= 2: + parser.error("--iterations must be 1 or 2") + # Check for API key — resolves --api-key, the environment, then any .env file api_key = resolve_api_key(args.api_key) if not api_key: @@ -173,12 +178,9 @@ Environment Variables: if args.doc_type != "default": cmd.extend(["--doc-type", args.doc_type]) - - # Enforce max 2 iterations - iterations = min(args.iterations, 2) - if iterations != 2: - cmd.extend(["--iterations", str(iterations)]) - + + cmd.extend(["--iterations", str(args.iterations)]) + if args.verbose: cmd.append("-v") diff --git a/skills/latex-posters/scripts/generate_schematic_ai.py b/skills/latex-posters/scripts/generate_schematic_ai.py index 3e3e475f..85c4fd29 100644 --- a/skills/latex-posters/scripts/generate_schematic_ai.py +++ b/skills/latex-posters/scripts/generate_schematic_ai.py @@ -22,17 +22,94 @@ import argparse import base64 import json import os +import re import sys import time from pathlib import Path -from typing import Optional, Dict, Any, List, Tuple +from typing import Optional, Dict, Any, List, NamedTuple try: import requests except ImportError: - print("Error: requests library not found. Install with: pip install requests") + print("Error: requests library not found. Install with: uv pip install requests") sys.exit(1) + +class ReviewResult(NamedTuple): + """The outcome of one quality review. + + A named tuple rather than a bare tuple because the review has several + failure modes -- the model returns no choices, the request raises, the + answer arrives in an unexpected shape -- and each of them used to be a + chance to return the wrong number of values to the caller. + + `score` is None whenever no usable number was parsed, and `reviewed` is + False whenever the review never produced an answer at all. Neither case + invents a score: a diagram whose quality was not measured is reported as + unmeasured, not as passing. + """ + + critique: str + score: Optional[float] + needs_improvement: bool + reviewed: bool + error: Optional[str] = None + + +# Markdown decoration the reviewer routinely wraps its answer in. Gemini writes +# "**SCORE:** 8.5" far more often than the bare "SCORE: 8.5" the rubric asks +# for, and a pattern that does not allow for it silently scores every diagram +# at whatever the default happens to be. +_MARKUP = re.compile(r"[*_`#]") + +_SCORE_PATTERN = re.compile(r"\bSCORE\s*:?\s*(\d+(?:\.\d+)?)", re.IGNORECASE) +_LOOSE_SCORE_PATTERN = re.compile( + r"(?:score|rating|quality)\s*[:\s]\s*(\d+(?:\.\d+)?)\s*(?:/\s*10)?", re.IGNORECASE +) +# The underscore is optional because normalization strips it out of +# NEEDS_IMPROVEMENT along with the surrounding markdown. +_VERDICT_PATTERN = re.compile( + r"^\s*VERDICT\s*:?\s*(ACCEPTABLE|NEEDS[_ ]?IMPROVEMENT)", re.IGNORECASE | re.MULTILINE +) + + +def _normalize_review_text(text: str) -> str: + """Strip markdown decoration so the rubric's fields can be found.""" + return _MARKUP.sub("", text or "") + + +def _parse_score(text: str) -> Optional[float]: + """Return the reviewer's 0-10 score, or None when there isn't a usable one. + + None rather than a default: a fabricated score is indistinguishable from a + real one once it reaches the review log, and a default near the middle of + the range quietly passes lenient document types while failing strict ones. + """ + normalized = _normalize_review_text(text) + match = _SCORE_PATTERN.search(normalized) or _LOOSE_SCORE_PATTERN.search(normalized) + if not match: + return None + score = float(match.group(1)) + # A number outside the rubric's range means something other than the score + # was matched -- a figure count, a percentage, an iteration number. + return score if 0.0 <= score <= 10.0 else None + + +def _parse_verdict(text: str) -> Optional[str]: + """Return ACCEPTABLE / NEEDS_IMPROVEMENT from the verdict line, or None. + + Anchored to the start of a line. The rubric prompt spells out both tokens + when it explains the response format, so a reviewer that echoes those + instructions back would fail a perfectly good diagram under a plain + substring search. + """ + match = _VERDICT_PATTERN.search(_normalize_review_text(text)) + if not match: + return None + verdict = match.group(1).upper().replace(" ", "").replace("_", "") + return "NEEDS_IMPROVEMENT" if verdict == "NEEDSIMPROVEMENT" else "ACCEPTABLE" + + def _resolve_api_key(explicit: Optional[str] = None) -> Optional[str]: """Resolve the OpenRouter key from --api-key, the environment, then any .env file. @@ -282,7 +359,6 @@ IMPORTANT - NO FIGURE NUMBERS: # Handle string content if isinstance(content, str) and "data:image" in content: - import re match = re.search(r'data:image/[^;]+;base64,([A-Za-z0-9+/=\n\r]+)', content, re.DOTALL) if match: base64_str = match.group(1).replace('\n', '').replace('\r', '').replace(' ', '') @@ -417,24 +493,24 @@ IMPORTANT - NO FIGURE NUMBERS: def review_image(self, image_path: str, original_prompt: str, iteration: int, doc_type: str = "default", - max_iterations: int = 2) -> Tuple[str, float, bool]: + max_iterations: int = 2) -> ReviewResult: """ - Review generated image using Gemini 3.6 Flash for quality analysis. - - Uses Gemini 3.6 Flash's superior vision and reasoning capabilities to - evaluate the schematic quality and determine if regeneration is needed. - + Review the generated image for quality, using the vision review model. + Args: image_path: Path to the generated image original_prompt: Original user prompt iteration: Current iteration number doc_type: Document type (journal, poster, presentation, etc.) max_iterations: Maximum iterations allowed - + Returns: - Tuple of (critique text, quality score 0-10, needs_improvement bool) + A ReviewResult. When the review cannot be completed -- the request + fails, or the model answers with nothing usable -- `reviewed` is + False and `score` is None rather than a stand-in number, and + `needs_improvement` is False: the fault is in the reviewer, not in + the diagram, so regenerating would not help. """ - # Use Gemini 3.6 Flash for review - excellent vision and analysis image_data_url = self._image_to_base64(image_path) # Get quality threshold for this document type @@ -510,25 +586,32 @@ If score < {threshold}, mark as NEEDS_IMPROVEMENT with specific suggestions.""" ] try: - # Use Gemini 3.6 Flash for high-quality review response = self._make_request( model=self.review_model, messages=messages ) - + # Extract text response choices = response.get("choices", []) if not choices: - return "Image generated successfully", 8.0 - + # A normal enough outcome -- a rate limit, a content filter, a + # provider hiccup. The diagram itself is fine; only its review + # is missing, and saying so beats inventing a score. + reason = "the review model returned no choices" + self._log(f"⚠ Review unavailable: {reason}") + return ReviewResult( + f"Review unavailable: {reason}.", + None, False, reviewed=False, error=reason, + ) + message = choices[0].get("message", {}) content = message.get("content", "") - - # Check reasoning field (Nano Banana 2 puts analysis here) + + # Some models put their analysis in a separate reasoning field reasoning = message.get("reasoning", "") if reasoning and not content: content = reasoning - + if isinstance(content, list): # Extract text from content blocks text_parts = [] @@ -536,38 +619,41 @@ If score < {threshold}, mark as NEEDS_IMPROVEMENT with specific suggestions.""" if isinstance(block, dict) and block.get("type") == "text": text_parts.append(block.get("text", "")) content = "\n".join(text_parts) - - # Try to extract score - score = 7.5 # Default score if extraction fails - import re - - # Look for SCORE: X or SCORE: X/10 format - score_match = re.search(r'SCORE:\s*(\d+(?:\.\d+)?)', content, re.IGNORECASE) - if score_match: - score = float(score_match.group(1)) - else: - # Fallback: look for any score pattern - score_match = re.search(r'(?:score|rating|quality)[:\s]+(\d+(?:\.\d+)?)\s*(?:/\s*10)?', content, re.IGNORECASE) - if score_match: - score = float(score_match.group(1)) - - # Determine if improvement is needed based on verdict or score - needs_improvement = False - if "NEEDS_IMPROVEMENT" in content.upper(): - needs_improvement = True - elif score < threshold: - needs_improvement = True - - self._log(f"✓ Review complete (Score: {score}/10, Threshold: {threshold}/10)") + + score = _parse_score(content) + verdict = _parse_verdict(content) + + if score is None and verdict is None: + reason = "no score or verdict found in the review" + self._log(f"⚠ Review unusable: {reason}") + return ReviewResult( + content if content else f"Review unusable: {reason}.", + None, False, reviewed=True, error=reason, + ) + + needs_improvement = verdict == "NEEDS_IMPROVEMENT" or ( + score is not None and score < threshold + ) + + shown = f"{score}/10" if score is not None else "not stated" + self._log(f"✓ Review complete (Score: {shown}, Threshold: {threshold}/10)") self._log(f" Verdict: {'Needs improvement' if needs_improvement else 'Acceptable'}") - - return (content if content else "Image generated successfully", - score, - needs_improvement) + + return ReviewResult( + content if content else "Review returned no text", + score, + needs_improvement, + reviewed=True, + error=None if score is not None else "no score found in the review", + ) except Exception as e: - self._log(f"Review skipped: {str(e)}") - # Don't fail the whole process if review fails - assume acceptable - return "Image generated successfully (review skipped)", 7.5, False + # A failed review must not fail the run -- the image is already + # generated and saved -- but it must not read as a pass either. + self._log(f"⚠ Review failed: {str(e)}") + return ReviewResult( + f"Review failed: {str(e)}", + None, False, reviewed=False, error=str(e), + ) def improve_prompt(self, original_prompt: str, critique: str, iteration: int) -> str: @@ -629,7 +715,10 @@ Generate an improved version that addresses all the critique points while mainta "quality_threshold": threshold, "iterations": [], "final_image": None, - "final_score": 0.0, + # None, not 0.0 -- a run whose review never completed has no score, + # and a number here would be read as one the reviewer gave. + "final_score": None, + "final_reviewed": False, "success": False, "early_stop": False, "early_stop_reason": None @@ -675,48 +764,63 @@ Generate a publication-quality scientific diagram that meets all the guidelines f.write(image_data) print(f"✓ Saved: {iter_path}") - # Review image using Gemini 3.6 Flash - print(f"Reviewing image with Gemini 3.6 Flash...") - critique, score, needs_improvement = self.review_image( + # Review the image with the vision review model + print(f"Reviewing image with {self.review_model}...") + review = self.review_image( str(iter_path), user_prompt, i, doc_type, iterations ) - print(f"✓ Score: {score}/10 (threshold: {threshold}/10)") - + if review.score is not None: + print(f"✓ Score: {review.score}/10 (threshold: {threshold}/10)") + else: + print(f"⚠ Review unavailable — image kept, quality not verified") + print(f" Reason: {review.error}") + # Save iteration results iteration_result = { "iteration": i, "image_path": str(iter_path), "prompt": current_prompt, - "critique": critique, - "score": score, - "needs_improvement": needs_improvement, + "critique": review.critique, + "score": review.score, + "reviewed": review.reviewed, + "review_error": review.error, + "needs_improvement": review.needs_improvement, "success": True } results["iterations"].append(iteration_result) - + # Check if quality is acceptable - STOP EARLY if so - if not needs_improvement: - print(f"\n✓ Quality meets {doc_type} threshold ({score} >= {threshold})") - print(f" No further iterations needed!") + if not review.needs_improvement: + if review.score is not None: + print(f"\n✓ Quality meets {doc_type} threshold ({review.score} >= {threshold})") + print(f" No further iterations needed!") + reason = (f"Quality score {review.score} meets threshold " + f"{threshold} for {doc_type}") + else: + # Regenerating cannot fix a reviewer that did not answer. + print(f"\n⚠ Stopping without a verified score — review the image yourself") + reason = f"Review did not produce a score: {review.error}" results["final_image"] = str(iter_path) - results["final_score"] = score + results["final_score"] = review.score + results["final_reviewed"] = review.reviewed and review.score is not None results["success"] = True results["early_stop"] = True - results["early_stop_reason"] = f"Quality score {score} meets threshold {threshold} for {doc_type}" + results["early_stop_reason"] = reason break - + # If this is the last iteration, we're done regardless if i == iterations: print(f"\n⚠ Maximum iterations reached") results["final_image"] = str(iter_path) - results["final_score"] = score + results["final_score"] = review.score + results["final_reviewed"] = review.reviewed and review.score is not None results["success"] = True break - + # Quality below threshold - improve prompt for next iteration - print(f"\n⚠ Quality below threshold ({score} < {threshold})") + print(f"\n⚠ Quality below threshold ({review.score} < {threshold})") print(f"Improving prompt based on feedback...") - current_prompt = self.improve_prompt(user_prompt, critique, i + 1) + current_prompt = self.improve_prompt(user_prompt, review.critique, i + 1) # Copy final version to output path if results["success"] and results["final_image"]: @@ -734,7 +838,10 @@ Generate a publication-quality scientific diagram that meets all the guidelines print(f"\n{'='*60}") print(f"Generation Complete!") - print(f"Final Score: {results['final_score']}/10") + if results["final_score"] is not None: + print(f"Final Score: {results['final_score']}/10") + else: + print(f"Final Score: unavailable (the review did not produce one)") if results["early_stop"]: print(f"Iterations Used: {len([r for r in results['iterations'] if r.get('success')])}/{iterations} (early stop)") print(f"{'='*60}\n") @@ -821,8 +928,14 @@ Environment: if results["success"]: print(f"\n✓ Success! Image saved to: {args.output}") - if results.get("early_stop"): - print(f" (Completed in {len([r for r in results['iterations'] if r.get('success')])} iteration(s) - quality threshold met)") + used = len([r for r in results['iterations'] if r.get('success')]) + if results.get("final_reviewed"): + if results.get("early_stop"): + print(f" (Completed in {used} iteration(s) - quality threshold met)") + else: + # The image is real; the quality claim is not. Say which. + print(f" (Completed in {used} iteration(s) - quality NOT verified," + f" the review produced no score. Check the image yourself.)") sys.exit(0) else: print(f"\n✗ Generation failed. Check review log for details.") diff --git a/skills/literature-review/SKILL.md b/skills/literature-review/SKILL.md index 6f7bb8c5..eb3cfa0d 100644 --- a/skills/literature-review/SKILL.md +++ b/skills/literature-review/SKILL.md @@ -4,7 +4,7 @@ description: Conduct comprehensive, systematic literature reviews using multiple allowed-tools: Read Write Edit Bash license: MIT license metadata: - version: "1.5" + version: "1.6" skill-author: K-Dense Inc. openclaw: primaryEnv: OPENROUTER_API_KEY @@ -228,7 +228,7 @@ curl -fsSL https://parallel.ai/install.sh | bash ### Required Python Packages ```bash -pip install requests # For citation verification +uv pip install requests # For citation verification ``` ### Required System Tools diff --git a/skills/literature-review/scripts/generate_schematic.py b/skills/literature-review/scripts/generate_schematic.py index 64246559..6392aebf 100644 --- a/skills/literature-review/scripts/generate_schematic.py +++ b/skills/literature-review/scripts/generate_schematic.py @@ -147,7 +147,12 @@ Environment Variables: help="Verbose output") args = parser.parse_args() - + + # Validated here rather than clamped silently, and before the credential + # lookup so an out-of-range value reports itself rather than an absent key. + if not 1 <= args.iterations <= 2: + parser.error("--iterations must be 1 or 2") + # Check for API key — resolves --api-key, the environment, then any .env file api_key = resolve_api_key(args.api_key) if not api_key: @@ -173,12 +178,9 @@ Environment Variables: if args.doc_type != "default": cmd.extend(["--doc-type", args.doc_type]) - - # Enforce max 2 iterations - iterations = min(args.iterations, 2) - if iterations != 2: - cmd.extend(["--iterations", str(iterations)]) - + + cmd.extend(["--iterations", str(args.iterations)]) + if args.verbose: cmd.append("-v") diff --git a/skills/literature-review/scripts/generate_schematic_ai.py b/skills/literature-review/scripts/generate_schematic_ai.py index 3e3e475f..85c4fd29 100644 --- a/skills/literature-review/scripts/generate_schematic_ai.py +++ b/skills/literature-review/scripts/generate_schematic_ai.py @@ -22,17 +22,94 @@ import argparse import base64 import json import os +import re import sys import time from pathlib import Path -from typing import Optional, Dict, Any, List, Tuple +from typing import Optional, Dict, Any, List, NamedTuple try: import requests except ImportError: - print("Error: requests library not found. Install with: pip install requests") + print("Error: requests library not found. Install with: uv pip install requests") sys.exit(1) + +class ReviewResult(NamedTuple): + """The outcome of one quality review. + + A named tuple rather than a bare tuple because the review has several + failure modes -- the model returns no choices, the request raises, the + answer arrives in an unexpected shape -- and each of them used to be a + chance to return the wrong number of values to the caller. + + `score` is None whenever no usable number was parsed, and `reviewed` is + False whenever the review never produced an answer at all. Neither case + invents a score: a diagram whose quality was not measured is reported as + unmeasured, not as passing. + """ + + critique: str + score: Optional[float] + needs_improvement: bool + reviewed: bool + error: Optional[str] = None + + +# Markdown decoration the reviewer routinely wraps its answer in. Gemini writes +# "**SCORE:** 8.5" far more often than the bare "SCORE: 8.5" the rubric asks +# for, and a pattern that does not allow for it silently scores every diagram +# at whatever the default happens to be. +_MARKUP = re.compile(r"[*_`#]") + +_SCORE_PATTERN = re.compile(r"\bSCORE\s*:?\s*(\d+(?:\.\d+)?)", re.IGNORECASE) +_LOOSE_SCORE_PATTERN = re.compile( + r"(?:score|rating|quality)\s*[:\s]\s*(\d+(?:\.\d+)?)\s*(?:/\s*10)?", re.IGNORECASE +) +# The underscore is optional because normalization strips it out of +# NEEDS_IMPROVEMENT along with the surrounding markdown. +_VERDICT_PATTERN = re.compile( + r"^\s*VERDICT\s*:?\s*(ACCEPTABLE|NEEDS[_ ]?IMPROVEMENT)", re.IGNORECASE | re.MULTILINE +) + + +def _normalize_review_text(text: str) -> str: + """Strip markdown decoration so the rubric's fields can be found.""" + return _MARKUP.sub("", text or "") + + +def _parse_score(text: str) -> Optional[float]: + """Return the reviewer's 0-10 score, or None when there isn't a usable one. + + None rather than a default: a fabricated score is indistinguishable from a + real one once it reaches the review log, and a default near the middle of + the range quietly passes lenient document types while failing strict ones. + """ + normalized = _normalize_review_text(text) + match = _SCORE_PATTERN.search(normalized) or _LOOSE_SCORE_PATTERN.search(normalized) + if not match: + return None + score = float(match.group(1)) + # A number outside the rubric's range means something other than the score + # was matched -- a figure count, a percentage, an iteration number. + return score if 0.0 <= score <= 10.0 else None + + +def _parse_verdict(text: str) -> Optional[str]: + """Return ACCEPTABLE / NEEDS_IMPROVEMENT from the verdict line, or None. + + Anchored to the start of a line. The rubric prompt spells out both tokens + when it explains the response format, so a reviewer that echoes those + instructions back would fail a perfectly good diagram under a plain + substring search. + """ + match = _VERDICT_PATTERN.search(_normalize_review_text(text)) + if not match: + return None + verdict = match.group(1).upper().replace(" ", "").replace("_", "") + return "NEEDS_IMPROVEMENT" if verdict == "NEEDSIMPROVEMENT" else "ACCEPTABLE" + + def _resolve_api_key(explicit: Optional[str] = None) -> Optional[str]: """Resolve the OpenRouter key from --api-key, the environment, then any .env file. @@ -282,7 +359,6 @@ IMPORTANT - NO FIGURE NUMBERS: # Handle string content if isinstance(content, str) and "data:image" in content: - import re match = re.search(r'data:image/[^;]+;base64,([A-Za-z0-9+/=\n\r]+)', content, re.DOTALL) if match: base64_str = match.group(1).replace('\n', '').replace('\r', '').replace(' ', '') @@ -417,24 +493,24 @@ IMPORTANT - NO FIGURE NUMBERS: def review_image(self, image_path: str, original_prompt: str, iteration: int, doc_type: str = "default", - max_iterations: int = 2) -> Tuple[str, float, bool]: + max_iterations: int = 2) -> ReviewResult: """ - Review generated image using Gemini 3.6 Flash for quality analysis. - - Uses Gemini 3.6 Flash's superior vision and reasoning capabilities to - evaluate the schematic quality and determine if regeneration is needed. - + Review the generated image for quality, using the vision review model. + Args: image_path: Path to the generated image original_prompt: Original user prompt iteration: Current iteration number doc_type: Document type (journal, poster, presentation, etc.) max_iterations: Maximum iterations allowed - + Returns: - Tuple of (critique text, quality score 0-10, needs_improvement bool) + A ReviewResult. When the review cannot be completed -- the request + fails, or the model answers with nothing usable -- `reviewed` is + False and `score` is None rather than a stand-in number, and + `needs_improvement` is False: the fault is in the reviewer, not in + the diagram, so regenerating would not help. """ - # Use Gemini 3.6 Flash for review - excellent vision and analysis image_data_url = self._image_to_base64(image_path) # Get quality threshold for this document type @@ -510,25 +586,32 @@ If score < {threshold}, mark as NEEDS_IMPROVEMENT with specific suggestions.""" ] try: - # Use Gemini 3.6 Flash for high-quality review response = self._make_request( model=self.review_model, messages=messages ) - + # Extract text response choices = response.get("choices", []) if not choices: - return "Image generated successfully", 8.0 - + # A normal enough outcome -- a rate limit, a content filter, a + # provider hiccup. The diagram itself is fine; only its review + # is missing, and saying so beats inventing a score. + reason = "the review model returned no choices" + self._log(f"⚠ Review unavailable: {reason}") + return ReviewResult( + f"Review unavailable: {reason}.", + None, False, reviewed=False, error=reason, + ) + message = choices[0].get("message", {}) content = message.get("content", "") - - # Check reasoning field (Nano Banana 2 puts analysis here) + + # Some models put their analysis in a separate reasoning field reasoning = message.get("reasoning", "") if reasoning and not content: content = reasoning - + if isinstance(content, list): # Extract text from content blocks text_parts = [] @@ -536,38 +619,41 @@ If score < {threshold}, mark as NEEDS_IMPROVEMENT with specific suggestions.""" if isinstance(block, dict) and block.get("type") == "text": text_parts.append(block.get("text", "")) content = "\n".join(text_parts) - - # Try to extract score - score = 7.5 # Default score if extraction fails - import re - - # Look for SCORE: X or SCORE: X/10 format - score_match = re.search(r'SCORE:\s*(\d+(?:\.\d+)?)', content, re.IGNORECASE) - if score_match: - score = float(score_match.group(1)) - else: - # Fallback: look for any score pattern - score_match = re.search(r'(?:score|rating|quality)[:\s]+(\d+(?:\.\d+)?)\s*(?:/\s*10)?', content, re.IGNORECASE) - if score_match: - score = float(score_match.group(1)) - - # Determine if improvement is needed based on verdict or score - needs_improvement = False - if "NEEDS_IMPROVEMENT" in content.upper(): - needs_improvement = True - elif score < threshold: - needs_improvement = True - - self._log(f"✓ Review complete (Score: {score}/10, Threshold: {threshold}/10)") + + score = _parse_score(content) + verdict = _parse_verdict(content) + + if score is None and verdict is None: + reason = "no score or verdict found in the review" + self._log(f"⚠ Review unusable: {reason}") + return ReviewResult( + content if content else f"Review unusable: {reason}.", + None, False, reviewed=True, error=reason, + ) + + needs_improvement = verdict == "NEEDS_IMPROVEMENT" or ( + score is not None and score < threshold + ) + + shown = f"{score}/10" if score is not None else "not stated" + self._log(f"✓ Review complete (Score: {shown}, Threshold: {threshold}/10)") self._log(f" Verdict: {'Needs improvement' if needs_improvement else 'Acceptable'}") - - return (content if content else "Image generated successfully", - score, - needs_improvement) + + return ReviewResult( + content if content else "Review returned no text", + score, + needs_improvement, + reviewed=True, + error=None if score is not None else "no score found in the review", + ) except Exception as e: - self._log(f"Review skipped: {str(e)}") - # Don't fail the whole process if review fails - assume acceptable - return "Image generated successfully (review skipped)", 7.5, False + # A failed review must not fail the run -- the image is already + # generated and saved -- but it must not read as a pass either. + self._log(f"⚠ Review failed: {str(e)}") + return ReviewResult( + f"Review failed: {str(e)}", + None, False, reviewed=False, error=str(e), + ) def improve_prompt(self, original_prompt: str, critique: str, iteration: int) -> str: @@ -629,7 +715,10 @@ Generate an improved version that addresses all the critique points while mainta "quality_threshold": threshold, "iterations": [], "final_image": None, - "final_score": 0.0, + # None, not 0.0 -- a run whose review never completed has no score, + # and a number here would be read as one the reviewer gave. + "final_score": None, + "final_reviewed": False, "success": False, "early_stop": False, "early_stop_reason": None @@ -675,48 +764,63 @@ Generate a publication-quality scientific diagram that meets all the guidelines f.write(image_data) print(f"✓ Saved: {iter_path}") - # Review image using Gemini 3.6 Flash - print(f"Reviewing image with Gemini 3.6 Flash...") - critique, score, needs_improvement = self.review_image( + # Review the image with the vision review model + print(f"Reviewing image with {self.review_model}...") + review = self.review_image( str(iter_path), user_prompt, i, doc_type, iterations ) - print(f"✓ Score: {score}/10 (threshold: {threshold}/10)") - + if review.score is not None: + print(f"✓ Score: {review.score}/10 (threshold: {threshold}/10)") + else: + print(f"⚠ Review unavailable — image kept, quality not verified") + print(f" Reason: {review.error}") + # Save iteration results iteration_result = { "iteration": i, "image_path": str(iter_path), "prompt": current_prompt, - "critique": critique, - "score": score, - "needs_improvement": needs_improvement, + "critique": review.critique, + "score": review.score, + "reviewed": review.reviewed, + "review_error": review.error, + "needs_improvement": review.needs_improvement, "success": True } results["iterations"].append(iteration_result) - + # Check if quality is acceptable - STOP EARLY if so - if not needs_improvement: - print(f"\n✓ Quality meets {doc_type} threshold ({score} >= {threshold})") - print(f" No further iterations needed!") + if not review.needs_improvement: + if review.score is not None: + print(f"\n✓ Quality meets {doc_type} threshold ({review.score} >= {threshold})") + print(f" No further iterations needed!") + reason = (f"Quality score {review.score} meets threshold " + f"{threshold} for {doc_type}") + else: + # Regenerating cannot fix a reviewer that did not answer. + print(f"\n⚠ Stopping without a verified score — review the image yourself") + reason = f"Review did not produce a score: {review.error}" results["final_image"] = str(iter_path) - results["final_score"] = score + results["final_score"] = review.score + results["final_reviewed"] = review.reviewed and review.score is not None results["success"] = True results["early_stop"] = True - results["early_stop_reason"] = f"Quality score {score} meets threshold {threshold} for {doc_type}" + results["early_stop_reason"] = reason break - + # If this is the last iteration, we're done regardless if i == iterations: print(f"\n⚠ Maximum iterations reached") results["final_image"] = str(iter_path) - results["final_score"] = score + results["final_score"] = review.score + results["final_reviewed"] = review.reviewed and review.score is not None results["success"] = True break - + # Quality below threshold - improve prompt for next iteration - print(f"\n⚠ Quality below threshold ({score} < {threshold})") + print(f"\n⚠ Quality below threshold ({review.score} < {threshold})") print(f"Improving prompt based on feedback...") - current_prompt = self.improve_prompt(user_prompt, critique, i + 1) + current_prompt = self.improve_prompt(user_prompt, review.critique, i + 1) # Copy final version to output path if results["success"] and results["final_image"]: @@ -734,7 +838,10 @@ Generate a publication-quality scientific diagram that meets all the guidelines print(f"\n{'='*60}") print(f"Generation Complete!") - print(f"Final Score: {results['final_score']}/10") + if results["final_score"] is not None: + print(f"Final Score: {results['final_score']}/10") + else: + print(f"Final Score: unavailable (the review did not produce one)") if results["early_stop"]: print(f"Iterations Used: {len([r for r in results['iterations'] if r.get('success')])}/{iterations} (early stop)") print(f"{'='*60}\n") @@ -821,8 +928,14 @@ Environment: if results["success"]: print(f"\n✓ Success! Image saved to: {args.output}") - if results.get("early_stop"): - print(f" (Completed in {len([r for r in results['iterations'] if r.get('success')])} iteration(s) - quality threshold met)") + used = len([r for r in results['iterations'] if r.get('success')]) + if results.get("final_reviewed"): + if results.get("early_stop"): + print(f" (Completed in {used} iteration(s) - quality threshold met)") + else: + # The image is real; the quality claim is not. Say which. + print(f" (Completed in {used} iteration(s) - quality NOT verified," + f" the review produced no score. Check the image yourself.)") sys.exit(0) else: print(f"\n✗ Generation failed. Check review log for details.") diff --git a/skills/markitdown/references/migration.md b/skills/markitdown/references/migration.md index 3826f6ac..875b3b1e 100644 --- a/skills/markitdown/references/migration.md +++ b/skills/markitdown/references/migration.md @@ -252,8 +252,8 @@ Use `pyproject.toml`; old `setup.py`-only examples are no longer the preferred p Outdated: ```bash -pip install markitdown -pip install "markitdown[all]" +uv pip install markitdown +uv pip install "markitdown[all]" ``` Repository-standard reproducible install: diff --git a/skills/molecular-dynamics/SKILL.md b/skills/molecular-dynamics/SKILL.md index e48b2d12..89f5bf22 100644 --- a/skills/molecular-dynamics/SKILL.md +++ b/skills/molecular-dynamics/SKILL.md @@ -20,7 +20,7 @@ Molecular dynamics (MD) simulation computationally models the time evolution of ```bash conda install -c conda-forge openmm mdanalysis nglview # or -pip install openmm mdanalysis +uv pip install openmm mdanalysis ``` ## When to Use This Skill @@ -421,7 +421,7 @@ def fix_pdb(input_pdb, output_pdb, ph=7.0): ```python # For ligand parameterization, use OpenFF toolkit or ACPYPE -# pip install openff-toolkit +# uv pip install openff-toolkit from openff.toolkit import Molecule, ForceField as OFFForceField from openff.interchange import Interchange diff --git a/skills/neuropixels-analysis/references/AUTOMATED_CURATION.md b/skills/neuropixels-analysis/references/AUTOMATED_CURATION.md index 3bafed81..023ac9f9 100644 --- a/skills/neuropixels-analysis/references/AUTOMATED_CURATION.md +++ b/skills/neuropixels-analysis/references/AUTOMATED_CURATION.md @@ -34,12 +34,12 @@ Bombcell classifies units into 4 categories: ```bash # Python -pip install bombcell +uv pip install bombcell # Or development version git clone https://github.com/Julie-Fabre/bombcell.git cd bombcell/py_bombcell -pip install -e . +uv pip install -e . ``` ### Basic Usage (Python) @@ -264,7 +264,7 @@ Track the same neurons across recording days. ### Installation ```bash -pip install unitmatch +uv pip install unitmatch # Or from source git clone https://github.com/EnnyvanBeest/UnitMatch.git ``` diff --git a/skills/neuropixels-analysis/references/SPIKE_SORTING.md b/skills/neuropixels-analysis/references/SPIKE_SORTING.md index adae1a7b..c3626343 100644 --- a/skills/neuropixels-analysis/references/SPIKE_SORTING.md +++ b/skills/neuropixels-analysis/references/SPIKE_SORTING.md @@ -17,7 +17,7 @@ Comprehensive guide to spike sorting Neuropixels data. ### Installation ```bash -pip install kilosort +uv pip install kilosort ``` ### Basic Usage @@ -106,7 +106,7 @@ sorting = si.run_sorter( ### Installation ```bash -pip install spykingcircus +uv pip install spykingcircus ``` ### Usage @@ -125,7 +125,7 @@ sorting = si.run_sorter( ### Installation ```bash -pip install mountainsort5 +uv pip install mountainsort5 ``` ### Usage diff --git a/skills/nextflow/SKILL.md b/skills/nextflow/SKILL.md index 083cab81..eaed0d79 100644 --- a/skills/nextflow/SKILL.md +++ b/skills/nextflow/SKILL.md @@ -47,7 +47,7 @@ conda create -n nf -c bioconda -c conda-forge nextflow nf-core ```bash # nf-core tools (Python) for creating/linting/running nf-core assets -pip install nf-core # or: conda install -c bioconda nf-core +uv pip install nf-core # or: conda install -c bioconda nf-core nf-core --version ``` diff --git a/skills/nextflow/references/nf-core-tools.md b/skills/nextflow/references/nf-core-tools.md index 6920e7fa..c5ababe5 100644 --- a/skills/nextflow/references/nf-core-tools.md +++ b/skills/nextflow/references/nf-core-tools.md @@ -5,7 +5,7 @@ ## Install ```bash -pip install nf-core # PyPI +uv pip install nf-core # PyPI conda install -c bioconda nf-core nf-core --version ``` diff --git a/skills/open-notebook/scripts/chat_interaction.py b/skills/open-notebook/scripts/chat_interaction.py index 02e015a9..ea77e938 100644 --- a/skills/open-notebook/scripts/chat_interaction.py +++ b/skills/open-notebook/scripts/chat_interaction.py @@ -5,7 +5,7 @@ Demonstrates creating chat sessions, sending messages with context, and searching across research materials. Prerequisites: - pip install requests + uv pip install requests Usage: export OPEN_NOTEBOOK_URL="http://localhost:5055" diff --git a/skills/open-notebook/scripts/notebook_management.py b/skills/open-notebook/scripts/notebook_management.py index 84819436..d14e6d06 100644 --- a/skills/open-notebook/scripts/notebook_management.py +++ b/skills/open-notebook/scripts/notebook_management.py @@ -5,7 +5,7 @@ Demonstrates creating, listing, updating, and deleting notebooks using the Open Notebook REST API. Prerequisites: - pip install requests + uv pip install requests Usage: export OPEN_NOTEBOOK_URL="http://localhost:5055" diff --git a/skills/open-notebook/scripts/source_ingestion.py b/skills/open-notebook/scripts/source_ingestion.py index 0165e1f3..b893d6ec 100644 --- a/skills/open-notebook/scripts/source_ingestion.py +++ b/skills/open-notebook/scripts/source_ingestion.py @@ -5,7 +5,7 @@ Demonstrates ingesting various content types (URLs, files, text) into Open Notebook and monitoring processing status. Prerequisites: - pip install requests + uv pip install requests Usage: export OPEN_NOTEBOOK_URL="http://localhost:5055" diff --git a/skills/paperclip/SKILL.md b/skills/paperclip/SKILL.md index 1c35a6b8..e9a3953e 100644 --- a/skills/paperclip/SKILL.md +++ b/skills/paperclip/SKILL.md @@ -397,7 +397,7 @@ as `PAPERCLIP_API_KEY=gxl_...`, gitignore that file, and use the prefix from rul prefers OAuth, ask *them* to run `paperclip login` — it needs a browser and will not work from a tool call. -Full matrix — pip/uv install, the hosted MCP server, per-client setup for Claude Code, Claude Desktop, +Full matrix — uv install, the hosted MCP server, per-client setup for Claude Code, Claude Desktop, Codex, Cursor and Windsurf, auth precedence, and troubleshooting — is in [references/installation.md](references/installation.md). diff --git a/skills/paperclip/references/cli-reference.md b/skills/paperclip/references/cli-reference.md index 7180cef1..616610fd 100644 --- a/skills/paperclip/references/cli-reference.md +++ b/skills/paperclip/references/cli-reference.md @@ -281,7 +281,7 @@ paperclip results s_4a2b61f6 --save out.csv # export to CSV or TXT | Command | Purpose | |---|---| | `login` / `logout` | Browser OAuth | -| `setup` | `login` + `install`, for pip/uv installs | +| `setup` | `login` + `install`, for uv installs | | `install [--dir]` | Write Paperclip skill files into a project | | `config` | Diagnostics and settings | | `update` | Upgrade CLI and refresh agent skills | diff --git a/skills/paperclip/references/installation.md b/skills/paperclip/references/installation.md index 926de97b..379e10ea 100644 --- a/skills/paperclip/references/installation.md +++ b/skills/paperclip/references/installation.md @@ -37,19 +37,19 @@ If `paperclip` is not found afterwards, `~/.local/bin` is not on your `PATH`: export PATH="$HOME/.local/bin:$PATH" # add to ~/.zshrc or ~/.bashrc to persist ``` -### Via pip or uv +### Via uv Use this when you want the package inside an environment you control — for example to import the Python SDK alongside your own code. ```bash -pip install https://paperclip.gxl.ai/paperclip.whl +uv pip install https://paperclip.gxl.ai/paperclip.whl paperclip setup # = paperclip login + paperclip install ``` Two caveats. The wheel URL is unversioned, so it resolves to whatever is current — there is no pinned, hash-verified release to install instead, and `gxl-paperclip` is not published on PyPI. And the -unrelated `paperclip` package **is** on PyPI: `pip install paperclip` installs the wrong software. +unrelated `paperclip` package **is** on PyPI: `uv pip install paperclip` installs the wrong software. Always install from the full URL. ### Windows diff --git a/skills/paperclip/references/python-sdk.md b/skills/paperclip/references/python-sdk.md index 20b7cf56..43113405 100644 --- a/skills/paperclip/references/python-sdk.md +++ b/skills/paperclip/references/python-sdk.md @@ -14,7 +14,7 @@ The curl installer bundles the SDK inside its private tree at `~/.paperclip/lib/ your `sys.path`. For real use, install it into the environment you control: ```bash -pip install https://paperclip.gxl.ai/paperclip.whl +uv pip install https://paperclip.gxl.ai/paperclip.whl # or uv add https://paperclip.gxl.ai/paperclip.whl ``` diff --git a/skills/pdf/SKILL.md b/skills/pdf/SKILL.md index 1b3184ab..40dc988c 100644 --- a/skills/pdf/SKILL.md +++ b/skills/pdf/SKILL.md @@ -236,7 +236,7 @@ pdftk input.pdf rotate 1east output rotated.pdf ### Extract Text from Scanned PDFs ```python -# Requires: pip install pytesseract pdf2image +# Requires: uv pip install pytesseract pdf2image import pytesseract from pdf2image import convert_from_path diff --git a/skills/phylogenetics/SKILL.md b/skills/phylogenetics/SKILL.md index 996bd983..2256dbc7 100644 --- a/skills/phylogenetics/SKILL.md +++ b/skills/phylogenetics/SKILL.md @@ -22,11 +22,11 @@ Phylogenetic analysis reconstructs the evolutionary history of biological sequen ```bash # Conda (recommended for CLI tools) conda install -c bioconda mafft iqtree fasttree -pip install ete3 +uv pip install ete3 # ete3's TreeStyle/NodeStyle rendering lives in its Qt backend, so image output # needs PyQt5 as well; tree parsing and statistics work without it. -pip install PyQt5 +uv pip install PyQt5 ``` ## When to Use This Skill diff --git a/skills/phylogenetics/scripts/phylogenetic_analysis.py b/skills/phylogenetics/scripts/phylogenetic_analysis.py index 53a68b3b..fea5cfed 100644 --- a/skills/phylogenetics/scripts/phylogenetic_analysis.py +++ b/skills/phylogenetics/scripts/phylogenetic_analysis.py @@ -5,7 +5,7 @@ Complete workflow: MAFFT alignment → IQ-TREE tree → ETE3 visualization. Requirements: conda install -c bioconda mafft iqtree - pip install ete3 + uv pip install ete3 Usage: python phylogenetic_analysis.py sequences.fasta --type nt --threads 4 @@ -142,7 +142,7 @@ def visualize_tree(tree_file: str, output_png: str, outgroup: str = None) -> Non # TreeStyle and NodeStyle live in ete3's Qt-backed treeview module, so # this also fires when ete3 itself imported fine but PyQt5 is missing. print(f"ETE3 rendering unavailable ({exc}). Skipping visualization.") - print(" Install: pip install ete3 PyQt5") + print(" Install: uv pip install ete3 PyQt5") return t = Tree(tree_file) diff --git a/skills/pkpd-modeling/SKILL.md b/skills/pkpd-modeling/SKILL.md index af4c35c4..ff4d88fb 100644 --- a/skills/pkpd-modeling/SKILL.md +++ b/skills/pkpd-modeling/SKILL.md @@ -338,7 +338,7 @@ map and `references/source-ledger.md` for provenance. - **nlmixr2** (requires rxode2 ≥ 5.0.0) is the credible open-source NLME alternative; `babelmixr2` and `monolix2rx` translate models between it, NONMEM and Monolix. - **PKPy** (PeerJ, 2025) is a Python popPK framework but is **GitHub-only — not on PyPI**, so - `pip install pkpy` fails. `chi-drm` (1.0.3) is on PyPI for Bayesian PKPD. + `uv pip install pkpy` fails. `chi-drm` (1.0.3) is on PyPI for Bayesian PKPD. - **Open Systems Pharmacology Suite v12** (PK-Sim/MoBi) is the open-source PBPK platform; Simcyp and GastroPlus are the commercial ones. `ospsuite` is R-only and needs .NET 8. diff --git a/skills/pkpd-modeling/references/software-ecosystem.md b/skills/pkpd-modeling/references/software-ecosystem.md index 352a92ab..7457882e 100644 --- a/skills/pkpd-modeling/references/software-ecosystem.md +++ b/skills/pkpd-modeling/references/software-ecosystem.md @@ -73,7 +73,7 @@ m.calculate_eta_shrinkage(model, ...) | **`nca.py` in this skill** | MIT | Validated against analytical profiles; explicit about all four conventions | **PKPy** (PeerJ, 2025) is a Python framework combining NCA with population modelling, but it is -**GitHub-only and not published on PyPI** — `pip install pkpy` fails. Install from source if you +**GitHub-only and not published on PyPI** — `uv pip install pkpy` fails. Install from source if you want it. ## Simulation and trial design diff --git a/skills/pkpd-modeling/scripts/bioequivalence.py b/skills/pkpd-modeling/scripts/bioequivalence.py index 741a6a73..ea7d0e19 100644 --- a/skills/pkpd-modeling/scripts/bioequivalence.py +++ b/skills/pkpd-modeling/scripts/bioequivalence.py @@ -40,7 +40,7 @@ try: from scipy.stats import chi2, norm from scipy.stats import t as t_dist except ImportError as exc: # pragma: no cover - raise SystemExit("bioequivalence.py needs scipy: pip install scipy") from exc + raise SystemExit("bioequivalence.py needs scipy: uv pip install scipy") from exc # The FDA regulatory constant: ln(1.25) / 0.25, the point at which the scaled diff --git a/skills/pkpd-modeling/scripts/exposure_response.py b/skills/pkpd-modeling/scripts/exposure_response.py index 7d676d59..e7c59c17 100644 --- a/skills/pkpd-modeling/scripts/exposure_response.py +++ b/skills/pkpd-modeling/scripts/exposure_response.py @@ -41,7 +41,7 @@ try: from scipy.stats import norm from scipy.stats import t as t_dist except ImportError as exc: # pragma: no cover - raise SystemExit("exposure_response.py needs scipy: pip install scipy") from exc + raise SystemExit("exposure_response.py needs scipy: uv pip install scipy") from exc # ICH E14's threshold of regulatory concern: an upper bound of the two-sided # 90% confidence interval for placebo-corrected change-from-baseline QTc above diff --git a/skills/pkpd-modeling/scripts/fit_compartmental.py b/skills/pkpd-modeling/scripts/fit_compartmental.py index 135e8115..25ec8f07 100644 --- a/skills/pkpd-modeling/scripts/fit_compartmental.py +++ b/skills/pkpd-modeling/scripts/fit_compartmental.py @@ -46,7 +46,7 @@ try: from scipy.stats import f as f_dist from scipy.stats import t as t_dist except ImportError as exc: # pragma: no cover - raise SystemExit("fit_compartmental.py needs scipy: pip install scipy") from exc + raise SystemExit("fit_compartmental.py needs scipy: uv pip install scipy") from exc MODELS = { diff --git a/skills/pkpd-modeling/scripts/tdm_bayes.py b/skills/pkpd-modeling/scripts/tdm_bayes.py index d93d1974..010dbb2d 100644 --- a/skills/pkpd-modeling/scripts/tdm_bayes.py +++ b/skills/pkpd-modeling/scripts/tdm_bayes.py @@ -36,7 +36,7 @@ from _models import build_regimen, disposition, simulate_linear try: from scipy.optimize import minimize except ImportError as exc: # pragma: no cover - raise SystemExit("tdm_bayes.py needs scipy: pip install scipy") from exc + raise SystemExit("tdm_bayes.py needs scipy: uv pip install scipy") from exc @dataclass diff --git a/skills/rowan/SKILL.md b/skills/rowan/SKILL.md index 6dba6714..a1c28e99 100644 --- a/skills/rowan/SKILL.md +++ b/skills/rowan/SKILL.md @@ -64,7 +64,7 @@ If that prints without error, you're set up correctly. ```bash uv pip install rowan-python -# or: pip install rowan-python +# or: uv pip install rowan-python ``` ## User and webhook management diff --git a/skills/scientific-schematics/SKILL.md b/skills/scientific-schematics/SKILL.md index f7292c9e..d00b02f0 100644 --- a/skills/scientific-schematics/SKILL.md +++ b/skills/scientific-schematics/SKILL.md @@ -4,7 +4,7 @@ description: Create publication-quality scientific diagrams using Nano Banana 2 allowed-tools: Read Write Edit Bash license: MIT license metadata: - version: "1.4" + version: "1.5" skill-author: K-Dense Inc. openclaw: primaryEnv: OPENROUTER_API_KEY @@ -43,6 +43,10 @@ Scientific schematics and diagrams transform complex concepts into clear visual **Simply describe what you want, and Nano Banana 2 creates it.** All diagrams are stored in the figures/ subfolder and referenced in papers/posters. +**What the output is:** a raster PNG at whatever resolution the image model returns. This skill has +no vector path and no DPI control — if a journal demands PDF, EPS, or 300 dpi TIFF, convert the PNG +downstream and check the result at final print size. + ## Quick Start: Generate Any Diagram Create any scientific diagram by simply describing it. Nano Banana 2 handles everything automatically with **smart iteration**: @@ -74,7 +78,14 @@ python scripts/generate_schematic.py "Complex circuit diagram with op-amp, resis - ✅ Faster turnaround for presentations/posters - ✅ Appropriate quality for each use case -**Output**: Versioned images plus a detailed review log with quality scores, critiques, and early-stop information. +**Output**: Versioned images (`name_v1.png`, `name_v2.png`), a copy of the winner at the path you +asked for, and `name_review_log.json` with the score, critique, and early-stop reason per iteration. + +**When the review cannot run** — a rate limit, a content filter, a reviewer that answers in some +unexpected shape — the image is still generated and saved, but no score is invented for it. The log +records `"score": null` and `"reviewed": false` with the reason in `"review_error"`, and the run +prints `Review unavailable — image kept, quality not verified`. Treat that image as unchecked and +look at it yourself; re-running is worth a try, since the failure is usually transient. ### Configuration @@ -85,6 +96,11 @@ export OPENROUTER_API_KEY='your_api_key_here' Get an API key at: https://openrouter.ai/keys +**Data leaves the machine.** Your prompt is sent to OpenRouter to generate the image, and the +generated image is sent back to OpenRouter for the quality review. Both are subject to OpenRouter's +data policies and those of the underlying model providers. Do not describe unpublished data, +patient information, or anything under embargo in the prompt. + ### AI Generation Best Practices **Effective Prompts for Scientific Diagrams:** @@ -188,21 +204,26 @@ python scripts/generate_schematic.py "diagram" -o out.png -v ## Best Practices Summary -### Design Principles +### Design principles — ask for these in the prompt 1. **Clarity over complexity** - Simplify, remove unnecessary elements -2. **Consistent styling** - Use templates and style files -3. **Colorblind accessibility** - Use Okabe-Ito palette, redundant encoding -4. **Appropriate typography** - Sans-serif fonts, minimum 7-8 pt -5. **Vector format** - Always use PDF/SVG for publication +2. **Consistent styling** - Describe the same visual conventions across a paper's figures +3. **Colorblind accessibility** - Ask for the Okabe-Ito palette and redundant encoding +4. **Appropriate typography** - Sans-serif fonts, generously sized labels +5. **Logical flow** - State the direction (left-to-right, top-to-bottom) explicitly -### Technical Requirements +The generator applies all of these by default, but naming them in your own words for the specific +diagram works better than relying on the built-in guidelines alone. -1. **Resolution** - Vector preferred, or 300+ DPI for raster -2. **File format** - PDF for LaTeX, SVG for web, PNG as fallback -3. **Color space** - RGB for digital, CMYK for print (convert if needed) -4. **Line weights** - Minimum 0.5 pt, typical 1-2 pt -5. **Text size** - 7-8 pt minimum at final size +### What the pipeline cannot do + +1. **Vector output** - PNG only; no PDF, SVG, or EPS is produced +2. **Resolution control** - the image model chooses; there is no DPI flag +3. **Color space** - RGB only; convert for CMYK print workflows downstream +4. **Exact line weights or text sizes** - describe them in the prompt, then verify by eye + +For a journal that requires vector art or 300+ dpi TIFF, convert the PNG after generation and check +the result at the size it will actually be printed. ### Integration Guidelines @@ -214,68 +235,49 @@ python scripts/generate_schematic.py "diagram" -o out.png -v ## Troubleshooting Common Issues -### AI Generation Issues +Generation is stochastic and iteration is capped at 2, so the levers that actually change the +outcome are the prompt, the document type, and re-running. There is no post-processing step and no +quality-checking library in this skill: everything you can inspect lives in the generated PNG and +in `_review_log.json`. -**Problem**: Overlapping text or elements -- **Solution**: AI generation automatically handles spacing -- **Solution**: Increase iterations: `--iterations 2` for better refinement +### The diagram is wrong -**Problem**: Elements not connecting properly -- **Solution**: Make your prompt more specific about connections and layout -- **Solution**: Increase iterations for better refinement +**Overlapping text, crowded elements, or arrows that miss their targets** +- Name the layout in the prompt: "vertical flow, one box per row, generous spacing between stages" +- Name the connections: "arrow from RAF to MEK labelled phosphorylation", not "show the cascade" +- Re-run. Two runs of the same prompt differ, and a bad layout is often just an unlucky draw -### Image Quality Issues +**Content is scientifically wrong or a component is missing** +- List the components explicitly, with counts and labels — the model will not infer them +- Read the `critique` field in the review log: the reviewer usually names what it saw missing -**Problem**: Export quality poor -- **Solution**: AI generation produces high-quality images automatically -- **Solution**: Increase iterations for better results: `--iterations 2` +**Wrong text in labels, or figure numbering baked into the image** +- The prompt already forbids "Figure 1:" captions; if one appears anyway, re-run +- Misspelled labels are the most common failure of image models. Read every label before using it -**Problem**: Elements overlap after generation -- **Solution**: AI generation automatically handles spacing -- **Solution**: Increase iterations: `--iterations 2` for better refinement -- **Solution**: Make your prompt more specific about layout and spacing requirements +### The score seems wrong -### Quality Check Issues +**Score is lower than the diagram deserves** +- Read the critique before re-running; the reviewer's complaint is often legitimate and specific +- The threshold, not the score, decides whether it iterates — `--doc-type journal` demands 8.5 -**Problem**: False positive overlap detection -- **Solution**: Adjust threshold: `detect_overlaps(image_path, threshold=0.98)` -- **Solution**: Manually review flagged regions in visual report +**A run stops at a score below the threshold** +- That is the iteration cap. `--iterations 2` is the maximum; the last image is kept and reported + with its real score -**Problem**: Generated image quality is low -- **Solution**: AI generation produces high-quality images by default -- **Solution**: Increase iterations for better results: `--iterations 2` +**`"score": null` and `"reviewed": false` in the log** +- The review call failed or answered in an unusable shape. The image is fine and was kept; only its + quality was never measured. Check `"review_error"`, look at the image yourself, and re-run -**Problem**: Colorblind simulation shows poor contrast -- **Solution**: Switch to Okabe-Ito palette explicitly in code -- **Solution**: Add redundant encoding (shapes, patterns, line styles) -- **Solution**: Increase color saturation and lightness differences +### Setup -**Problem**: High-severity overlaps detected -- **Solution**: Review overlap_report.json for exact positions -- **Solution**: Increase spacing in those specific regions -- **Solution**: Re-run with adjusted parameters and verify again +**`Error: OPENROUTER_API_KEY not found`** +- `export OPENROUTER_API_KEY='sk-or-v1-...'`, or add it to a `.env` file, or pass `--api-key` -**Problem**: Visual report generation fails -- **Solution**: Check Pillow and matplotlib installations -- **Solution**: Ensure image file is readable: `Image.open(path).verify()` -- **Solution**: Check sufficient disk space for report generation +**`Error: requests library not found`** +- `uv pip install requests` -### Accessibility Problems - -**Problem**: Colors indistinguishable in grayscale -- **Solution**: Run accessibility checker: `verify_accessibility(image_path)` -- **Solution**: Add patterns, shapes, or line styles for redundancy -- **Solution**: Increase contrast between adjacent elements - -**Problem**: Text too small when printed -- **Solution**: Run resolution validator: `validate_resolution(image_path)` -- **Solution**: Design at final size, use minimum 7-8 pt fonts -- **Solution**: Check physical dimensions in resolution report - -**Problem**: Accessibility checks consistently fail -- **Solution**: Review accessibility_report.json for specific failures -- **Solution**: Increase color contrast by at least 20% -- **Solution**: Test with actual grayscale conversion before finalizing +**Any API error** — run with `-v` to see the request, the model slug, and the full error body ## Resources and References @@ -283,15 +285,13 @@ python scripts/generate_schematic.py "diagram" -o out.png -v Load these files for comprehensive information on specific topics: -- **`references/best_practices.md`** - Publication standards and accessibility guidelines +- **`references/iterative_refinement.md`** - The generate-review-refine loop, the Python API, every + command-line option, prompt engineering guidance, and four worked examples +- **`references/best_practices.md`** - Publication standards and accessibility guidelines to draw + on when writing prompts and when judging the result ### External Resources -**Python Libraries** -- Schemdraw Documentation: https://schemdraw.readthedocs.io/ -- NetworkX Documentation: https://networkx.org/documentation/ -- Matplotlib Documentation: https://matplotlib.org/ - **Publication Standards** - Nature Figure Guidelines: https://www.nature.com/nature/for-authors/final-submission - Science Figure Guidelines: https://www.science.org/content/page/instructions-preparing-initial-manuscript @@ -311,48 +311,36 @@ This skill works synergistically with: Before submitting diagrams, verify: -### Visual Quality -- [ ] High-quality image format (PNG from AI generation) -- [ ] No overlapping elements (AI handles automatically) -- [ ] Adequate spacing between all components (AI optimizes) -- [ ] Clean, professional alignment -- [ ] All arrows connect properly to intended targets +### Read the review log (this is the only automated check there is) +- [ ] `_review_log.json` exists and `"reviewed"` is `true` on the final iteration +- [ ] `"final_score"` is a real number, not `null`, and meets the threshold for your document type +- [ ] Read the `"critique"` — the reviewer's remaining issues are listed even on a passing score +- [ ] If more than one version was generated, compare `_v1` and `_v2` and keep the better one -### Accessibility -- [ ] Colorblind-safe palette (Okabe-Ito) used -- [ ] Works in grayscale (tested with accessibility checker) -- [ ] Sufficient contrast between elements (verified) -- [ ] Redundant encoding where appropriate (shapes + colors) -- [ ] Colorblind simulation passes all checks +### Look at the image yourself +- [ ] Every label is spelled correctly — image models misspell text, and no automated check here + catches it +- [ ] No overlapping or clipped text +- [ ] All arrows connect the elements they are meant to connect +- [ ] The science is right: correct components, correct direction, nothing invented +- [ ] Units and counts match what you asked for -### Typography and Readability -- [ ] Text minimum 7-8 pt at final size -- [ ] All elements labeled clearly and completely -- [ ] Consistent font family and sizing -- [ ] No text overlaps or cutoffs -- [ ] Units included where applicable +### Accessibility (by eye, or in an external checker) +- [ ] Colorblind-safe palette, and the encoding is not colour alone +- [ ] Still readable converted to grayscale +- [ ] Adequate contrast between adjacent elements -### Publication Standards -- [ ] Consistent styling with other figures in manuscript -- [ ] Comprehensive caption written with all abbreviations defined -- [ ] Referenced appropriately in manuscript text -- [ ] Meets journal-specific dimension requirements -- [ ] Exported in required format for journal (PDF/EPS/TIFF) +### Publication fit +- [ ] Consistent styling with the other figures in the manuscript +- [ ] Legible at the column width it will actually be printed at +- [ ] Converted to the journal's required format if PNG is not accepted +- [ ] Caption written, with every abbreviation defined +- [ ] Referenced in the manuscript text -### Quality Verification (Required) -- [ ] Ran `run_quality_checks()` and achieved PASS status -- [ ] Reviewed overlap detection report (zero high-severity overlaps) -- [ ] Passed accessibility verification (grayscale and colorblind) -- [ ] Resolution validated at target DPI (300+ for print) -- [ ] Visual quality report generated and reviewed -- [ ] All quality reports saved with figure files - -### Documentation and Version Control -- [ ] Source files (.tex, .py) saved for future revision -- [ ] Quality reports archived in `quality_reports/` directory -- [ ] Configuration parameters documented (colors, spacing, sizes) -- [ ] Git commit includes source, output, and quality reports -- [ ] README or comments explain how to regenerate figure +### Version control +- [ ] The prompt is recorded (it is stored verbatim in the review log) +- [ ] Review log committed alongside the image, so the score is auditable +- [ ] The command that regenerates the figure is written down ### Final Integration Check - [ ] Figure displays correctly in compiled manuscript diff --git a/skills/scientific-schematics/references/QUICK_REFERENCE.md b/skills/scientific-schematics/references/QUICK_REFERENCE.md deleted file mode 100644 index f03c5280..00000000 --- a/skills/scientific-schematics/references/QUICK_REFERENCE.md +++ /dev/null @@ -1,207 +0,0 @@ -# Scientific Schematics - Quick Reference - -**How it works:** Describe your diagram → Nano Banana 2 generates it automatically - -## Setup (One-Time) - -```bash -# Get API key from https://openrouter.ai/keys -export OPENROUTER_API_KEY='sk-or-v1-your_key_here' - -# Add to shell profile for persistence -echo 'export OPENROUTER_API_KEY="sk-or-v1-your_key"' >> ~/.bashrc # or ~/.zshrc -``` - -## Basic Usage - -```bash -# Describe your diagram, Nano Banana 2 creates it -python scripts/generate_schematic.py "your diagram description" -o output.png - -# That's it! Automatic: -# - Iterative refinement (3 rounds) -# - Quality review and improvement -# - Publication-ready output -``` - -## Common Examples - -### CONSORT Flowchart -```bash -python scripts/generate_schematic.py \ - "CONSORT flow: screened n=500, excluded n=150, randomized n=350" \ - -o consort.png -``` - -### Neural Network -```bash -python scripts/generate_schematic.py \ - "Transformer architecture with encoder and decoder stacks" \ - -o transformer.png -``` - -### Biological Pathway -```bash -python scripts/generate_schematic.py \ - "MAPK pathway: EGFR → RAS → RAF → MEK → ERK" \ - -o mapk.png -``` - -### Circuit Diagram -```bash -python scripts/generate_schematic.py \ - "Op-amp circuit with 1kΩ resistor and 10µF capacitor" \ - -o circuit.png -``` - -## Command Options - -| Option | Description | Example | -|--------|-------------|---------| -| `-o, --output` | Output file path | `-o figures/diagram.png` | -| `--iterations N` | Number of refinements (1-2) | `--iterations 2` | -| `-v, --verbose` | Show detailed output | `-v` | -| `--api-key KEY` | Provide API key | `--api-key sk-or-v1-...` | - -## Prompt Tips - -### ✓ Good Prompts (Specific) -- "CONSORT flowchart with screening (n=500), exclusion (n=150), randomization (n=350)" -- "Transformer architecture: encoder on left with 6 layers, decoder on right, cross-attention connections" -- "MAPK signaling: receptor → RAS → RAF → MEK → ERK → nucleus, label each phosphorylation" - -### ✗ Avoid (Too Vague) -- "Make a flowchart" -- "Neural network" -- "Pathway diagram" - -## Output Files - -For input `diagram.png`, you get: -- `diagram_v1.png` - First iteration -- `diagram_v2.png` - Second iteration -- `diagram_v3.png` - Final iteration -- `diagram.png` - Copy of final -- `diagram_review_log.json` - Quality scores and critiques - -## Review Log - -```json -{ - "iterations": [ - { - "iteration": 1, - "score": 7.0, - "critique": "Good start. Font too small..." - }, - { - "iteration": 2, - "score": 8.5, - "critique": "Much improved. Minor spacing issues..." - }, - { - "iteration": 3, - "score": 9.5, - "critique": "Excellent. Publication ready." - } - ], - "final_score": 9.5 -} -``` - -## Python API - -```python -from scripts.generate_schematic_ai import ScientificSchematicGenerator - -# Initialize -gen = ScientificSchematicGenerator(api_key="your_key") - -# Generate -results = gen.generate_iterative( - user_prompt="diagram description", - output_path="output.png", - iterations=2 -) - -# Check quality -print(f"Score: {results['final_score']}/10") -``` - -## Troubleshooting - -### API Key Not Found -```bash -# Check if set -echo $OPENROUTER_API_KEY - -# Set it -export OPENROUTER_API_KEY='your_key' -``` - -### Import Error -```bash -# Install requests -pip install requests -``` - -### Low Quality Score -- Make prompt more specific -- Include layout details (left-to-right, top-to-bottom) -- Specify label requirements -- Increase iterations: `--iterations 2` - -## Testing - -```bash -# Verify installation -python test_ai_generation.py - -# Should show: "6/6 tests passed" -``` - -## Cost - -Typical cost per diagram (max 2 iterations): -- Simple (1 iteration): $0.05-0.15 -- Complex (2 iterations): $0.10-0.30 - -## How Nano Banana 2 Works - -**Simply describe your diagram in natural language:** -- ✓ No coding required -- ✓ No templates needed -- ✓ No manual drawing -- ✓ Automatic quality review -- ✓ Publication-ready output -- ✓ Works for any diagram type - -**Just describe what you want, and it's generated automatically.** - -## Getting Help - -```bash -# Show help -python scripts/generate_schematic.py --help - -# Verbose mode for debugging -python scripts/generate_schematic.py "diagram" -o out.png -v -``` - -## Quick Start Checklist - -- [ ] Set `OPENROUTER_API_KEY` environment variable -- [ ] Run `python test_ai_generation.py` (should pass 6/6) -- [ ] Try: `python scripts/generate_schematic.py "test diagram" -o test.png` -- [ ] Review output files (test_v1.png, v2, v3, review_log.json) -- [ ] Read SKILL.md for detailed documentation -- [ ] Check README.md for examples - -## Resources - -- Full documentation: `SKILL.md` -- Detailed guide: `README.md` -- Implementation details: `IMPLEMENTATION_SUMMARY.md` -- Example script: `example_usage.sh` -- Get API key: https://openrouter.ai/keys - diff --git a/skills/scientific-schematics/references/README.md b/skills/scientific-schematics/references/README.md deleted file mode 100644 index e5edb1cc..00000000 --- a/skills/scientific-schematics/references/README.md +++ /dev/null @@ -1,330 +0,0 @@ -# Scientific Schematics - Nano Banana 2 - -**Generate any scientific diagram by describing it in natural language.** - -Nano Banana 2 creates publication-quality diagrams automatically - no coding, no templates, no manual drawing required. - -## Quick Start - -### Generate Any Diagram - -```bash -# Set your OpenRouter API key -export OPENROUTER_API_KEY='your_api_key_here' - -# Generate any scientific diagram -python scripts/generate_schematic.py "CONSORT participant flow diagram" -o figures/consort.png - -# Neural network architecture -python scripts/generate_schematic.py "Transformer encoder-decoder architecture" -o figures/transformer.png - -# Biological pathway -python scripts/generate_schematic.py "MAPK signaling pathway" -o figures/pathway.png -``` - -### What You Get - -- **Up to two iterations** (v1, v2) with progressive refinement -- **Automatic quality review** after each iteration -- **Detailed review log** with scores and critiques (JSON format) -- **Publication-ready images** following scientific standards - -## Features - -### Iterative Refinement Process - -1. **Generation 1**: Create initial diagram from your description -2. **Review 1**: AI evaluates clarity, labels, accuracy, accessibility -3. **Generation 2**: Improve based on critique -4. **Review 2**: Second evaluation with specific feedback -5. **Generation 3**: Final polished version - -### Automatic Quality Standards - -All diagrams automatically follow: -- Clean white/light background -- High contrast for readability -- Clear labels (minimum 10pt font) -- Professional typography -- Colorblind-friendly colors -- Proper spacing between elements -- Scale bars, legends, axes where appropriate - -## Installation - -### For AI Generation - -```bash -# Get OpenRouter API key -# Visit: https://openrouter.ai/keys - -# Set environment variable -export OPENROUTER_API_KEY='sk-or-v1-...' - -# Or add to .env file -echo "OPENROUTER_API_KEY=sk-or-v1-..." >> .env - -# Install Python dependencies (if not already installed) -pip install requests -``` - -## Usage Examples - -### Example 1: CONSORT Flowchart - -```bash -python scripts/generate_schematic.py \ - "CONSORT participant flow diagram for RCT. \ - Assessed for eligibility (n=500). \ - Excluded (n=150): age<18 (n=80), declined (n=50), other (n=20). \ - Randomized (n=350) into Treatment (n=175) and Control (n=175). \ - Lost to follow-up: 15 and 10 respectively. \ - Final analysis: 160 and 165." \ - -o figures/consort.png -``` - -**Output:** -- `figures/consort_v1.png` - Initial generation -- `figures/consort_v2.png` - After first review -- `figures/consort_v3.png` - Final version -- `figures/consort.png` - Copy of final version -- `figures/consort_review_log.json` - Detailed review log - -### Example 2: Neural Network Architecture - -```bash -python scripts/generate_schematic.py \ - "Transformer architecture with encoder on left (input embedding, \ - positional encoding, multi-head attention, feed-forward) and \ - decoder on right (masked attention, cross-attention, feed-forward). \ - Show cross-attention connection from encoder to decoder." \ - -o figures/transformer.png \ - --iterations 2 -``` - -### Example 3: Biological Pathway - -```bash -python scripts/generate_schematic.py \ - "MAPK signaling pathway: EGFR receptor → RAS → RAF → MEK → ERK → nucleus. \ - Label each step with phosphorylation. Use different colors for each kinase." \ - -o figures/mapk.png -``` - -### Example 4: System Architecture - -```bash -python scripts/generate_schematic.py \ - "IoT system block diagram: sensors (bottom) → microcontroller → \ - WiFi module and display (middle) → cloud server → mobile app (top). \ - Label all connections with protocols." \ - -o figures/iot_system.png -``` - -## Command-Line Options - -```bash -python scripts/generate_schematic.py [OPTIONS] "description" -o output.png - -Options: - --iterations N Number of AI refinement iterations (default: 2, max: 2) - --api-key KEY OpenRouter API key (or use env var) - -v, --verbose Verbose output - -h, --help Show help message -``` - -## Python API - -```python -from scripts.generate_schematic_ai import ScientificSchematicGenerator - -# Initialize -generator = ScientificSchematicGenerator( - api_key="your_key", - verbose=True -) - -# Generate with iterative refinement -results = generator.generate_iterative( - user_prompt="CONSORT flowchart", - output_path="figures/consort.png", - iterations=2 -) - -# Access results -print(f"Final score: {results['final_score']}/10") -print(f"Final image: {results['final_image']}") - -# Review iterations -for iteration in results['iterations']: - print(f"Iteration {iteration['iteration']}: {iteration['score']}/10") - print(f"Critique: {iteration['critique']}") -``` - -## Prompt Engineering Tips - -### Be Specific About Layout -✓ "Flowchart with vertical flow, top to bottom" -✓ "Architecture diagram with encoder on left, decoder on right" -✗ "Make a diagram" (too vague) - -### Include Quantitative Details -✓ "Neural network: input (784), hidden (128), output (10)" -✓ "Flowchart: n=500 screened, n=150 excluded, n=350 randomized" -✗ "Some numbers" (not specific) - -### Specify Visual Style -✓ "Minimalist block diagram with clean lines" -✓ "Detailed biological pathway with protein structures" -✓ "Technical schematic with engineering notation" - -### Request Specific Labels -✓ "Label all arrows with activation/inhibition" -✓ "Include layer dimensions in each box" -✓ "Show time progression with timestamps" - -### Mention Color Requirements -✓ "Use colorblind-friendly colors" -✓ "Grayscale-compatible design" -✓ "Color-code by function: blue=input, green=processing, red=output" - -## Review Log Format - -Each generation produces a JSON review log: - -```json -{ - "user_prompt": "CONSORT participant flow diagram...", - "iterations": [ - { - "iteration": 1, - "image_path": "figures/consort_v1.png", - "prompt": "Full generation prompt...", - "critique": "Score: 7/10. Issues: font too small...", - "score": 7.0, - "success": true - }, - { - "iteration": 2, - "image_path": "figures/consort_v2.png", - "score": 8.5, - "critique": "Much improved. Remaining issues..." - }, - { - "iteration": 3, - "image_path": "figures/consort_v3.png", - "score": 9.5, - "critique": "Excellent. Publication ready." - } - ], - "final_image": "figures/consort_v3.png", - "final_score": 9.5, - "success": true -} -``` - -## Why Use Nano Banana 2 - -**Simply describe what you want - Nano Banana 2 creates it:** - -- ✓ **Fast**: Results in minutes -- ✓ **Easy**: Natural language descriptions (no coding) -- ✓ **Quality**: Automatic review and refinement -- ✓ **Universal**: Works for all diagram types -- ✓ **Publication-ready**: High-quality output immediately - -**Just describe your diagram, and it's generated automatically.** - -## Troubleshooting - -### API Key Issues - -```bash -# Check if key is set -echo $OPENROUTER_API_KEY - -# Set temporarily -export OPENROUTER_API_KEY='your_key' - -# Set permanently (add to ~/.bashrc or ~/.zshrc) -echo 'export OPENROUTER_API_KEY="your_key"' >> ~/.bashrc -``` - -### Import Errors - -```bash -# Install requests library -pip install requests - -# Or use the package manager -pip install -r requirements.txt -``` - -### Generation Fails - -```bash -# Use verbose mode to see detailed errors -python scripts/generate_schematic.py "diagram" -o out.png -v - -# Check API status -curl https://openrouter.ai/api/v1/models -``` - -### Low Quality Scores - -If iterations consistently score below 7/10: -1. Make your prompt more specific -2. Include more details about layout and labels -3. Specify visual requirements explicitly -4. Increase iterations: `--iterations 2` - -## Testing - -Run verification tests: - -```bash -python test_ai_generation.py -``` - -This tests: -- File structure -- Module imports -- Class initialization -- Error handling -- Prompt engineering -- Wrapper script - -## Cost Considerations - -OpenRouter pricing for models used: -- **Nano Banana 2**: ~$2/M input tokens, ~$12/M output tokens - -Typical costs per diagram: -- Simple diagram (1 iteration): ~$0.05-0.15 -- Complex diagram (2 iterations): ~$0.10-0.30 - -## Examples Gallery - -See `iterative_refinement.md` for worked examples including: -- CONSORT flowcharts -- Neural network architectures (Transformers, CNNs, RNNs) -- Biological pathways -- Circuit diagrams -- System architectures -- Block diagrams - -That file also documents the generate-review-refine loop, the Python API, the -command-line options, and prompt engineering guidance. - -## Support - -For issues or questions: -1. Check SKILL.md, then `iterative_refinement.md` for detailed documentation -2. Run test_ai_generation.py to verify setup -3. Use verbose mode (-v) to see detailed errors -4. Review the review_log.json for quality feedback - -## License - -Part of the scientific-writer package. See main repository for license information. - diff --git a/skills/scientific-schematics/references/best_practices.md b/skills/scientific-schematics/references/best_practices.md index e6033b33..a09d6f0e 100644 --- a/skills/scientific-schematics/references/best_practices.md +++ b/skills/scientific-schematics/references/best_practices.md @@ -4,6 +4,20 @@ This guide provides publication standards, accessibility guidelines, and best practices for creating high-quality scientific diagrams that meet journal requirements and communicate effectively to all readers. +### How this relates to the generator + +These are the standards a figure is judged against — not a description of what +`scripts/generate_schematic.py` does for you. The generator produces a **PNG** and nothing else. +Read this file for two purposes: + +- **To write the prompt.** Typography, colour, contrast, layout, labelling, and accessibility are + all things the image model will attempt if you ask for them specifically. The sections below are + the vocabulary for asking. +- **To judge the result, and to plan post-processing.** File format, resolution, colour space, and + physical dimensions are fixed once the PNG exists. Where a journal's requirement differs from what + came out, that is a conversion step you perform afterwards — the skill has no vector path, no DPI + control, and no CMYK output. + ## Publication Standards ### 1. File Format Requirements diff --git a/skills/scientific-schematics/references/iterative_refinement.md b/skills/scientific-schematics/references/iterative_refinement.md index bb933e35..ecb0224f 100644 --- a/skills/scientific-schematics/references/iterative_refinement.md +++ b/skills/scientific-schematics/references/iterative_refinement.md @@ -90,11 +90,14 @@ All iterations are saved with a JSON review log that includes early-stop informa "iteration": 1, "image_path": "figures/consort_v1.png", "score": 7.5, + "reviewed": true, + "review_error": null, "needs_improvement": false, "critique": "SCORE: 7.5\nSTRENGTHS:..." } ], "final_score": 7.5, + "final_reviewed": true, "early_stop": true, "early_stop_reason": "Quality score 7.5 meets threshold 7.0 for poster" } @@ -102,6 +105,39 @@ All iterations are saved with a JSON review log that includes early-stop informa **Note:** With smart iteration, you may see only 1 iteration instead of the full 2 if quality is achieved early! +### When the review does not run + +The reviewer is a second model call, and it can fail on its own — a rate limit, a content filter, +an answer in a shape the parser cannot read. The image is generated first and is kept regardless; +what is missing in that case is the *measurement*, so the log says so rather than substituting a +number: + +```json +{ + "iterations": [ + { + "iteration": 1, + "image_path": "figures/consort_v1.png", + "score": null, + "reviewed": false, + "review_error": "the review model returned no choices", + "needs_improvement": false, + "critique": "Review unavailable: the review model returned no choices." + } + ], + "final_score": null, + "final_reviewed": false +} +``` + +The run exits 0 — the diagram is real — and prints +`Review unavailable — image kept, quality not verified`. It does **not** regenerate: a reviewer that +did not answer says nothing about the diagram, so another generation would be guesswork. Look at the +image yourself, and re-run if you want a score; these failures are usually transient. + +`final_reviewed` is the field to check in automation. `final_score` alone cannot distinguish +"scored 7.5" from "never scored". + ## Advanced AI Generation Usage ### Python API @@ -157,6 +193,28 @@ python scripts/generate_schematic.py "diagram" -o out.png --api-key "sk-or-v1-.. python scripts/generate_schematic.py "neural network" -o nn.png --doc-type journal --iterations 2 -v ``` +### Setup and Cost + +```bash +# Get a key at https://openrouter.ai/keys +export OPENROUTER_API_KEY='sk-or-v1-your_key_here' + +# Or persist it in the shell profile +echo 'export OPENROUTER_API_KEY="sk-or-v1-your_key"' >> ~/.zshrc + +# Or drop it in a .env file at the project root +echo "OPENROUTER_API_KEY=sk-or-v1-..." >> .env + +# The only Python dependency +uv pip install requests +``` + +Each iteration costs **two API calls**: one image generation and one vision review. A diagram that +passes on the first try therefore costs two calls, and the maximum for any single run is four. The +image model dominates the bill. Check current per-token pricing for +`google/gemini-3.1-flash-image` and `google/gemini-3.6-flash` on OpenRouter — it changes, and any +figure written here would go stale. + ### Prompt Engineering Tips **1. Be Specific About Layout:** diff --git a/skills/scientific-schematics/scripts/example_usage.sh b/skills/scientific-schematics/scripts/example_usage.sh index 2e638d92..a8cba290 100755 --- a/skills/scientific-schematics/scripts/example_usage.sh +++ b/skills/scientific-schematics/scripts/example_usage.sh @@ -4,7 +4,7 @@ # Prerequisites: # 1. Set OPENROUTER_API_KEY environment variable # 2. Ensure Python 3.10+ is installed -# 3. Install requests: pip install requests +# 3. Install requests: uv pip install requests set -e @@ -13,6 +13,9 @@ echo "Scientific Schematics - AI Generation" echo "Example Usage Demonstrations" echo "==========================================" echo "" +echo "This runs three real generations against OpenRouter and will be billed" +echo "to your account: 2 API calls per iteration, up to 4 per example." +echo "" # Check for API key if [ -z "$OPENROUTER_API_KEY" ]; then @@ -41,7 +44,7 @@ python scripts/generate_schematic.py \ echo "" echo "✓ Generated: figures/consort_example.png" -echo " - Also created: consort_example_v1.png, v2.png, v3.png" +echo " - Also created: consort_example_v1.png (and v2.png if it needed a second pass)" echo " - Review log: consort_example_review_log.json" echo "" diff --git a/skills/scientific-schematics/scripts/generate_schematic.py b/skills/scientific-schematics/scripts/generate_schematic.py index 64246559..6392aebf 100644 --- a/skills/scientific-schematics/scripts/generate_schematic.py +++ b/skills/scientific-schematics/scripts/generate_schematic.py @@ -147,7 +147,12 @@ Environment Variables: help="Verbose output") args = parser.parse_args() - + + # Validated here rather than clamped silently, and before the credential + # lookup so an out-of-range value reports itself rather than an absent key. + if not 1 <= args.iterations <= 2: + parser.error("--iterations must be 1 or 2") + # Check for API key — resolves --api-key, the environment, then any .env file api_key = resolve_api_key(args.api_key) if not api_key: @@ -173,12 +178,9 @@ Environment Variables: if args.doc_type != "default": cmd.extend(["--doc-type", args.doc_type]) - - # Enforce max 2 iterations - iterations = min(args.iterations, 2) - if iterations != 2: - cmd.extend(["--iterations", str(iterations)]) - + + cmd.extend(["--iterations", str(args.iterations)]) + if args.verbose: cmd.append("-v") diff --git a/skills/scientific-schematics/scripts/generate_schematic_ai.py b/skills/scientific-schematics/scripts/generate_schematic_ai.py index 3e3e475f..85c4fd29 100644 --- a/skills/scientific-schematics/scripts/generate_schematic_ai.py +++ b/skills/scientific-schematics/scripts/generate_schematic_ai.py @@ -22,17 +22,94 @@ import argparse import base64 import json import os +import re import sys import time from pathlib import Path -from typing import Optional, Dict, Any, List, Tuple +from typing import Optional, Dict, Any, List, NamedTuple try: import requests except ImportError: - print("Error: requests library not found. Install with: pip install requests") + print("Error: requests library not found. Install with: uv pip install requests") sys.exit(1) + +class ReviewResult(NamedTuple): + """The outcome of one quality review. + + A named tuple rather than a bare tuple because the review has several + failure modes -- the model returns no choices, the request raises, the + answer arrives in an unexpected shape -- and each of them used to be a + chance to return the wrong number of values to the caller. + + `score` is None whenever no usable number was parsed, and `reviewed` is + False whenever the review never produced an answer at all. Neither case + invents a score: a diagram whose quality was not measured is reported as + unmeasured, not as passing. + """ + + critique: str + score: Optional[float] + needs_improvement: bool + reviewed: bool + error: Optional[str] = None + + +# Markdown decoration the reviewer routinely wraps its answer in. Gemini writes +# "**SCORE:** 8.5" far more often than the bare "SCORE: 8.5" the rubric asks +# for, and a pattern that does not allow for it silently scores every diagram +# at whatever the default happens to be. +_MARKUP = re.compile(r"[*_`#]") + +_SCORE_PATTERN = re.compile(r"\bSCORE\s*:?\s*(\d+(?:\.\d+)?)", re.IGNORECASE) +_LOOSE_SCORE_PATTERN = re.compile( + r"(?:score|rating|quality)\s*[:\s]\s*(\d+(?:\.\d+)?)\s*(?:/\s*10)?", re.IGNORECASE +) +# The underscore is optional because normalization strips it out of +# NEEDS_IMPROVEMENT along with the surrounding markdown. +_VERDICT_PATTERN = re.compile( + r"^\s*VERDICT\s*:?\s*(ACCEPTABLE|NEEDS[_ ]?IMPROVEMENT)", re.IGNORECASE | re.MULTILINE +) + + +def _normalize_review_text(text: str) -> str: + """Strip markdown decoration so the rubric's fields can be found.""" + return _MARKUP.sub("", text or "") + + +def _parse_score(text: str) -> Optional[float]: + """Return the reviewer's 0-10 score, or None when there isn't a usable one. + + None rather than a default: a fabricated score is indistinguishable from a + real one once it reaches the review log, and a default near the middle of + the range quietly passes lenient document types while failing strict ones. + """ + normalized = _normalize_review_text(text) + match = _SCORE_PATTERN.search(normalized) or _LOOSE_SCORE_PATTERN.search(normalized) + if not match: + return None + score = float(match.group(1)) + # A number outside the rubric's range means something other than the score + # was matched -- a figure count, a percentage, an iteration number. + return score if 0.0 <= score <= 10.0 else None + + +def _parse_verdict(text: str) -> Optional[str]: + """Return ACCEPTABLE / NEEDS_IMPROVEMENT from the verdict line, or None. + + Anchored to the start of a line. The rubric prompt spells out both tokens + when it explains the response format, so a reviewer that echoes those + instructions back would fail a perfectly good diagram under a plain + substring search. + """ + match = _VERDICT_PATTERN.search(_normalize_review_text(text)) + if not match: + return None + verdict = match.group(1).upper().replace(" ", "").replace("_", "") + return "NEEDS_IMPROVEMENT" if verdict == "NEEDSIMPROVEMENT" else "ACCEPTABLE" + + def _resolve_api_key(explicit: Optional[str] = None) -> Optional[str]: """Resolve the OpenRouter key from --api-key, the environment, then any .env file. @@ -282,7 +359,6 @@ IMPORTANT - NO FIGURE NUMBERS: # Handle string content if isinstance(content, str) and "data:image" in content: - import re match = re.search(r'data:image/[^;]+;base64,([A-Za-z0-9+/=\n\r]+)', content, re.DOTALL) if match: base64_str = match.group(1).replace('\n', '').replace('\r', '').replace(' ', '') @@ -417,24 +493,24 @@ IMPORTANT - NO FIGURE NUMBERS: def review_image(self, image_path: str, original_prompt: str, iteration: int, doc_type: str = "default", - max_iterations: int = 2) -> Tuple[str, float, bool]: + max_iterations: int = 2) -> ReviewResult: """ - Review generated image using Gemini 3.6 Flash for quality analysis. - - Uses Gemini 3.6 Flash's superior vision and reasoning capabilities to - evaluate the schematic quality and determine if regeneration is needed. - + Review the generated image for quality, using the vision review model. + Args: image_path: Path to the generated image original_prompt: Original user prompt iteration: Current iteration number doc_type: Document type (journal, poster, presentation, etc.) max_iterations: Maximum iterations allowed - + Returns: - Tuple of (critique text, quality score 0-10, needs_improvement bool) + A ReviewResult. When the review cannot be completed -- the request + fails, or the model answers with nothing usable -- `reviewed` is + False and `score` is None rather than a stand-in number, and + `needs_improvement` is False: the fault is in the reviewer, not in + the diagram, so regenerating would not help. """ - # Use Gemini 3.6 Flash for review - excellent vision and analysis image_data_url = self._image_to_base64(image_path) # Get quality threshold for this document type @@ -510,25 +586,32 @@ If score < {threshold}, mark as NEEDS_IMPROVEMENT with specific suggestions.""" ] try: - # Use Gemini 3.6 Flash for high-quality review response = self._make_request( model=self.review_model, messages=messages ) - + # Extract text response choices = response.get("choices", []) if not choices: - return "Image generated successfully", 8.0 - + # A normal enough outcome -- a rate limit, a content filter, a + # provider hiccup. The diagram itself is fine; only its review + # is missing, and saying so beats inventing a score. + reason = "the review model returned no choices" + self._log(f"⚠ Review unavailable: {reason}") + return ReviewResult( + f"Review unavailable: {reason}.", + None, False, reviewed=False, error=reason, + ) + message = choices[0].get("message", {}) content = message.get("content", "") - - # Check reasoning field (Nano Banana 2 puts analysis here) + + # Some models put their analysis in a separate reasoning field reasoning = message.get("reasoning", "") if reasoning and not content: content = reasoning - + if isinstance(content, list): # Extract text from content blocks text_parts = [] @@ -536,38 +619,41 @@ If score < {threshold}, mark as NEEDS_IMPROVEMENT with specific suggestions.""" if isinstance(block, dict) and block.get("type") == "text": text_parts.append(block.get("text", "")) content = "\n".join(text_parts) - - # Try to extract score - score = 7.5 # Default score if extraction fails - import re - - # Look for SCORE: X or SCORE: X/10 format - score_match = re.search(r'SCORE:\s*(\d+(?:\.\d+)?)', content, re.IGNORECASE) - if score_match: - score = float(score_match.group(1)) - else: - # Fallback: look for any score pattern - score_match = re.search(r'(?:score|rating|quality)[:\s]+(\d+(?:\.\d+)?)\s*(?:/\s*10)?', content, re.IGNORECASE) - if score_match: - score = float(score_match.group(1)) - - # Determine if improvement is needed based on verdict or score - needs_improvement = False - if "NEEDS_IMPROVEMENT" in content.upper(): - needs_improvement = True - elif score < threshold: - needs_improvement = True - - self._log(f"✓ Review complete (Score: {score}/10, Threshold: {threshold}/10)") + + score = _parse_score(content) + verdict = _parse_verdict(content) + + if score is None and verdict is None: + reason = "no score or verdict found in the review" + self._log(f"⚠ Review unusable: {reason}") + return ReviewResult( + content if content else f"Review unusable: {reason}.", + None, False, reviewed=True, error=reason, + ) + + needs_improvement = verdict == "NEEDS_IMPROVEMENT" or ( + score is not None and score < threshold + ) + + shown = f"{score}/10" if score is not None else "not stated" + self._log(f"✓ Review complete (Score: {shown}, Threshold: {threshold}/10)") self._log(f" Verdict: {'Needs improvement' if needs_improvement else 'Acceptable'}") - - return (content if content else "Image generated successfully", - score, - needs_improvement) + + return ReviewResult( + content if content else "Review returned no text", + score, + needs_improvement, + reviewed=True, + error=None if score is not None else "no score found in the review", + ) except Exception as e: - self._log(f"Review skipped: {str(e)}") - # Don't fail the whole process if review fails - assume acceptable - return "Image generated successfully (review skipped)", 7.5, False + # A failed review must not fail the run -- the image is already + # generated and saved -- but it must not read as a pass either. + self._log(f"⚠ Review failed: {str(e)}") + return ReviewResult( + f"Review failed: {str(e)}", + None, False, reviewed=False, error=str(e), + ) def improve_prompt(self, original_prompt: str, critique: str, iteration: int) -> str: @@ -629,7 +715,10 @@ Generate an improved version that addresses all the critique points while mainta "quality_threshold": threshold, "iterations": [], "final_image": None, - "final_score": 0.0, + # None, not 0.0 -- a run whose review never completed has no score, + # and a number here would be read as one the reviewer gave. + "final_score": None, + "final_reviewed": False, "success": False, "early_stop": False, "early_stop_reason": None @@ -675,48 +764,63 @@ Generate a publication-quality scientific diagram that meets all the guidelines f.write(image_data) print(f"✓ Saved: {iter_path}") - # Review image using Gemini 3.6 Flash - print(f"Reviewing image with Gemini 3.6 Flash...") - critique, score, needs_improvement = self.review_image( + # Review the image with the vision review model + print(f"Reviewing image with {self.review_model}...") + review = self.review_image( str(iter_path), user_prompt, i, doc_type, iterations ) - print(f"✓ Score: {score}/10 (threshold: {threshold}/10)") - + if review.score is not None: + print(f"✓ Score: {review.score}/10 (threshold: {threshold}/10)") + else: + print(f"⚠ Review unavailable — image kept, quality not verified") + print(f" Reason: {review.error}") + # Save iteration results iteration_result = { "iteration": i, "image_path": str(iter_path), "prompt": current_prompt, - "critique": critique, - "score": score, - "needs_improvement": needs_improvement, + "critique": review.critique, + "score": review.score, + "reviewed": review.reviewed, + "review_error": review.error, + "needs_improvement": review.needs_improvement, "success": True } results["iterations"].append(iteration_result) - + # Check if quality is acceptable - STOP EARLY if so - if not needs_improvement: - print(f"\n✓ Quality meets {doc_type} threshold ({score} >= {threshold})") - print(f" No further iterations needed!") + if not review.needs_improvement: + if review.score is not None: + print(f"\n✓ Quality meets {doc_type} threshold ({review.score} >= {threshold})") + print(f" No further iterations needed!") + reason = (f"Quality score {review.score} meets threshold " + f"{threshold} for {doc_type}") + else: + # Regenerating cannot fix a reviewer that did not answer. + print(f"\n⚠ Stopping without a verified score — review the image yourself") + reason = f"Review did not produce a score: {review.error}" results["final_image"] = str(iter_path) - results["final_score"] = score + results["final_score"] = review.score + results["final_reviewed"] = review.reviewed and review.score is not None results["success"] = True results["early_stop"] = True - results["early_stop_reason"] = f"Quality score {score} meets threshold {threshold} for {doc_type}" + results["early_stop_reason"] = reason break - + # If this is the last iteration, we're done regardless if i == iterations: print(f"\n⚠ Maximum iterations reached") results["final_image"] = str(iter_path) - results["final_score"] = score + results["final_score"] = review.score + results["final_reviewed"] = review.reviewed and review.score is not None results["success"] = True break - + # Quality below threshold - improve prompt for next iteration - print(f"\n⚠ Quality below threshold ({score} < {threshold})") + print(f"\n⚠ Quality below threshold ({review.score} < {threshold})") print(f"Improving prompt based on feedback...") - current_prompt = self.improve_prompt(user_prompt, critique, i + 1) + current_prompt = self.improve_prompt(user_prompt, review.critique, i + 1) # Copy final version to output path if results["success"] and results["final_image"]: @@ -734,7 +838,10 @@ Generate a publication-quality scientific diagram that meets all the guidelines print(f"\n{'='*60}") print(f"Generation Complete!") - print(f"Final Score: {results['final_score']}/10") + if results["final_score"] is not None: + print(f"Final Score: {results['final_score']}/10") + else: + print(f"Final Score: unavailable (the review did not produce one)") if results["early_stop"]: print(f"Iterations Used: {len([r for r in results['iterations'] if r.get('success')])}/{iterations} (early stop)") print(f"{'='*60}\n") @@ -821,8 +928,14 @@ Environment: if results["success"]: print(f"\n✓ Success! Image saved to: {args.output}") - if results.get("early_stop"): - print(f" (Completed in {len([r for r in results['iterations'] if r.get('success')])} iteration(s) - quality threshold met)") + used = len([r for r in results['iterations'] if r.get('success')]) + if results.get("final_reviewed"): + if results.get("early_stop"): + print(f" (Completed in {used} iteration(s) - quality threshold met)") + else: + # The image is real; the quality claim is not. Say which. + print(f" (Completed in {used} iteration(s) - quality NOT verified," + f" the review produced no score. Check the image yourself.)") sys.exit(0) else: print(f"\n✗ Generation failed. Check review log for details.") diff --git a/skills/scientific-slides/SKILL.md b/skills/scientific-slides/SKILL.md index be478eec..6e9fdc95 100644 --- a/skills/scientific-slides/SKILL.md +++ b/skills/scientific-slides/SKILL.md @@ -4,7 +4,7 @@ description: Build slide decks and presentations for research talks. Use this fo allowed-tools: Read Write Edit Bash license: MIT license metadata: - version: "1.5" + version: "1.6" skill-author: K-Dense Inc. openclaw: primaryEnv: OPENROUTER_API_KEY diff --git a/skills/scientific-slides/references/visual_review_workflow.md b/skills/scientific-slides/references/visual_review_workflow.md index 76de8847..c6be9663 100644 --- a/skills/scientific-slides/references/visual_review_workflow.md +++ b/skills/scientific-slides/references/visual_review_workflow.md @@ -75,7 +75,7 @@ The script uses PyMuPDF, a self-contained Python library - no poppler or other s **Installation**: ```bash # PyMuPDF is included as a project dependency -pip install pymupdf +uv pip install pymupdf ``` **Basic Conversion**: @@ -175,7 +175,7 @@ doc.close() **Install PyMuPDF**: ```bash -pip install pymupdf +uv pip install pymupdf # No external dependencies needed! ``` diff --git a/skills/scientific-slides/scripts/generate_schematic.py b/skills/scientific-slides/scripts/generate_schematic.py index 64246559..6392aebf 100644 --- a/skills/scientific-slides/scripts/generate_schematic.py +++ b/skills/scientific-slides/scripts/generate_schematic.py @@ -147,7 +147,12 @@ Environment Variables: help="Verbose output") args = parser.parse_args() - + + # Validated here rather than clamped silently, and before the credential + # lookup so an out-of-range value reports itself rather than an absent key. + if not 1 <= args.iterations <= 2: + parser.error("--iterations must be 1 or 2") + # Check for API key — resolves --api-key, the environment, then any .env file api_key = resolve_api_key(args.api_key) if not api_key: @@ -173,12 +178,9 @@ Environment Variables: if args.doc_type != "default": cmd.extend(["--doc-type", args.doc_type]) - - # Enforce max 2 iterations - iterations = min(args.iterations, 2) - if iterations != 2: - cmd.extend(["--iterations", str(iterations)]) - + + cmd.extend(["--iterations", str(args.iterations)]) + if args.verbose: cmd.append("-v") diff --git a/skills/scientific-slides/scripts/generate_schematic_ai.py b/skills/scientific-slides/scripts/generate_schematic_ai.py index 3e3e475f..85c4fd29 100644 --- a/skills/scientific-slides/scripts/generate_schematic_ai.py +++ b/skills/scientific-slides/scripts/generate_schematic_ai.py @@ -22,17 +22,94 @@ import argparse import base64 import json import os +import re import sys import time from pathlib import Path -from typing import Optional, Dict, Any, List, Tuple +from typing import Optional, Dict, Any, List, NamedTuple try: import requests except ImportError: - print("Error: requests library not found. Install with: pip install requests") + print("Error: requests library not found. Install with: uv pip install requests") sys.exit(1) + +class ReviewResult(NamedTuple): + """The outcome of one quality review. + + A named tuple rather than a bare tuple because the review has several + failure modes -- the model returns no choices, the request raises, the + answer arrives in an unexpected shape -- and each of them used to be a + chance to return the wrong number of values to the caller. + + `score` is None whenever no usable number was parsed, and `reviewed` is + False whenever the review never produced an answer at all. Neither case + invents a score: a diagram whose quality was not measured is reported as + unmeasured, not as passing. + """ + + critique: str + score: Optional[float] + needs_improvement: bool + reviewed: bool + error: Optional[str] = None + + +# Markdown decoration the reviewer routinely wraps its answer in. Gemini writes +# "**SCORE:** 8.5" far more often than the bare "SCORE: 8.5" the rubric asks +# for, and a pattern that does not allow for it silently scores every diagram +# at whatever the default happens to be. +_MARKUP = re.compile(r"[*_`#]") + +_SCORE_PATTERN = re.compile(r"\bSCORE\s*:?\s*(\d+(?:\.\d+)?)", re.IGNORECASE) +_LOOSE_SCORE_PATTERN = re.compile( + r"(?:score|rating|quality)\s*[:\s]\s*(\d+(?:\.\d+)?)\s*(?:/\s*10)?", re.IGNORECASE +) +# The underscore is optional because normalization strips it out of +# NEEDS_IMPROVEMENT along with the surrounding markdown. +_VERDICT_PATTERN = re.compile( + r"^\s*VERDICT\s*:?\s*(ACCEPTABLE|NEEDS[_ ]?IMPROVEMENT)", re.IGNORECASE | re.MULTILINE +) + + +def _normalize_review_text(text: str) -> str: + """Strip markdown decoration so the rubric's fields can be found.""" + return _MARKUP.sub("", text or "") + + +def _parse_score(text: str) -> Optional[float]: + """Return the reviewer's 0-10 score, or None when there isn't a usable one. + + None rather than a default: a fabricated score is indistinguishable from a + real one once it reaches the review log, and a default near the middle of + the range quietly passes lenient document types while failing strict ones. + """ + normalized = _normalize_review_text(text) + match = _SCORE_PATTERN.search(normalized) or _LOOSE_SCORE_PATTERN.search(normalized) + if not match: + return None + score = float(match.group(1)) + # A number outside the rubric's range means something other than the score + # was matched -- a figure count, a percentage, an iteration number. + return score if 0.0 <= score <= 10.0 else None + + +def _parse_verdict(text: str) -> Optional[str]: + """Return ACCEPTABLE / NEEDS_IMPROVEMENT from the verdict line, or None. + + Anchored to the start of a line. The rubric prompt spells out both tokens + when it explains the response format, so a reviewer that echoes those + instructions back would fail a perfectly good diagram under a plain + substring search. + """ + match = _VERDICT_PATTERN.search(_normalize_review_text(text)) + if not match: + return None + verdict = match.group(1).upper().replace(" ", "").replace("_", "") + return "NEEDS_IMPROVEMENT" if verdict == "NEEDSIMPROVEMENT" else "ACCEPTABLE" + + def _resolve_api_key(explicit: Optional[str] = None) -> Optional[str]: """Resolve the OpenRouter key from --api-key, the environment, then any .env file. @@ -282,7 +359,6 @@ IMPORTANT - NO FIGURE NUMBERS: # Handle string content if isinstance(content, str) and "data:image" in content: - import re match = re.search(r'data:image/[^;]+;base64,([A-Za-z0-9+/=\n\r]+)', content, re.DOTALL) if match: base64_str = match.group(1).replace('\n', '').replace('\r', '').replace(' ', '') @@ -417,24 +493,24 @@ IMPORTANT - NO FIGURE NUMBERS: def review_image(self, image_path: str, original_prompt: str, iteration: int, doc_type: str = "default", - max_iterations: int = 2) -> Tuple[str, float, bool]: + max_iterations: int = 2) -> ReviewResult: """ - Review generated image using Gemini 3.6 Flash for quality analysis. - - Uses Gemini 3.6 Flash's superior vision and reasoning capabilities to - evaluate the schematic quality and determine if regeneration is needed. - + Review the generated image for quality, using the vision review model. + Args: image_path: Path to the generated image original_prompt: Original user prompt iteration: Current iteration number doc_type: Document type (journal, poster, presentation, etc.) max_iterations: Maximum iterations allowed - + Returns: - Tuple of (critique text, quality score 0-10, needs_improvement bool) + A ReviewResult. When the review cannot be completed -- the request + fails, or the model answers with nothing usable -- `reviewed` is + False and `score` is None rather than a stand-in number, and + `needs_improvement` is False: the fault is in the reviewer, not in + the diagram, so regenerating would not help. """ - # Use Gemini 3.6 Flash for review - excellent vision and analysis image_data_url = self._image_to_base64(image_path) # Get quality threshold for this document type @@ -510,25 +586,32 @@ If score < {threshold}, mark as NEEDS_IMPROVEMENT with specific suggestions.""" ] try: - # Use Gemini 3.6 Flash for high-quality review response = self._make_request( model=self.review_model, messages=messages ) - + # Extract text response choices = response.get("choices", []) if not choices: - return "Image generated successfully", 8.0 - + # A normal enough outcome -- a rate limit, a content filter, a + # provider hiccup. The diagram itself is fine; only its review + # is missing, and saying so beats inventing a score. + reason = "the review model returned no choices" + self._log(f"⚠ Review unavailable: {reason}") + return ReviewResult( + f"Review unavailable: {reason}.", + None, False, reviewed=False, error=reason, + ) + message = choices[0].get("message", {}) content = message.get("content", "") - - # Check reasoning field (Nano Banana 2 puts analysis here) + + # Some models put their analysis in a separate reasoning field reasoning = message.get("reasoning", "") if reasoning and not content: content = reasoning - + if isinstance(content, list): # Extract text from content blocks text_parts = [] @@ -536,38 +619,41 @@ If score < {threshold}, mark as NEEDS_IMPROVEMENT with specific suggestions.""" if isinstance(block, dict) and block.get("type") == "text": text_parts.append(block.get("text", "")) content = "\n".join(text_parts) - - # Try to extract score - score = 7.5 # Default score if extraction fails - import re - - # Look for SCORE: X or SCORE: X/10 format - score_match = re.search(r'SCORE:\s*(\d+(?:\.\d+)?)', content, re.IGNORECASE) - if score_match: - score = float(score_match.group(1)) - else: - # Fallback: look for any score pattern - score_match = re.search(r'(?:score|rating|quality)[:\s]+(\d+(?:\.\d+)?)\s*(?:/\s*10)?', content, re.IGNORECASE) - if score_match: - score = float(score_match.group(1)) - - # Determine if improvement is needed based on verdict or score - needs_improvement = False - if "NEEDS_IMPROVEMENT" in content.upper(): - needs_improvement = True - elif score < threshold: - needs_improvement = True - - self._log(f"✓ Review complete (Score: {score}/10, Threshold: {threshold}/10)") + + score = _parse_score(content) + verdict = _parse_verdict(content) + + if score is None and verdict is None: + reason = "no score or verdict found in the review" + self._log(f"⚠ Review unusable: {reason}") + return ReviewResult( + content if content else f"Review unusable: {reason}.", + None, False, reviewed=True, error=reason, + ) + + needs_improvement = verdict == "NEEDS_IMPROVEMENT" or ( + score is not None and score < threshold + ) + + shown = f"{score}/10" if score is not None else "not stated" + self._log(f"✓ Review complete (Score: {shown}, Threshold: {threshold}/10)") self._log(f" Verdict: {'Needs improvement' if needs_improvement else 'Acceptable'}") - - return (content if content else "Image generated successfully", - score, - needs_improvement) + + return ReviewResult( + content if content else "Review returned no text", + score, + needs_improvement, + reviewed=True, + error=None if score is not None else "no score found in the review", + ) except Exception as e: - self._log(f"Review skipped: {str(e)}") - # Don't fail the whole process if review fails - assume acceptable - return "Image generated successfully (review skipped)", 7.5, False + # A failed review must not fail the run -- the image is already + # generated and saved -- but it must not read as a pass either. + self._log(f"⚠ Review failed: {str(e)}") + return ReviewResult( + f"Review failed: {str(e)}", + None, False, reviewed=False, error=str(e), + ) def improve_prompt(self, original_prompt: str, critique: str, iteration: int) -> str: @@ -629,7 +715,10 @@ Generate an improved version that addresses all the critique points while mainta "quality_threshold": threshold, "iterations": [], "final_image": None, - "final_score": 0.0, + # None, not 0.0 -- a run whose review never completed has no score, + # and a number here would be read as one the reviewer gave. + "final_score": None, + "final_reviewed": False, "success": False, "early_stop": False, "early_stop_reason": None @@ -675,48 +764,63 @@ Generate a publication-quality scientific diagram that meets all the guidelines f.write(image_data) print(f"✓ Saved: {iter_path}") - # Review image using Gemini 3.6 Flash - print(f"Reviewing image with Gemini 3.6 Flash...") - critique, score, needs_improvement = self.review_image( + # Review the image with the vision review model + print(f"Reviewing image with {self.review_model}...") + review = self.review_image( str(iter_path), user_prompt, i, doc_type, iterations ) - print(f"✓ Score: {score}/10 (threshold: {threshold}/10)") - + if review.score is not None: + print(f"✓ Score: {review.score}/10 (threshold: {threshold}/10)") + else: + print(f"⚠ Review unavailable — image kept, quality not verified") + print(f" Reason: {review.error}") + # Save iteration results iteration_result = { "iteration": i, "image_path": str(iter_path), "prompt": current_prompt, - "critique": critique, - "score": score, - "needs_improvement": needs_improvement, + "critique": review.critique, + "score": review.score, + "reviewed": review.reviewed, + "review_error": review.error, + "needs_improvement": review.needs_improvement, "success": True } results["iterations"].append(iteration_result) - + # Check if quality is acceptable - STOP EARLY if so - if not needs_improvement: - print(f"\n✓ Quality meets {doc_type} threshold ({score} >= {threshold})") - print(f" No further iterations needed!") + if not review.needs_improvement: + if review.score is not None: + print(f"\n✓ Quality meets {doc_type} threshold ({review.score} >= {threshold})") + print(f" No further iterations needed!") + reason = (f"Quality score {review.score} meets threshold " + f"{threshold} for {doc_type}") + else: + # Regenerating cannot fix a reviewer that did not answer. + print(f"\n⚠ Stopping without a verified score — review the image yourself") + reason = f"Review did not produce a score: {review.error}" results["final_image"] = str(iter_path) - results["final_score"] = score + results["final_score"] = review.score + results["final_reviewed"] = review.reviewed and review.score is not None results["success"] = True results["early_stop"] = True - results["early_stop_reason"] = f"Quality score {score} meets threshold {threshold} for {doc_type}" + results["early_stop_reason"] = reason break - + # If this is the last iteration, we're done regardless if i == iterations: print(f"\n⚠ Maximum iterations reached") results["final_image"] = str(iter_path) - results["final_score"] = score + results["final_score"] = review.score + results["final_reviewed"] = review.reviewed and review.score is not None results["success"] = True break - + # Quality below threshold - improve prompt for next iteration - print(f"\n⚠ Quality below threshold ({score} < {threshold})") + print(f"\n⚠ Quality below threshold ({review.score} < {threshold})") print(f"Improving prompt based on feedback...") - current_prompt = self.improve_prompt(user_prompt, critique, i + 1) + current_prompt = self.improve_prompt(user_prompt, review.critique, i + 1) # Copy final version to output path if results["success"] and results["final_image"]: @@ -734,7 +838,10 @@ Generate a publication-quality scientific diagram that meets all the guidelines print(f"\n{'='*60}") print(f"Generation Complete!") - print(f"Final Score: {results['final_score']}/10") + if results["final_score"] is not None: + print(f"Final Score: {results['final_score']}/10") + else: + print(f"Final Score: unavailable (the review did not produce one)") if results["early_stop"]: print(f"Iterations Used: {len([r for r in results['iterations'] if r.get('success')])}/{iterations} (early stop)") print(f"{'='*60}\n") @@ -821,8 +928,14 @@ Environment: if results["success"]: print(f"\n✓ Success! Image saved to: {args.output}") - if results.get("early_stop"): - print(f" (Completed in {len([r for r in results['iterations'] if r.get('success')])} iteration(s) - quality threshold met)") + used = len([r for r in results['iterations'] if r.get('success')]) + if results.get("final_reviewed"): + if results.get("early_stop"): + print(f" (Completed in {used} iteration(s) - quality threshold met)") + else: + # The image is real; the quality claim is not. Say which. + print(f" (Completed in {used} iteration(s) - quality NOT verified," + f" the review produced no score. Check the image yourself.)") sys.exit(0) else: print(f"\n✗ Generation failed. Check review log for details.") diff --git a/skills/scientific-slides/scripts/generate_slide_image_ai.py b/skills/scientific-slides/scripts/generate_slide_image_ai.py index b2f16c53..339693e4 100644 --- a/skills/scientific-slides/scripts/generate_slide_image_ai.py +++ b/skills/scientific-slides/scripts/generate_slide_image_ai.py @@ -33,19 +33,95 @@ import argparse import base64 import json import os +import re import sys import time from pathlib import Path -from typing import Optional, Dict, Any, List, Tuple +from typing import Optional, Dict, Any, List, NamedTuple try: import requests except ImportError: - print("Error: requests library not found. Install with: pip install requests") + print("Error: requests library not found. Install with: uv pip install requests") sys.exit(1) +class ReviewResult(NamedTuple): + """The outcome of one quality review. + + A named tuple rather than a bare tuple because the review has several + failure modes -- the model returns no choices, the request raises, the + answer arrives in an unexpected shape -- and each of them used to be a + chance to return the wrong number of values to the caller. + + `score` is None whenever no usable number was parsed, and `reviewed` is + False whenever the review never produced an answer at all. Neither case + invents a score: a slide whose quality was not measured is reported as + unmeasured, not as passing. + """ + + critique: str + score: Optional[float] + needs_improvement: bool + reviewed: bool + error: Optional[str] = None + + +# Markdown decoration the reviewer routinely wraps its answer in. Gemini writes +# "**SCORE:** 8.5" far more often than the bare "SCORE: 8.5" the rubric asks +# for, and a pattern that does not allow for it silently scores every image +# at whatever the default happens to be. +_MARKUP = re.compile(r"[*_`#]") + +_SCORE_PATTERN = re.compile(r"\bSCORE\s*:?\s*(\d+(?:\.\d+)?)", re.IGNORECASE) +_LOOSE_SCORE_PATTERN = re.compile( + r"(?:score|rating|quality)\s*[:\s]\s*(\d+(?:\.\d+)?)\s*(?:/\s*10)?", re.IGNORECASE +) +# The underscore is optional because normalization strips it out of +# NEEDS_IMPROVEMENT along with the surrounding markdown. +_VERDICT_PATTERN = re.compile( + r"^\s*VERDICT\s*:?\s*(ACCEPTABLE|NEEDS[_ ]?IMPROVEMENT)", re.IGNORECASE | re.MULTILINE +) + + +def _normalize_review_text(text: str) -> str: + """Strip markdown decoration so the rubric's fields can be found.""" + return _MARKUP.sub("", text or "") + + +def _parse_score(text: str) -> Optional[float]: + """Return the reviewer's 0-10 score, or None when there isn't a usable one. + + None rather than a default: a fabricated score is indistinguishable from a + real one once it reaches the review log, and a default near the middle of + the range quietly passes lenient thresholds while failing strict ones. + """ + normalized = _normalize_review_text(text) + match = _SCORE_PATTERN.search(normalized) or _LOOSE_SCORE_PATTERN.search(normalized) + if not match: + return None + score = float(match.group(1)) + # A number outside the rubric's range means something other than the score + # was matched -- a slide number, a percentage, an iteration number. + return score if 0.0 <= score <= 10.0 else None + + +def _parse_verdict(text: str) -> Optional[str]: + """Return ACCEPTABLE / NEEDS_IMPROVEMENT from the verdict line, or None. + + Anchored to the start of a line. The rubric prompt spells out both tokens + when it explains the response format, so a reviewer that echoes those + instructions back would fail a perfectly good image under a plain + substring search. + """ + match = _VERDICT_PATTERN.search(_normalize_review_text(text)) + if not match: + return None + verdict = match.group(1).upper().replace(" ", "").replace("_", "") + return "NEEDS_IMPROVEMENT" if verdict == "NEEDSIMPROVEMENT" else "ACCEPTABLE" + + def _resolve_api_key(explicit: Optional[str] = None) -> Optional[str]: """Resolve the OpenRouter key from --api-key, the environment, then any .env file. @@ -402,7 +478,7 @@ STYLE: def review_image(self, image_path: str, original_prompt: str, iteration: int, visual_only: bool = False, - max_iterations: int = 2) -> Tuple[str, float, bool]: + max_iterations: int = 2) -> ReviewResult: """Review generated image using Gemini 3.6 Flash.""" image_data_url = self._image_to_base64(image_path) threshold = self.QUALITY_THRESHOLD @@ -474,45 +550,63 @@ If score < {threshold}, mark as NEEDS_IMPROVEMENT with specific suggestions.""" choices = response.get("choices", []) if not choices: - return "Image generated successfully", 7.0, False - + # A normal enough outcome -- a rate limit, a content filter, a + # provider hiccup. The image itself is fine; only its review is + # missing, and saying so beats inventing a score. + reason = "the review model returned no choices" + self._log(f"⚠ Review unavailable: {reason}") + return ReviewResult( + f"Review unavailable: {reason}.", + None, False, reviewed=False, error=reason, + ) + message = choices[0].get("message", {}) content = message.get("content", "") - + reasoning = message.get("reasoning", "") if reasoning and not content: content = reasoning - + if isinstance(content, list): text_parts = [] for block in content: if isinstance(block, dict) and block.get("type") == "text": text_parts.append(block.get("text", "")) content = "\n".join(text_parts) - - # Extract score - score = 7.0 - import re - score_match = re.search(r'SCORE:\s*(\d+(?:\.\d+)?)', content, re.IGNORECASE) - if score_match: - score = float(score_match.group(1)) - else: - score_match = re.search(r'(?:score|rating|quality)[:\s]+(\d+(?:\.\d+)?)', content, re.IGNORECASE) - if score_match: - score = float(score_match.group(1)) - - needs_improvement = False - if "NEEDS_IMPROVEMENT" in content.upper(): - needs_improvement = True - elif score < threshold: - needs_improvement = True - - self._log(f"✓ Review complete (Score: {score}/10, Threshold: {threshold}/10)") - - return (content if content else "Image generated successfully", score, needs_improvement) + + score = _parse_score(content) + verdict = _parse_verdict(content) + + if score is None and verdict is None: + reason = "no score or verdict found in the review" + self._log(f"⚠ Review unusable: {reason}") + return ReviewResult( + content if content else f"Review unusable: {reason}.", + None, False, reviewed=True, error=reason, + ) + + needs_improvement = verdict == "NEEDS_IMPROVEMENT" or ( + score is not None and score < threshold + ) + + shown = f"{score}/10" if score is not None else "not stated" + self._log(f"✓ Review complete (Score: {shown}, Threshold: {threshold}/10)") + + return ReviewResult( + content if content else "Review returned no text", + score, + needs_improvement, + reviewed=True, + error=None if score is not None else "no score found in the review", + ) except Exception as e: - self._log(f"Review skipped: {str(e)}") - return "Image generated successfully (review skipped)", 7.0, False + # A failed review must not fail the run -- the image is already + # generated -- but it must not read as a pass either. + self._log(f"⚠ Review failed: {str(e)}") + return ReviewResult( + f"Review failed: {str(e)}", + None, False, reviewed=False, error=str(e), + ) def improve_prompt(self, original_prompt: str, critique: str, iteration: int, visual_only: bool = False) -> str: @@ -562,7 +656,10 @@ Generate an improved version that addresses all the critique points.""" "attachments": attachments or [], "iterations": [], "final_image": None, - "final_score": 0.0, + # None, not 0.0 -- a run whose review never completed has no score, + # and a number here would be read as one the reviewer gave. + "final_score": None, + "final_reviewed": False, "success": False, "early_stop": False } @@ -619,38 +716,50 @@ Generate a high-quality {'visual/figure' if visual_only else 'presentation slide f.write(image_data) print(f"✓ Generated image (iteration {i})") - print(f"Reviewing image with Gemini 3.6 Flash...") - critique, score, needs_improvement = self.review_image( + print(f"Reviewing image with {self.review_model}...") + review = self.review_image( str(temp_path), user_prompt, i, visual_only, iterations ) - print(f"✓ Score: {score}/10 (threshold: {self.QUALITY_THRESHOLD}/10)") - + if review.score is not None: + print(f"✓ Score: {review.score}/10 (threshold: {self.QUALITY_THRESHOLD}/10)") + else: + print(f"⚠ Review unavailable — image kept, quality not verified") + print(f" Reason: {review.error}") + results["iterations"].append({ "iteration": i, - "critique": critique, - "score": score, - "needs_improvement": needs_improvement, + "critique": review.critique, + "score": review.score, + "reviewed": review.reviewed, + "review_error": review.error, + "needs_improvement": review.needs_improvement, "success": True }) - - if not needs_improvement: - print(f"\n✓ Quality meets threshold ({score} >= {self.QUALITY_THRESHOLD})") + + if not review.needs_improvement: + if review.score is not None: + print(f"\n✓ Quality meets threshold ({review.score} >= {self.QUALITY_THRESHOLD})") + else: + # Regenerating cannot fix a reviewer that did not answer. + print(f"\n⚠ Stopping without a verified score — review the image yourself") final_image_data = image_data - results["final_score"] = score + results["final_score"] = review.score + results["final_reviewed"] = review.reviewed and review.score is not None results["success"] = True results["early_stop"] = True break - + if i == iterations: print(f"\n⚠ Maximum iterations reached") final_image_data = image_data - results["final_score"] = score + results["final_score"] = review.score + results["final_reviewed"] = review.reviewed and review.score is not None results["success"] = True break - - print(f"\n⚠ Quality below threshold ({score} < {self.QUALITY_THRESHOLD})") + + print(f"\n⚠ Quality below threshold ({review.score} < {self.QUALITY_THRESHOLD})") print(f"Improving prompt...") - current_prompt = self.improve_prompt(user_prompt, critique, i + 1, visual_only) + current_prompt = self.improve_prompt(user_prompt, review.critique, i + 1, visual_only) # Clean up temporary files for temp_file in temp_files: @@ -669,7 +778,10 @@ Generate a high-quality {'visual/figure' if visual_only else 'presentation slide print(f"\n{'='*60}") print(f"Generation Complete!") - print(f"Final Score: {results['final_score']}/10") + if results["final_score"] is not None: + print(f"Final Score: {results['final_score']}/10") + else: + print(f"Final Score: unavailable (the review did not produce one)") if results["early_stop"]: success_count = len([r for r in results['iterations'] if r.get('success')]) print(f"Iterations Used: {success_count}/{iterations} (early stop)") diff --git a/skills/scientific-slides/scripts/pdf_to_images.py b/skills/scientific-slides/scripts/pdf_to_images.py index 0bc3234a..bfa95f16 100644 --- a/skills/scientific-slides/scripts/pdf_to_images.py +++ b/skills/scientific-slides/scripts/pdf_to_images.py @@ -60,7 +60,7 @@ class PDFToImagesConverter: else: raise RuntimeError( "PyMuPDF not installed. Install it with:\n" - " pip install pymupdf\n\n" + " uv pip install pymupdf\n\n" "PyMuPDF is a self-contained library - no external dependencies needed." ) @@ -130,7 +130,7 @@ Resolution: Requirements: Install PyMuPDF (no external dependencies needed): - pip install pymupdf + uv pip install pymupdf """ ) diff --git a/skills/scientific-slides/scripts/slides_to_pdf.py b/skills/scientific-slides/scripts/slides_to_pdf.py index 550a828a..4f076f15 100644 --- a/skills/scientific-slides/scripts/slides_to_pdf.py +++ b/skills/scientific-slides/scripts/slides_to_pdf.py @@ -24,7 +24,7 @@ from typing import List try: from PIL import Image except ImportError: - print("Error: Pillow library not found. Install with: pip install Pillow") + print("Error: Pillow library not found. Install with: uv pip install Pillow") sys.exit(1) diff --git a/skills/scientific-slides/scripts/validate_presentation.py b/skills/scientific-slides/scripts/validate_presentation.py index c701b7f3..1dcd058a 100644 --- a/skills/scientific-slides/scripts/validate_presentation.py +++ b/skills/scientific-slides/scripts/validate_presentation.py @@ -104,7 +104,7 @@ class PresentationValidator: """Validate PDF presentation.""" if not HAS_PDF_READER: self.warnings.append( - "pypdf not installed. Install with: pip install pypdf" + "pypdf not installed. Install with: uv pip install pypdf" ) return @@ -153,7 +153,7 @@ class PresentationValidator: """Validate PowerPoint presentation.""" if not HAS_PPTX: self.warnings.append( - "python-pptx not installed. Install with: pip install python-pptx" + "python-pptx not installed. Install with: uv pip install python-pptx" ) return diff --git a/skills/scvelo/SKILL.md b/skills/scvelo/SKILL.md index 47f91cad..c958a798 100644 --- a/skills/scvelo/SKILL.md +++ b/skills/scvelo/SKILL.md @@ -14,7 +14,7 @@ metadata: scVelo is the leading Python package for RNA velocity analysis in single-cell RNA-seq data. It infers cell state transitions by modeling the kinetics of mRNA splicing — using the ratio of unspliced (pre-mRNA) to spliced (mature mRNA) abundances to determine whether a gene is being upregulated or downregulated in each cell. This allows reconstruction of developmental trajectories and identification of cell fate decisions without requiring time-course data. -**Installation:** `pip install scvelo` +**Installation:** `uv pip install scvelo` **Key resources:** - Documentation: https://scvelo.readthedocs.io/ diff --git a/skills/tamarind/SKILL.md b/skills/tamarind/SKILL.md index 0bd2a149..7f0cbdd2 100644 --- a/skills/tamarind/SKILL.md +++ b/skills/tamarind/SKILL.md @@ -64,7 +64,7 @@ curl https://app.tamarind.bio/api/tools \ **Base URL:** `https://app.tamarind.bio/api/` -There is **no official Python SDK** — the PyPI package named `tamarind` is an unrelated Neo4j tool. Do not `pip install tamarind`. Write plain `requests` calls against the REST API (the endpoint shapes are in `openapi.yaml`), or use the MCP server for agent hosts. +There is **no official Python SDK** — the PyPI package named `tamarind` is an unrelated Neo4j tool. Do not `uv pip install tamarind`. Write plain `requests` calls against the REST API (the endpoint shapes are in `openapi.yaml`), or use the MCP server for agent hosts. ## Two ways to call Tamarind diff --git a/skills/tiledbvcf/SKILL.md b/skills/tiledbvcf/SKILL.md index 995e4101..3aebc69b 100644 --- a/skills/tiledbvcf/SKILL.md +++ b/skills/tiledbvcf/SKILL.md @@ -340,10 +340,10 @@ When your genomics workloads outgrow single-node processing, TileDB-Cloud provid **2. Install TileDB-Cloud Python Client** ```bash # Base installation -pip install tiledb-cloud +uv pip install tiledb-cloud # With genomics-specific functionality -pip install tiledb-cloud[life-sciences] +uv pip install tiledb-cloud[life-sciences] ``` **3. Configure Authentication** diff --git a/skills/timesfm-forecasting/SKILL.md b/skills/timesfm-forecasting/SKILL.md index 59ba9e28..1bf8b34b 100644 --- a/skills/timesfm-forecasting/SKILL.md +++ b/skills/timesfm-forecasting/SKILL.md @@ -123,9 +123,6 @@ python scripts/check_system.py # Using uv (recommended by this repo) uv pip install timesfm[torch] -# Or using pip -pip install timesfm[torch] - # For JAX/Flax backend (faster on TPU/GPU) uv pip install timesfm[flax] ``` @@ -134,13 +131,13 @@ uv pip install timesfm[flax] ```bash # CUDA 12.1 (NVIDIA GPU) -pip install torch>=2.0.0 --index-url https://download.pytorch.org/whl/cu121 +uv pip install torch>=2.0.0 --index-url https://download.pytorch.org/whl/cu121 # CPU only -pip install torch>=2.0.0 --index-url https://download.pytorch.org/whl/cpu +uv pip install torch>=2.0.0 --index-url https://download.pytorch.org/whl/cpu # Apple Silicon (MPS) -pip install torch>=2.0.0 # MPS support is built-in +uv pip install torch>=2.0.0 # MPS support is built-in ``` ### Step 4: Verify Installation diff --git a/skills/timesfm-forecasting/examples/covariates-forecasting/demo_covariates.py b/skills/timesfm-forecasting/examples/covariates-forecasting/demo_covariates.py index 65153c01..13b3cfce 100644 --- a/skills/timesfm-forecasting/examples/covariates-forecasting/demo_covariates.py +++ b/skills/timesfm-forecasting/examples/covariates-forecasting/demo_covariates.py @@ -4,7 +4,7 @@ TimesFM Covariates (XReg) Example Demonstrates the TimesFM covariate API using synthetic retail sales data. TimesFM 1.0 does NOT support forecast_with_covariates(); that requires -TimesFM 2.5 + `pip install timesfm[xreg]`. +TimesFM 2.5 + `uv pip install timesfm[xreg]`. This script: 1. Generates synthetic 3-store weekly retail data (24-week context, 12-week horizon) @@ -408,7 +408,7 @@ def demonstrate_api() -> None: print("=" * 70) print(""" # Installation -pip install timesfm[xreg] +uv pip install timesfm[xreg] import timesfm hparams = timesfm.TimesFmHparams(backend="cpu", per_core_batch_size=32, horizon_len=12) diff --git a/skills/timesfm-forecasting/references/examples_and_validation.md b/skills/timesfm-forecasting/references/examples_and_validation.md index 2df0d75d..7c31e709 100644 --- a/skills/timesfm-forecasting/references/examples_and_validation.md +++ b/skills/timesfm-forecasting/references/examples_and_validation.md @@ -69,7 +69,7 @@ These bugs have appeared in this skill's examples. Learn from them: 4. **`tight_layout()` warning with `sharex=True`** -- Harmless; suppress with `plt.tight_layout(rect=[0, 0, 1, 0.97])` or ignore. -5. **TimesFM 2.5 required for `forecast_with_covariates()`** -- TimesFM 1.0 does NOT have this method. Install `pip install timesfm[xreg]` and use checkpoint `google/timesfm-2.5-200m-pytorch`. +5. **TimesFM 2.5 required for `forecast_with_covariates()`** -- TimesFM 1.0 does NOT have this method. Install `uv pip install timesfm[xreg]` and use checkpoint `google/timesfm-2.5-200m-pytorch`. 6. **Future covariates must span the full horizon** -- Dynamic covariates (price, promotions, holidays) must have values for BOTH the context AND the forecast horizon. You cannot pass context-only arrays. diff --git a/skills/timesfm-forecasting/references/system_requirements.md b/skills/timesfm-forecasting/references/system_requirements.md index c71e0848..3c2983f0 100644 --- a/skills/timesfm-forecasting/references/system_requirements.md +++ b/skills/timesfm-forecasting/references/system_requirements.md @@ -145,9 +145,9 @@ Works on any CPU with sufficient RAM. Expect 5–20× slower than GPU. | Package | Purpose | Install | | ------- | ------- | ------- | -| jax | Flax backend | `pip install jax[cuda]` | -| flax | Flax backend | `pip install flax` | -| scikit-learn | XReg covariates | `pip install scikit-learn` | +| jax | Flax backend | `uv pip install jax[cuda]` | +| flax | Flax backend | `uv pip install flax` | +| scikit-learn | XReg covariates | `uv pip install scikit-learn` | ## Operating System Compatibility diff --git a/skills/xlsx/SKILL.md b/skills/xlsx/SKILL.md index c8960d3f..3728cc5a 100644 --- a/skills/xlsx/SKILL.md +++ b/skills/xlsx/SKILL.md @@ -20,7 +20,7 @@ compatibility: Requires Python 3.8+, LibreOffice (soffice on PATH), and gcc only | **Quick look** at a sheet | `markitdown file.xlsx` — `## SheetName` per sheet; reads `.xlsm` too. No cell coordinates, so don't plan edits from it | | **Read** a model (formulas *and* values) | two `load_workbook` passes — see gotchas | -> `openpyxl`, `pandas`, and `markitdown` are preinstalled — do not run `pip install` first; write the script and import directly. Only if an import fails (or the `markitdown` command is missing): `pip install` the missing package. +> `openpyxl`, `pandas`, and `markitdown` are preinstalled — do not run `uv pip install` first; write the script and import directly. Only if an import fails (or the `markitdown` command is missing): `uv pip install` the missing package. > Script paths below are relative to this skill's directory. diff --git a/tests/_contract/schematic.py b/tests/_contract/schematic.py index 55b9e8cf..6a7b6862 100644 --- a/tests/_contract/schematic.py +++ b/tests/_contract/schematic.py @@ -1,21 +1,36 @@ -"""Shared tests for the AI schematic generator bundled by three skills. +"""Shared tests for the AI schematic generator bundled by several skills. -`scientific-schematics`, `latex-posters`, and `literature-review` each ship a -byte-identical `scripts/generate_schematic.py` (a thin CLI) and -`scripts/generate_schematic_ai.py` (the generator). Rather than write the same -tests three times, each suite instantiates `schematic_test_case()` against its -own copy; `tests/_meta` separately pins the copies together. +`scientific-schematics`, `latex-posters`, `literature-review`, +`citation-management`, and `scientific-slides` each ship a byte-identical +`scripts/generate_schematic.py` (a thin CLI) and `scripts/generate_schematic_ai.py` +(the generator). Rather than write the same tests five times, each suite +instantiates the factories below against its own copy; `tests/_meta` separately +pins the copies together. -The behaviour worth testing offline is the environment allowlist. The CLI -re-executes the generator as a subprocess, and it deliberately forwards a -named set of variables rather than the whole parent environment -- copying -everything would hand the child every unrelated secret exported in the calling -shell. Nothing here makes a network call or needs an API key. +Two lineages descend from that generator with the same review-parsing code: +`infographics/scripts/generate_infographic_ai.py` and +`scientific-slides/scripts/generate_slide_image_ai.py`. They reuse +`review_parsing_test_case()` and `review_failure_test_case()`. + +Three behaviours are worth testing offline: + +- **The environment allowlist.** The CLI re-executes the generator as a + subprocess, and it deliberately forwards a named set of variables rather than + the whole parent environment -- copying everything would hand the child every + unrelated secret exported in the calling shell. +- **Review parsing.** The reviewer answers in prose, and the score and verdict + have to survive whatever markdown it wraps them in. +- **Review failure.** The review is a second model call that can fail on its + own; when it does, the run must neither crash nor report a score it never + received. + +Nothing here makes a network call or needs an API key. """ from __future__ import annotations import importlib +import importlib.util import sys import unittest from pathlib import Path @@ -98,5 +113,172 @@ def schematic_test_case(skill_root: Path) -> type[unittest.TestCase]: def test_the_generator_script_is_shipped_alongside_the_cli(self) -> None: self.assertTrue((scripts / "generate_schematic_ai.py").is_file()) + def test_the_iteration_count_is_rejected_rather_than_clamped(self) -> None: + # Silently clamping an out-of-range value used to send 0 to the + # child, which failed there with a message about the child's own + # flag. The check runs before the credential lookup, so this needs + # no API key. + import subprocess + + for value in ("0", "3", "-1"): + with self.subTest(iterations=value): + result = subprocess.run( + [sys.executable, str(scripts / "generate_schematic.py"), + "a diagram", "-o", "out.png", "--iterations", value], + capture_output=True, text=True, timeout=60, + ) + self.assertNotEqual(result.returncode, 0) + self.assertIn("--iterations", result.stderr) + SchematicContractTests.__qualname__ = f"SchematicContractTests[{skill_root.name}]" return SchematicContractTests + + +def review_parsing_test_case(scripts_dir: Path, module_name: str) -> type[unittest.TestCase]: + """Build the review-parsing TestCase for one AI generator module. + + Parameterised by module name because three lineages of the same generator + ship across six skills -- `generate_schematic_ai` (five skills, byte + identical), `generate_infographic_ai`, and `generate_slide_image_ai`. They + share the parsing helpers, and they shared the bugs. + + Everything here is offline: the helpers are pure functions, and the one + test that reaches `review_image` stubs the request out. + """ + + requests_available = importlib.util.find_spec("requests") is not None + + def load(): + if str(scripts_dir) not in sys.path: + sys.path.insert(0, str(scripts_dir)) + return importlib.import_module(module_name) + + @unittest.skipUnless(requests_available, "requests is not installed") + class ReviewParsingTests(unittest.TestCase): + maxDiff = None + + def setUp(self) -> None: + self.module = load() + + def test_the_score_survives_the_markdown_the_reviewer_writes_it_in(self) -> None: + # Gemini emits "**SCORE:** 8.5" far more often than the bare form + # the rubric asks for. A pattern that only matched the bare form + # scored every one of those runs at the old hardcoded default. + for text, expected in ( + ("SCORE: 8.5", 8.5), + ("**SCORE:** 8.5", 8.5), + ("**SCORE: 8.5**", 8.5), + ("__SCORE__: 9.0", 9.0), + ("### SCORE: 8", 8.0), + ("SCORE: 8/10", 8.0), + ("Score: 7", 7.0), + ): + with self.subTest(text=text): + self.assertEqual(self.module._parse_score(text), expected) + + def test_an_unparseable_score_is_none_rather_than_a_stand_in(self) -> None: + # A default here reaches the review log indistinguishable from a + # number the reviewer actually gave. + for text in ("no number anywhere", "", "SCORE: 85", "SCORE: -1"): + with self.subTest(text=text): + self.assertIsNone(self.module._parse_score(text)) + + def test_the_verdict_comes_from_the_verdict_line_only(self) -> None: + # The rubric prompt spells out both tokens when it explains the + # response format. A reviewer echoing that back must not be read + # as failing the diagram. + echoed = ( + "SCORE: 9.0\n" + "VERDICT: ACCEPTABLE\n" + "Reminder: if score < 8.5, mark as NEEDS_IMPROVEMENT with suggestions." + ) + self.assertEqual(self.module._parse_verdict(echoed), "ACCEPTABLE") + self.assertIsNone( + self.module._parse_verdict("someday I might say NEEDS_IMPROVEMENT") + ) + + def test_a_real_failing_verdict_is_still_recognised(self) -> None: + for text in ( + "VERDICT: NEEDS_IMPROVEMENT", + "**VERDICT:** NEEDS_IMPROVEMENT", + "**VERDICT: NEEDS IMPROVEMENT**", + ): + with self.subTest(text=text): + self.assertEqual( + self.module._parse_verdict(text), "NEEDS_IMPROVEMENT" + ) + + def test_the_review_result_carries_whether_the_review_happened(self) -> None: + self.assertEqual( + self.module.ReviewResult._fields, + ("critique", "score", "needs_improvement", "reviewed", "error"), + ) + + ReviewParsingTests.__qualname__ = f"ReviewParsingTests[{module_name}]" + return ReviewParsingTests + + +def review_failure_test_case( + scripts_dir: Path, module_name: str, class_name: str, review_args: tuple +) -> type[unittest.TestCase]: + """Build the TestCase covering `review_image`'s failure paths. + + Separate from `review_parsing_test_case` because it has to instantiate the + generator, whose class name and `review_image` signature differ between the + three lineages. + """ + + requests_available = importlib.util.find_spec("requests") is not None + + def load(): + if str(scripts_dir) not in sys.path: + sys.path.insert(0, str(scripts_dir)) + return importlib.import_module(module_name) + + @unittest.skipUnless(requests_available, "requests is not installed") + class ReviewFailureTests(unittest.TestCase): + maxDiff = None + + def setUp(self) -> None: + self.module = load() + generator = getattr(self.module, class_name)(api_key="sk-or-test") + generator._image_to_base64 = lambda path: "data:image/png;base64,AAAA" + self.generator = generator + + def test_a_response_with_no_choices_does_not_crash_the_run(self) -> None: + # This used to return two values into a three-value unpack, so a + # rate-limited review killed a run whose image was already on disk. + self.generator._make_request = lambda **kwargs: {"choices": []} + review = self.generator.review_image(*review_args) + + self.assertIsNone(review.score) + self.assertFalse(review.reviewed) + self.assertFalse(review.needs_improvement) + self.assertTrue(review.error) + + def test_a_failed_review_is_not_reported_as_a_passing_one(self) -> None: + def explode(**kwargs): + raise RuntimeError("API request timed out after 120 seconds") + + self.generator._make_request = explode + review = self.generator.review_image(*review_args) + + self.assertIsNone(review.score) + self.assertFalse(review.reviewed) + # No retry: a reviewer that did not answer says nothing about the + # image, so regenerating would be guesswork. + self.assertFalse(review.needs_improvement) + self.assertIn("timed out", review.error) + + def test_a_scored_review_is_reported_verbatim(self) -> None: + self.generator._make_request = lambda **kwargs: { + "choices": [{"message": {"content": "**SCORE:** 9.5\n**VERDICT:** ACCEPTABLE"}}] + } + review = self.generator.review_image(*review_args) + + self.assertEqual(review.score, 9.5) + self.assertTrue(review.reviewed) + self.assertIsNone(review.error) + + ReviewFailureTests.__qualname__ = f"ReviewFailureTests[{module_name}]" + return ReviewFailureTests diff --git a/tests/citation-management/test_scripts.py b/tests/citation-management/test_scripts.py index 81e8b3a7..ab77db85 100644 --- a/tests/citation-management/test_scripts.py +++ b/tests/citation-management/test_scripts.py @@ -27,6 +27,13 @@ import format_bibtex # noqa: E402 import validate_citations # noqa: E402 SchematicTests = skill_contract.schematic.schematic_test_case(SKILL_ROOT) +ReviewParsingTests = skill_contract.schematic.review_parsing_test_case( + SCRIPTS, "generate_schematic_ai" +) +ReviewFailureTests = skill_contract.schematic.review_failure_test_case( + SCRIPTS, "generate_schematic_ai", "ScientificSchematicGenerator", + ("diagram.png", "a prompt", 1, "journal", 2), +) BIBLIOGRAPHY = """\ @article{jumper2021, diff --git a/tests/generate-image/test_scripts.py b/tests/generate-image/test_scripts.py index 3b35c208..8418c48c 100644 --- a/tests/generate-image/test_scripts.py +++ b/tests/generate-image/test_scripts.py @@ -45,7 +45,6 @@ def make_args(**overrides) -> argparse.Namespace: n=None, aspect_ratio=None, resolution=None, - size=None, quality=None, output_format=None, background=None, @@ -56,6 +55,53 @@ def make_args(**overrides) -> argparse.Namespace: return argparse.Namespace(**defaults) +# A trimmed stand-in for GET /api/v1/images/models, carrying the shapes that +# matter: enum values, ranges, and a bare capability flag. +CATALOGUE = { + "google/gemini-3.1-flash-image": { + "id": "google/gemini-3.1-flash-image", + "supported_parameters": { + "aspect_ratio": {"type": "enum", "values": ["1:1", "16:9", "21:9"]}, + "resolution": {"type": "enum", "values": ["512", "1K", "2K", "4K"]}, + "n": {"type": "range", "min": 1, "max": 1}, + "input_references": {"type": "range", "min": 0, "max": 14}, + }, + }, + "openai/gpt-image-2": { + "id": "openai/gpt-image-2", + "supported_parameters": { + "background": {"type": "enum", "values": ["auto", "opaque"]}, + "quality": {"type": "enum", "values": ["auto", "low", "medium", "high"]}, + "n": {"type": "range", "min": 1, "max": 10}, + "input_references": {"type": "range", "min": 0, "max": 16}, + }, + }, + "openai/gpt-image-1": { + "id": "openai/gpt-image-1", + "supported_parameters": { + "background": {"type": "enum", "values": ["auto", "transparent", "opaque"]}, + "n": {"type": "range", "min": 1, "max": 10}, + "input_references": {"type": "range", "min": 0, "max": 16}, + }, + }, + "bytedance-seed/seedream-4.5": { + "id": "bytedance-seed/seedream-4.5", + "supported_parameters": { + "seed": {"type": "boolean"}, + "n": {"type": "range", "min": 1, "max": 10}, + "input_references": {"type": "range", "min": 0, "max": 14}, + }, + }, + "black-forest-labs/flux.2-pro": { + "id": "black-forest-labs/flux.2-pro", + "supported_parameters": { + "seed": {"type": "boolean"}, + "input_references": {"type": "range", "min": 0, "max": 8}, + }, + }, +} + + class CliSurfaceTests(unittest.TestCase): def test_help_exits_zero(self): completed = subprocess.run( @@ -73,6 +119,45 @@ class CliSurfaceTests(unittest.TestCase): self.assertNotEqual(completed.returncode, 0) self.assertIn("prompt is required", completed.stderr) + def test_dry_run_prints_the_payload_without_network_or_key(self): + completed = subprocess.run( + [sys.executable, "-B", str(SCRIPT), "a cat", "--aspect-ratio", "16:9", + "--no-preflight", "--dry-run"], + text=True, capture_output=True, timeout=20, check=False, + env={**os.environ, "OPENROUTER_API_KEY": ""}, + ) + self.assertEqual(completed.returncode, 0, completed.stderr) + self.assertIn('"aspect_ratio": "16:9"', completed.stdout) + self.assertIn("nothing billed", completed.stdout) + + def test_size_flag_is_gone(self): + """No catalogue model accepts `size`; offering the flag only invites a 400.""" + completed = subprocess.run( + [sys.executable, "-B", str(SCRIPT), "a cat", "--size", "2048x2048", + "--no-preflight", "--dry-run"], + text=True, capture_output=True, timeout=20, check=False, + ) + self.assertNotEqual(completed.returncode, 0) + self.assertIn("unrecognized arguments", completed.stderr) + + def test_output_format_does_not_offer_svg(self): + completed = subprocess.run( + [sys.executable, "-B", str(SCRIPT), "a cat", "--output-format", "svg", + "--no-preflight", "--dry-run"], + text=True, capture_output=True, timeout=20, check=False, + ) + self.assertNotEqual(completed.returncode, 0) + self.assertIn("invalid choice", completed.stderr) + + def test_out_of_range_compression_is_rejected_locally(self): + completed = subprocess.run( + [sys.executable, "-B", str(SCRIPT), "a cat", "--output-compression", "150", + "--no-preflight", "--dry-run"], + text=True, capture_output=True, timeout=20, check=False, + ) + self.assertNotEqual(completed.returncode, 0) + self.assertIn("between 0 and 100", completed.stderr) + def test_targets_the_images_endpoint_not_chat_completions(self): self.assertEqual(gi.IMAGES_URL, "https://openrouter.ai/api/v1/images") self.assertEqual(gi.MODELS_URL, "https://openrouter.ai/api/v1/images/models") @@ -114,6 +199,19 @@ class ApiKeyResolutionTests(unittest.TestCase): finally: os.chdir(previous) + def test_dotenv_export_prefix_is_tolerated(self): + with tempfile.TemporaryDirectory() as tmp: + (Path(tmp) / ".env").write_text( + "export OPENROUTER_API_KEY=exported-key\n", encoding="utf-8" + ) + previous = os.getcwd() + os.chdir(tmp) + try: + os.environ.pop("OPENROUTER_API_KEY", None) + self.assertEqual(gi.find_api_key(None), "exported-key") + finally: + os.chdir(previous) + def test_absent_key_raises_with_guidance(self): with tempfile.TemporaryDirectory() as tmp: previous = os.getcwd() @@ -150,6 +248,163 @@ class PayloadTests(unittest.TestCase): [{"type": "image_url", "image_url": {"url": "https://example.com/a.png"}}], ) + def test_printed_payload_shortens_base64_references(self): + blob = "data:image/png;base64," + "A" * 500 + payload = {"model": "m", "prompt": "p", + "input_references": [{"type": "image_url", "image_url": {"url": blob}}]} + shown = gi.redacted_payload(payload) + url = shown["input_references"][0]["image_url"]["url"] + self.assertLess(len(url), 80) + self.assertIn("chars of base64", url) + # The original is untouched, so the request still carries the real bytes. + self.assertEqual(payload["input_references"][0]["image_url"]["url"], blob) + + +class PreflightTests(unittest.TestCase): + """The check that turns per-model parameter rules into free local errors.""" + + def test_valid_request_passes(self): + payload = gi.build_payload(make_args(aspect_ratio="16:9", resolution="2K")) + gi.preflight(payload, CATALOGUE) + + def test_unsupported_parameter_is_caught(self): + payload = gi.build_payload(make_args(seed=42)) + with self.assertRaises(gi.RequestRejected) as caught: + gi.preflight(payload, CATALOGUE) + self.assertIn("seed is not supported", str(caught.exception)) + + def test_value_outside_the_model_enum_is_caught(self): + payload = gi.build_payload( + make_args(model="openai/gpt-image-2", background="transparent") + ) + with self.assertRaises(gi.RequestRejected) as caught: + gi.preflight(payload, CATALOGUE) + message = str(caught.exception) + self.assertIn("background=transparent is not allowed", message) + self.assertIn("auto, opaque", message) + + def test_n_above_the_model_maximum_is_caught(self): + payload = gi.build_payload(make_args(n=4)) + with self.assertRaises(gi.RequestRejected) as caught: + gi.preflight(payload, CATALOGUE) + self.assertIn("exceeds this model's maximum of 1", str(caught.exception)) + + def test_too_many_reference_images_are_caught(self): + payload = gi.build_payload( + make_args(model="black-forest-labs/flux.2-pro", + input=[f"https://e.com/{i}.png" for i in range(9)]) + ) + with self.assertRaises(gi.RequestRejected) as caught: + gi.preflight(payload, CATALOGUE) + self.assertIn("accepts at most 8", str(caught.exception)) + + def test_every_problem_is_reported_at_once(self): + payload = gi.build_payload(make_args(aspect_ratio="3:2", seed=1, n=9)) + with self.assertRaises(gi.RequestRejected) as caught: + gi.preflight(payload, CATALOGUE) + self.assertIn("3 problems", str(caught.exception)) + + def test_unknown_model_suggests_close_matches(self): + payload = gi.build_payload(make_args(model="google/gemini-3.1-flash-imag")) + with self.assertRaises(gi.RequestRejected) as caught: + gi.preflight(payload, CATALOGUE) + self.assertIn("google/gemini-3.1-flash-image", str(caught.exception)) + + def test_suggestions_name_a_model_that_accepts_the_value(self): + payload = gi.build_payload( + make_args(model="openai/gpt-image-2", background="transparent") + ) + with self.assertRaises(gi.RequestRejected): + gi.preflight(payload, CATALOGUE) + supporting = gi.models_supporting(CATALOGUE, "background", "transparent") + self.assertIn("openai/gpt-image-1", supporting) + self.assertNotIn("openai/gpt-image-2", supporting) + + def test_suggestions_skip_undocumented_families(self): + """FLUX is in the live catalogue but outside this skill's documented set.""" + supporting = gi.models_supporting(CATALOGUE, "seed") + self.assertIn("bytedance-seed/seedream-4.5", supporting) + self.assertNotIn("black-forest-labs/flux.2-pro", supporting) + + +class SpecDescriptionTests(unittest.TestCase): + def test_enum_lists_its_values(self): + self.assertEqual( + gi.describe_spec({"type": "enum", "values": ["1K", "2K"]}), "1K, 2K" + ) + + def test_range_shows_its_bounds(self): + self.assertEqual(gi.describe_spec({"type": "range", "min": 0, "max": 16}), "0-16") + + def test_bare_capability_reads_as_supported(self): + self.assertEqual(gi.describe_spec({"type": "boolean"}), "supported") + + +class RetryTests(unittest.TestCase): + def test_retry_after_header_is_honoured(self): + self.assertEqual(gi.retry_delay("7", 0), 7.0) + + def test_absurd_retry_after_is_capped(self): + self.assertEqual(gi.retry_delay("99999", 0), 60.0) + + def test_unparsable_retry_after_falls_back_to_backoff(self): + self.assertEqual(gi.retry_delay("in a bit", 2), 4.0) + + def test_backoff_grows(self): + self.assertEqual([gi.retry_delay(None, i) for i in range(3)], [1.0, 2.0, 4.0]) + + def test_only_transient_statuses_retry(self): + self.assertIn(429, gi.RETRY_STATUS) + self.assertIn(503, gi.RETRY_STATUS) + self.assertNotIn(400, gi.RETRY_STATUS) + self.assertNotIn(401, gi.RETRY_STATUS) + + +class ErrorMessageTests(unittest.TestCase): + def test_bad_request_points_at_model_info(self): + detail = gi.error_detail(400, '{"error": {"message": "unsupported parameter"}}') + self.assertIn("unsupported parameter", detail) + self.assertIn("--model-info", detail) + + def test_auth_failure_mentions_the_key_and_content_policy(self): + detail = gi.error_detail(403, '{"error": {"message": "forbidden"}}') + self.assertIn("openrouter.ai/keys", detail) + self.assertIn("content-policy", detail) + + def test_non_json_body_is_passed_through(self): + self.assertIn("gateway timeout", gi.error_detail(504, "gateway timeout")) + + +class CostReportingTests(unittest.TestCase): + def test_reports_the_billed_cost(self): + lines = gi.cost_lines({"cost": 0.0672}) + self.assertEqual(lines[0], "Cost: $0.0672") + + def test_byok_upstream_cost_is_not_reported_as_free(self): + """usage.cost is 0 on a BYOK key; the real spend is upstream.""" + lines = gi.cost_lines( + {"cost": 0, "is_byok": True, + "cost_details": {"upstream_inference_cost": 0.03360275}} + ) + self.assertIn("$0.03360275", lines[0]) + self.assertIn("BYOK", lines[0]) + + def test_genuinely_free_generation_says_so(self): + self.assertEqual(gi.cost_lines({"cost": 0}), ["Cost: $0 reported"]) + + def test_image_tokens_are_reported_when_present(self): + lines = gi.cost_lines( + {"cost": 0.0672, "completion_tokens_details": {"image_tokens": 1120}} + ) + self.assertIn("Image tokens: 1120", lines) + + def test_missing_usage_reports_nothing(self): + self.assertEqual(gi.cost_lines({}), []) + + def test_cost_never_prints_in_scientific_notation(self): + self.assertEqual(gi.format_cost(3e-05), "0.00003") + self.assertEqual(gi.format_cost(0.3), "0.3") + class ReferenceEncodingTests(unittest.TestCase): def test_urls_and_data_urls_pass_through(self): @@ -193,6 +448,10 @@ class OutputPathTests(unittest.TestCase): def test_unknown_media_type_falls_back_to_png(self): self.assertEqual(gi.output_paths(None, "image/unheard-of", 1), [Path("generated_image.png")]) + def test_media_type_parameters_are_ignored(self): + self.assertEqual(gi.output_paths(None, "IMAGE/PNG; charset=binary", 1), + [Path("generated_image.png")]) + def test_explicit_output_is_respected(self): self.assertEqual(gi.output_paths("art.png", "image/png", 1), [Path("art.png")]) @@ -202,6 +461,10 @@ class OutputPathTests(unittest.TestCase): [Path("out_1.png"), Path("out_2.png"), Path("out_3.png")], ) + def test_jpeg_spelling_is_not_a_mismatch(self): + """`-o out.jpeg` names an image/jpeg response correctly, so say nothing.""" + self.assertEqual(gi.acceptable_suffixes("image/jpeg"), {".jpg", ".jpeg"}) + class SaveImageTests(unittest.TestCase): def test_saves_base64_payload(self): @@ -221,10 +484,35 @@ class SaveImageTests(unittest.TestCase): gi.save_images(response, str(target)) self.assertTrue(target.is_file()) + def test_numbering_has_no_gaps_when_an_entry_is_empty(self): + good = base64.b64encode(b"x").decode("ascii") + response = {"data": [ + {"b64_json": good, "media_type": "image/png"}, + {"media_type": "image/png"}, + {"b64_json": good, "media_type": "image/png"}, + ]} + with tempfile.TemporaryDirectory() as tmp: + target = Path(tmp) / "out.png" + written = gi.save_images(response, str(target)) + self.assertEqual([p.name for p in written], ["out_1.png", "out_2.png"]) + def test_empty_data_raises(self): with self.assertRaises(gi.ApiError): gi.save_images({"data": []}, None) + def test_entries_without_any_image_data_raise(self): + with self.assertRaises(gi.ApiError): + gi.save_images({"data": [{"media_type": "image/png"}]}, None) + + def test_non_https_url_in_a_response_is_refused(self): + """The URL comes from the response, not the caller, so it is not trusted.""" + with self.assertRaises(gi.ApiError) as caught: + gi.image_bytes({"url": "http://evil.example/x.png"}, 5.0) + self.assertIn("non-HTTPS", str(caught.exception)) + + def test_downloaded_images_are_size_capped(self): + self.assertGreater(gi.MAX_DOWNLOAD_BYTES, 0) + class SkillDocumentTests(unittest.TestCase): def test_frontmatter_version_matches_expected(self): @@ -238,6 +526,28 @@ class SkillDocumentTests(unittest.TestCase): def test_reference_file_is_present(self): self.assertTrue((SKILL_ROOT / "references" / "models.md").is_file()) + def test_documentation_does_not_promise_a_size_parameter(self): + for name in ("SKILL.md", "references/models.md"): + text = (SKILL_ROOT / name).read_text(encoding="utf-8") + self.assertNotIn("--size", text.replace("There is no `--size`", "")) + + def test_transparent_background_is_not_offered_on_models_that_refuse_it(self): + """gpt-image-2 allows only auto and opaque; recommending it wastes a call.""" + text = (SKILL_ROOT / "SKILL.md").read_text(encoding="utf-8") + for line in text.splitlines(): + stripped = line.strip() + # `$ ...` lines demonstrate the rejection itself, and prose that says + # the combination is unavailable is the warning, not a recommendation. + if stripped.startswith("$ ") or "not available" in stripped: + continue + if "--background transparent" in stripped: + self.assertNotIn("gpt-image-2", stripped) + + def test_text_and_integrity_caveats_are_documented(self): + text = (SKILL_ROOT / "SKILL.md").read_text(encoding="utf-8").lower() + self.assertIn("never evidence", text) + self.assertIn("cannot be trusted with text", text) + if __name__ == "__main__": unittest.main() diff --git a/tests/infographics/test_scripts.py b/tests/infographics/test_scripts.py index d8456d64..5c290e61 100644 --- a/tests/infographics/test_scripts.py +++ b/tests/infographics/test_scripts.py @@ -30,6 +30,16 @@ import generate_infographic # noqa: E402 CliHelpTests = skill_contract.cli.help_test_case(SKILL_ROOT) +# `generate_infographic_ai.py` is a fork of the schematic generator and shares +# its review-parsing code, so it reuses the same contract. +ReviewParsingTests = skill_contract.schematic.review_parsing_test_case( + SCRIPTS, "generate_infographic_ai" +) +ReviewFailureTests = skill_contract.schematic.review_failure_test_case( + SCRIPTS, "generate_infographic_ai", "InfographicGenerator", + ("infographic.png", "a prompt", "statistical", 1, "default", 3), +) + class SubprocessEnvironmentTests(unittest.TestCase): def test_only_allowlisted_variables_are_forwarded(self) -> None: diff --git a/tests/latex-posters/test_scripts.py b/tests/latex-posters/test_scripts.py index 877764c1..40ccb5bb 100644 --- a/tests/latex-posters/test_scripts.py +++ b/tests/latex-posters/test_scripts.py @@ -21,6 +21,13 @@ SCRIPTS = SKILL_ROOT / "scripts" sys.path.insert(0, str(SCRIPTS)) SchematicTests = skill_contract.schematic.schematic_test_case(SKILL_ROOT) +ReviewParsingTests = skill_contract.schematic.review_parsing_test_case( + SCRIPTS, "generate_schematic_ai" +) +ReviewFailureTests = skill_contract.schematic.review_failure_test_case( + SCRIPTS, "generate_schematic_ai", "ScientificSchematicGenerator", + ("diagram.png", "a prompt", 1, "journal", 2), +) CliHelpTests = skill_contract.cli.help_test_case(SKILL_ROOT) REVIEW_SCRIPT = SCRIPTS / "review_poster.sh" diff --git a/tests/literature-review/test_scripts.py b/tests/literature-review/test_scripts.py index 7267bfa8..d910ec70 100644 --- a/tests/literature-review/test_scripts.py +++ b/tests/literature-review/test_scripts.py @@ -28,6 +28,13 @@ sys.path.insert(0, str(SCRIPTS)) import search_databases # noqa: E402 SchematicTests = skill_contract.schematic.schematic_test_case(SKILL_ROOT) +ReviewParsingTests = skill_contract.schematic.review_parsing_test_case( + SCRIPTS, "generate_schematic_ai" +) +ReviewFailureTests = skill_contract.schematic.review_failure_test_case( + SCRIPTS, "generate_schematic_ai", "ScientificSchematicGenerator", + ("diagram.png", "a prompt", 1, "journal", 2), +) RESULTS = [ { diff --git a/tests/scientific-schematics/test_scripts.py b/tests/scientific-schematics/test_scripts.py index db10e79b..2214858f 100644 --- a/tests/scientific-schematics/test_scripts.py +++ b/tests/scientific-schematics/test_scripts.py @@ -20,6 +20,13 @@ SCRIPTS = SKILL_ROOT / "scripts" sys.path.insert(0, str(SCRIPTS)) SchematicTests = skill_contract.schematic.schematic_test_case(SKILL_ROOT) +ReviewParsingTests = skill_contract.schematic.review_parsing_test_case( + SCRIPTS, "generate_schematic_ai" +) +ReviewFailureTests = skill_contract.schematic.review_failure_test_case( + SCRIPTS, "generate_schematic_ai", "ScientificSchematicGenerator", + ("diagram.png", "a prompt", 1, "journal", 2), +) CliHelpTests = skill_contract.cli.help_test_case(SKILL_ROOT) diff --git a/tests/scientific-slides/test_scripts.py b/tests/scientific-slides/test_scripts.py index fd0aa16d..ec1bcb03 100644 --- a/tests/scientific-slides/test_scripts.py +++ b/tests/scientific-slides/test_scripts.py @@ -57,6 +57,24 @@ import slides_to_pdf # noqa: E402 import validate_presentation # noqa: E402 SchematicTests = skill_contract.schematic.schematic_test_case(SKILL_ROOT) +ReviewParsingTests = skill_contract.schematic.review_parsing_test_case( + SCRIPTS, "generate_schematic_ai" +) +ReviewFailureTests = skill_contract.schematic.review_failure_test_case( + SCRIPTS, "generate_schematic_ai", "ScientificSchematicGenerator", + ("diagram.png", "a prompt", 1, "journal", 2), +) + +# `generate_slide_image_ai.py` is a fork of the schematic generator, not one of +# the byte-identical copies, so it needs its own instantiation of the same +# review-parsing contract. +SlideImageReviewParsingTests = skill_contract.schematic.review_parsing_test_case( + SCRIPTS, "generate_slide_image_ai" +) +SlideImageReviewFailureTests = skill_contract.schematic.review_failure_test_case( + SCRIPTS, "generate_slide_image_ai", "SlideImageGenerator", + ("slide.png", "a prompt", 1, False, 2), +) CliHelpTests = skill_contract.cli.help_test_case(SKILL_ROOT) @@ -822,64 +840,70 @@ class ReviewDecisionTests(SlideGeneratorTestCase): def test_a_score_at_the_threshold_is_accepted(self) -> None: # 6.5 is the threshold itself, so it must not trigger another round. - _, score, needs_improvement = self.review( - {"content": "SCORE: 6.5\nVERDICT: ACCEPTABLE"} - ) - self.assertEqual(score, 6.5) - self.assertFalse(needs_improvement) + review = self.review({"content": "SCORE: 6.5\nVERDICT: ACCEPTABLE"}) + self.assertEqual(review.score, 6.5) + self.assertFalse(review.needs_improvement) def test_a_score_below_the_threshold_asks_for_another_round(self) -> None: - _, score, needs_improvement = self.review({"content": "SCORE: 6.4"}) - self.assertEqual(score, 6.4) - self.assertTrue(needs_improvement) + review = self.review({"content": "SCORE: 6.4"}) + self.assertEqual(review.score, 6.4) + self.assertTrue(review.needs_improvement) def test_an_explicit_verdict_overrides_a_high_score(self) -> None: # The reviewer's words win: a 9 with NEEDS_IMPROVEMENT is not accepted. - _, score, needs_improvement = self.review( - {"content": "SCORE: 9\nVERDICT: NEEDS_IMPROVEMENT"} - ) - self.assertEqual(score, 9.0) - self.assertTrue(needs_improvement) + review = self.review({"content": "SCORE: 9\nVERDICT: NEEDS_IMPROVEMENT"}) + self.assertEqual(review.score, 9.0) + self.assertTrue(review.needs_improvement) def test_a_loosely_worded_score_is_still_read(self) -> None: - _, score, _ = self.review({"content": "Overall quality: 8.5 out of 10"}) - self.assertEqual(score, 8.5) + review = self.review({"content": "Overall quality: 8.5 out of 10"}) + self.assertEqual(review.score, 8.5) def test_an_unscored_review_does_not_block_the_pipeline(self) -> None: - # No parseable score: assume acceptable rather than loop pointlessly. - _, score, needs_improvement = self.review({"content": "Looks good to me"}) - self.assertEqual(score, 7.0) - self.assertFalse(needs_improvement) + # No parseable score and no verdict: still no extra round, because a + # reviewer that said nothing measurable says nothing about the image. + # The score stays None -- a stand-in number here would reach the review + # log indistinguishable from one the reviewer actually gave. + review = self.review({"content": "Looks good to me"}) + self.assertIsNone(review.score) + self.assertFalse(review.needs_improvement) + self.assertTrue(review.error) def test_a_review_returned_as_content_blocks_is_flattened(self) -> None: - critique, score, _ = self.review( + review = self.review( {"content": [{"type": "text", "text": "SCORE: 6.0"}, {"type": "text", "text": "ISSUES: crowded"}]} ) - self.assertEqual(score, 6.0) - self.assertIn("crowded", critique) + self.assertEqual(review.score, 6.0) + self.assertIn("crowded", review.critique) def test_a_reasoning_only_reply_is_used_as_the_critique(self) -> None: - critique, score, _ = self.review({"content": "", "reasoning": "SCORE: 6.0"}) - self.assertEqual(score, 6.0) - self.assertIn("SCORE", critique) + review = self.review({"content": "", "reasoning": "SCORE: 6.0"}) + self.assertEqual(review.score, 6.0) + self.assertIn("SCORE", review.critique) def test_a_failed_review_is_not_treated_as_a_bad_image(self) -> None: with mock.patch.object( self.generator, "_make_request", side_effect=RuntimeError("API down") ): - critique, score, needs_improvement = self.generator.review_image( - str(self.image_path), "a slide", 1 - ) - self.assertFalse(needs_improvement) - self.assertEqual(score, 7.0) - self.assertIn("review skipped", critique) + review = self.generator.review_image(str(self.image_path), "a slide", 1) + self.assertFalse(review.needs_improvement) + # Nor as a passing one: the image was never actually measured. + self.assertIsNone(review.score) + self.assertFalse(review.reviewed) + self.assertIn("API down", review.critique) class RefinementLoopTests(SlideGeneratorTestCase): PAYLOAD = b"first-image" BETTER = b"second-image" + def reviewed(self, critique, score, needs_improvement): + """A completed review, in the shape `review_image` returns.""" + return self.module.ReviewResult( + critique, score, needs_improvement, reviewed=True + ) + def generate(self, images, reviews, **kwargs): destination = self.root / "slides" / "01_title.png" with mock.patch.object(self.generator, "generate_image", side_effect=images) as drew, \ @@ -892,7 +916,7 @@ class RefinementLoopTests(SlideGeneratorTestCase): def test_a_good_first_image_stops_early_and_is_written(self) -> None: results, destination, drew = self.generate( - [self.PAYLOAD], [("great", 8.0, False)] + [self.PAYLOAD], [self.reviewed("great", 8.0, False)] ) self.assertTrue(results["success"]) self.assertTrue(results["early_stop"]) @@ -905,7 +929,7 @@ class RefinementLoopTests(SlideGeneratorTestCase): def test_a_weak_image_is_regenerated_from_an_improved_prompt(self) -> None: results, destination, drew = self.generate( [self.PAYLOAD, self.BETTER], - [("text too small", 5.0, True), ("better", 7.5, False)], + [self.reviewed("text too small", 5.0, True), self.reviewed("better", 7.5, False)], ) self.assertTrue(results["success"]) self.assertEqual(len(results["iterations"]), 2) @@ -917,7 +941,7 @@ class RefinementLoopTests(SlideGeneratorTestCase): def test_the_iteration_ceiling_still_keeps_the_last_image(self) -> None: results, destination, drew = self.generate( [self.PAYLOAD, self.BETTER], - [("bad", 3.0, True), ("still bad", 4.0, True)], + [self.reviewed("bad", 3.0, True), self.reviewed("still bad", 4.0, True)], iterations=2, ) self.assertEqual(drew.call_count, 2) @@ -935,7 +959,7 @@ class RefinementLoopTests(SlideGeneratorTestCase): def test_the_mode_and_threshold_are_recorded_in_the_results(self) -> None: results, _, _ = self.generate( - [self.PAYLOAD], [("fine", 7.0, False)], visual_only=True + [self.PAYLOAD], [self.reviewed("fine", 7.0, False)], visual_only=True ) self.assertEqual(results["mode"], "visual_only") self.assertEqual(results["quality_threshold"], 6.5) diff --git a/tests/skill-requirements.toml b/tests/skill-requirements.toml index da21b63e..e5103828 100644 --- a/tests/skill-requirements.toml +++ b/tests/skill-requirements.toml @@ -61,7 +61,8 @@ packages = ["requests", "python-dotenv"] packages = ["requests", "python-dotenv"] [skills.generate-image] -packages = ["requests"] +# The bundled CLI is standard-library only, and a test enforces that. +packages = [] [skills.markdown-mermaid-writing] packages = [] @@ -86,7 +87,7 @@ packages = [ ] [skills.scientific-schematics] -packages = ["schemdraw", "matplotlib", "requests", "python-dotenv"] +packages = ["requests", "python-dotenv"] [skills.scientific-visualization] packages = ["matplotlib", "seaborn", "plotly", "pypdf", "pillow", "numpy"]