Turn any AI agent into an AI Scientist. The #1 Agent Skills library for science, used by 250,000+ scientists worldwide. 177 ready-to-use validated skills plus 100+ scientific databases covering biology, chemistry, medicine, and drug discovery. Compatible with Cursor, Claude Code, Codex, Pi, Antigravity, and the open Agent Skills standard.
Python agent-skillsai-scientistbioinformaticschemoinformaticsclaudeclaude-skillsclaudecodeclinical-researchcomputational-biologydata-analysisdrug-discoverygenomicsmaterials-sciencemetabolomicsproteomicsscientific-computingscientific-visualization
docs: update skills documentation for scientific-critical-thinking and stable-baselines3
Timothy Kassise60e84e63590
diff --git a/docs/skills.md b/docs/skills.mdindex a17367ce..274b0af6 100644--- a/docs/skills.md+++ b/docs/skills.md@@ -6,7 +6,7 @@- **DepMap** - Query the Cancer Dependency Map (DepMap) for cancer cell line gene dependency scores (CRISPR Chronos), drug sensitivity data, and gene effect profiles. Use for identifying cancer-specific vulnerabilities, synthetic lethal interactions, and validating oncology drug targets- **Imaging Data Commons** - Query and download public cancer imaging data from NCI Imaging Data Commons using idc-index. Use for accessing large-scale radiology (CT, MR, PET) and pathology datasets for AI training or research. No authentication required. Query by metadata, visualize in browser, check licenses- **PrimeKG** - Query the Precision Medicine Knowledge Graph (PrimeKG) for multiscale biological data including genes, drugs, diseases, phenotypes, and more. Integrates 20+ biomedical resources into a single knowledge graph for drug repurposing, disease mechanism exploration, and target identification-- **U.S. Treasury Fiscal Data** - Free, open REST API from the U.S. Department of the Treasury providing 54 datasets and 182 data tables covering federal fiscal data. No API key required. Access national debt (Debt to the Penny back to 1993, Historical Debt back to 1790), Daily Treasury Statements (TGA balances, deposits/withdrawals), Monthly Treasury Statements (federal budget receipts and outlays), Treasury securities auctions data (bills, notes, bonds, TIPS, FRNs since 1979), average interest rates on Treasury securities, Treasury reporting exchange rates (quarterly for 170+ currencies), I Bond and savings bond rates, TIPS/CPI data, and more. Supports filtering, sorting, pagination, and CSV/XML/JSON output formats+- **U.S. Treasury Fiscal Data** - Free, open REST API from the U.S. Department of the Treasury providing 54 datasets and 179 data tables covering federal fiscal data. No API key required. Access national debt (Debt to the Penny back to 1993, Historical Debt back to 1790), Daily Treasury Statements (TGA balances, deposits/withdrawals), Monthly Treasury Statements (federal budget receipts and outlays), Treasury securities auctions data (bills, notes, bonds, TIPS, FRNs since 1979), average interest rates on Treasury securities, Treasury reporting exchange rates (quarterly for 170+ currencies), I Bond and savings bond rates, TIPS/CPI data, and more. Supports filtering, sorting, pagination, and CSV/XML/JSON output formats- **Hugging Science** - Curated, LLM-friendly catalog of scientific datasets, models, blog posts, and interactive Spaces hosted on Hugging Face, spanning 17 scientific domains (astronomy, benchmark, biology, biotechnology, chemistry, climate, conservation, earth-science, ecology, energy, engineering, genomics, materials-science, mathematics, medicine, physics, scientific-reasoning). Discovery happens via huggingscience.co (with `llms.txt`, `llms-full.txt`, and per-topic markdown files designed for agent consumption); usage goes through standard Hugging Face APIs. Includes a bundled `fetch_catalog.py` script for filtered access by topic, type (datasets/models/blogs/spaces), or free-text search, plus reference guides for loading datasets via the `datasets` library (with streaming for billion-token corpora), running models via `transformers` or the Inference API/Providers (handling `trust_remote_code` requirements for custom architectures like Evo-2), and calling Spaces via `gradio_client` (with a worked BoltzGen example for protein binder design). Authenticates gated resources via `HF_TOKEN` from `.env`. Use cases: discovering the right dataset/model for a scientific ML task without trawling the broader Hub, fine-tuning on curated scientific data, citing methodology blogs from dataset/model authors, running interactive scientific demos (binder design, theorem proving, weather modeling) without local GPU setup, and bridging from "I need a model for protein/genome/molecule/climate/materials/astronomy" to working code## Scientific Integrations@@ -114,11 +114,11 @@- **scikit-learn** - Industry-standard Python library for classical machine learning (current stable **1.8.0**, Python 3.11–3.14, free-threaded CPython wheels). Provides comprehensive supervised learning (classification: Logistic Regression, SVM, Decision Trees, Random Forests with 17+ variants, Gradient Boosting with XGBoost-compatible HistGradientBoosting, Naive Bayes, KNN, Neural Networks/MLP; regression: Linear, Ridge, Lasso, ElasticNet, SVR, ensemble methods), unsupervised learning (clustering: K-Means, DBSCAN, native HDBSCAN since 1.3, OPTICS, Agglomerative/Hierarchical, Spectral, Gaussian Mixture Models, BIRCH, MeanShift; dimensionality reduction: PCA, Kernel PCA, t-SNE, Isomap, LLE, MDS, ClassicalMDS, NMF, TruncatedSVD, FastICA, LDA; outlier detection: IsolationForest, LocalOutlierFactor, OneClassSVM), data preprocessing (scaling: StandardScaler, MinMaxScaler, RobustScaler; encoding: OneHotEncoder, OrdinalEncoder, LabelEncoder; imputation: SimpleImputer, KNNImputer, IterativeImputer; feature engineering: PolynomialFeatures, KBinsDiscretizer, text vectorization with CountVectorizer/TfidfVectorizer), model evaluation (cross-validation: KFold, StratifiedKFold, TimeSeriesSplit, GroupKFold; hyperparameter tuning: GridSearchCV, RandomizedSearchCV, HalvingGridSearchCV; metrics: 30+ evaluation metrics for classification/regression/clustering including accuracy, precision, recall, F1, ROC-AUC, MSE, RMSE via root_mean_squared_error, R², silhouette score), and Pipeline/ColumnTransformer for production-ready workflows. Features consistent API (fit/predict/transform), extensive documentation, integration with NumPy/pandas/SciPy, joblib persistence, and scikit-learn-compatible ecosystem (XGBoost, LightGBM, CatBoost, imbalanced-learn, UMAP via umap-learn). Optimized implementations using Cython/OpenMP for performance. Use cases: predictive modeling, customer segmentation, anomaly detection, feature engineering, model selection/validation, text classification, image classification (with feature extraction), time series forecasting (with preprocessing), medical diagnosis, fraud detection, recommendation systems, and any tabular data ML task requiring interpretable models or established algorithms- **scikit-survival** - Survival analysis and time-to-event modeling with censored data. Built on scikit-learn, provides Cox proportional hazards models (CoxPHSurvivalAnalysis, CoxnetSurvivalAnalysis with elastic net regularization), ensemble methods (Random Survival Forests, Gradient Boosting), Survival Support Vector Machines (linear and kernel), non-parametric estimators (Kaplan-Meier, Nelson-Aalen), competing risks analysis, and specialized evaluation metrics (concordance index, time-dependent AUC, Brier score). Handles right-censored data, integrates with scikit-learn pipelines, and supports feature selection and hyperparameter tuning via cross-validation- **SHAP** - Model interpretability and explainability using Shapley values from game theory. Provides unified approach to explain any ML model with TreeExplainer (fast exact explanations for XGBoost/LightGBM/Random Forest), DeepExplainer (TensorFlow/PyTorch neural networks), KernelExplainer (model-agnostic), and LinearExplainer. Includes comprehensive visualizations (waterfall plots for individual predictions, beeswarm plots for global importance, scatter plots for feature relationships, bar/force/heatmap plots), supports model debugging, fairness analysis, feature engineering guidance, and production deployment-- **Stable Baselines3** - PyTorch-based reinforcement learning library providing reliable implementations of RL algorithms (PPO, SAC, DQN, TD3, DDPG, A2C, HER, RecurrentPPO). Use this skill for training RL agents on standard or custom Gymnasium environments, implementing callbacks for monitoring and control, using vectorized environments for parallel training, creating custom environments with proper Gymnasium API implementation, and integrating with deep RL workflows. Includes comprehensive training templates, evaluation utilities, algorithm selection guidance (on-policy vs off-policy, continuous vs discrete actions), support for multi-input policies (dict observations), goal-conditioned learning with HER, and integration with TensorBoard for experiment tracking+- **Stable Baselines3** - PyTorch-based reinforcement learning library (current stable **2.8.0**, Python 3.10+, PyTorch >= 2.3). Provides reliable implementations of RL algorithms (PPO, SAC, DQN, TD3, DDPG, A2C, HER, RecurrentPPO via SB3-Contrib). Use this skill for training RL agents on standard or custom Gymnasium environments, implementing callbacks for monitoring and control, using vectorized environments for parallel training, creating custom environments with proper Gymnasium API implementation, and integrating with deep RL workflows. Includes comprehensive training templates, evaluation utilities, algorithm selection guidance (on-policy vs off-policy, continuous vs discrete actions), support for multi-input policies (dict observations), goal-conditioned learning with HER, and integration with TensorBoard for experiment tracking- **statsmodels** - Statistical modeling and econometrics (OLS, GLM, logit/probit, ARIMA, time series forecasting, hypothesis testing, diagnostics)- **TimesFM Forecasting** - Zero-shot time series forecasting with Google's TimesFM foundation model. Use for any univariate time series (sales, sensors, energy, vitals, weather) without training a custom model. Supports CSV/DataFrame/array inputs with point forecasts and prediction intervals. Includes a preflight system checker script to verify RAM/GPU before first use-- **Torch Geometric** - Graph Neural Networks for molecular and geometric data-- **Transformers** - State-of-the-art machine learning models for NLP, computer vision, audio, and multimodal tasks. Provides 1M+ pre-trained models accessible via pipelines (text-classification, NER, QA, summarization, translation, text-generation, image-classification, object-detection, ASR, VQA), comprehensive training via Trainer API with distributed training and mixed precision, flexible text generation with multiple decoding strategies (greedy, beam search, sampling), and Auto classes for automatic architecture selection (BERT, GPT, T5, ViT, BART, etc.)+- **Torch Geometric** - PyTorch Geometric (PyG 2.7.x) for graph neural networks on PyTorch 2.6+. Covers `Data`/`HeteroData`, 60+ conv layers (GCN, GAT, GraphSAGE, GIN), node/link/graph classification, heterogeneous graphs, neighbor sampling (`NeighborLoader`, `LinkNeighborLoader`), OGB and built-in datasets, custom dataset loading, GNN explainability, and scaling via DDP, Lightning, and `torch.compile`+- **Transformers** - Hugging Face Transformers 5.x (PyTorch) for NLP, computer vision, audio, and multimodal tasks. Provides 1M+ pre-trained Hub models via pipelines (text-classification, NER, QA, summarization, translation, text-generation, image-classification, object-detection, ASR, VQA), Trainer API fine-tuning with mixed precision and distributed training, flexible text generation (greedy, beam search, sampling), and Auto classes for architecture selection (BERT, GPT, T5, ViT, BART, etc.)- **UMAP-learn** - Python implementation of Uniform Manifold Approximation and Projection (UMAP) for dimensionality reduction and manifold learning. Provides fast, scalable nonlinear dimensionality reduction that preserves both local and global structure of high-dimensional data. Key features include: support for both supervised and unsupervised dimensionality reduction, ability to handle mixed data types, integration with scikit-learn API, and efficient implementation using numba for performance. Produces low-dimensional embeddings (typically 2D or 3D) suitable for visualization and downstream analysis. Often outperforms t-SNE in preserving global structure while maintaining local neighborhoods. Use cases: data visualization, feature extraction, preprocessing for machine learning, single-cell data analysis, and exploratory data analysis of high-dimensional datasets### Materials Science & Chemistrydiff --git a/skills/scientific-critical-thinking/SKILL.md b/skills/scientific-critical-thinking/SKILL.mdindex 76489125..9f9e7211 100644--- a/skills/scientific-critical-thinking/SKILL.md+++ b/skills/scientific-critical-thinking/SKILL.md@@ -1,10 +1,11 @@---name: scientific-critical-thinkingdescription: Evaluate scientific claims and evidence quality. Use for assessing experimental design validity, identifying biases and confounders, applying evidence grading frameworks (GRADE, Cochrane Risk of Bias), or teaching critical analysis. Best for understanding evidence quality, identifying flaws. For formal peer review writing use peer-review.-allowed-tools: Read Write Edit Bash+allowed-tools: Read Write Editlicense: MIT license+compatibility: Analytical guidance needs no network. Optional figures via the scientific-schematics skill require OPENROUTER_API_KEY and outbound API access to OpenRouter.metadata:- version: "1.0"+ version: "1.1"skill-author: K-Dense Inc.---@@ -25,38 +26,27 @@ This skill should be used when:- Applying GRADE or Cochrane risk of bias assessments- Providing critical analysis of research papers-## Visual Enhancement with Scientific Schematics+## Visual Aids (Optional)-**When creating documents with this skill, always consider adding scientific diagrams and schematics to enhance visual communication.**+Only add figures when the **user explicitly requests** a diagram (for example, a GRADE flowchart, bias decision tree, or evidence-quality framework).-If your document does not already contain schematics or diagrams:-- Use the **scientific-schematics** skill to generate AI-powered publication-quality diagrams-- Simply describe your desired diagram in natural language-- Nano Banana Pro will automatically generate, review, and refine the schematic+**When figures help:**+- Critical thinking framework diagrams+- Bias identification decision trees+- Evidence quality assessment flowcharts+- GRADE or risk-of-bias evaluation frameworks-**For new documents:** Scientific schematics should be generated by default to visually represent key concepts, workflows, architectures, or relationships described in the text.+**How to create figures:**+- **Preferred:** Use the **scientific-schematics** skill for AI-generated diagrams from a natural-language description+- **Alternative:** Build figures in your usual tools (draw.io, PowerPoint, matplotlib, etc.)++From the `scientific-schematics` skill directory, with `OPENROUTER_API_KEY` set:-**How to generate schematics:**```bash-python scripts/generate_schematic.py "your diagram description" -o figures/output.png+python scripts/generate_schematic.py "GRADE evidence assessment flowchart with downgrade and upgrade factors" -o figures/grade_flowchart.png --doc-type report```-The AI will automatically:-- Create publication-quality images with proper formatting-- Review and refine through multiple iterations-- Ensure accessibility (colorblind-friendly, high contrast)-- Save outputs in the figures/ directory--**When to add schematics:**-- Critical thinking framework diagrams-- Bias identification decision trees-- Evidence quality assessment flowcharts-- GRADE assessment methodology diagrams-- Risk of bias evaluation frameworks-- Validity assessment visualizations-- Any complex concept that benefits from visualization--For detailed guidance on creating schematics, refer to the scientific-schematics skill documentation.+**Disclosure:** AI schematic generation sends your prompt to [OpenRouter](https://openrouter.ai/) (a third-party API). Do not include unpublished sensitive details unless that transmission is appropriate for your project.---@@ -249,7 +239,7 @@ Evaluate the strength and quality of evidence systematically.**Important:** Higher-level designs aren't always better quality. A well-designed observational study can be stronger than a poorly-conducted RCT.2. **Quality Within Design Type**- - Risk of bias assessment (use appropriate tool: Cochrane ROB, Newcastle-Ottawa, etc.)+ - Risk of bias assessment (use appropriate tool: Cochrane RoB 2 for RCTs, ROBINS-I for non-randomized studies, Newcastle-Ottawa, etc.)- Methodological rigor- Transparency and reporting completeness- Conflicts of interestdiff --git a/skills/scientific-critical-thinking/references/evidence_hierarchy.md b/skills/scientific-critical-thinking/references/evidence_hierarchy.mdindex 4dd08a15..7d638eb9 100644--- a/skills/scientific-critical-thinking/references/evidence_hierarchy.md+++ b/skills/scientific-critical-thinking/references/evidence_hierarchy.md@@ -264,18 +264,19 @@ GRADE (Grading of Recommendations Assessment, Development and Evaluation) assess### For Different Study Types**RCTs:**-- Cochrane Risk of Bias Tool-- Jadad Scale+- Cochrane RoB 2 (Risk of Bias 2) — current standard for randomized trials- PEDro Scale (for trials in physical therapy)+- Legacy: Cochrane RoB 1, Jadad Scale (historical; prefer RoB 2 for new reviews)**Observational Studies:**+- ROBINS-I (Risk of Bias in Non-randomized Studies — of Interventions)- Newcastle-Ottawa Scale-- ROBINS-I (Risk of Bias in Non-randomized Studies)**Diagnostic Studies:**- QUADAS-2 (Quality Assessment of Diagnostic Accuracy Studies)**Systematic Reviews:**+- PRISMA 2020 checklist (reporting standard for systematic reviews)- AMSTAR-2 (A Measurement Tool to Assess Systematic Reviews)**All Study Types:**diff --git a/skills/scientific-critical-thinking/references/experimental_design.md b/skills/scientific-critical-thinking/references/experimental_design.mdindex 2e76c323..c278b2d8 100644--- a/skills/scientific-critical-thinking/references/experimental_design.md+++ b/skills/scientific-critical-thinking/references/experimental_design.md@@ -396,9 +396,9 @@- [ ] Distinguishes confirmatory from exploratory### Reporting Guidelines-- [ ] **RCTs:** CONSORT checklist+- [ ] **RCTs:** CONSORT 2010 checklist (with applicable extensions)- [ ] **Observational studies:** STROBE checklist-- [ ] **Systematic reviews:** PRISMA checklist+- [ ] **Systematic reviews:** PRISMA 2020 checklist- [ ] **Diagnostic studies:** STARD checklist- [ ] **Qualitative research:** COREQ checklist- [ ] **Case reports:** CARE guidelinesdiff --git a/skills/scientific-critical-thinking/scripts/generate_schematic.py b/skills/scientific-critical-thinking/scripts/generate_schematic.pydeleted file mode 100644index 6843e0a1..00000000--- a/skills/scientific-critical-thinking/scripts/generate_schematic.py+++ /dev/null@@ -1,139 +0,0 @@-#!/usr/bin/env python3-"""-Scientific schematic generation using Nano Banana 2.--Generate any scientific diagram by describing it in natural language.-Nano Banana 2 handles everything automatically with smart iterative refinement.--Smart iteration: Only regenerates if quality is below threshold for your document type.-Quality review: Uses Gemini 3.1 Pro Preview for professional scientific evaluation.--Usage:- # Generate for journal paper (highest quality threshold)- python generate_schematic.py "CONSORT flowchart" -o flowchart.png --doc-type journal-- # Generate for presentation (lower threshold, faster)- python generate_schematic.py "Transformer architecture" -o transformer.png --doc-type presentation-- # Generate for poster- python generate_schematic.py "MAPK signaling pathway" -o pathway.png --doc-type poster-"""--import argparse-import os-import subprocess-import sys-from pathlib import Path---def main():- """Command-line interface."""- parser = argparse.ArgumentParser(- description="Generate scientific schematics using AI with smart iterative refinement",- formatter_class=argparse.RawDescriptionHelpFormatter,- epilog="""-How it works:- Simply describe your diagram in natural language- Nano Banana 2 generates it automatically with:- - Smart iteration (only regenerates if quality is below threshold)- - Quality review by Gemini 3.1 Pro Preview- - Document-type aware quality thresholds- - Publication-ready output--Document Types (quality thresholds):- journal 8.5/10 - Nature, Science, peer-reviewed journals- conference 8.0/10 - Conference papers- thesis 8.0/10 - Dissertations, theses- grant 8.0/10 - Grant proposals- preprint 7.5/10 - arXiv, bioRxiv, etc.- report 7.5/10 - Technical reports- poster 7.0/10 - Academic posters- presentation 6.5/10 - Slides, talks- default 7.5/10 - General purpose--Examples:- # Generate for journal paper (strict quality)- python generate_schematic.py "CONSORT participant flow" -o flowchart.png --doc-type journal-- # Generate for poster (moderate quality)- python generate_schematic.py "Transformer architecture" -o arch.png --doc-type poster-- # Generate for slides (faster, lower threshold)- python generate_schematic.py "System diagram" -o system.png --doc-type presentation-- # Custom max iterations- python generate_schematic.py "Complex pathway" -o pathway.png --iterations 2-- # Verbose output- python generate_schematic.py "Circuit diagram" -o circuit.png -v--Environment Variables:- OPENROUTER_API_KEY Required for AI generation- """- )-- parser.add_argument("prompt",- help="Description of the diagram to generate")- parser.add_argument("-o", "--output", required=True,- help="Output file path")- parser.add_argument("--doc-type", default="default",- choices=["journal", "conference", "poster", "presentation",- "report", "grant", "thesis", "preprint", "default"],- help="Document type for quality threshold (default: default)")- parser.add_argument("--iterations", type=int, default=2,- help="Maximum refinement iterations (default: 2, max: 2)")- parser.add_argument("--api-key",- help="OpenRouter API key (or use OPENROUTER_API_KEY env var)")- parser.add_argument("-v", "--verbose", action="store_true",- help="Verbose output")-- args = parser.parse_args()-- # Check for API key- api_key = args.api_key or os.getenv("OPENROUTER_API_KEY")- if not api_key:- print("Error: OPENROUTER_API_KEY environment variable not set")- print("\nFor AI generation, you need an OpenRouter API key.")- print("Get one at: https://openrouter.ai/keys")- print("\nSet it with:")- print(" export OPENROUTER_API_KEY='your_api_key'")- print("\nOr use --api-key flag")- sys.exit(1)-- # Find AI generation script- script_dir = Path(__file__).parent- ai_script = script_dir / "generate_schematic_ai.py"-- if not ai_script.exists():- print(f"Error: AI generation script not found: {ai_script}")- sys.exit(1)-- # Build command- cmd = [sys.executable, str(ai_script), args.prompt, "-o", args.output]-- 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)])-- if args.verbose:- cmd.append("-v")-- # Execute — pass API key via environment to avoid exposure in process listings- try:- env = os.environ.copy()- if api_key:- env["OPENROUTER_API_KEY"] = api_key- result = subprocess.run(cmd, check=False, env=env)- sys.exit(result.returncode)- except Exception as e:- print(f"Error executing AI generation: {e}")- sys.exit(1)---if __name__ == "__main__":- main()-diff --git a/skills/scientific-critical-thinking/scripts/generate_schematic_ai.py b/skills/scientific-critical-thinking/scripts/generate_schematic_ai.pydeleted file mode 100644index 52170753..00000000--- a/skills/scientific-critical-thinking/scripts/generate_schematic_ai.py+++ /dev/null@@ -1,817 +0,0 @@-#!/usr/bin/env python3-"""-AI-powered scientific schematic generation using Nano Banana 2.--This script uses a smart iterative refinement approach:-1. Generate initial image with Nano Banana 2-2. AI quality review using Gemini 3.1 Pro Preview for scientific critique-3. Only regenerate if quality is below threshold for document type-4. Repeat until quality meets standards (max iterations)--Requirements:- - OPENROUTER_API_KEY environment variable- - requests library--Usage:- python generate_schematic_ai.py "Create a flowchart showing CONSORT participant flow" -o flowchart.png- python generate_schematic_ai.py "Neural network architecture diagram" -o architecture.png --iterations 2- python generate_schematic_ai.py "Simple block diagram" -o diagram.png --doc-type poster-"""--import argparse-import base64-import json-import os-import sys-import time-from pathlib import Path-from typing import Optional, Dict, Any, List, Tuple--try:- import requests-except ImportError:- print("Error: requests library not found. Install with: pip install requests")- sys.exit(1)--# Try to load .env file from multiple potential locations-def _load_env_file():- """Load .env file from current directory or script directory only."""- try:- from dotenv import load_dotenv- except ImportError:- return False-- for candidate in [Path.cwd() / ".env", Path(__file__).resolve().parent / ".env"]:- if candidate.exists():- load_dotenv(dotenv_path=candidate, override=False)- return True-- return False---class ScientificSchematicGenerator:- """Generate scientific schematics using AI with smart iterative refinement.-- Uses Gemini 3.1 Pro Preview for quality review to determine if regeneration is needed.- Multiple passes only occur if the generated schematic doesn't meet the- quality threshold for the target document type.- """-- # Quality thresholds by document type (score out of 10)- # Higher thresholds for more formal publications- QUALITY_THRESHOLDS = {- "journal": 8.5, # Nature, Science, etc. - highest standards- "conference": 8.0, # Conference papers - high standards- "poster": 7.0, # Academic posters - good quality- "presentation": 6.5, # Slides/talks - clear but less formal- "report": 7.5, # Technical reports - professional- "grant": 8.0, # Grant proposals - must be compelling- "thesis": 8.0, # Dissertations - formal academic- "preprint": 7.5, # arXiv, etc. - good quality- "default": 7.5, # Default threshold- }-- # Scientific diagram best practices prompt template- SCIENTIFIC_DIAGRAM_GUIDELINES = """-Create a high-quality scientific diagram with these requirements:--VISUAL QUALITY:-- Clean white or light background (no textures or gradients)-- High contrast for readability and printing-- Professional, publication-ready appearance-- Sharp, clear lines and text-- Adequate spacing between elements to prevent crowding--TYPOGRAPHY:-- Clear, readable sans-serif fonts (Arial, Helvetica style)-- Minimum 10pt font size for all labels-- Consistent font sizes throughout-- All text horizontal or clearly readable-- No overlapping text--SCIENTIFIC STANDARDS:-- Accurate representation of concepts-- Clear labels for all components-- Include scale bars, legends, or axes where appropriate-- Use standard scientific notation and symbols-- Include units where applicable--ACCESSIBILITY:-- Colorblind-friendly color palette (use Okabe-Ito colors if using color)-- High contrast between elements-- Redundant encoding (shapes + colors, not just colors)-- Works well in grayscale--LAYOUT:-- Logical flow (left-to-right or top-to-bottom)-- Clear visual hierarchy-- Balanced composition-- Appropriate use of whitespace-- No clutter or unnecessary decorative elements--IMPORTANT - NO FIGURE NUMBERS:-- Do NOT include "Figure 1:", "Fig. 1", or any figure numbering in the image-- Do NOT add captions or titles like "Figure: ..." at the top or bottom-- Figure numbers and captions are added separately in the document/LaTeX-- The diagram should contain only the visual content itself-"""-- def __init__(self, api_key: Optional[str] = None, verbose: bool = False):- """- Initialize the generator.-- Args:- api_key: OpenRouter API key (or use OPENROUTER_API_KEY env var)- verbose: Print detailed progress information- """- # Priority: 1) explicit api_key param, 2) environment variable, 3) .env file- self.api_key = api_key or os.getenv("OPENROUTER_API_KEY")-- # If not found in environment, try loading from .env file- if not self.api_key:- _load_env_file()- self.api_key = os.getenv("OPENROUTER_API_KEY")-- if not self.api_key:- raise ValueError(- "OPENROUTER_API_KEY not found. Please either:\n"- " 1. Set the OPENROUTER_API_KEY environment variable\n"- " 2. Add OPENROUTER_API_KEY to your .env file\n"- " 3. Pass api_key parameter to the constructor\n"- "Get your API key from: https://openrouter.ai/keys"- )-- self.verbose = verbose- self._last_error = None # Track last error for better reporting- self.base_url = "https://openrouter.ai/api/v1"- # Nano Banana 2 - Google's advanced image generation model- # https://openrouter.ai/google/gemini-3-pro-image-preview- self.image_model = "google/gemini-3.1-flash-image-preview"- # Gemini 3.1 Pro Preview for quality review - excellent vision and reasoning- self.review_model = "google/gemini-3.1-pro-preview"-- def _log(self, message: str):- """Log message if verbose mode is enabled."""- if self.verbose:- print(f"[{time.strftime('%H:%M:%S')}] {message}")-- def _make_request(self, model: str, messages: List[Dict[str, Any]],- modalities: Optional[List[str]] = None) -> Dict[str, Any]:- """- Make a request to OpenRouter API.-- Args:- model: Model identifier- messages: List of message dictionaries- modalities: Optional list of modalities (e.g., ["image", "text"])-- Returns:- API response as dictionary- """- headers = {- "Authorization": f"Bearer {self.api_key}",- "Content-Type": "application/json",- "HTTP-Referer": "https://github.com/scientific-writer",- "X-Title": "Scientific Schematic Generator"- }-- payload = {- "model": model,- "messages": messages- }-- if modalities:- payload["modalities"] = modalities-- self._log(f"Making request to {model}...")-- try:- response = requests.post(- f"{self.base_url}/chat/completions",- headers=headers,- json=payload,- timeout=120- )-- # Try to get response body even on error- try:- response_json = response.json()- except json.JSONDecodeError:- response_json = {"raw_text": response.text[:500]}-- # Check for HTTP errors but include response body in error message- if response.status_code != 200:- error_detail = response_json.get("error", response_json)- self._log(f"HTTP {response.status_code}: {error_detail}")- raise RuntimeError(f"API request failed (HTTP {response.status_code}): {error_detail}")-- return response_json- except requests.exceptions.Timeout:- raise RuntimeError("API request timed out after 120 seconds")- except requests.exceptions.RequestException as e:- raise RuntimeError(f"API request failed: {str(e)}")-- def _extract_image_from_response(self, response: Dict[str, Any]) -> Optional[bytes]:- """- Extract base64-encoded image from API response.-- For Nano Banana 2, images are returned in the 'images' field of the message,- not in the 'content' field.-- Args:- response: API response dictionary-- Returns:- Image bytes or None if not found- """- try:- choices = response.get("choices", [])- if not choices:- self._log("No choices in response")- return None-- message = choices[0].get("message", {})-- # IMPORTANT: Nano Banana 2 returns images in the 'images' field- images = message.get("images", [])- if images and len(images) > 0:- self._log(f"Found {len(images)} image(s) in 'images' field")-- # Get first image- first_image = images[0]- if isinstance(first_image, dict):- # Extract image_url- if first_image.get("type") == "image_url":- url = first_image.get("image_url", {})- if isinstance(url, dict):- url = url.get("url", "")-- if url and url.startswith("data:image"):- # Extract base64 data after comma- if "," in url:- base64_str = url.split(",", 1)[1]- # Clean whitespace- base64_str = base64_str.replace('\n', '').replace('\r', '').replace(' ', '')- self._log(f"Extracted base64 data (length: {len(base64_str)})")- return base64.b64decode(base64_str)-- # Fallback: check content field (for other models or future changes)- content = message.get("content", "")-- if self.verbose:- self._log(f"Content type: {type(content)}, length: {len(str(content))}")-- # 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(' ', '')- self._log(f"Found image in content field (length: {len(base64_str)})")- return base64.b64decode(base64_str)-- # Handle list content- if isinstance(content, list):- for i, block in enumerate(content):- if isinstance(block, dict) and block.get("type") == "image_url":- url = block.get("image_url", {})- if isinstance(url, dict):- url = url.get("url", "")- if url and url.startswith("data:image") and "," in url:- base64_str = url.split(",", 1)[1].replace('\n', '').replace('\r', '').replace(' ', '')- self._log(f"Found image in content block {i}")- return base64.b64decode(base64_str)-- self._log("No image data found in response")- return None-- except Exception as e:- self._log(f"Error extracting image: {str(e)}")- import traceback- if self.verbose:- traceback.print_exc()- return None-- def _image_to_base64(self, image_path: str) -> str:- """- Convert image file to base64 data URL.-- Args:- image_path: Path to image file-- Returns:- Base64 data URL string- """- with open(image_path, "rb") as f:- image_data = f.read()-- # Determine image type from extension- ext = Path(image_path).suffix.lower()- mime_type = {- ".png": "image/png",- ".jpg": "image/jpeg",- ".jpeg": "image/jpeg",- ".gif": "image/gif",- ".webp": "image/webp"- }.get(ext, "image/png")-- base64_data = base64.b64encode(image_data).decode("utf-8")- return f"data:{mime_type};base64,{base64_data}"-- def generate_image(self, prompt: str) -> Optional[bytes]:- """- Generate an image using Nano Banana 2.-- Args:- prompt: Description of the diagram to generate-- Returns:- Image bytes or None if generation failed- """- self._last_error = None # Reset error-- messages = [- {- "role": "user",- "content": prompt- }- ]-- try:- response = self._make_request(- model=self.image_model,- messages=messages,- modalities=["image", "text"]- )-- # Debug: print response structure if verbose- if self.verbose:- self._log(f"Response keys: {response.keys()}")- if "error" in response:- self._log(f"API Error: {response['error']}")- if "choices" in response and response["choices"]:- msg = response["choices"][0].get("message", {})- self._log(f"Message keys: {msg.keys()}")- # Show content preview without printing huge base64 data- content = msg.get("content", "")- if isinstance(content, str):- preview = content[:200] + "..." if len(content) > 200 else content- self._log(f"Content preview: {preview}")- elif isinstance(content, list):- self._log(f"Content is list with {len(content)} items")- for i, item in enumerate(content[:3]):- if isinstance(item, dict):- self._log(f" Item {i}: type={item.get('type')}")-- # Check for API errors in response- if "error" in response:- error_msg = response["error"]- if isinstance(error_msg, dict):- error_msg = error_msg.get("message", str(error_msg))- self._last_error = f"API Error: {error_msg}"- print(f"✗ {self._last_error}")- return None-- image_data = self._extract_image_from_response(response)- if image_data:- self._log(f"✓ Generated image ({len(image_data)} bytes)")- else:- self._last_error = "No image data in API response - model may not support image generation"- self._log(f"✗ {self._last_error}")- # Additional debug info when image extraction fails- if self.verbose and "choices" in response:- msg = response["choices"][0].get("message", {})- self._log(f"Full message structure: {json.dumps({k: type(v).__name__ for k, v in msg.items()})}")-- return image_data- except RuntimeError as e:- self._last_error = str(e)- self._log(f"✗ Generation failed: {self._last_error}")- return None- except Exception as e:- self._last_error = f"Unexpected error: {str(e)}"- self._log(f"✗ Generation failed: {self._last_error}")- import traceback- if self.verbose:- traceback.print_exc()- return None-- def review_image(self, image_path: str, original_prompt: str,- iteration: int, doc_type: str = "default",- max_iterations: int = 2) -> Tuple[str, float, bool]:- """- Review generated image using Gemini 3.1 Pro Preview for quality analysis.-- Uses Gemini 3.1 Pro Preview's superior vision and reasoning capabilities to- evaluate the schematic quality and determine if regeneration is needed.-- 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)- """- # Use Gemini 3.1 Pro Preview for review - excellent vision and analysis- image_data_url = self._image_to_base64(image_path)-- # Get quality threshold for this document type- threshold = self.QUALITY_THRESHOLDS.get(doc_type.lower(),- self.QUALITY_THRESHOLDS["default"])-- review_prompt = f"""You are an expert reviewer evaluating a scientific diagram for publication quality.--ORIGINAL REQUEST: {original_prompt}--DOCUMENT TYPE: {doc_type} (quality threshold: {threshold}/10)-ITERATION: {iteration}/{max_iterations}--Carefully evaluate this diagram on these criteria:--1. **Scientific Accuracy** (0-2 points)- - Correct representation of concepts- - Proper notation and symbols- - Accurate relationships shown--2. **Clarity and Readability** (0-2 points)- - Easy to understand at a glance- - Clear visual hierarchy- - No ambiguous elements--3. **Label Quality** (0-2 points)- - All important elements labeled- - Labels are readable (appropriate font size)- - Consistent labeling style--4. **Layout and Composition** (0-2 points)- - Logical flow (top-to-bottom or left-to-right)- - Balanced use of space- - No overlapping elements--5. **Professional Appearance** (0-2 points)- - Publication-ready quality- - Clean, crisp lines and shapes- - Appropriate colors/contrast--RESPOND IN THIS EXACT FORMAT:-SCORE: [total score 0-10]--STRENGTHS:-- [strength 1]-- [strength 2]--ISSUES:-- [issue 1 if any]-- [issue 2 if any]--VERDICT: [ACCEPTABLE or NEEDS_IMPROVEMENT]--If score >= {threshold}, the diagram is ACCEPTABLE for {doc_type} publication.-If score < {threshold}, mark as NEEDS_IMPROVEMENT with specific suggestions."""-- messages = [- {- "role": "user",- "content": [- {- "type": "text",- "text": review_prompt- },- {- "type": "image_url",- "image_url": {- "url": image_data_url- }- }- ]- }- ]-- try:- # Use Gemini 3.1 Pro Preview 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-- message = choices[0].get("message", {})- content = message.get("content", "")-- # Check reasoning field (Nano Banana 2 puts analysis here)- reasoning = message.get("reasoning", "")- if reasoning and not content:- content = reasoning-- if isinstance(content, list):- # Extract text from content blocks- 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)-- # 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)")- self._log(f" Verdict: {'Needs improvement' if needs_improvement else 'Acceptable'}")-- return (content if content else "Image generated successfully",- score,- needs_improvement)- 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-- def improve_prompt(self, original_prompt: str, critique: str,- iteration: int) -> str:- """- Improve the generation prompt based on critique.-- Args:- original_prompt: Original user prompt- critique: Review critique from previous iteration- iteration: Current iteration number-- Returns:- Improved prompt for next generation- """- improved_prompt = f"""{self.SCIENTIFIC_DIAGRAM_GUIDELINES}--USER REQUEST: {original_prompt}--ITERATION {iteration}: Based on previous feedback, address these specific improvements:-{critique}--Generate an improved version that addresses all the critique points while maintaining scientific accuracy and professional quality."""-- return improved_prompt-- def generate_iterative(self, user_prompt: str, output_path: str,- iterations: int = 2,- doc_type: str = "default") -> Dict[str, Any]:- """- Generate scientific schematic with smart iterative refinement.-- Only regenerates if the quality score is below the threshold for the- specified document type. This saves API calls and time when the first- generation is already good enough.-- Args:- user_prompt: User's description of desired diagram- output_path: Path to save final image- iterations: Maximum refinement iterations (default: 2, max: 2)- doc_type: Document type for quality threshold (journal, poster, etc.)-- Returns:- Dictionary with generation results and metadata- """- output_path = Path(output_path)- output_dir = output_path.parent- output_dir.mkdir(parents=True, exist_ok=True)-- base_name = output_path.stem- extension = output_path.suffix or ".png"-- # Get quality threshold for this document type- threshold = self.QUALITY_THRESHOLDS.get(doc_type.lower(),- self.QUALITY_THRESHOLDS["default"])-- results = {- "user_prompt": user_prompt,- "doc_type": doc_type,- "quality_threshold": threshold,- "iterations": [],- "final_image": None,- "final_score": 0.0,- "success": False,- "early_stop": False,- "early_stop_reason": None- }-- current_prompt = f"""{self.SCIENTIFIC_DIAGRAM_GUIDELINES}--USER REQUEST: {user_prompt}--Generate a publication-quality scientific diagram that meets all the guidelines above."""-- print(f"\n{'='*60}")- print(f"Generating Scientific Schematic")- print(f"{'='*60}")- print(f"Description: {user_prompt}")- print(f"Document Type: {doc_type}")- print(f"Quality Threshold: {threshold}/10")- print(f"Max Iterations: {iterations}")- print(f"Output: {output_path}")- print(f"{'='*60}\n")-- for i in range(1, iterations + 1):- print(f"\n[Iteration {i}/{iterations}]")- print("-" * 40)-- # Generate image- print(f"Generating image...")- image_data = self.generate_image(current_prompt)-- if not image_data:- error_msg = getattr(self, '_last_error', 'Image generation failed - no image data returned')- print(f"✗ Generation failed: {error_msg}")- results["iterations"].append({- "iteration": i,- "success": False,- "error": error_msg- })- continue-- # Save iteration image- iter_path = output_dir / f"{base_name}_v{i}{extension}"- with open(iter_path, "wb") as f:- f.write(image_data)- print(f"✓ Saved: {iter_path}")-- # Review image using Gemini 3.1 Pro Preview- print(f"Reviewing image with Gemini 3.1 Pro Preview...")- critique, score, needs_improvement = self.review_image(- str(iter_path), user_prompt, i, doc_type, iterations- )- print(f"✓ Score: {score}/10 (threshold: {threshold}/10)")-- # Save iteration results- iteration_result = {- "iteration": i,- "image_path": str(iter_path),- "prompt": current_prompt,- "critique": critique,- "score": score,- "needs_improvement": 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!")- results["final_image"] = str(iter_path)- results["final_score"] = score- results["success"] = True- results["early_stop"] = True- results["early_stop_reason"] = f"Quality score {score} meets threshold {threshold} for {doc_type}"- 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["success"] = True- break-- # Quality below threshold - improve prompt for next iteration- print(f"\n⚠ Quality below threshold ({score} < {threshold})")- print(f"Improving prompt based on feedback...")- current_prompt = self.improve_prompt(user_prompt, critique, i + 1)-- # Copy final version to output path- if results["success"] and results["final_image"]:- final_iter_path = Path(results["final_image"])- if final_iter_path != output_path:- import shutil- shutil.copy(final_iter_path, output_path)- print(f"\n✓ Final image: {output_path}")-- # Save review log- log_path = output_dir / f"{base_name}_review_log.json"- with open(log_path, "w") as f:- json.dump(results, f, indent=2)- print(f"✓ Review log: {log_path}")-- print(f"\n{'='*60}")- print(f"Generation Complete!")- print(f"Final Score: {results['final_score']}/10")- 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")-- return results---def main():- """Command-line interface."""- parser = argparse.ArgumentParser(- description="Generate scientific schematics using AI with smart iterative refinement",- formatter_class=argparse.RawDescriptionHelpFormatter,- epilog="""-Examples:- # Generate a flowchart for a journal paper- python generate_schematic_ai.py "CONSORT participant flow diagram" -o flowchart.png --doc-type journal-- # Generate neural network architecture for presentation (lower threshold)- python generate_schematic_ai.py "Transformer encoder-decoder architecture" -o transformer.png --doc-type presentation-- # Generate with custom max iterations for poster- python generate_schematic_ai.py "Biological signaling pathway" -o pathway.png --iterations 2 --doc-type poster-- # Verbose output- python generate_schematic_ai.py "Circuit diagram" -o circuit.png -v--Document Types (quality thresholds):- journal 8.5/10 - Nature, Science, peer-reviewed journals- conference 8.0/10 - Conference papers- thesis 8.0/10 - Dissertations, theses- grant 8.0/10 - Grant proposals- preprint 7.5/10 - arXiv, bioRxiv, etc.- report 7.5/10 - Technical reports- poster 7.0/10 - Academic posters- presentation 6.5/10 - Slides, talks- default 7.5/10 - General purpose--Note: Multiple iterations only occur if quality is BELOW the threshold.- If the first generation meets the threshold, no extra API calls are made.--Environment:- OPENROUTER_API_KEY OpenRouter API key (required)- """- )-- parser.add_argument("prompt", help="Description of the diagram to generate")- parser.add_argument("-o", "--output", required=True,- help="Output image path (e.g., diagram.png)")- parser.add_argument("--iterations", type=int, default=2,- help="Maximum refinement iterations (default: 2, max: 2)")- parser.add_argument("--doc-type", default="default",- choices=["journal", "conference", "poster", "presentation",- "report", "grant", "thesis", "preprint", "default"],- help="Document type for quality threshold (default: default)")- parser.add_argument("--api-key", help="OpenRouter API key (or set OPENROUTER_API_KEY)")- parser.add_argument("-v", "--verbose", action="store_true",- help="Verbose output")-- args = parser.parse_args()-- # Check for API key- api_key = args.api_key or os.getenv("OPENROUTER_API_KEY")- if not api_key:- print("Error: OPENROUTER_API_KEY environment variable not set")- print("\nSet it with:")- print(" export OPENROUTER_API_KEY='your_api_key'")- print("\nOr provide via --api-key flag")- sys.exit(1)-- # Validate iterations - enforce max of 2- if args.iterations < 1 or args.iterations > 2:- print("Error: Iterations must be between 1 and 2")- sys.exit(1)-- try:- generator = ScientificSchematicGenerator(api_key=api_key, verbose=args.verbose)- results = generator.generate_iterative(- user_prompt=args.prompt,- output_path=args.output,- iterations=args.iterations,- doc_type=args.doc_type- )-- 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)")- sys.exit(0)- else:- print(f"\n✗ Generation failed. Check review log for details.")- sys.exit(1)- except Exception as e:- print(f"\n✗ Error: {str(e)}")- sys.exit(1)---if __name__ == "__main__":- main()-diff --git a/skills/stable-baselines3/SKILL.md b/skills/stable-baselines3/SKILL.mdindex fbf215f8..0f255ff4 100644--- a/skills/stable-baselines3/SKILL.md+++ b/skills/stable-baselines3/SKILL.md@@ -2,8 +2,10 @@name: stable-baselines3description: Production-ready reinforcement learning algorithms (PPO, SAC, DQN, TD3, DDPG, A2C) with scikit-learn-like API. Use for standard RL experiments, quick prototyping, and well-documented algorithm implementations. Best for single-agent RL with Gymnasium environments. For high-performance parallel training, multi-agent systems, or custom vectorized environments, use pufferlib instead.license: MIT license+allowed-tools: Read Write Edit Bash+compatibility: Requires Python 3.10+, PyTorch >= 2.3, and stable-baselines3 2.8+. Gymnasium environments; optional extras for TensorBoard and Atari (ale-py).metadata:- version: "1.0"+ version: "1.1"skill-author: K-Dense Inc.---@@ -13,6 +15,41 @@ metadata:Stable Baselines3 (SB3) is a PyTorch-based library providing reliable implementations of reinforcement learning algorithms. This skill provides comprehensive guidance for training RL agents, creating custom environments, implementing callbacks, and optimizing training workflows using SB3's unified API.+**Current upstream:** SB3 **2.8.0** (April 2026). Docs: [stable-baselines3.readthedocs.io](https://stable-baselines3.readthedocs.io/en/master/).++## Installation++Tested against **stable-baselines3 2.8.0**. Requires **Python 3.10+** (3.9 dropped in 2.8.0) and **PyTorch >= 2.3**.++```bash+# Basic installation+uv pip install "stable-baselines3>=2.8"++# With extra dependencies (TensorBoard, ale-py for Atari, etc.)+uv pip install "stable-baselines3[extra]>=2.8"+```++On zsh, quote brackets: `uv pip install 'stable-baselines3[extra]>=2.8'`.++For MuJoCo continuous-control benchmarks:++```bash+uv pip install "gymnasium[mujoco]"+```++Check your version:++```python+import stable_baselines3+print(stable_baselines3.__version__)+```++## Related Projects++- **[SB3-Contrib](https://github.com/Stable-Baselines-Team/stable-baselines3-contrib)**: experimental algorithms (MaskablePPO, CrossQ, QR-DQN, RecurrentPPO) — separate `sb3-contrib` package+- **[RL Baselines3 Zoo](https://github.com/DLR-RM/rl-baselines3-zoo)**: pre-trained agents, hyperparameters, training scripts+- **[SBX](https://github.com/araffin/sbx)**: SB3 + JAX implementations for users who prefer JAX over PyTorch+## Core Capabilities### 1. Training RL Agents@@ -26,7 +63,7 @@ from stable_baselines3 import PPO# Create environmentenv = gym.make("CartPole-v1")-# Initialize agent+# Initialize agent (device="cpu" is often faster for MlpPolicy on small envs)model = PPO("MlpPolicy", env, verbose=1)# Train the agent@@ -271,7 +308,7 @@ model.learn(total_timesteps=10000)- **Memory errors**: Reduce `buffer_size` for off-policy algorithms or use fewer parallel environments- **Slow training**: Consider SubprocVecEnv for parallel environments- **Unstable training**: Try different algorithms, tune hyperparameters, or check reward scaling-- **Import errors**: Ensure `stable_baselines3` is installed: `uv pip install stable-baselines3[extra]`+- **Import errors**: Ensure `stable_baselines3` is installed: `uv pip install 'stable-baselines3[extra]>=2.8'`## Resources@@ -286,13 +323,3 @@ model.learn(total_timesteps=10000)- `callbacks.md`: Complete callback system reference- `vectorized_envs.md`: Vectorized environment usage and wrappers-## Installation--```bash-# Basic installation-uv pip install stable-baselines3--# With extra dependencies (Tensorboard, etc.)-uv pip install stable-baselines3[extra]-```-diff --git a/skills/stable-baselines3/references/algorithms.md b/skills/stable-baselines3/references/algorithms.mdindex 9cbc23b7..f9ade5e2 100644--- a/skills/stable-baselines3/references/algorithms.md+++ b/skills/stable-baselines3/references/algorithms.md@@ -172,8 +172,8 @@ This document provides detailed characteristics of all RL algorithms in Stable B- `exploration_final_eps`: 0.05**Variants:**-- **QR-DQN**: Distributional RL version for better value estimates-- **Maskable DQN**: For environments with action masking+- **QR-DQN**: Distributional RL version for better value estimates (SB3-Contrib)+- **Maskable DQN**: For environments with action masking (SB3-Contrib)### HER (Hindsight Experience Replay)@@ -278,6 +278,7 @@ model = PPO(n_epochs=10,learning_rate=3e-4,gamma=0.99,+ device="cpu", # Often faster than GPU for small MLP tasks)```@@ -311,12 +312,12 @@ model = SAC(## Performance Benchmarks-Approximate expected performance (mean reward) on common benchmarks:+Approximate expected performance (mean reward) on common benchmarks. Numbers are **indicative only** — actual results vary significantly with hyperparameters, training time, and random seed.-### Continuous Control (MuJoCo)-- **HalfCheetah-v3**: PPO ~1800, SAC ~12000, TD3 ~9500-- **Hopper-v3**: PPO ~2500, SAC ~3600, TD3 ~3600-- **Walker2d-v3**: PPO ~3000, SAC ~5500, TD3 ~5000+### Continuous Control (MuJoCo, Gymnasium v4)+- **HalfCheetah-v4**: PPO ~1800, SAC ~12000, TD3 ~9500+- **Hopper-v4**: PPO ~2500, SAC ~3600, TD3 ~3600+- **Walker2d-v4**: PPO ~3000, SAC ~5500, TD3 ~5000### Discrete Control (Atari)- **Breakout**: PPO ~400, DQN ~300@@ -325,9 +326,23 @@ Approximate expected performance (mean reward) on common benchmarks:*Note: Performance varies significantly with hyperparameters and training time.*+## SB3-Contrib (Experimental Algorithms)++These algorithms live in the separate **[sb3-contrib](https://github.com/Stable-Baselines-Team/stable-baselines3-contrib)** package, not core SB3:++| Algorithm | Use Case |+|-----------|----------|+| **MaskablePPO** | Discrete actions with action masking (invalid moves masked out) |+| **CrossQ** | Continuous control; sample-efficient off-policy (added SB3-Contrib 2.4+) |+| **QR-DQN** | Distributional DQN for better value estimates |+| **RecurrentPPO** | Partial observability (POMDP) with LSTM policy |+| **TQC** | Continuous control with distributional critics |++Install with `uv pip install sb3-contrib`.+## Additional Resources- **RL Baselines3 Zoo**: Collection of pre-trained agents and hyperparameters: https://github.com/DLR-RM/rl-baselines3-zoo- **Hyperparameter Tuning**: Use Optuna for systematic tuning- **Custom Policies**: Extend base policies for custom network architectures-- **Contribution Repo**: SB3-Contrib for experimental algorithms (QR-DQN, TQC, etc.)+- **PPO + MlpPolicy on CPU**: For small MLP tasks (CartPole, Pendulum), `device="cpu"` often trains faster than GPUdiff --git a/skills/stable-baselines3/references/callbacks.md b/skills/stable-baselines3/references/callbacks.mdindex 78a40561..64dce99a 100644--- a/skills/stable-baselines3/references/callbacks.md+++ b/skills/stable-baselines3/references/callbacks.md@@ -41,7 +41,8 @@ model.learn(total_timesteps=100000, callback=eval_callback)- Logs evaluation metrics to TensorBoard- Can stop training if reward threshold reached-**Important:** When using vectorized training environments, adjust `eval_freq`:+**Important:** Callback frequencies (`eval_freq`, `save_freq`) are measured in **environment steps per sub-environment**, not total timesteps across all parallel envs. Divide by `n_envs` to align with total training timesteps:+```python# With 4 parallel environments, divide eval_freq by n_envseval_freq = 10000 // 4 # Evaluate every 10000 total environment steps@@ -71,7 +72,21 @@ model.learn(total_timesteps=100000, callback=checkpoint_callback)- `rl_model_20000_steps.zip` - Model at 20k steps- etc.-**Important:** Adjust `save_freq` for vectorized environments (divide by n_envs).+**Important:** `save_freq` is in **environment steps per sub-environment**; divide by `n_envs` for total-timestep alignment (same as `EvalCallback` above).++### LogEveryNTimesteps++Dumps training logs every N timesteps (added SB3 2.6.0). Useful when the algorithm's built-in `log_interval` is too coarse.++```python+from stable_baselines3.common.callbacks import LogEveryNTimesteps++log_callback = LogEveryNTimesteps(n_steps=1000)++# Pass log_interval=None to avoid interference with the algorithm's default logging+model = PPO("MlpPolicy", env, log_interval=None, verbose=1)+model.learn(total_timesteps=100000, callback=log_callback)+```### StopTrainingOnRewardThresholddiff --git a/skills/stable-baselines3/references/custom_environments.md b/skills/stable-baselines3/references/custom_environments.mdindex a0437066..ef48715f 100644--- a/skills/stable-baselines3/references/custom_environments.md+++ b/skills/stable-baselines3/references/custom_environments.md@@ -183,6 +183,8 @@ For multiple discrete variables.self.action_space = spaces.MultiDiscrete([3, 4])```+**Important (SB3 2.8+ env checker):** If your `MultiDiscrete` space uses multi-dimensional arrays (not a flat vector), the env checker will warn you. Use a wrapper to flatten the space or reshape observations/actions to match SB3's expected 1D layout. See the [SB3 custom env guide](https://stable-baselines3.readthedocs.io/en/master/guide/custom_env.html) for the recommended wrapper pattern.+### MultiBinaryFor binary vectors.diff --git a/skills/stable-baselines3/references/vectorized_envs.md b/skills/stable-baselines3/references/vectorized_envs.mdindex b47a63ad..b197b51d 100644--- a/skills/stable-baselines3/references/vectorized_envs.md+++ b/skills/stable-baselines3/references/vectorized_envs.md@@ -113,6 +113,10 @@ obs = env.reset() # Returns only observations (numpy array)infos = env.reset_infos```+**Seeding and options:** Call `vec_env.seed(seed=seed)` and/or `vec_env.set_options(options)` before the initial `reset()`. Seed and options are discarded after each `reset()` call.++**Truncation vs termination:** When an episode ends, check `infos[env_idx]["TimeLimit.truncated"]` to distinguish timeout/truncation from natural termination. Bootstrap value targets when `TimeLimit.truncated` is True or when the episode has not ended.+### step()**Standard Gym:**@@ -383,6 +387,14 @@ env.set_attr("difficulty", "hard")env.set_attr("max_steps", 1000, indices=[1, 3])```+### Checking Attributes++```python+# Check if attribute exists on all sub-environments (added SB3 2.6.0)+if env.has_attr("current_level"):+ levels = env.get_attr("current_level")+```+## Performance Optimization### Choosing Number of Environmentsdiff --git a/skills/stable-baselines3/scripts/train_rl_agent.py b/skills/stable-baselines3/scripts/train_rl_agent.pyindex baaa39ab..fdf25a88 100644--- a/skills/stable-baselines3/scripts/train_rl_agent.py+++ b/skills/stable-baselines3/scripts/train_rl_agent.py@@ -157,7 +157,7 @@ if __name__ == "__main__":# Example: Train DQN on discrete task# from stable_baselines3 import DQN# train_agent(- # env_id="LunarLander-v2",+ # env_id="LunarLander-v3",# algorithm=DQN,# policy="MlpPolicy",# n_envs=1, # DQN typically uses single envdiff --git a/skills/sympy/SKILL.md b/skills/sympy/SKILL.mdindex 6b513ef8..ca17c761 100644--- a/skills/sympy/SKILL.md+++ b/skills/sympy/SKILL.md@@ -1,9 +1,11 @@---name: sympy-description: Use this skill when working with symbolic mathematics in Python. This skill should be used for symbolic computation tasks including solving equations algebraically, performing calculus operations (derivatives, integrals, limits), manipulating algebraic expressions, working with matrices symbolically, physics calculations, number theory problems, geometry computations, and generating executable code from mathematical expressions. Apply this skill when the user needs exact symbolic results rather than numerical approximations, or when working with mathematical formulas that contain variables and parameters.+description: Use when you need exact symbolic math in Python — algebra, calculus, equation solving, symbolic linear algebra, or code generation via lambdify/LaTeX. Prefer NumPy or SciPy when floating-point approximations are sufficient.license: https://github.com/sympy/sympy/blob/master/LICENSE+allowed-tools: Read Write Edit Bash+compatibility: Requires Python 3.9+ and SymPy 1.14+. Optional NumPy/SciPy/Matplotlib for lambdify examples; C/Fortran compiler for autowrap/codegen.metadata:- version: "1.0"+ version: "1.1"skill-author: K-Dense Inc.---@@ -13,6 +15,25 @@ metadata:SymPy is a Python library for symbolic mathematics that enables exact computation using mathematical symbols rather than numerical approximations. This skill provides comprehensive guidance for performing symbolic algebra, calculus, linear algebra, equation solving, physics calculations, and code generation using SymPy.+## Installation++Tested against **SymPy 1.14.0** (stable; April 2025). Requires **Python 3.9+**.++```bash+# Install SymPy using uv+uv pip install "sympy>=1.14"++# Optional: for lambdify and plotting examples+uv pip install numpy scipy matplotlib+```++Check your version:++```python+import sympy+print(sympy.__version__)+```+## When to Use This SkillUse this skill when:@@ -161,9 +182,9 @@ cross(v1, v2) # Cross product**Quantum mechanics:**```python-from sympy.physics.quantum import Ket, Bra, Commutator+from sympy.physics.quantum import Ket, Bra, Operator, Commutator+A, B = Operator('A'), Operator('B')psi = Ket('psi')-A = Operator('A')comm = Commutator(A, B).doit()```diff --git a/skills/sympy/references/code-generation-printing.md b/skills/sympy/references/code-generation-printing.mdindex 2387b835..a54763e7 100644--- a/skills/sympy/references/code-generation-printing.md+++ b/skills/sympy/references/code-generation-printing.md@@ -202,7 +202,10 @@ sstr(expr) # 'sin(x)**2'# Reproducible representationsrepr(expr) # "Pow(sin(Symbol('x')), Integer(2))"-# This can be eval()'ed to recreate the expression++# Reconstruct from srepr via sympify (supported round-trip pattern)+from sympy import sympify+restored = sympify(srepr(expr))```### Custom Printing@@ -336,26 +339,46 @@ def plot_expr(a):## Converting Between Representations+### Parsing untrusted input++**Security warning:** `parse_expr()` uses `eval` internally and must not be called on unsanitized user input. See the [SymPy parsing docs](https://docs.sympy.org/latest/modules/parsing.html). Prefer building expressions from typed values (`symbols()`, `Integer()`, operators) or a validated grammar. Never use Python `eval()` on `srepr()` output or parsed strings.++For trusted/local strings only, use restricted parsing:++```python+from sympy.parsing.sympy_parser import parse_expr, standard_transformations+from sympy import symbols++x, y = symbols('x y')+local_dict = {'x': x, 'y': y}++# Restrict to standard_transformations only (no 'all' or implicit multiplication)+expr = parse_expr('x**2 + 2*x + 1', local_dict=local_dict,+ transformations=standard_transformations)+```++If you must accept interactive input, validate first: limit length, allow only math characters, and reject strings containing `__`, `import`, `=`, or assignment syntax.+### String to SymPy```python-from sympy.parsing.sympy_parser import parse_expr+from sympy.parsing.sympy_parser import parse_expr, standard_transformationsfrom sympy import symbolsx, y = symbols('x y')+local_dict = {'x': x, 'y': y}-# Parse string to expression-expr = parse_expr('x**2 + 2*x + 1')-expr = parse_expr('sin(x) + cos(y)')+# Parse trusted string literals (not raw user input)+expr = parse_expr('x**2 + 2*x + 1', local_dict=local_dict,+ transformations=standard_transformations)+expr = parse_expr('sin(x) + cos(y)', local_dict=local_dict,+ transformations=standard_transformations)-# With transformations-from sympy.parsing.sympy_parser import (- standard_transformations,- implicit_multiplication_application-)+# Implicit multiplication — trusted input only+from sympy.parsing.sympy_parser import implicit_multiplication_applicationtransformations = standard_transformations + (implicit_multiplication_application,)-expr = parse_expr('2x', transformations=transformations) # Treats '2x' as 2*x+expr = parse_expr('2x', local_dict={'x': x}, transformations=transformations)```### LaTeX to SymPy@@ -517,23 +540,29 @@ with open('document.tex', 'w') as f:f.write(latex_doc)```-### Pattern 3: Interactive Computation+### Pattern 3: Interactive Computation (trusted input only)```python-from sympy import symbols, simplify, expand-from sympy.parsing.sympy_parser import parse_expr+import re+from sympy import symbols, simplify, expand, latex+from sympy.parsing.sympy_parser import parse_expr, standard_transformationsx, y = symbols('x y')+local_dict = {'x': x, 'y': y}++def parse_trusted_expr(s: str):+ """Validate and parse a restricted math expression."""+ if len(s) > 200 or re.search(r'__|import|=|\(', s):+ raise ValueError("Invalid expression")+ return parse_expr(s, local_dict=local_dict,+ transformations=standard_transformations)-# Interactive input-user_input = input("Enter expression: ")-expr = parse_expr(user_input)+# Trusted local example (do not pass raw user input without validation)+expr = parse_trusted_expr('x**2 + 2*x + 1')-# Processsimplified = simplify(expr)expanded = expand(expr)-# Displayprint(f"Simplified: {simplified}")print(f"Expanded: {expanded}")print(f"LaTeX: {latex(expr)}")@@ -594,6 +623,6 @@ print(f"result = {reduced[0]}")5. **Compilation:** `autowrap` and `ufuncify` require a C/Fortran compiler and may need configuration on your system.-6. **Parsing:** When parsing user input, validate and sanitize to avoid code injection vulnerabilities.+6. **Parsing security:** `parse_expr()` calls `eval` internally — never use it on unsanitized input. Use `local_dict` with pre-defined symbols, restrict to `standard_transformations`, validate input (length, charset, reject `__` and assignment syntax), and reconstruct expressions with `sympify(srepr(expr))` instead of `eval()`. See [SymPy parsing docs](https://docs.sympy.org/latest/modules/parsing.html).7. **Jupyter:** For best results in Jupyter notebooks, call `init_printing()` at the start of your session.diff --git a/skills/sympy/references/core-capabilities.md b/skills/sympy/references/core-capabilities.mdindex c3acd57c..1238e8b5 100644--- a/skills/sympy/references/core-capabilities.md+++ b/skills/sympy/references/core-capabilities.md@@ -306,7 +306,7 @@ dsolve(Derivative(f(x), x, 2) + f(x), f(x))### Pattern 1: Building Complex Expressions Incrementally```python-from sympy import *+from sympy import symbols, simplifyx, y = symbols('x y')# Build step by stepdiff --git a/skills/torch-geometric/SKILL.md b/skills/torch-geometric/SKILL.mdindex 5b319b5c..b6326b3c 100644--- a/skills/torch-geometric/SKILL.md+++ b/skills/torch-geometric/SKILL.md@@ -1,15 +1,50 @@---name: torch-geometric-description: "Guide for building Graph Neural Networks with PyTorch Geometric (PyG). Use this skill whenever the user asks about graph neural networks, GNNs, node classification, link prediction, graph classification, message passing networks, heterogeneous graphs, neighbor sampling, or any task involving torch_geometric / PyG. Also trigger when you see imports from torch_geometric, or the user mentions graph convolutions (GCN, GAT, GraphSAGE, GIN), graph data structures, or working with relational/network data. Even if the user just says 'graph learning' or 'geometric deep learning', use this skill."+description: PyTorch Geometric (PyG) for graph neural networks — node/link/graph classification, message passing (GCN, GAT, GraphSAGE, GIN), heterogeneous graphs, neighbor sampling, and custom datasets. Use when working with torch_geometric, not for general NetworkX analytics or non-graph PyTorch models.+license: MIT license+compatibility: Requires Python 3.10+, PyTorch 2.6+, and torch-geometric 2.7.x. Optional extension wheels (pyg-lib, torch-scatter, torch-sparse, torch-cluster) must match your PyTorch/CUDA build from https://data.pyg.org/whl.metadata:- version: "1.0"+ version: "1.1"+ skill-author: K-Dense Inc.---# PyTorch Geometric (PyG)PyG is the standard library for Graph Neural Networks built on PyTorch. It provides data structures for graphs, 60+ GNN layer implementations, scalable mini-batch training, and support for heterogeneous graphs.-Install: `uv add torch_geometric` (or `uv pip install torch_geometric`; requires PyTorch). Optional: `pyg-lib`, `torch-scatter`, `torch-sparse`, `torch-cluster` for accelerated ops.+## Installation++Tested against **torch-geometric 2.7.x** (Oct 2025). Requires **Python 3.10+** and **PyTorch 2.6+**.++```bash+# 1. Install PyTorch first (match your CUDA/CPU setup — see https://pytorch.org/get-started/locally/)+uv pip install torch++# 2. Core PyG (no extension wheels required for basic usage)+uv pip install torch_geometric+```++Optional accelerated ops (`pyg-lib`, `torch-scatter`, `torch-sparse`, `torch-cluster`) are **not required** for basic PyG usage (since PyG 2.3). Install version-matched wheels from the [PyG wheel index](https://data.pyg.org/whl) after checking your PyTorch and CUDA versions:++```bash+python -c "import torch; print(torch.__version__, torch.version.cuda)"+# Then install wheels for your torch+CUDA combo, e.g.:+uv pip install pyg-lib torch-scatter torch-sparse torch-cluster \+ -f https://data.pyg.org/whl/torch-2.8.0+cu128.html+```++Check your version:++```python+import torch_geometric+print(torch_geometric.__version__)+```++**Conda:** the `pyg` conda channel is no longer maintained for PyTorch >2.5 — use `uv pip install` and the wheel index above instead.++### PyG 2.7 notes++PyG 2.7 dropped Python 3.9 and PyTorch ≤2.5. See the [2.7.0 release notes](https://github.com/pyg-team/pytorch_geometric/releases/tag/2.7.0) for PyTorch 2.6–2.8 compatibility tables. `torch_geometric.distributed` is deprecated — use standard `torch.distributed` DDP (see `references/scaling.md`).## Core Concepts@@ -200,8 +235,8 @@ for epoch in range(200):loss.backward()optimizer.step()-# Evaluation-model.eval()+# Evaluation — train(False) puts the model in inference mode (disables dropout/BN)+model.train(False)pred = model(data.x, data.edge_index).argmax(dim=1)acc = (pred[data.test_mask] == data.y[data.test_mask]).float().mean()```diff --git a/skills/torch-geometric/references/custom_datasets.md b/skills/torch-geometric/references/custom_datasets.mdindex e3b91f66..8815a396 100644--- a/skills/torch-geometric/references/custom_datasets.md+++ b/skills/torch-geometric/references/custom_datasets.md@@ -38,6 +38,7 @@ class MyDataset(InMemoryDataset):def download(self):# Download raw files to self.raw_dir+ # Use trusted sources only; verify checksums or signatures before loading.download_url('https://example.com/data.csv', self.raw_dir)def process(self):diff --git a/skills/torch-geometric/references/explainability.md b/skills/torch-geometric/references/explainability.mdindex b090ba59..d7c19bda 100644--- a/skills/torch-geometric/references/explainability.md+++ b/skills/torch-geometric/references/explainability.md@@ -130,7 +130,7 @@ from torch_geometric.explain import CaptumExplaineralgorithm = CaptumExplainer('IntegratedGradients')```-Requires `pip install captum` (or `uv add captum`).+Requires `uv pip install captum` (or `uv add captum`).### AttentionExplainerdiff --git a/skills/torch-geometric/references/link_prediction.md b/skills/torch-geometric/references/link_prediction.mdindex 1159f2ab..4f5595d9 100644--- a/skills/torch-geometric/references/link_prediction.md+++ b/skills/torch-geometric/references/link_prediction.md@@ -92,7 +92,7 @@ def train(train_data):@torch.no_grad()def test(data_split):- model.eval()+ model.train(False) # Inference mode (disables dropout; not Python eval)z = model(data_split.x, data_split.edge_index)pred = decode(z, data_split.edge_label_index).sigmoid()# AUC is the standard metric for link prediction@@ -135,7 +135,7 @@ def train():@torch.no_grad()def test(data_split):- model.eval()+ model.train(False) # Inference mode (disables dropout; not Python eval)z = model.encode(data_split.x, data_split.edge_index)return model.test(z, data_split.edge_label_index[0], # positive edgesdata_split.edge_label_index[1]) # negative edgesdiff --git a/skills/torch-geometric/references/scaling.md b/skills/torch-geometric/references/scaling.mdindex dc7f6fb9..1d3ff18b 100644--- a/skills/torch-geometric/references/scaling.md+++ b/skills/torch-geometric/references/scaling.md@@ -51,6 +51,7 @@ for batch in loader:- `batch.n_id` maps local indices back to original node IDs- Sampling >2-3 hops is generally infeasible (exponential neighborhood growth)- Keep `len(num_neighbors) == num_gnn_layers` for efficiency+- PyG 2.7 adds `BidirectionalSampler` and forward+reverse edge sampling on `NeighborSampler` for undirected graphs### LinkNeighborLoader (for link prediction)@@ -130,6 +131,8 @@ loader = ShaDowKHopSampler(## 3. Multi-GPU / Distributed Training+`torch_geometric.distributed` is deprecated as of PyG 2.7 — use standard PyTorch DDP below.+### DistributedDataParallel (DDP)Standard PyTorch DDP works with PyG. Each GPU gets a partition of the seed nodes:@@ -200,9 +203,10 @@ if __name__ == '__main__':### PyTorch Lightning Integration-PyG provides Lightning wrappers for minimal boilerplate:+PyG provides Lightning wrappers for minimal boilerplate. PyG 2.7 supports the `lightning` package (not only legacy `pytorch-lightning`):```python+import lightning as Lfrom torch_geometric.data import LightningNodeDatadatamodule = LightningNodeData(diff --git a/skills/transformers/SKILL.md b/skills/transformers/SKILL.mdindex 963034ab..01f52c23 100644--- a/skills/transformers/SKILL.md+++ b/skills/transformers/SKILL.md@@ -1,10 +1,10 @@---name: transformers-description: This skill should be used when working with pre-trained transformer models for natural language processing, computer vision, audio, or multimodal tasks. Use for text generation, classification, question answering, translation, summarization, image classification, object detection, speech recognition, and fine-tuning models on custom datasets.+description: Hugging Face Transformers for loading Hub models, running pipeline inference, text generation, and Trainer fine-tuning on NLP, vision, audio, and multimodal tasks. Use when working with AutoModel, pipelines, tokenizers, or TrainingArguments—not for general ML outside the Transformers library.license: Apache-2.0 license-compatibility: Some features require an Huggingface token+compatibility: Requires Python 3.10+, PyTorch 2.4+, and transformers 5.x. Gated or private Hub models need an HF token (hf auth login or HF_TOKEN).metadata:- version: "1.0"+ version: "1.1"skill-author: K-Dense Inc.---@@ -16,38 +16,66 @@ The Hugging Face Transformers library provides access to thousands of pre-traine## Installation-Install transformers and core dependencies:+Tested against **transformers 5.9.x** (stable; May 2026). Requires **Python 3.10+** and **PyTorch 2.4+**.```bash-uv pip install torch transformers datasets evaluate accelerate+uv pip install "transformers[torch]>=5.9" huggingface_hub datasets evaluate accelerate```For vision tasks, add:+```bashuv pip install timm pillow```For audio tasks, add:+```bashuv pip install librosa soundfile```+Check your version:++```python+import transformers+print(transformers.__version__)+```+## Authentication-Many models on the Hugging Face Hub require authentication. Set up access:+Many models on the Hugging Face Hub are gated or private. Authenticate before loading them.++**Recommended:** CLI login (stores token in `~/.cache/huggingface/token`):++```bash+hf auth login+```++**Python:**```pythonfrom huggingface_hub import login-login() # Follow prompts to enter token+login() # Interactive prompt; do not hardcode tokens in scripts```-Or set environment variable:+**Servers / CI:** set `HF_TOKEN` in the environment (never commit tokens to git or shell profiles):+```bash-export HUGGINGFACE_TOKEN="your_token_here"+export HF_TOKEN="..." # Read token from a secret manager, not source code```Get tokens at: https://huggingface.co/settings/tokens+**Security:** Never paste tokens into notebooks, repos, or shared configs. Prefer `hf auth login` over exporting tokens in `.bashrc` or `.zshrc`.++## Transformers v5++Transformers v5 is **PyTorch-only** (TensorFlow and JAX backends were removed). For upgrades from v4, see the [v5 migration guide](https://github.com/huggingface/transformers/blob/main/MIGRATION_GUIDE_V5.md). New projects should pair **transformers 5.x** with **huggingface_hub 1.x**.++**Gated or custom architectures:** accept the model license on the Hub, then load with `trust_remote_code=True` only when the model card requires custom code you have reviewed.++**Cache location:** set `HF_HOME` for a writable cache root (Hub files default under `$HF_HOME/hub`).+## Quick StartUse the Pipeline API for fast inference without manual configuration:@@ -55,9 +83,9 @@ Use the Pipeline API for fast inference without manual configuration:```pythonfrom transformers import pipeline-# Text generation-generator = pipeline("text-generation", model="gpt2")-result = generator("The future of AI is", max_length=50)+# Text generation (prefer max_new_tokens for causal LMs)+generator = pipeline("text-generation", model="Qwen/Qwen2.5-1.5B")+result = generator("The future of AI is", max_new_tokens=50)# Text classificationclassifier = pipeline("text-classification")@@ -160,4 +188,3 @@ For detailed information on specific components:- **Generation**: `references/generation.md` - Text generation strategies and parameters- **Training**: `references/training.md` - Fine-tuning with Trainer API- **Tokenizers**: `references/tokenizers.md` - Tokenization and preprocessing-diff --git a/skills/transformers/references/generation.md b/skills/transformers/references/generation.mdindex fb718d19..f0e0b0e7 100644--- a/skills/transformers/references/generation.md+++ b/skills/transformers/references/generation.md@@ -4,6 +4,8 @@Generate text with language models using the `generate()` method. Control output quality and style through generation strategies and parameters.+For quick prototyping, the [Pipeline API](pipelines.md) wraps tokenization and `generate()`; use `model.generate()` directly when you need custom preprocessing or decoding control.+## Basic Generation```pythondiff --git a/skills/transformers/references/models.md b/skills/transformers/references/models.mdindex 5598a3ee..ec72ff60 100644--- a/skills/transformers/references/models.md+++ b/skills/transformers/references/models.md@@ -111,18 +111,18 @@ model.to(torch.device("cuda" if torch.cuda.is_available() else "cpu"))### Precision Control-**torch_dtype**: Set model precision+**dtype**: Set model precision (preferred in v5; `torch_dtype` still works but is deprecated)```pythonimport torch# Float16 (half precision)-model = AutoModel.from_pretrained("model-id", torch_dtype=torch.float16)+model = AutoModel.from_pretrained("model-id", dtype=torch.float16)# BFloat16 (better range than float16)-model = AutoModel.from_pretrained("model-id", torch_dtype=torch.bfloat16)+model = AutoModel.from_pretrained("model-id", dtype=torch.bfloat16)# Auto (use original dtype)-model = AutoModel.from_pretrained("model-id", torch_dtype="auto")+model = AutoModel.from_pretrained("model-id", dtype="auto")```### Attention Implementation@@ -150,7 +150,7 @@ model = AutoModelForCausalLM.from_pretrained()```-**load_in_8bit**: 8-bit quantization (requires bitsandbytes)+**load_in_8bit**: 8-bit quantization (requires optional `bitsandbytes`; `uv pip install bitsandbytes`)```pythonmodel = AutoModelForCausalLM.from_pretrained("model-id",@@ -209,13 +209,13 @@ model = AutoModel.from_pretrained("model-id")print(model.training) # False# Switch to training mode-model.train()+model.train(True)-# Switch back to evaluation mode-model.eval()+# Switch back to evaluation mode (equivalent to eval mode on nn.Module)+model.train(False)```-Evaluation mode disables dropout and uses batch norm statistics.+Evaluation mode disables dropout and uses batch norm statistics. `model.train(False)` is equivalent to `model.eval()` in PyTorch.## Saving Models@@ -324,20 +324,20 @@ export(## Best Practices1. **Use AutoModel classes**: Automatic architecture detection-2. **Specify dtype explicitly**: Control precision and memory+2. **Specify `dtype` explicitly**: Control precision and memory (avoid deprecated `torch_dtype` in new code)3. **Use device_map="auto"**: For large models4. **Enable low_cpu_mem_usage**: When loading large models5. **Use safetensors format**: Faster and safer serialization6. **Check model.training**: Ensure correct mode for task7. **Consider quantization**: For deployment on resource-constrained devices-8. **Cache models locally**: Set TRANSFORMERS_CACHE environment variable+8. **Cache models locally**: Set `HF_HOME` (Hub cache at `$HF_HOME/hub`)## Common Issues**CUDA out of memory:**```python# Use smaller precision-model = AutoModel.from_pretrained("model-id", torch_dtype=torch.float16)+model = AutoModel.from_pretrained("model-id", dtype=torch.float16)# Or use quantizationmodel = AutoModel.from_pretrained("model-id", load_in_8bit=True)diff --git a/skills/transformers/references/pipelines.md b/skills/transformers/references/pipelines.mdindex 7134642e..30b5c90a 100644--- a/skills/transformers/references/pipelines.md+++ b/skills/transformers/references/pipelines.md@@ -29,7 +29,7 @@ pipe = pipeline("text-classification", model="distilbert-base-uncased-finetuned-**text-generation**: Generate text continuations```pythongenerator = pipeline("text-generation", model="gpt2")-output = generator("Once upon a time", max_length=50, num_return_sequences=2)+output = generator("Once upon a time", max_new_tokens=50, num_return_sequences=2)```**text-classification**: Classify text into categories@@ -177,10 +177,10 @@ pipe = pipeline("task", device=0) # Use first GPUpipe = pipeline("task", model="large-model", device_map="auto")```-**dtype**: Model precision (reduces memory)+**dtype**: Model precision (reduces memory; `torch_dtype` is deprecated but still accepted)```pythonimport torch-pipe = pipeline("task", torch_dtype=torch.float16)+pipe = pipeline("task", dtype=torch.float16)```**batch_size**: Process multiple inputs at once@@ -189,10 +189,7 @@ pipe = pipeline("task", batch_size=8)results = pipe(["text1", "text2", "text3"])```-**framework**: Choose PyTorch or TensorFlow-```python-pipe = pipeline("task", framework="pt") # or "tf"-```+**Backend**: Transformers v5 pipelines use PyTorch only (TensorFlow/JAX backends were removed in v5).## Batch Processing@@ -231,7 +228,7 @@ pipe = pipeline("task", device=0)Use float16 for 2x speedup on supported GPUs:```pythonimport torch-pipe = pipeline("task", torch_dtype=torch.float16, device=0)+pipe = pipeline("task", dtype=torch.float16, device=0)```### Batching Guidelines@@ -252,10 +249,12 @@ results = pipe(list_of_texts)For text generation, stream tokens as they're generated:```python-from transformers import TextStreamer+from transformers import AutoTokenizer, TextStreamer, pipeline-generator = pipeline("text-generation", model="gpt2", streamer=TextStreamer())-generator("The future of AI", max_length=100)+tokenizer = AutoTokenizer.from_pretrained("gpt2")+streamer = TextStreamer(tokenizer)+generator = pipeline("text-generation", model="gpt2", streamer=streamer)+generator("The future of AI", max_new_tokens=100)```## Custom Pipeline Configurationdiff --git a/skills/transformers/references/tokenizers.md b/skills/transformers/references/tokenizers.mdindex 7585f22d..e957e324 100644--- a/skills/transformers/references/tokenizers.md+++ b/skills/transformers/references/tokenizers.md@@ -74,14 +74,11 @@ inputs = tokenizer(texts, padding=True, truncation=True)### Return Tensors-**return_tensors**: Output format ("pt", "tf", "np")+**return_tensors**: Output format (`"pt"` for PyTorch, `"np"` for NumPy)```python-# PyTorch tensors+# PyTorch tensors (default for Transformers v5 workflows)inputs = tokenizer("text", return_tensors="pt")-# TensorFlow tensors-inputs = tokenizer("text", return_tensors="tf")-# NumPy arraysinputs = tokenizer("text", return_tensors="np")```diff --git a/skills/transformers/references/training.md b/skills/transformers/references/training.mdindex 5fd2433e..f564f49c 100644--- a/skills/transformers/references/training.md+++ b/skills/transformers/references/training.md@@ -4,6 +4,10 @@Fine-tune pre-trained models on custom datasets using the Trainer API. The Trainer handles training loops, gradient accumulation, mixed precision, logging, and checkpointing.+**Metrics:** use `evaluate.load("metric_name")` — the old `datasets.load_metric` API was removed.++**Hub uploads:** `trainer.push_to_hub()` requires authentication (`hf auth login` or `HF_TOKEN`).+## Basic Fine-Tuning Workflow### Step 1: Load and Preprocess Data@@ -168,12 +172,12 @@ metric_for_best_model="accuracy" # Metric to comparegradient_accumulation_steps=4 # Effective batch size = batch_size * 4```-**fp16**: Enable mixed precision (NVIDIA GPUs)+**fp16**: Enable mixed precision (NVIDIA GPUs without native bfloat16)```pythonfp16=True```-**bf16**: Enable bfloat16 (newer GPUs)+**bf16**: Enable bfloat16 (preferred on Ampere+ and newer GPUs when supported)```pythonbf16=True```diff --git a/skills/usfiscaldata/SKILL.md b/skills/usfiscaldata/SKILL.mdindex 7a02cd8b..d10d09f7 100644--- a/skills/usfiscaldata/SKILL.md+++ b/skills/usfiscaldata/SKILL.md@@ -1,9 +1,10 @@---name: usfiscaldata-description: Query the U.S. Treasury Fiscal Data API for federal financial data including national debt, government spending, revenue, interest rates, exchange rates, and savings bonds. Access 54 datasets and 182 data tables with no API key required. Use when working with U.S. federal fiscal data, national debt tracking (Debt to the Penny), Daily Treasury Statements, Monthly Treasury Statements, Treasury securities auctions, interest rates on Treasury securities, foreign exchange rates, savings bonds, or any U.S. government financial statistics.+description: Query the U.S. Treasury Fiscal Data REST API for federal financial data. No API key required. Use for national debt (Debt to the Penny), Daily Treasury Statements, Monthly Treasury Statements, Treasury securities auctions, interest rates, foreign exchange rates, savings bonds, or U.S. government revenue and spending statistics.license: MIT+allowed-tools: Read Write Edit Bashmetadata:- version: "1.0"+ version: "1.1"skill-author: K-Dense Inc.---@@ -13,6 +14,14 @@ Free, open REST API from the U.S. Department of the Treasury for federal financi**Base URL:** `https://api.fiscaldata.treasury.gov/services/api/fiscal_service`+Browse [54 datasets and 179 data tables](https://fiscaldata.treasury.gov/datasets/) via the dataset search. Verify endpoint paths on each dataset's API Quick Guide — paths change over time.++## Installation++```bash+uv pip install requests pandas+```+## Quick Start```python@@ -70,7 +79,7 @@ None required. The API is fully open and free.| Dataset | Endpoint | Frequency ||---------|----------|-----------|| Debt to the Penny | `/v2/accounting/od/debt_to_penny` | Daily |-| Historical Debt Outstanding | `/v2/accounting/od/historical_debt_outstanding` | Annual |+| Historical Debt Outstanding | `/v2/accounting/od/debt_outstanding` | Annual || Schedules of Federal Debt | `/v1/accounting/od/schedules_fed_debt` | Monthly |### Daily & Monthly Statements@@ -79,7 +88,7 @@ None required. The API is fully open and free.|---------|----------|-----------|| DTS Operating Cash Balance | `/v1/accounting/dts/operating_cash_balance` | Daily || DTS Deposits & Withdrawals | `/v1/accounting/dts/deposits_withdrawals_operating_cash` | Daily |-| Monthly Treasury Statement (MTS) | `/v1/accounting/mts/mts_table_1` (16 tables) | Monthly |+| Monthly Treasury Statement (MTS) | `/v1/accounting/mts/mts_table_1` (18 tables — see [datasets-fiscal.md](references/datasets-fiscal.md)) | Monthly |### Interest Rates & Exchange@@ -95,14 +104,14 @@ None required. The API is fully open and free.|---------|----------|-----------|| Treasury Securities Auctions Data | `/v1/accounting/od/auctions_query` | As Needed || Treasury Securities Upcoming Auctions | `/v1/accounting/od/upcoming_auctions` | As Needed |-| Average Interest Rates | `/v2/accounting/od/avg_interest_rates` | Monthly |+| Treasury Securities Buybacks | `/v1/accounting/od/buybacks_operations` | As Needed |### Savings Bonds| Dataset | Endpoint | Frequency ||---------|----------|-----------|-| I Bonds Interest Rates | `/v2/accounting/od/i_bond_interest_rates` | Semi-Annual |-| U.S. Treasury Savings Bonds: Issues, Redemptions & Maturities | `/v1/accounting/od/sb_issues_redemptions` | Monthly |+| I Bonds Interest Rates | `/v1/accounting/od/i_bonds_interest_rates` | Semi-Annual |+| Savings Bonds Issues, Redemptions & Maturities | `/v1/accounting/od/savings_bonds_report` | Monthly |## Response Structure@@ -127,14 +136,16 @@ None required. The API is fully open and free.### Load all pages into a DataFrame+Use the bounded `fetch_all()` helper in [parameters.md](references/parameters.md). For small result sets, a single request with `page[size]=10000` may suffice when `meta.total-pages` is 1.+```python-def fetch_all_pages(endpoint, params=None):- params = params or {}- params["page[size]"] = 10000 # max size to minimize requests- resp = requests.get(f"{BASE_URL}{endpoint}", params=params)- result = resp.json()- df = pd.DataFrame(result["data"])- return df+# Single-page fetch when total-pages == 1+params = {"sort": "-record_date", "page[size]": 10000}+resp = requests.get(f"{BASE_URL}/v2/accounting/od/debt_outstanding", params=params)+result = resp.json()+if result["meta"]["total-pages"] > 1:+ raise ValueError("Use fetch_all() from parameters.md for multi-page results")+df = pd.DataFrame(result["data"])```### Aggregation (automatic sum)diff --git a/skills/usfiscaldata/references/api-basics.md b/skills/usfiscaldata/references/api-basics.mdindex 13eb56dc..aeefc4c4 100644--- a/skills/usfiscaldata/references/api-basics.md+++ b/skills/usfiscaldata/references/api-basics.md@@ -30,6 +30,16 @@ https://api.fiscaldata.treasury.gov/services/api/fiscal_service/v2/accounting/od- **v2**: Newer or updated datasets (Debt to Penny, TROR, avg interest rates)- Check the specific dataset page at `fiscaldata.treasury.gov/datasets/` to confirm the version+## Verifying Endpoint Paths++Endpoint paths change when datasets are restructured. Always confirm the current path on the dataset's **API Quick Guide** before querying.++Authoritative sources (in order):++1. Dataset detail page at `https://fiscaldata.treasury.gov/datasets/{slug}/`+2. Gatsby page data: `https://fiscaldata.treasury.gov/page-data/datasets/{slug}/page-data.json` (look for `"endpoint"` fields)+3. [API endpoint table](https://fiscaldata.treasury.gov/api-documentation/#list-of-endpoints-table)+## Data TypesAll field values in responses are **strings** (quoted), regardless of their logical type.@@ -81,6 +91,15 @@ def get_with_retry(url, params, retries=3):- HTTP 304 (Not Modified) can be returned for cached responses- Safe to cache responses; most datasets update daily, monthly, or quarterly+## Pagination Headers++Responses include pagination in two places:++- **`links` object** in the JSON body (`self`, `first`, `prev`, `next`, `last`)+- **`Link` HTTP header** with RFC 5988 relations (`rel="first"`, `rel="next"`, etc.)++Either can be used to navigate pages programmatically. See [response-format.md](response-format.md) for details.+## Data RegistryThe [Fiscal Service Data Registry](https://fiscal.treasury.gov/data-registry/index.html) contains field definitions, authoritative sources, data types, and formats across federal government data.diff --git a/skills/usfiscaldata/references/datasets-debt.md b/skills/usfiscaldata/references/datasets-debt.mdindex 460f4db1..6c5a71ae 100644--- a/skills/usfiscaldata/references/datasets-debt.md+++ b/skills/usfiscaldata/references/datasets-debt.md@@ -40,7 +40,7 @@ df["tot_pub_debt_out_amt"] = df["tot_pub_debt_out_amt"].astype(float)## Historical Debt Outstanding-**Endpoint:** `/v2/accounting/od/historical_debt_outstanding`+**Endpoint:** `/v2/accounting/od/debt_outstanding`**Frequency:** Annual**Date Range:** 1790 to present@@ -55,7 +55,7 @@ Annual record of U.S. national debt going back to the founding of the republic.```python# Full historical debt seriesresp = requests.get(- "https://api.fiscaldata.treasury.gov/services/api/fiscal_service/v2/accounting/od/historical_debt_outstanding",+ "https://api.fiscaldata.treasury.gov/services/api/fiscal_service/v2/accounting/od/debt_outstanding",params={"sort": "-record_date", "page[size]": 10000})df = pd.DataFrame(resp.json()["data"])@@ -79,11 +79,14 @@ Monthly breakdown of federal debt by security type and component.## Schedules of Federal Debt by Day-**Endpoint:** `/v1/accounting/od/schedules_fed_debt_daily`-**Frequency:** Daily-**Date Range:** September 2006 to present+Two daily data tables under `/v1/accounting/od/`:++| Table | Endpoint | Description |+|-------|----------|-------------|+| Daily Activity | `/v1/accounting/od/schedules_fed_debt_daily_activity` | Daily debt activity |+| Daily Summary | `/v1/accounting/od/schedules_fed_debt_daily_summary` | Daily debt summary |-Daily version of federal debt schedules with two data tables.+**Related:** `/v1/accounting/od/schedules_fed_debt_fytd` — fiscal year-to-date schedules.## Treasury Report on Receivables (TROR)diff --git a/skills/usfiscaldata/references/datasets-fiscal.md b/skills/usfiscaldata/references/datasets-fiscal.mdindex e951cb84..b8a75a8e 100644--- a/skills/usfiscaldata/references/datasets-fiscal.md+++ b/skills/usfiscaldata/references/datasets-fiscal.md@@ -71,30 +71,32 @@ resp = requests.get(## Monthly Treasury Statement (MTS)-The MTS dataset has **16 data tables**, all under `/v1/accounting/mts/`. Updated monthly.+The MTS dataset has **18 data tables**, all under `/v1/accounting/mts/`. Updated monthly.**Date Range:** October 1980 to present### MTS Tables-| Table | Endpoint | Description |-|-------|----------|-------------|-| MTS Table 1 | `/v1/accounting/mts/mts_table_1` | Summary of Receipts and Outlays |-| MTS Table 2 | `/v1/accounting/mts/mts_table_2` | Receipts by Source |-| MTS Table 3 | `/v1/accounting/mts/mts_table_3` | Outlays by Function |-| MTS Table 4 | `/v1/accounting/mts/mts_table_4` | Outlays by Agency |-| MTS Table 5 | `/v1/accounting/mts/mts_table_5` | Outlays by Category |-| MTS Table 6 | `/v1/accounting/mts/mts_table_6` | Means of Financing |-| MTS Table 7 | `/v1/accounting/mts/mts_table_7` | Receipts by Source (Quarterly) |-| MTS Table 8 | `/v1/accounting/mts/mts_table_8` | Outlays by Function (Quarterly) |-| MTS Table 9 | `/v1/accounting/mts/mts_table_9` | Receipts: Comparative Summary |-| MTS Table 10 | `/v1/accounting/mts/mts_table_10` | Outlays: Comparative Summary |-| MTS Table 11 | `/v1/accounting/mts/mts_table_11` | Supplemental Detail on Receipts |-| MTS Table 12 | `/v1/accounting/mts/mts_table_12` | Supplemental Detail on Outlays |-| MTS Table 13 | `/v1/accounting/mts/mts_table_13` | Federal Borrowing and Debt |-| MTS Table 14 | `/v1/accounting/mts/mts_table_14` | Means of Financing: Federal |-| MTS Table 15 | `/v1/accounting/mts/mts_table_15` | Federal Trust Fund Summary |-| MTS Table 16 | `/v1/accounting/mts/mts_table_16` | Means of Financing: Off-Budget |+| Endpoint | Description |+|----------|-------------|+| `/v1/accounting/mts/mts_table_1` | Summary of receipts, outlays, and deficit/surplus |+| `/v1/accounting/mts/mts_table_2` | Summary of budget and off-budget results |+| `/v1/accounting/mts/mts_table_3` | Summary of receipts and outlays |+| `/v1/accounting/mts/mts_table_4` | Receipts of the U.S. Government |+| `/v1/accounting/mts/mts_table_5` | Outlays of the U.S. Government |+| `/v1/accounting/mts/mts_table_5m` | Receipts and outlays by month |+| `/v1/accounting/mts/mts_table_6` | Means of financing the deficit or disposition of surplus |+| `/v1/accounting/mts/mts_table_6a` | Analysis of change in excess of liabilities |+| `/v1/accounting/mts/mts_table_6b` | Securities issued under special financing authorities |+| `/v1/accounting/mts/mts_table_6c` | Federal agency borrowing via Treasury securities |+| `/v1/accounting/mts/mts_table_6d` | Investments of federal accounts in federal securities |+| `/v1/accounting/mts/mts_table_6e` | Guaranteed and direct loan financing, net activity |+| `/v1/accounting/mts/mts_table_7` | Receipts and outlays by month |+| `/v1/accounting/mts/mts_table_8` | Trust fund impact on budget results and holdings |+| `/v1/accounting/mts/mts_table_9` | Summary of receipts by source and outlays by function |+| `/v1/accounting/mts/mts_table_9_outlays_functions_subfunctions` | Outlays by function and subfunction |+| `/v1/accounting/mts/mts_distributed_offsetting_receipts` | Distributed offsetting receipts |+| `/v1/accounting/mts/mts_receipts_outlays_deficit_surplus` | Receipts, outlays, and deficit/surplus |### Common MTS Fields@@ -136,7 +138,7 @@ resp = requests.get(## U.S. Government Revenue Collections-**Endpoint:** `/v1/accounting/od/rev_collections`+**Endpoint:** `/v2/revenue/rcm`**Frequency:** Daily**Date Range:** October 2004 to present@@ -169,7 +171,7 @@ Monthly federal disbursements data.## Receipts by Department-**Endpoint:** `/v2/accounting/od/receipts_by_dept`+**Endpoint:** `/v1/accounting/od/receipts_by_department`**Frequency:** Annual**Date Range:** September 2015 to present@@ -191,6 +193,20 @@ Treasury-managed trust and special funds account data.**Frequency:** Quarterly**Date Range:** March 2021 to present (13 tables)-Quarterly financial report covering government finances, public debt, savings bonds, and more.--**Endpoint prefix:** `/v1/accounting/od/treasury_bulletin_`+Quarterly financial report covering government finances, public debt, savings bonds, and more. Endpoints use the `/v1/accounting/tb/` prefix (not `/v1/accounting/od/`).++| Endpoint | Description |+|----------|-------------|+| `/v1/accounting/tb/esf1_balances` | Exchange Stabilization Fund balances |+| `/v1/accounting/tb/esf2_statement_net_cost` | ESF statement of net cost |+| `/v1/accounting/tb/fcp1_weekly_report_major_market_participants` | Major market participants (weekly) |+| `/v1/accounting/tb/fcp2_monthly_report_major_market_participants` | Major market participants (monthly) |+| `/v1/accounting/tb/fcp3_quarterly_report_large_market_participants` | Large market participants (quarterly) |+| `/v1/accounting/tb/ffo5_internal_revenue_by_state` | Internal revenue receipts by state |+| `/v1/accounting/tb/ffo6_customs_border_protection_collections` | Customs and border protection collections |+| `/v1/accounting/tb/ofs1_distribution_federal_securities_class_investors_type_issues` | Distribution of federal securities by class and investor |+| `/v1/accounting/tb/ofs2_estimated_ownership_treasury_securities` | Estimated ownership of Treasury securities |+| `/v1/accounting/tb/pdo1_offerings_regular_weekly_treasury_bills` | Offerings of regular weekly Treasury bills |+| `/v1/accounting/tb/pdo2_offerings_marketable_securities_other_regular_weekly_treasury_bills` | Other marketable securities offerings |+| `/v1/accounting/tb/uscc1_amounts_outstanding_circulation` | Amounts outstanding and in circulation |+| `/v1/accounting/tb/uscc2_amounts_outstanding_circulation` | Amounts outstanding and in circulation (continued) |diff --git a/skills/usfiscaldata/references/datasets-interest-rates.md b/skills/usfiscaldata/references/datasets-interest-rates.mdindex 2d5dbe49..47bb279e 100644--- a/skills/usfiscaldata/references/datasets-interest-rates.md+++ b/skills/usfiscaldata/references/datasets-interest-rates.md@@ -105,9 +105,15 @@ euro_df["record_date"] = pd.to_datetime(euro_df["record_date"])## TIPS and CPI Data-**Endpoint:** `/v1/accounting/od/tips_cpi_data`+Two data tables under `/v1/accounting/od/`:++| Table | Endpoint | Description |+|-------|----------|-------------|+| Summary | `/v1/accounting/od/tips_cpi_data_summary` | Reference CPI numbers and daily index ratios (summary) |+| Detail | `/v1/accounting/od/tips_cpi_data_detail` | Reference CPI numbers and daily index ratios (detail) |+**Frequency:** Monthly-**Date Range:** April 1998 to present (2 data tables)+**Date Range:** April 1998 to presentTreasury Inflation-Protected Securities (TIPS) reference CPI data and index ratios used to calculate TIPS values.@@ -123,10 +129,10 @@ Treasury Inflation-Protected Securities (TIPS) reference CPI data and index rati## FRN Daily Indexes**Endpoint:** `/v1/accounting/od/frn_daily_indexes`-**Frequency:** Daily+**Frequency:** Monthly release (daily index rows per CUSIP)**Date Range:** April 2024 to present-Daily index values for Treasury Floating Rate Notes (FRNs). The rate is based on the 13-week Treasury bill auction rate.+Daily index values for Treasury Floating Rate Notes (FRNs). The rate is based on the 13-week Treasury bill auction rate. Data is published monthly with daily index rows for each CUSIP.---@@ -156,7 +162,7 @@ These certified interest rates are used for federal loans, financing programs, a## Federal Credit Similar Maturity Rates-**Endpoint:** `/v1/accounting/od/fed_credit_similar_maturity_rates`+**Endpoint:** `/v1/accounting/od/federal_maturity_rates`**Frequency:** Annual**Date Range:** September 1992 to presentdiff --git a/skills/usfiscaldata/references/datasets-securities.md b/skills/usfiscaldata/references/datasets-securities.mdindex d03313b0..10022454 100644--- a/skills/usfiscaldata/references/datasets-securities.md+++ b/skills/usfiscaldata/references/datasets-securities.md@@ -85,11 +85,26 @@ Tracks auction records (largest, highest rate, lowest rate, etc.) for each securData on Treasury's secondary market buyback (repurchase) operations. Active since the program's relaunch in 2024.+| Table | Endpoint | Description |+|-------|----------|-------------|+| Buybacks Operations | `/v1/accounting/od/buybacks_operations` | Announcements and results per operation |+| Security Details | `/v1/accounting/od/buybacks_security_details` | Security details per operation |++```python+# Recent buyback operations+resp = requests.get(+ "https://api.fiscaldata.treasury.gov/services/api/fiscal_service/v1/accounting/od/buybacks_operations",+ params={"sort": "-operation_date", "page[size]": 10}+)+df = pd.DataFrame(resp.json()["data"])+print(df[["operation_date", "settlement_date"]].head())+```+---## I Bonds Interest Rates-**Endpoint:** `/v2/accounting/od/i_bond_interest_rates`+**Endpoint:** `/v1/accounting/od/i_bonds_interest_rates`**Frequency:** Semi-Annual (May and November)**Date Range:** September 1998 to present@@ -98,34 +113,41 @@ Composite interest rates for Series I Savings Bonds, including fixed rate and in**Key fields:**| Field | Type | Description ||-------|------|-------------|-| `effective_date` | DATE | Rate effective date |-| `announcement_date` | DATE | Announcement date |+| `earning_period_start` | DATE | Start of six-month earning period |+| `earning_period_end` | DATE | End of six-month earning period || `fixed_rate` | PERCENTAGE | Fixed rate component |-| `semiannual_inflation_rate` | PERCENTAGE | Semi-annual CPI-U inflation rate |-| `earnings_rate_i_bonds` | PERCENTAGE | Combined composite rate |+| `semi_annual_inflation_rate` | PERCENTAGE | Semi-annual CPI-U inflation rate |+| `combined_rate` | PERCENTAGE | Combined composite rate |```python# Current I Bond ratesresp = requests.get(- "https://api.fiscaldata.treasury.gov/services/api/fiscal_service/v2/accounting/od/i_bond_interest_rates",- params={"sort": "-effective_date", "page[size]": 5}+ "https://api.fiscaldata.treasury.gov/services/api/fiscal_service/v1/accounting/od/i_bonds_interest_rates",+ params={"sort": "-earning_period_start", "page[size]": 5})df = pd.DataFrame(resp.json()["data"])latest = df.iloc[0]-print(f"Current I Bond rate: {latest['earnings_rate_i_bonds']}%")+print(f"Current I Bond rate: {latest['combined_rate']}%")print(f" Fixed rate: {latest['fixed_rate']}%")-print(f" Inflation component: {latest['semiannual_inflation_rate']}%")+print(f" Inflation component: {latest['semi_annual_inflation_rate']}%")```## U.S. Treasury Savings Bonds: Issues, Redemptions & Maturities-**Endpoint:** `/v1/accounting/od/sb_issues_redemptions` (3 tables)+Three data tables under `/v1/accounting/od/`:++| Table | Endpoint | Description |+|-------|----------|-------------|+| Issues, Redemptions & Maturities | `/v1/accounting/od/savings_bonds_report` | Monthly statistics by series |+| Matured Unredeemed Debt | `/v1/accounting/od/savings_bonds_mud` | Matured unredeemed debt |+| Piece Information by Series | `/v1/accounting/od/savings_bonds_pcs` | Piece information by series |+**Frequency:** Monthly**Date Range:** September 1998 to presentMonthly statistics on Series EE, Series I, and Series HH savings bonds outstanding, issued, and redeemed.-**Key fields:**+**Key fields (savings_bonds_report):**| Field | Type | Description ||-------|------|-------------|| `record_date` | DATE | Month end date |@@ -159,7 +181,7 @@ Monthly redemption value tables for historical savings bonds.## State and Local Government Series (SLGS) Securities-**Endpoint:** `/v1/accounting/od/slgs_statistics`+**Endpoint:** `/v2/accounting/od/slgs_statistics`**Frequency:** Daily**Date Range:** October 1998 to presentdiff --git a/skills/usfiscaldata/references/examples.md b/skills/usfiscaldata/references/examples.mdindex 840bb198..ed8c473d 100644--- a/skills/usfiscaldata/references/examples.md+++ b/skills/usfiscaldata/references/examples.md@@ -151,13 +151,13 @@ pivot = df.pivot_table(index="date", columns="security_desc", values="rate")print(pivot.tail(5))# I Bond rates history-result = fetch("/v2/accounting/od/i_bond_interest_rates",- sort="-effective_date", **{"page[size]": 20})+result = fetch("/v1/accounting/od/i_bonds_interest_rates",+ sort="-earning_period_start", **{"page[size]": 20})df = pd.DataFrame(result["data"])-df["total_rate"] = df["earnings_rate_i_bonds"].astype(float)+df["combined_rate"] = df["combined_rate"].astype(float)df["fixed_rate"] = df["fixed_rate"].astype(float)print("I Bond rate history:")-print(df[["effective_date", "fixed_rate", "total_rate"]].head(10))+print(df[["earning_period_start", "fixed_rate", "combined_rate"]].head(10))```### Fiscal Year Summary@@ -253,6 +253,6 @@ for field, label in meta["labels"].items():## Finding Datasets-Browse the full list of 54 datasets and 182 endpoints at:-- `https://fiscaldata.treasury.gov/datasets/` — searchable dataset catalog-- `https://fiscaldata.treasury.gov/api-documentation/#list-of-endpoints-table` — full endpoint table+Browse the full list of 54 datasets and 179 data tables at:+- [Dataset Search](https://fiscaldata.treasury.gov/datasets/) — searchable dataset catalog+- [API endpoint table](https://fiscaldata.treasury.gov/api-documentation/#list-of-endpoints-table) — full endpoint listdiff --git a/skills/usfiscaldata/references/parameters.md b/skills/usfiscaldata/references/parameters.mdindex 3208e78f..d95ed1c2 100644--- a/skills/usfiscaldata/references/parameters.md+++ b/skills/usfiscaldata/references/parameters.md@@ -111,29 +111,56 @@ Controls how many records per page and which page to return.### Fetch All Records+For small result sets where `meta.total-pages` is 1, a single request with `page[size]=10000` is enough. Use `fetch_all()` below when pagination is required.+```python+import timeimport requestsimport pandas as pd-def fetch_all(endpoint, params=None):- """Fetch all pages and return as DataFrame."""+def fetch_all(endpoint, params=None, max_pages=50, max_records=500_000):+ """Fetch paginated results and return as DataFrame.++ Stops when all pages are retrieved or when max_pages / max_records limits+ are reached. Retries on HTTP 429 with exponential backoff.+ """params = dict(params or {})- params["page[size]"] = 10000+ params["page[size]"] = min(params.get("page[size]", 10000), 10000)params["page[number]"] = 1-+base = "https://api.fiscaldata.treasury.gov/services/api/fiscal_service"all_data = []-- while True:- resp = requests.get(f"{base}{endpoint}", params=params)++ for _ in range(max_pages):+ for attempt in range(3):+ resp = requests.get(f"{base}{endpoint}", params=params)+ if resp.status_code == 429:+ time.sleep(2 ** attempt)+ continue+ resp.raise_for_status()+ break+ else:+ raise RuntimeError("Rate limited after retries")+result = resp.json()+ if "error" in result:+ raise ValueError(f"API error: {result['error']} — {result.get('message', '')}")+all_data.extend(result["data"])-+ if len(all_data) >= max_records:+ all_data = all_data[:max_records]+ break+meta = result["meta"]if params["page[number]"] >= meta["total-pages"]:breakparams["page[number]"] += 1-+ time.sleep(0.1)+ else:+ raise RuntimeError(+ f"Reached max_pages={max_pages}; increase limit or narrow filters"+ )+return pd.DataFrame(all_data)```diff --git a/skills/usfiscaldata/references/response-format.md b/skills/usfiscaldata/references/response-format.mdindex d8da474c..91d459ba 100644--- a/skills/usfiscaldata/references/response-format.md+++ b/skills/usfiscaldata/references/response-format.md@@ -60,6 +60,8 @@ Use the `links` object to navigate pagination programmatically:| `next` | Next page (null if on last page) || `last` | Last page |+The HTTP response also includes a **`Link` header** with RFC 5988 relations (`rel="first"`, `rel="prev"`, `rel="next"`, `rel="last"`). Either the JSON `links` object or the `Link` header can be used for pagination.+## `data` ObjectArray of row objects. All values are **strings**, regardless of logical type.