Add agent skills under .agents/skills for Codex

Copy of the project skills (.claude/skills is gitignored) so Codex on
other machines picks them up; skills-lock.json records their sources.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-27 16:09:25 +00:00
parent 5a6fb2fc8c
commit 954bbf0127
135 changed files with 39094 additions and 0 deletions

View File

@@ -0,0 +1,229 @@
---
name: literature-review
description: Conducts systematic, scoping, and narrative literature reviews using PubMed, arXiv, bioRxiv, Semantic Scholar, and other appropriate sources. Use for research synthesis, reproducible literature searches, screening, citation checking, or preparing Markdown and PDF reviews. Tracks search coverage, records versus studies, and evidence limitations; supports meta-analysis planning but does not supply a meta-analysis engine.
allowed-tools: Read Write Edit Bash
license: MIT license
compatibility: Python 3.10+ with requests; network for DOI checks and searches. Optional parallel-cli requires Parallel authentication. PDF export needs Pandoc and XeLaTeX; AI schematics need OPENROUTER_API_KEY.
metadata:
version: "1.11"
last-reviewed: "2026-09-30"
skill-author: K-Dense Inc.
openclaw:
primaryEnv: OPENROUTER_API_KEY
envVars:
- name: OPENROUTER_API_KEY
required: false
description: OpenRouter API key for the skill's LLM-powered steps.
---
# Literature Review
## Overview
Conduct systematic, comprehensive literature reviews following rigorous academic methodology. Search multiple literature databases, synthesize findings thematically, verify all citations for accuracy, and generate professional output documents in markdown and PDF formats.
Use discipline-appropriate bibliographic databases for the reproducible search, with **parallel-web** (`parallel-cli search`) for scoping and supplementary discovery. Ranked web results and extracted excerpts cannot establish exhaustive coverage or substitute for full-text assessment. Bundled scripts process normalized records, check DOI registration, and render documents; they do not run a complete systematic review automatically.
## When to Use This Skill
Use this skill when:
- Conducting a systematic literature review for research or publication
- Synthesizing current knowledge on a specific topic across multiple sources
- Performing meta-analysis or scoping reviews
- Writing the literature review section of a research paper or thesis
- Investigating the state of the art in a research domain
- Identifying research gaps and future directions
- Requiring verified citations and professional formatting
## Figures and PRISMA reporting
For systematic reviews, use the appropriate [PRISMA 2020 flow template](https://www.prisma-statement.org/prisma-2020-flow-diagram) and reconciled screening counts. Distinguish records, reports, and studies, including reports not retrieved and reasons for full-text exclusions. Use tables or deterministic plotting for exact numbers, effect estimates, and risk-of-bias results.
Conceptual schematics are optional. The bundled generator needs `OPENROUTER_API_KEY` and creates a PNG draft with up to two generation/review iterations:
```bash
python scripts/generate_schematic.py "Conceptual evidence map; labels from the reviewed extraction table" \
-o figures/evidence_map.png --doc-type journal --iterations 2
```
Generation uses OpenRouter's `POST /api/v1/images` with
`google/gemini-3.1-flash-image`; review uses `POST /api/v1/chat/completions` with
`google/gemini-3.7-flash`. The output path must end in `.png`. Inspect labels,
counts, arrows, and accessibility yourself: `success` means an image was saved,
whereas `quality_met`, `final_reviewed`, and `termination_reason` in the review
log describe the automated review. Neither proves scientific accuracy. A failed
refinement preserves the previous draft. Check current model availability before
running paid generation; do not fabricate study counts in an image prompt.
## Core Workflow
A literature review runs in seven phases, documented in full with commands and templates
in [references/core_workflow.md](references/core_workflow.md):
1. **Planning and scoping** — the question, inclusion and exclusion criteria, and scope.
2. **Systematic literature search** — multi-database searching with recorded queries.
3. **Screening and selection** — title/abstract then full-text screening with counts kept
for the PRISMA flow.
4. **Data extraction and quality assessment** — structured extraction and risk-of-bias
or quality appraisal.
5. **Synthesis and analysis** — thematic or quantitative synthesis across studies.
6. **Citation verification** — every citation checked against the actual source.
7. **Document generation** — assembling the review with a complete bibliography.
Record every search string and date as you go: a review that cannot reproduce its own
search is not systematic. Per-database search guidance and citation styles are in
[references/search_and_citation.md](references/search_and_citation.md), and a full worked
review is in [references/example_workflow.md](references/example_workflow.md).
## Best Practices
### Search Strategy
1. **Pilot the question**: Optionally use `parallel-cli search` for scoping, then test database queries against known eligible reports
2. **Choose complementary sources**: Justify database and registry coverage for the question; no fixed number of databases guarantees completeness
3. **Include preprint servers**: Captures latest unpublished findings
4. **Document everything**: Search strings, dates, result counts for reproducibility — save all parallel-cli output to `sources/`
5. **Test and refine**: Run pilot searches, review results, adjust search terms
6. **Preserve all eligible records**: Citation counts can order exploratory reading but must not determine eligibility or replace risk-of-bias assessment
7. **Verify retrieved content**: Extraction can be incomplete; obtain the actual full report, or record it as not retrieved
### Records, Reports, and Studies
1. **Deduplicate records, then link reports**: DOI/title deduplication removes repeated search hits; it does not identify every paper from the same study. Link preprints, journal articles, protocols, and follow-up reports using trial IDs, cohort descriptions, sites, and recruitment dates.
2. **Keep a study-to-report map**: Preserve each source and explain which report supplies each outcome; do not count overlapping participants twice in a meta-analysis.
3. **Reconcile PRISMA counts**: Track records screened, reports sought/not retrieved/assessed, reports excluded with reasons, and included studies separately. Report counts can exceed study counts. See the [Cochrane selection guidance](https://www.cochrane.org/authors/handbooks-and-manuals/handbook/current/chapter-04).
### Screening and Selection
1. **Use clear criteria**: Document inclusion/exclusion criteria before screening
2. **Screen systematically**: Title → Abstract → Full text
3. **Document exclusions**: Record reasons for excluding studies
4. **Use independent eligibility decisions**: For systematic reviews, use two reviewers for final full-text eligibility and document disagreement resolution; disclose any single-reviewer limitation
### Synthesis
1. **Organize thematically**: Group by themes, NOT by individual studies
2. **Synthesize across studies**: Compare, contrast, identify patterns
3. **Be critical**: Evaluate quality and consistency of evidence
4. **Identify gaps**: Note what's missing or understudied
### Quality and Reproducibility
1. **Assess study quality**: Use appropriate quality assessment tools
2. **Verify citations and claims**: Run verify_citations.py for DOI registration/metadata, then compare the reference and the cited claim with the actual source
3. **Document methodology**: Provide enough detail for others to reproduce
4. **Follow guidelines**: Use PRISMA for systematic reviews
### Writing
1. **Be objective**: Present evidence fairly, acknowledge limitations
2. **Be systematic**: Follow structured template
3. **Be specific**: Include numbers, statistics, effect sizes where available
4. **Be clear**: Use clear headings, logical flow, thematic organization
## Common Pitfalls to Avoid
1. **Single database search**: Misses relevant papers; always search multiple databases
2. **No search documentation**: Makes review irreproducible; document all searches
3. **Study-by-study summary**: Lacks synthesis; organize thematically instead
4. **Treating DOI existence as support**: A registered DOI can still identify the wrong work; check identity, claim support, corrections, and retractions
5. **Too broad search**: Yields thousands of irrelevant results; refine with specific terms
6. **Too narrow search**: Misses relevant papers; include synonyms and related terms
7. **Ignoring preprints**: Misses latest findings; include bioRxiv, medRxiv, arXiv
8. **No quality assessment**: Treats all evidence equally; assess and report quality
9. **Publication bias**: Only positive results published; note potential bias
10. **Outdated search**: Field evolves rapidly; clearly state search date
## Integration with Other Skills
- **parallel-web**: Supplementary discovery, citation chaining, and URL extraction.
- **citation-management**: Metadata normalization, BibTeX/CSL export, and citation formatting.
- **pubmed-database / paper-lookup**: Domain-specific retrieval and lawful full-text discovery.
- **matplotlib / seaborn**: Reproducible evidence plots and quantitative figures.
- **venue-templates**: Target-journal structure, reference style, and submission requirements.
`gget search` queries Ensembl identifiers; it is not a PubMed or bioRxiv search command. Biological entity databases can inform background sections but do not replace bibliographic searching.
## Resources
### Bundled Resources
**Scripts:**
- `scripts/verify_citations.py`: Check DOI registration and retrieve Crossref metadata for manual review
- `scripts/generate_pdf.py`: Convert markdown to professional PDF
- `scripts/search_databases.py`: Process, deduplicate, and format search results
**References:**
- `references/citation_styles.md`: Detailed citation formatting guide (APA, Nature, Vancouver, Chicago, IEEE)
- `references/database_strategies.md`: Comprehensive database search strategies
**Assets:**
- `assets/review_template.md`: Complete literature review template with all sections
### External Resources
**Guidelines:**
- PRISMA (Systematic Reviews): https://www.prisma-statement.org/
- Cochrane Handbook: https://training.cochrane.org/handbook
- AMSTAR 2 (Review Quality): https://amstar.ca/
**Tools:**
- MeSH Browser: https://meshb.nlm.nih.gov/search
- PubMed Advanced Search: https://pubmed.ncbi.nlm.nih.gov/advanced/
- Boolean Search Guide: https://www.ncbi.nlm.nih.gov/books/NBK3827/
**Citation Styles:**
- APA Style: https://apastyle.apa.org/
- Nature Portfolio: https://www.nature.com/nature-portfolio/editorial-policies/reporting-standards
- NLM/Vancouver: https://www.nlm.nih.gov/bsd/uniform_requirements.html
## Dependencies
### Optional search CLI
```bash
# CLI syntax checked with parallel-cli 0.9.3
uv tool install "parallel-web-tools[cli]==0.9.3"
# Authenticate: parallel-cli auth (or set PARALLEL_API_KEY)
```
### Python tooling
```bash
uv run --isolated --with requests==2.34.2 python scripts/verify_citations.py review.md
```
### Required System Tools
```bash
# For PDF generation
brew install pandoc # macOS
apt-get install pandoc # Linux
# For LaTeX (PDF generation)
brew install --cask mactex # macOS
apt-get install texlive-xetex # Linux
```
Check dependencies:
```bash
python scripts/generate_pdf.py --check-deps
```
## Verification scope
The 2026-09-30 refresh checks the documented service contracts and runs the
bundled offline tests plus small public read-only probes. Search examples with
placeholder topics, credentials, or local bibliography files are illustrative;
they are not evidence that a particular review search is complete. See
[references/database_strategies.md](references/database_strategies.md) for exact
request/response limits and [references/example_workflow.md](references/example_workflow.md)
for an explicitly illustrative end-to-end recipe.
## Citing Scientific Agent Skills
This skill is part of Scientific Agent Skills by K-Dense. If it materially contributed to a
manuscript, report, presentation, or code release, add the paper to the references or
software section and tell the user you did so:
> Kassis, T., Agarwal, V., He, Y., Patel, D., & Brueckner, A. M. (2026). Scientific Agent
> Skills: A Library of Procedural Knowledge for Research Agents. arXiv:2609.00065.
> https://doi.org/10.48550/arXiv.2609.00065
Always cite the current version. The DOI and https://arxiv.org/abs/2609.00065 resolve to the
latest arXiv version, so never append a version suffix such as `v1`. When network access is
available, fetch https://arxiv.org/abs/2609.00065 (or
http://export.arxiv.org/api/query?id_list=2609.00065) before writing the reference and take
the author list, year, and version from that record. If the record lists a journal reference
or publisher DOI, cite the published version instead.

View File

@@ -0,0 +1,419 @@
# [Literature Review Title]
**Authors**: [Author Names and Affiliations]
**Date**: [Date]
**Review Type**: [Narrative / Systematic / Scoping / Meta-Analysis / Umbrella Review]
**Review Protocol**: [PROSPERO ID if registered, or state "Not registered"]
**PRISMA Compliance**: [Yes/No/Partial - specify which guidelines]
---
## Abstract
**Background**: [Context and rationale]
**Objectives**: [Primary and secondary objectives]
**Methods**: [Databases, dates, selection criteria, quality assessment]
**Results**: [n studies included; key findings by theme]
**Conclusions**: [Main conclusions and implications]
**Registration**: [PROSPERO ID or "Not registered"]
**Keywords**: [5-8 keywords]
---
## 1. Introduction
### 1.1 Background and Context
[Provide background information on the topic. Establish why this literature review is important and timely. Discuss the broader context and current state of knowledge.]
### 1.2 Scope and Objectives
[Clearly define the scope of the review and state the specific objectives. What questions will this review address?]
**Primary Research Questions:**
1. [Research question 1]
2. [Research question 2]
3. [Research question 3]
### 1.3 Significance
[Explain the significance of this review. Why is it important to synthesize this literature now? What gaps does it fill?]
---
## 2. Methodology
### 2.1 Protocol and Registration
**Protocol**: [PROSPERO ID / OSF link / Not registered]
**Deviations**: [Document any protocol deviations]
**PRISMA**: [Checklist in Appendix B]
### 2.2 Search Strategy
**Databases:** [PubMed, Scopus, Web of Science, bioRxiv, etc.]
**Supplementary:** [Citation chaining, grey literature, trial registries]
**Search String Example:**
```
("CRISPR"[Title/Abstract] OR "Cas9"[Title/Abstract]) AND
("disease"[MeSH Terms]) AND ("2015/01/01"[Publication Date] : "2024/12/31"[Publication Date])
```
**Dates:** [YYYY-MM-DD to YYYY-MM-DD] | **Executed:** [Date]
**Validation:** [Key papers used to test search strategy]
### 2.3 Tools and Software
**Screening:** [Rayyan, Covidence, ASReview]
**Analysis:** [VOSviewer, R, Python]
**Citation Management:** [Zotero, Mendeley, EndNote]
**AI Tools:** [Any AI-assisted tools used; document validation approach]
### 2.4 Inclusion and Exclusion Criteria
**Inclusion Criteria:**
- [Criterion 1: e.g., Published between 2015-2024]
- [Criterion 2: e.g., Peer-reviewed articles and preprints]
- [Criterion 3: e.g., English language]
- [Criterion 4: e.g., Human or animal studies]
- [Criterion 5: e.g., Original research or systematic reviews]
**Exclusion Criteria:**
- [Criterion 1: e.g., Case reports with n<5]
- [Criterion 2: e.g., Conference abstracts without full text]
- [Criterion 3: e.g., Editorials and commentaries]
- [Criterion 4: e.g., Duplicate publications]
- [Criterion 5: e.g., Retracted articles]
- [Criterion 6: e.g., Studies with unavailable full text after author contact]
### 2.5 Study Selection
**Reviewers:** [n independent reviewers] | **Conflict resolution:** [Method]
**Inter-rater reliability:** [Cohen's kappa = X]
**PRISMA Flow:**
```
Records identified (by source): n=[X]
Removed before screening (duplicates/other reasons): n=[D]
Records screened: n=[X-D]; records excluded: n=[E]
Reports sought: n=[S]; reports not retrieved: n=[U]
Reports assessed: n=[S-U]; reports excluded with reasons: n=[F]
Reports included: n=[S-U-F]; studies included: n=[N from study-report map]
```
**Exclusion reasons:** [List with counts; distinguish reports not retrieved]
**Study-report map:** [Study ID -> all reports, versions, trial IDs, and outcome sources]
### 2.6 Data Extraction
**Method:** [Standardized form (Appendix E); pilot-tested on n studies]
**Extractors:** [n independent] | **Verification:** [Double-checked]
**Items:** Study ID, design, population, interventions/exposures, outcomes, statistics, funding, COI, bias domains
**Missing data:** [Author contact protocol]
### 2.7 Quality Assessment
**Tool:** [Cochrane RoB 2 / ROBINS-I / Newcastle-Ottawa / AMSTAR 2 / JBI]\
**Method:** [2 independent reviewers; third for conflicts]
**Rating:** [Use tool-specific domain and overall judgments; RoB 2: low/some concerns/high]\
**Publication bias:** [Funnel plots, Egger's test - if meta-analysis]
### 2.8 Synthesis and Analysis
**Approach:** [Narrative / Meta-analysis / Both]
**Statistics** (if meta-analysis): Effect measures, heterogeneity (I², τ²), sensitivity analyses, subgroups
**Software:** [RevMan, R, Stata]
**Certainty:** [GRADE per outcome/body of evidence; risk of bias, inconsistency, indirectness, imprecision, publication bias]\
---
## 3. Results
### 3.1 Study Selection
**Summary:** [Records screened; reports sought/not retrieved/assessed/excluded/included; N distinct studies (M in meta-analysis)]\
**Study types:** [RCTs: n=X, Observational: n=Y, Reviews: n=Z]
**Years:** [Range; peak year]
**Geography:** [Countries represented]
**Source:** [Peer-reviewed: n=X, Preprints: n=Y]
### 3.2 Bibliometric Overview
[Optional: Trends, journal distribution, author networks, citations, keywords - if analyzed with VOSviewer or similar]
### 3.3 Study Characteristics
| Study | Year | Design | Sample Size | Key Methods | Main Findings | Quality |
|-------|------|--------|-------------|-------------|---------------|---------|
| First Author et al. | 2023 | [Type] | n=[X] | [Methods] | [Brief findings] | [Tool-specific judgment] |
**Risk of bias:** [Report tool-specific outcome/domain judgments and denominators]
### 3.4 Thematic Synthesis
[Organize by themes, NOT study-by-study. Synthesize across studies to identify consensus, controversies, and gaps.]
#### 3.4.1 Theme 1: [Title]
**Findings:** [Synthesis of key findings from multiple studies]
**Supporting studies:** [X, Y, Z]
**Contradictory evidence:** [If any]
**Certainty:** [GRADE rating if applicable]
### 3.5 Methodological Approaches
**Common methods:** [Method 1 (n studies), Method 2 (n studies)]
**Emerging techniques:** [New approaches observed]
**Methodological quality:** [Overall assessment]
### 3.6 Meta-Analysis Results
[Include only if conducting meta-analysis]
**Effect estimates:** [Primary/secondary outcomes with 95% CI, p-values]
**Heterogeneity:** [I²=X%, τ²=Y, interpretation]
**Subgroups & sensitivity:** [Key findings from analyses]
**Publication bias:** [Funnel plot, Egger's p=X]
**Forest plots:** [Include for primary outcomes]
### 3.7 Knowledge Gaps
**Knowledge:** [Unanswered research questions]
**Methodological:** [Study design/measurement issues]
**Translational:** [Research-to-practice gaps]
**Populations:** [Underrepresented groups/contexts]
---
## 4. Discussion
### 4.1 Main Findings
[Synthesize key findings by research question]
**Principal findings:** [Top 3-5 takeaways]
**Consensus:** [Where studies agree]
**Controversy:** [Conflicting results]
### 4.2 Interpretation and Implications
**Context:** [How findings advance/challenge current understanding]
**Mechanisms:** [Potential explanations for observed patterns]
**Implications for:**
- **Practice:** [Actionable recommendations]
- **Policy:** [If relevant]
- **Research:** [Theoretical, methodological, priority directions]
### 4.3 Strengths and Limitations
**Strengths:** [Comprehensive search, rigorous methods, large evidence base, transparency]
**Limitations:**
- Search/selection: [Language bias, database coverage, grey literature, publication bias]
- Methodological: [Heterogeneity, study quality]
- Temporal: [Rapid evolution, search cutoff date]
**Impact:** [How limitations affect conclusions]
### 4.4 Comparison with Previous Reviews
[If relevant: How does this review update/differ from prior reviews?]
### 4.5 Future Research
**Priority questions:**
1. [Question] - Rationale, suggested approach, expected impact
2. [Question] - Rationale, suggested approach, expected impact
3. [Question] - Rationale, suggested approach, expected impact
**Recommendations:** [Methodological improvements, understudied populations, emerging technologies]
---
## 5. Conclusions
[Concise conclusions addressing research questions]
1. [Conclusion directly addressing primary research question]
2. [Key finding conclusion]
3. [Gap/future direction conclusion]
**Evidence certainty:** [High/Moderate/Low/Very Low]
**Translation readiness:** [Ready / Needs more research / Preliminary]
---
## 6. Declarations
### Author Contributions
[CRediT taxonomy: Author 1 - Conceptualization, Methodology, Writing; Author 2 - Analysis, Review; etc.]
### Funding
[Grant details with numbers] OR [No funding received]
### Conflicts of Interest
[Author-specific declarations] OR [None]
### Data Availability
**Protocol:** [PROSPERO/OSF ID or "Not registered"]
**Data/Code:** [Repository URL/DOI or "Available upon request"]
**Materials:** [Search strategies (Appendix A), PRISMA checklist (Appendix B), extraction form (Appendix E)]
### Acknowledgments
[Contributors not meeting authorship criteria, librarians, patient involvement]
---
## 7. References
[Use consistent style: APA / Nature / Vancouver]
**Format examples:**
APA: Author, A. A., & Author, B. B. (Year). Title. *Journal*, *volume*(issue), pages. https://doi.org/xx.xxxx
Nature: Author, A. A. & Author, B. B. Title. *J. Name* **volume**, pages (year).
Vancouver: Author AA, Author BB. Title. J Abbrev. Year;volume(issue):pages. doi:xx.xxxx
1. [First reference]
2. [Second reference]
3. [Continue...]
---
## 8. Appendices
### Appendix A: Search Strings
**PubMed** (Date: YYYY-MM-DD; Results: n)
```
[Complete search string with operators and MeSH terms]
```
[Repeat for each database: Scopus, Web of Science, bioRxiv, etc.]
### Appendix B: PRISMA Checklist
[Summary below is not the complete checklist. Attach the official PRISMA 2020 checklist, including all applicable items/subitems, or the appropriate extension.]
| Section | Item | Reported? | Page |
|---------|------|-----------|------|
| Title | Identify as systematic review | Yes/No | # |
| Abstract | Structured summary | Yes/No | # |
| Methods | Eligibility, sources, search, selection, data, quality | Yes/No | # |
| Results | Selection, characteristics, risk of bias, syntheses | Yes/No | # |
| Discussion | Interpretation, limitations, conclusions | Yes/No | # |
| Other | Registration, support, conflicts, availability | Yes/No | # |
### Appendix C: Excluded Studies
| Study | Year | Reason | Category |
|-------|------|--------|----------|
| Author et al. | Year | [Reason] | [Wrong population/outcome/design/etc.] |
**Summary:** Wrong population (n=X), Wrong outcome (n=Y), etc.
### Appendix D: Quality Assessment
**Tool:** [Cochrane RoB 2 / ROBINS-I / Newcastle-Ottawa / etc.]\
| Study | Domain 1 | Domain 2 | Domain 3 | Overall |
|-------|----------|----------|----------|---------|
| Study 1 | Low | Low | Some concerns | Some concerns |
| Study 2 | [Score] | [Score] | [Score] | [Overall] |
### Appendix E: Data Extraction Form
```
STUDY: Author______ Year______ DOI______
DESIGN: □RCT □Cohort □Case-Control □Cross-sectional □Other______
POPULATION: n=_____ Age_____ Setting_____
INTERVENTION/EXPOSURE: _____
OUTCOMES: Primary_____ Secondary_____
RESULTS: Effect size_____ 95%CI_____ p=_____
RISK OF BIAS: Tool______ Outcome______ Judgment______ Rationale______
FUNDING/COI: _____
```
### Appendix F: Meta-Analysis Details
[Only if meta-analysis performed]
**Software:** [R 4.x.x with meta/metafor packages / RevMan / Stata]
**Model:** [Random-effects; justification]
**Code:** [Link to repository]
**Sensitivity analyses:** [Details]
### Appendix G: Author Contacts
| Study | Contact Date | Response | Data Received |
|-------|--------------|----------|---------------|
| Author et al. | YYYY-MM-DD | Yes/No | Yes/No/Partial |
---
## 9. Supplementary Materials
[If applicable]
**Tables:** S1 (Full study characteristics), S2 (Quality scores), S3 (Subgroups), S4 (Sensitivity)
**Figures:** S1 (PRISMA diagram), S2 (Risk of bias), S3 (Funnel plot), S4 (Forest plots), S5 (Networks)
**Data:** S1 (Extraction file), S2 (Search results), S3 (Analysis code), S4 (PRISMA checklist)
**Repository:** [OSF/GitHub/Zenodo URL with DOI]
---
## Review Metadata
**Registration:** [Registry] ID: [Number] (Date: YYYY-MM-DD)
**Search dates:** Initial: [Date]; Updated: [Date]
**Version:** [1.0] | **Last updated:** [Date]
**Quality checks:**
- [ ] DOI registration checked; identity, claim support, and correction/retraction status manually reviewed
- [ ] PRISMA checklist completed
- [ ] Search reproducible
- [ ] Independent data verification
- [ ] Code peer-reviewed
- [ ] All authors approved
---
## Usage Notes
**Review type adaptations:**
- Systematic Review: Use all sections
- Meta-Analysis: Include sections 3.6, Appendix F
- Narrative Review: May omit some methodology detail
- Scoping Review: Follow PRISMA-ScR, may omit quality assessment
**Key principles:**
1. Remove all [bracketed placeholders]
2. Follow PRISMA 2020 guidelines
3. Pre-register when feasible (PROSPERO/OSF)
4. Use thematic synthesis, not study-by-study
5. Be transparent and reproducible
6. Verify reference identity and claim support, including items without DOIs
7. Make data/code openly available
**Common pitfalls to avoid:**
- Don't list studies - synthesize them
- Don't cherry-pick results
- Don't ignore limitations
- Don't overstate conclusions
- Don't skip publication bias assessment
**Resources:**
- PRISMA 2020: https://www.prisma-statement.org/
- PROSPERO: https://www.crd.york.ac.uk/prospero/
- Cochrane Handbook: https://training.cochrane.org/handbook
- GRADE: https://www.gradeworkinggroup.org/
**DELETE THIS SECTION FROM YOUR FINAL REVIEW**
---

View File

@@ -0,0 +1,177 @@
# Citation Styles Reference
Reviewed 2026-09-30. This is a formatting aid; all sample author/title/page combinations below are illustrative, not verified references. Replace placeholders and use a current CSL style plus the target venue instructions for final output. The DOI-checking script verifies registration/metadata, not style compliance.
## APA Style (7th Edition)
### Journal Articles
**Format**: Author, A. A., Author, B. B., & Author, C. C. (Year). Title of article. *Title of Periodical*, *volume*(issue), page range. https://doi.org/xx.xxx/yyyy
**Example**: Smith, J. D., Johnson, M. L., & Williams, K. R. (2023). Machine learning approaches in drug discovery. *Nature Reviews Drug Discovery*, *22*(4), 301-318. [DOI URL]
### Books
**Format**: Author, A. A. (Year). *Title of work: Capital letter also for subtitle*. Publisher Name. https://doi.org/xxxx
**Example**: Kumar, V., Abbas, A. K., & Aster, J. C. (2021). *Robbins and Cotran pathologic basis of disease* (10th ed.). Elsevier.
### Book Chapters
**Format**: Author, A. A., & Author, B. B. (Year). Title of chapter. In E. E. Editor & F. F. Editor (Eds.), *Title of book* (pp. xx-xx). Publisher.
**Example**: Brown, P. O., & Botstein, D. (2020). Exploring the new world of the genome with DNA microarrays. In M. B. Eisen & P. O. Brown (Eds.), *DNA microarrays: A molecular cloning manual* (pp. 1-45). Cold Spring Harbor Laboratory Press.
### Preprints
**Format**: Author, A. A., & Author, B. B. (Year). Title of preprint. *Repository Name*. https://doi.org/xxxx
**Example**: Zhang, Y., Chen, L., & Wang, H. (2024). Novel therapeutic targets in Alzheimer's disease. *bioRxiv*. [preprint DOI URL]
### Conference Papers
**Format**: Author, A. A. (Year, Month day-day). Title of paper. In E. E. Editor (Ed.), *Title of conference proceedings* (pp. xx-xx). Publisher. https://doi.org/xxxx
---
## Nature Style
### Journal Articles
**Format**: Author, A. A., Author, B. B. & Author, C. C. Title of article. *J. Name* **volume**, page range (year).
**Example**: Smith, J. D., Johnson, M. L. & Williams, K. R. Machine learning approaches in drug discovery. *Nat. Rev. Drug Discov.* **22**, 301-318 (2023).
### Books
**Format**: Author, A. A. & Author, B. B. *Book Title* (Publisher, Year).
**Example**: Kumar, V., Abbas, A. K. & Aster, J. C. *Robbins and Cotran Pathologic Basis of Disease* 10th edn (Elsevier, 2021).
### Multiple Authors
- Nature reference lists: list all authors through five; above five use the first author followed by "et al.". Other Nature Portfolio journals may differ; check the actual journal instructions.
**Example**: Zhang, Y. et al. Novel therapeutic targets in Alzheimer's disease. *bioRxiv* [preprint DOI URL] (2024).
---
## Chicago Style (18th Edition, Author-Date)
### Journal Articles
**Format**: Author, First Name Middle Initial. Year. "Article Title." *Journal Title* volume, no. issue (Month): page range. https://doi.org/xxxx.
**Example**: Smith, John D., Mary L. Johnson, and Karen R. Williams. 2023. "Machine Learning Approaches in Drug Discovery." *Nature Reviews Drug Discovery* 22, no. 4 (April): 301-318. [DOI URL].
Reference lists include up to six authors; above six list the first three plus et al. Three or more authors use first author plus et al. in text. Current Chicago no longer requires a book publication place.
### Books
**Format**: Author, First Name Middle Initial. Year. *Book Title: Subtitle*. Edition. Publisher.
**Example**: Kumar, Vinay, Abul K. Abbas, and Jon C. Aster. 2021. *Robbins and Cotran Pathologic Basis of Disease*. 10th ed. Elsevier.
---
## Vancouver Style (Numbered)
### Journal Articles
**Format**: Author AA, Author BB, Author CC. Title of article. Abbreviated Journal Name. Year;volume(issue):page range.
**Example**: Smith JD, Johnson ML, Williams KR. Machine learning approaches in drug discovery. Nat Rev Drug Discov. 2023;22(4):301-18.
### Books
**Format**: Author AA, Author BB. Title of book. Edition. Place: Publisher; Year.
**Example**: Kumar V, Abbas AK, Aster JC. Robbins and Cotran pathologic basis of disease. 10th ed. Philadelphia: Elsevier; 2021.
### Citation in Text
Use superscript numbers in order of appearance: "Recent studies^1,2^ have shown..."
---
## IEEE Style
### Journal Articles
**Format**: [#] A. A. Author, B. B. Author, and C. C. Author, "Title of article," *Abbreviated Journal Name*, vol. x, no. x, pp. xxx-xxx, Month Year.
**Example**: [1] J. D. Smith, M. L. Johnson, and K. R. Williams, "Machine learning approaches in drug discovery," *Nat. Rev. Drug Discov.*, vol. 22, no. 4, pp. 301-318, Apr. 2023.
### Books
**Format**: [#] A. A. Author, *Title of Book*, xth ed. City, State: Publisher, Year.
**Example**: [2] V. Kumar, A. K. Abbas, and J. C. Aster, *Robbins and Cotran Pathologic Basis of Disease*, 10th ed. Philadelphia, PA: Elsevier, 2021.
---
## Common Abbreviations for Journal Names
- Nature: Nature (single-word journal titles are not shortened)
- Science: Science
- Cell: Cell
- Nature Reviews Drug Discovery: Nat. Rev. Drug Discov.
- Journal of the American Chemical Society: J. Am. Chem. Soc.
- Proceedings of the National Academy of Sciences: Proc. Natl. Acad. Sci. U.S.A.
- PLOS ONE: PLoS ONE
- Bioinformatics: Bioinformatics
- Nucleic Acids Research: Nucleic Acids Res.
---
## DOI Best Practices
1. **Always verify DOIs**: Use the verify_citations.py script to check all DOIs
2. **Format as URLs**: https://doi.org/10.xxxx/yyyy (preferred over doi:10.xxxx/yyyy)
3. **Separate punctuation from identifiers**: APA omits a final period after a DOI URL; other styles may differ. Do not copy prose punctuation into the identifier
4. **Resolve redirects**: Check that DOIs resolve to the correct article
---
## In-Text Citation Guidelines
### APA Style
- (Smith et al., 2023)
- Smith et al. (2023) demonstrated...
- Multiple citations: (Brown, 2022; Smith et al., 2023; Zhang, 2024)
### Nature Style
- Superscript numbers: Recent studies^1,2^ have shown...
- Or: Recent studies (refs 1,2) have shown...
### Chicago Style
- (Smith et al. 2023) for three or more authors
- Smith et al. (2023) found...
---
## Reference List Organization
### By Citation Style
- **APA, Chicago**: Alphabetical by first author's last name
- **Nature, Vancouver, IEEE**: Numerical order of first appearance in text
### Hanging Indents
Most styles use hanging indents where the first line is flush left and subsequent lines are indented.
### Consistency
Maintain consistent formatting throughout:
- Capitalization (title case vs. sentence case)
- Journal name abbreviations
- DOI presentation
- Author name format
## Authoritative style resources
- [APA reference examples](https://apastyle.apa.org/style-grammar-guidelines/references/examples) and [reference guide](https://apastyle.apa.org/instructional-aids/reference-guide.pdf).
- [Nature formatting guide](https://www.nature.com/nature/for-authors/formatting-guide).
- [Chicago author-date examples](https://www.chicagomanualofstyle.org/tools_citationguide/citation-guide-2.html).
- [NLM Citing Medicine](https://www.ncbi.nlm.nih.gov/books/NBK7256/); numbered citation punctuation and author truncation can be journal-specific.
- [IEEE reference guide](https://ieeeauthorcenter.ieee.org/wp-content/uploads/IEEE-Reference-Guide.pdf). Its full current text was not retrievable during this refresh; the IEEE examples above remain illustrative and require venue verification.
- [Pandoc citation processing](https://pandoc.org/MANUAL.html#citations); a local CSL file and complete bibliography are required for the selected nondefault style.

View File

@@ -0,0 +1,268 @@
# Core Workflow
Illustrative workflow; example queries, dates, counts, and numerical findings are not executed review results. Run commands from this skill directory, using paths to your review workspace.
All seven phases in full: planning and scoping, systematic search, screening and
selection, data extraction and quality assessment, synthesis and analysis, citation
verification, and document generation.
## Core Workflow
Literature reviews follow a structured, multi-phase workflow:
### Phase 1: Planning and Scoping
1. **Define Research Question**: Use PICO framework (Population, Intervention, Comparison, Outcome) for clinical/biomedical reviews
- Example: "What is the efficacy of CRISPR-Cas9 (I) for treating sickle cell disease (P) compared to standard care (C)?"
2. **Establish Scope and Objectives**:
- Define clear, specific research questions
- Determine review type (narrative, systematic, scoping, meta-analysis)
- Set boundaries (time period, geographic scope, study types)
3. **Develop Search Strategy**:
- Identify 2-4 main concepts from research question
- List synonyms, abbreviations, and related terms for each concept
- Plan Boolean operators (AND, OR, NOT) to combine terms
- Select complementary bibliographic databases and registries appropriate to the question
- **Optionally use parallel-web (`parallel-cli search`) for initial scoping** to quickly gauge the landscape before formal database searches
4. **Set Inclusion/Exclusion Criteria**:
- Date range (e.g., the explicitly historical interval 2015-2024)
- Language (typically English, or specify multilingual)
- Publication types (peer-reviewed, preprints, reviews)
- Study designs (RCTs, observational, in vitro, etc.)
- Document all criteria clearly
### Phase 2: Systematic Literature Search
1. **Multi-Database Search**:
Select bibliographic databases and registries appropriate for the domain. Use optional web search for scoping and supplementary discovery; record it separately from database exports.
**Supplementary web discovery (parallel-web):**
- Use `parallel-cli search` with academic domain filtering for broad scholarly coverage
- Consider academic-focused and general searches; ranked samples do not guarantee complete retrieval
```bash
mkdir -p sources
# Illustrative ranked sample; not a complete search
parallel-cli search "your research topic" -q "keyword1" -q "keyword2" \
--json --max-results 10 --excerpt-max-chars-total 27000 \
--include-domains "scholar.google.com,arxiv.org,pubmed.ncbi.nlm.nih.gov,semanticscholar.org,biorxiv.org,medrxiv.org,ncbi.nlm.nih.gov,nature.com,science.org,ieee.org,acm.org,springer.com,wiley.com,cell.com,pnas.org,nih.gov" \
-o sources/litreview_<topic>-academic.json
# General search for supplementary sources
parallel-cli search "your research topic" -q "keyword1" -q "keyword2" \
--json --max-results 10 --excerpt-max-chars-total 27000 \
-o sources/litreview_<topic>-general.json
```
- Use `parallel-cli extract --full-content` to request content from accessible paper URLs; check for truncation and retrieval errors
```bash
parallel-cli extract "https://arxiv.org/abs/1706.03762" --full-content --json
```
**Biomedical & Life Sciences:**
- Search PubMed via its interface or E-utilities; PMC has different full-text coverage
- Search bioRxiv/medRxiv interfaces, or retrieve date-range API metadata and explicitly filter it
- See `database_strategies.md` for exact requests, authentication, and export limits
**General Scientific Literature:**
- Search arXiv via direct API (preprints in physics, math, CS, q-bio)
- Search Semantic Scholar using its documented relevance or bulk API as appropriate
- Use Google Scholar manually for supplementary discovery and citation chaining; preserve search and screening limits
Biological entity databases can inform background, but do not count as
bibliographic sources simply because they contain references.
2. **Document Search Parameters**:
```markdown
## Search Strategy
### Database: PubMed
- **Date searched**: 2024-10-25
- **Date range**: 2015-01-01 to 2024-10-25
- **Search string**:
```
("CRISPR"[Title] OR "Cas9"[Title])
AND ("Anemia, Sickle Cell"[MeSH Terms] OR "SCD"[Title/Abstract])
AND 2015:2024[Publication Date]
```
- **Results**: 247 articles
```
Repeat for each database searched.
3. **Export and Aggregate Results**:
- Export results in JSON format from each database
- Normalize raw provider responses into a JSON array, preserving raw exports and provenance separately
- Use `scripts/search_databases.py` for post-processing:
```bash
python scripts/search_databases.py combined_results.json \
--deduplicate \
--format markdown \
--output aggregated_results.md
```
### Phase 3: Screening and Selection
1. **Deduplication**:
```bash
python scripts/search_databases.py results.json --deduplicate --format json --output unique_results.json
```
- Keeps first normalized DOI; title fallback compares DOI-less records only. Review matches and retain raw duplicates for enrichment
- Document number of duplicates removed
2. **Title Screening**:
- Review all titles against inclusion/exclusion criteria
- Exclude obviously irrelevant studies
- Document number excluded at this stage
3. **Abstract Screening**:
- Read abstracts of remaining studies
- Apply inclusion/exclusion criteria rigorously
- Document reasons for exclusion
4. **Full-Text Screening**:
- Obtain full texts of remaining studies
- Conduct detailed review against all criteria
- Document specific reasons for exclusion
- Record final number of included studies
5. **Create PRISMA Flow Diagram**:
- Use the official template matching new/updated review and source types.
- Track records identified and removed before screening, records screened
and excluded, reports sought/not retrieved/assessed, excluded reports with
reasons, and included studies plus reports of those studies.
- Reconcile counts at each transition; do not invent one included-study count
from the number of publications. Maintain a study-to-report map.
### Phase 4: Data Extraction and Quality Assessment
1. **Extract Key Data** from each included study:
- Study metadata (authors, year, journal, DOI)
- Study design and methods
- Sample size and population characteristics
- Key findings and results
- Limitations noted by authors
- Funding sources and conflicts of interest
2. **Assess Risk of Bias and Certainty**:
- Use a tool appropriate to the design and question: RoB 2 for randomized
trial results; ROBINS-I for nonrandomized intervention results; AMSTAR 2
for systematic reviews of healthcare interventions. Other designs require their own appraisal tool.
- Preserve domain judgments and rationale. RoB 2 uses low risk, some concerns,
or high risk; do not force every tool onto a common numerical scale.
- GRADE assesses a body of evidence for each outcome (high/moderate/low/very
low), not a generic grade for each individual study. See the
[Cochrane certainty guidance](https://www.cochrane.org/authors/handbooks-and-manuals/handbook/current/chapter-14).
- Pre-specify how bias affects synthesis; do not invent post-hoc exclusions.
3. **Organize by Themes**:
- Identify 3-5 major themes across studies
- Group studies by theme (studies may appear in multiple themes)
- Note patterns, consensus, and controversies
### Phase 5: Synthesis and Analysis
1. **Create Review Document** from template:
```bash
cp assets/review_template.md my_literature_review.md
```
2. **Write Thematic Synthesis** (NOT study-by-study summaries):
- Organize Results section by themes or research questions
- Synthesize findings across multiple studies within each theme
- Compare and contrast different approaches and results
- Identify consensus areas and points of controversy
- Highlight the strongest evidence
Fictitious structure example (replace every count and percentage with extracted evidence):
```markdown
#### 3.3.1 Theme: CRISPR Delivery Methods
Multiple delivery approaches have been investigated for therapeutic
gene editing. Viral vectors (AAV) were used in 15 studies^1-15^ and
showed high transduction efficiency (65-85%) but raised immunogenicity
concerns^3,7,12^. In contrast, lipid nanoparticles demonstrated lower
efficiency (40-60%) but improved safety profiles^16-23^.
```
3. **Critical Analysis**:
- Evaluate methodological strengths and limitations across studies
- Assess quality and consistency of evidence
- Identify knowledge gaps and methodological gaps
- Note areas requiring future research
4. **Write Discussion**:
- Interpret findings in broader context
- Discuss clinical, practical, or research implications
- Acknowledge limitations of the review itself
- Compare with previous reviews if applicable
- Propose specific future research directions
### Phase 6: Citation Verification
**CRITICAL**: All citations must be verified for accuracy before final submission.
1. **Verify All DOIs**:
```bash
python scripts/verify_citations.py my_literature_review.md
```
This script:
- Extracts all DOIs from the document
- Checks DOI registration via the Handle API
- Retrieves available Crossref metadata and preserves unresolved errors
- Generates verification report
- Does not verify claim support, publisher accessibility, or final citation style
2. **Review Verification Report**:
- Check for any failed DOIs
- Verify author names, titles, and publication details match
- Correct any errors in the original document
- Resolve errors against the source; do not delete a reference solely because a service timed out or lacks its metadata
3. **Format Citations Consistently**:
- Choose one citation style and use throughout (see `references/citation_styles.md`)
- Common styles: APA, Nature, Vancouver, Chicago, IEEE
- Use complete metadata with a CSL processor; the script only provides metadata previews
- Ensure in-text citations match reference list format
### Phase 7: Document Generation
1. **Generate PDF**:
```bash
python scripts/generate_pdf.py my_literature_review.md \
--bibliography my_literature_review.bib --csl styles/apa.csl \
--output my_review.pdf
```
Supply an existing `.bib` and `.csl` for that example; they are not bundled.
`[@key]` citations are formatted, while manually typed references remain unchanged.
Options:
- `--csl` / `--citation-style`: existing local CSL path/name; omitted uses Pandoc default
- `--bibliography`: bibliography file; sibling `.bib` also auto-detected
- `--output`: PDF destination
- `--no-toc`: Disable table of contents
- `--no-numbers`: Disable section numbering
- `--check-deps`: Check if pandoc/xelatex are installed
2. **Review Final Output**:
- Check PDF formatting and layout
- Verify all sections are present
- Ensure citations render correctly
- Check that figures/tables appear properly
- Verify table of contents is accurate
3. **Quality Checklist**:
- [ ] DOI registration checked; metadata identity and claim support reviewed manually
- [ ] Citations formatted consistently
- [ ] PRISMA flow diagram included (for systematic reviews)
- [ ] Search methodology fully documented
- [ ] Inclusion/exclusion criteria clearly stated
- [ ] Results organized thematically (not study-by-study)
- [ ] Quality assessment completed
- [ ] Limitations acknowledged
- [ ] References complete and accurate
- [ ] PDF generates without errors

View File

@@ -0,0 +1,183 @@
# Literature database search strategies
Reviewed 2026-09-30. These are bibliographic discovery contracts, not a promise
of complete retrieval. Save query, platform, date/time, date-field meaning,
filters, raw pages, reported total, exported count, and any failures. Mark a
capped or interrupted retrieval incomplete before screening it.
## Source selection and query design
1. Define the review type and eligibility criteria before seeing results. Use
PICO for intervention questions; adapt the framework for other questions.
2. Select complementary bibliographic databases, relevant registries, preprint
servers, and grey literature sources. A web search and a biological entity
database are not substitutes for a discipline's bibliographic index.
3. Build synonym groups with OR and combine concepts with AND. Pilot against
known eligible papers. Consider whether outcome filters, language limits,
publication-type limits, or NOT terms discard relevant studies.
4. Translate each query to that platform. Wildcards and field syntax are not
portable: do not copy PubMed `[MeSH]`, arXiv `ti:`, or search-engine operators
into another API. Record the actual translated query, not just keywords.
5. For systematic reviews, screen against protocol criteria regardless of venue,
author reputation, institutional affiliation, or citation count. Bibliometric
metrics reflect exposure and field/age effects, not risk of bias.
## PubMed and PMC
Use the [PubMed interface](https://pubmed.ncbi.nlm.nih.gov/advanced/) or NCBI
E-utilities. `gget search` searches Ensembl and has no PubMed/bioRxiv mode.
PubMed contains bibliographic records; PMC is a full-text repository with a
partly overlapping corpus. Do not equate access to an abstract with full text.
A small first-page request, not a complete review search:
```bash
mkdir -p sources
curl --fail-with-body --get 'https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi' \
--data-urlencode 'db=pubmed' \
--data-urlencode 'term=(CRISPR[Title/Abstract]) AND ("Anemia, Sickle Cell"[MeSH Terms])' \
--data-urlencode 'retmode=json' --data-urlencode 'retmax=5' \
--data-urlencode 'tool=literature_review' -o sources/pubmed-first-page.json
```
- ESearch returns `esearchresult.count` (often a string), `idlist`, and query
translation/warnings. Inspect these; HTTP 200 alone does not confirm success.
- Use `retstart`/`retmax` for paging **within the first 10,000 PubMed matches**.
Partition larger searches into recorded, deduplicated subqueries or use a
documented bulk method; the History server does not bypass this limit.
- EFetch is `GET .../efetch.fcgi?db=pubmed&id=PMID1,PMID2&retmode=xml` (or POST for
large ID sets). Parse `PubmedArticleSet` XML, preserve article/book records,
and reconcile requested versus returned IDs.
- No key is needed for small requests. Supply a real contact `email` and `tool`
for sustained use; optional `api_key` raises the default shared limit from
3 requests/s per IP to 10/s per key. Account for concurrent clients.
- Use explicit `[Publication Date]` ranges, and record the selected field.
A historical example such as `2020:2024[DP]` does not mean "current years".
Sources: [NLM parameter guide](https://www.nlm.nih.gov/dataguide/eutilities/utilities.html),
[PubMed 10,000-result ceiling](https://ncbiinsights.ncbi.nlm.nih.gov/2021/10/05/updated-pubmed-api/),
[NCBI usage guidelines](https://eutilities.github.io/site/API_Key/usageandkey/).
## bioRxiv and medRxiv
The [official API](https://api.biorxiv.org/) provides date/DOI metadata retrieval,
not a general keyword query endpoint. Use the server's search interface for
keyword discovery or filter the downloaded metadata explicitly.
- `GET https://api.biorxiv.org/details/{server}/{from}/{to}/{cursor}/json`, with
server `biorxiv` or `medrxiv`, date strings `YYYY-MM-DD`, zero-based
cursor (start at 0), and optional `category=cell_biology`.
- Response `collection[]` holds records; `messages[]` describes status, count,
cursor, and totals. Date-range calls return at most 30 records; advance the
cursor by the number received, retain all versions, and check totals/status.
- Single DOI: `/details/{server}/{doi}/na/json`. Preserve DOI, `version`, `date`,
abstract, license, and `published` linkage. A preprint and a published report
may describe one study but are distinct reports.
- `/pubs/{server}/{from}/{to}/{cursor}` maps publication links, with up to 100
entries per page. It has a different schema (`biorxiv_doi`, `published_doi`).
- Public reads need no API key. Use conservative sequential calls and stop on
throttling/errors; do not interpret missing publication links as proof that
a preprint remains unpublished.
## arXiv
`GET https://export.arxiv.org/api/query` accepts `search_query`, `id_list`,
`start` (zero-based), `max_results`, `sortBy`, and `sortOrder`. No key is needed.
```bash
curl --fail-with-body --get 'https://export.arxiv.org/api/query' \
--data-urlencode 'search_query=cat:q-bio.QM AND ti:"single cell"' \
--data-urlencode 'start=0' --data-urlencode 'max_results=5' \
--data-urlencode 'sortBy=submittedDate' --data-urlencode 'sortOrder=descending' \
-o sources/arxiv-first-page.xml
```
Parse Atom namespaces, `opensearch:totalResults`, and entry IDs; error entries
can arrive in an Atom feed. Preserve `vN`, original `published`, and `updated`
dates. `ti:` is the title field, not `title:`. Use a single connection with at
least three seconds between requests. Use pages no larger than 2,000 and do
not expect offsets to provide more than 30,000 matches; partition or use the
bulk interfaces. This is preprint discovery, not evidence of peer review.
Source: [arXiv API manual](https://info.arxiv.org/help/api/user-manual.html).
## Semantic Scholar
Use the [Graph API contract](https://api.semanticscholar.org/api-docs/graph)
(and its downloadable [schema](https://api.semanticscholar.org/graph/v1/swagger.json)).
- Relevance search: `GET https://api.semanticscholar.org/graph/v1/paper/search`;
plain-text `query`, separate `year=2020-2024`, optional `fields`, `offset`,
`limit` (maximum 100). Response has `data[]`, `total`, and optional `next`.
Only 1,000 relevance-ranked records are retrievable; not an exhaustive export.
- Bulk search: `GET .../paper/search/bulk`; query uses its documented Boolean
grammar (`+`, `|`, `-`, quotes, parentheses), with separate filters and
`fields`. Response has `data[]` and a continuation `token`; pass that token
unchanged to the next request. Up to 1,000 records/call, capped at 10 million.
Nested citation/reference data are not available on this endpoint.
- Do not invent `title:`/`author:` operators for the relevance API. Use separate
author or title search routes only after consulting their own contracts.
- API keys go in `x-api-key`; availability/quota depends on the endpoint and
account. Anonymous access is a shared, throttled pool. Follow your granted
quota, inspect HTTP 429, and back off; the former blanket "100 requests per
5 minutes" is not a current service guarantee.
- Citation counts and influential-citation labels are discovery aids. Check
paper identity, missing fields, date coverage, and source text yourself.
## OpenAlex, Crossref, and supplementary search
[OpenAlex authentication](https://help.openalex.org/api/authentication/) permits
keyless casual reads; a free key raises the daily budget. Use `api_key` or
`Authorization: Bearer` without saving secrets in search logs. `GET
https://api.openalex.org/works` accepts `search`, `filter`, `select`, and `sort`.
Responses have `results[]` and `meta`. The current `per_page` maximum is 100;
start `cursor=*` and follow `meta.next_cursor` unchanged. Basic page-based
retrieval stops at 10,000. Respect request credits and rate-limit headers;
keyless does not mean unlimited. See [paging](https://help.openalex.org/api/paging/).
Crossref `GET https://api.crossref.org/works/{doi}` is a singleton metadata
lookup with JSON `message`, no key or pagination. A 404 does not prove a DOI
from another registration agency is invalid. List searches (`/works?query...`)
have different quotas and pagination: public list limit 1/s, polite 3/s, versus
5/s and 10/s for single records. Provide real `mailto` for polite access; follow
[response headers](https://community.crossref.org/t/refining-rest-api-limits-for-improved-stability-and-reliability/16137).
Google Scholar's [interface](https://scholar.google.com/intl/en/scholar/help.html)
provides Cited by, Related articles, and Cite exports, but no supported bulk API.
Record queries and screened ranges; do not promise citation-count sorting,
unlimited results, or complete coverage from a ranked sample. Stop on access
blocks. Dimensions and licensed indexes require the access your institution
actually holds; a free website tier does not imply API entitlement.
## Result normalization and reproducibility
`search_databases.py` does **not** query or merge raw provider envelopes. Give it
a JSON array of normalized objects, preserving the raw exports separately:
```json
[
{"title": "Example title", "authors": "Author, A. and Author, B.",
"first_author": "Author", "year": 2026, "source": "PubMed",
"doi": null, "url": "https://pubmed.ncbi.nlm.nih.gov/", "citations": null}
]
```
Use strings for title/authors/source and numbers or null for citation counts;
BibTeX authors require `and` separators. Keep provider IDs, search/run IDs,
retrieval dates, and source provenance as extra fields. Missing is not zero.
```bash
python scripts/search_databases.py combined_results.json --deduplicate \
--format json --output unique_results.json --summary
```
Deduplication keeps the first normalized DOI; title fallback compares DOI-less
records only. Review title matches manually and enrich from raw duplicates;
the script does not choose the most complete metadata or link all reports of a
study. Unknown years remain for manual review. Ranking only orders the imported
sample. Use final BibTeX keys from the export; same-author/year keys receive
suffixes. An export timestamp is not the original search date.
Use the official [PRISMA guidance](https://www.prisma-statement.org/prisma-2020)
and [Cochrane selection guidance](https://www.cochrane.org/authors/handbooks-and-manuals/handbook/current/chapter-04)
to keep screening decisions and report/study links auditable.

View File

@@ -0,0 +1,71 @@
# Example Workflow
Illustrative end-to-end recipe, not an executed review. Run from the skill directory; populate the protocol, normalized search records, bibliography, and CSL file before the dependent commands. Dates below are a deliberately historical 2015-2024 interval.
## Example Workflow
Complete workflow for a biomedical literature review:
```bash
# 1. Create review document from template
mkdir -p sources styles
cp assets/review_template.md crispr_sickle_cell_review.md
# 2. Optional supplementary discovery (authenticated Parallel account)
parallel-cli search "CRISPR Cas9 sickle cell disease gene therapy efficacy" \
-q "CRISPR" -q "sickle cell" -q "gene therapy" \
--json --max-results 10 --excerpt-max-chars-total 27000 \
--include-domains "scholar.google.com,arxiv.org,pubmed.ncbi.nlm.nih.gov,semanticscholar.org,biorxiv.org,nature.com,science.org,cell.com,pnas.org,nih.gov" \
-o sources/litreview_crispr_scd-academic.json
parallel-cli search "CRISPR sickle cell disease clinical trials treatment" \
-q "CRISPR" -q "sickle cell" \
--json --max-results 10 --excerpt-max-chars-total 27000 \
-o sources/litreview_crispr_scd-general.json
# 3. Search specialized databases using appropriate skills
# - Use PubMed E-utilities and bioRxiv/medRxiv search or date-metadata APIs
# - Use direct API access for arXiv, Semantic Scholar
# - Save all pages and counts; document any API caps or failed requests
# - Normalize into a JSON array; keep raw exports and provenance
# 4. Process your normalized combined_results.json; raw API envelopes will fail
python scripts/search_databases.py combined_results.json \
--deduplicate \
--year-start 2015 \
--year-end 2024 \
--format markdown \
--output search_results.md \
--summary
# 5. Screen results and extract data
# - Request extracts with --full-content; obtain original reports and record failures
# - Use independent final full-text decisions and retain exclusion reasons
# - Track records, reports, studies, and overlapping participants separately
# - Extract key data into the review document
# - Organize by themes
# 6. Write the review following template structure
# - Introduction with clear objectives
# - Detailed methodology section
# - Results organized thematically
# - Critical discussion
# - Clear conclusions
# 7. Check DOI registration/metadata, then manually verify identity and claim support
python scripts/verify_citations.py crispr_sickle_cell_review.md
# Review the citation report
cat crispr_sickle_cell_review_citation_report.json
# Investigate missing/inconclusive results; transient failures do not invalidate citations
python scripts/verify_citations.py crispr_sickle_cell_review.md
# 8. Render after supplying bibliography, local CSL, and [@key] citations
# For manually typed references, omit those options; text will not be restyled
python scripts/generate_pdf.py crispr_sickle_cell_review.md \
--bibliography crispr_sickle_cell_review.bib --csl styles/nature.csl \
--output crispr_sickle_cell_review.pdf
# 9. Review final PDF and markdown outputs
```

View File

@@ -0,0 +1,93 @@
# Search, citation chaining, and source verification
Use [database_strategies.md](database_strategies.md) for current request syntax,
authentication, response shapes, and paging limits. Commands below are
illustrative discovery recipes, not executed searches or complete corpora.
## Supplementary web search
Parallel CLI 0.9.3 supports the flags below. Authenticate with `parallel-cli auth`
or `PARALLEL_API_KEY`; installation and authentication are described in the
[official CLI guide](https://docs.parallel.ai/integrations/cli). It is optional
for the review workflow and may incur provider charges.
```bash
mkdir -p sources
parallel-cli search "CRISPR sickle cell clinical studies" \
-q 'CRISPR sickle cell clinical trial' --json --max-results 10 \
--excerpt-max-chars-total 27000 \
--include-domains 'pubmed.ncbi.nlm.nih.gov,biorxiv.org,medrxiv.org' \
-o sources/scoping-web.json
parallel-cli extract 'https://arxiv.org/abs/1706.03762' \
--full-content --json -o sources/paper-extract.json
```
`--max-results` is a cap on ranked returned hits, not the database total.
`--full-content` requests a fuller extraction; unavailable or truncated content
still requires retrieval from the original source. Save the URL, extraction
status, date, and exact text supporting each inference. Never report a title,
web excerpt, or machine summary as if the full paper was assessed.
## Citation chaining
- **Forward:** use Google Scholar Cited by or documented Semantic Scholar /
OpenAlex citation queries. Search-engine queries such as "papers citing ..."
are supplementary leads, not complete forward-citation exports.
- **Backward:** inspect reference lists of eligible reports and relevant reviews;
retrieve candidate records and apply the same eligibility criteria.
- Track seed papers, tools, dates, retrieved counts, and screening decisions.
Link preprint, journal, protocol, and follow-up reports to a study ID before
synthesis. Citation-count thresholds and journal prestige are not eligibility
rules; recent and negative studies must have an equal chance of inclusion.
## DOI checks and bibliographic identity
```bash
python scripts/verify_citations.py review.md --output review_citation_report.json
```
Optional `--email` supplies a real contact to the Crossref polite pool. The
helper extracts unique DOI candidates, URL-encodes them, and checks
`GET https://doi.org/api/handles/{doi}`. Registration requires a successful
Handle `responseCode=1` and matching identifier, not HTTP 200 alone. It then
requests `GET https://api.crossref.org/works/{doi}` and checks metadata identity.
These public singleton reads require no key or pagination.
Read the report's `verified` as **registration confirmed**, `failed` as
**unresolved/missing/inconclusive**, and `metadata_unavailable` as **manual
metadata follow-up needed**. Transient errors and throttling are not proof of
fabrication. Crossref does not cover every registration agency. The script
preserves the original Crossref message and full author list; its compatibility
formatting methods are previews, not compliant APA or Nature output.
DOI extraction is heuristic: inspect ambiguous trailing punctuation and older
suffixes with parentheses. Citations without DOIs require manual verification.
Check titles, authors, year, version, correction/retraction notices, and that
the source actually supports the cited statement. Registered identifiers and
accessible URLs do not establish those properties.
Sources: [Handle proxy API](https://www.handle.net/proxy_servlet.html),
[Crossref REST API](https://www.crossref.org/documentation/retrieve-metadata/rest-api/).
## Rendering references
Use complete metadata in BibTeX/CSL JSON and a current, venue-appropriate CSL
file. See [citation_styles.md](citation_styles.md). With Pandoc, cite using
`[@citation_key]`; manually typed reference strings are not reformatted by
selecting a style.
```bash
# Requires your populated review.bib and local styles/apa.csl.
python scripts/generate_pdf.py review.md --bibliography review.bib \
--csl styles/apa.csl --output review.pdf
```
No CSL files are bundled or downloaded automatically. A sibling `.bib` is
recognized; otherwise provide `--bibliography` or Pandoc bibliography metadata.
Omitting `--csl` uses Pandoc's default citation style. `--citation-style` remains
an alias for a local file/name (e.g. `apa` requires `apa.csl`).
Inspect the rendered PDF and all warnings, including unresolved keys. Match
in-text citations to the bibliography and manually verify formatting against
the destination journal's instructions. [Pandoc citation documentation](https://pandoc.org/MANUAL.html#citations).

View File

@@ -0,0 +1,107 @@
#!/usr/bin/env python3
"""Render reviewed Markdown with Pandoc/XeLaTeX and optional local CSL bibliography."""
import argparse
import os
import subprocess
from pathlib import Path
def check_dependencies():
"""Check both executables; TeX package availability still needs a real render."""
available = True
for name in ('pandoc', 'xelatex'):
try:
subprocess.run([name, '--version'], capture_output=True, check=True)
print(f'[OK] {name} is installed')
except (subprocess.CalledProcessError, OSError):
print(f'[FAIL] {name} is NOT installed')
available = False
return available
def generate_pdf(markdown_file: str, output_pdf: str = None,
citation_style: str = None, template: str = None,
toc: bool = True, number_sections: bool = True,
bibliography: str = None) -> bool:
"""Render PDF. Style is a local CSL path/name; omitted uses Pandoc's default.
A sibling .bib is detected automatically. Pandoc citation syntax [@key] is
required for citeproc; manually typed reference text is not reformatted.
"""
source = Path(markdown_file).resolve()
destination = Path(output_pdf).resolve() if output_pdf else source.with_suffix('.pdf')
if not source.is_file() or source == destination:
print('[FAIL] Input must exist and output must differ from input')
return False
if not check_dependencies():
return False
cmd = ['pandoc', str(source), '-o', str(destination), '--pdf-engine=xelatex',
'--resource-path', os.pathsep.join([str(source.parent), str(Path.cwd())]),
'-V', 'geometry:margin=1in', '-V', 'fontsize=11pt',
'-V', 'colorlinks=true', '-V', 'linkcolor=blue', '-V', 'urlcolor=blue',
'-V', 'citecolor=blue', '--citeproc']
if toc:
cmd.extend(['--toc', '--toc-depth=3'])
if number_sections:
cmd.append('--number-sections')
bib = Path(bibliography).resolve() if bibliography else source.with_suffix('.bib')
if bibliography and not bib.is_file():
print(f'[FAIL] Bibliography not found: {bib}')
return False
if bib.is_file():
cmd.extend(['--bibliography', str(bib)])
if citation_style:
style = Path(citation_style if citation_style.endswith('.csl') else citation_style + '.csl')
if not style.is_file():
style = source.parent / style
if not style.is_file():
print('[FAIL] Supply an existing CSL file with --csl; style names are not downloaded automatically')
return False
cmd.extend(['--csl', str(style.resolve())])
if template:
if not Path(template).is_file():
print(f'[FAIL] Template not found: {template}')
return False
cmd.extend(['--template', str(Path(template).resolve())])
try:
result = subprocess.run(cmd, capture_output=True, text=True, check=True)
if result.stderr:
print(result.stderr.strip()) # Surface missing citation and rendering warnings.
if not destination.is_file() or not destination.read_bytes().startswith(b'%PDF-'):
print('[FAIL] Pandoc returned without a valid PDF output')
return False
print(f'[OK] PDF generated: {destination}')
return True
except (subprocess.CalledProcessError, OSError) as exc:
print(f'[FAIL] PDF generation: {getattr(exc, "stderr", None) or exc}')
return False
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('markdown_file', nargs='?')
parser.add_argument('output_pdf', nargs='?', help='Legacy positional output path')
parser.add_argument('-o', '--output')
parser.add_argument('--csl', '--citation-style', dest='citation_style',
help='Local CSL path, or local style name such as apa (requires apa.csl)')
parser.add_argument('--bibliography', help='Local .bib, .json or other Pandoc bibliography file')
parser.add_argument('--template')
parser.add_argument('--no-toc', action='store_true')
parser.add_argument('--no-numbers', action='store_true')
parser.add_argument('--check-deps', action='store_true')
args = parser.parse_args()
if args.check_deps:
raise SystemExit(0 if check_dependencies() else 1)
if not args.markdown_file:
parser.error('markdown_file is required unless --check-deps is used')
if args.output and args.output_pdf:
parser.error('choose either positional output or --output')
raise SystemExit(0 if generate_pdf(args.markdown_file, args.output or args.output_pdf,
citation_style=args.citation_style, template=args.template,
toc=not args.no_toc, number_sections=not args.no_numbers,
bibliography=args.bibliography) else 1)
if __name__ == '__main__':
main()

View File

@@ -0,0 +1,201 @@
#!/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.7 Flash 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
# Variables forwarded to the generation subprocess. The child needs the
# OpenRouter credential; the rest keep networking, TLS, and locale working.
# Copying the whole parent environment instead would hand the child every
# unrelated secret that happens to be exported in the calling shell.
FORWARDED_ENV_VARS = (
"PATH", "HOME", "LANG", "LC_ALL", "TMPDIR", "PYTHONPATH",
"HTTP_PROXY", "HTTPS_PROXY", "NO_PROXY",
"http_proxy", "https_proxy", "no_proxy",
"SSL_CERT_FILE", "SSL_CERT_DIR", "REQUESTS_CA_BUNDLE", "CURL_CA_BUNDLE",
# Windows needs these for sockets, temp files, and interpreter startup.
"SYSTEMROOT", "WINDIR", "COMSPEC", "PATHEXT",
"APPDATA", "LOCALAPPDATA", "USERPROFILE", "TEMP", "TMP",
)
def resolve_api_key(explicit=None):
"""Resolve the OpenRouter key from --api-key, the environment, then any .env file.
The .env scan walks up from the working directory and finally checks the
script's own directory, so running from anywhere inside a project picks up
the key at its root. The child process is handed the resolved value through
build_subprocess_env, so it never has to repeat this search.
"""
if explicit:
return explicit
from_env = os.environ.get("OPENROUTER_API_KEY", "").strip()
if from_env:
return from_env
cwd = Path.cwd()
for directory in [cwd, *cwd.parents, Path(__file__).resolve().parent]:
env_file = directory / ".env"
if not env_file.is_file():
continue
try:
content = env_file.read_text(encoding="utf-8", errors="replace")
except OSError:
continue
for raw in content.splitlines():
line = raw.strip()
if line.startswith("#") or "=" not in line:
continue
name, _, value = line.partition("=")
if name.strip() == "OPENROUTER_API_KEY":
value = value.strip().strip('"').strip("'")
if value:
return value
return None
def build_subprocess_env(api_key):
"""Return a minimal environment for the AI generation subprocess."""
env = {name: os.environ[name] for name in FORWARDED_ENV_VARS if name in os.environ}
if api_key:
env["OPENROUTER_API_KEY"] = api_key
return env
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.7 Flash
- Document-type aware quality thresholds
- PNG draft for visual and scientific verification
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 PNG file path (.png required)")
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()
# Validated here rather than clamped silently, and before the credential
# lookup so an out-of-range value reports itself rather than an absent key.
if not 1 <= args.iterations <= 2:
parser.error("--iterations must be 1 or 2")
if Path(args.output).suffix.lower() != ".png":
parser.error("--output must end in .png; format conversion is not supported")
# Check for API key — resolves --api-key, the environment, then any .env file
api_key = resolve_api_key(args.api_key)
if not api_key:
print("Error: OPENROUTER_API_KEY not found")
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 add OPENROUTER_API_KEY=your_api_key to a .env file")
print("Or 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])
cmd.extend(["--iterations", str(args.iterations)])
if args.verbose:
cmd.append("-v")
# Execute — pass API key via environment to avoid exposure in process listings
try:
result = subprocess.run(cmd, check=False, env=build_subprocess_env(api_key))
sys.exit(result.returncode)
except Exception as e:
print(f"Error executing AI generation: {e}")
sys.exit(1)
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,857 @@
#!/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.7 Flash 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 re
import sys
import time
from pathlib import Path
from typing import Optional, Dict, Any, List, NamedTuple
try:
import requests
except ImportError:
print("Error: requests library not found. Install with: uv pip install requests")
sys.exit(1)
class ReviewResult(NamedTuple):
"""The outcome of one quality review.
A named tuple rather than a bare tuple because the review has several
failure modes -- the model returns no choices, the request raises, the
answer arrives in an unexpected shape -- and each of them used to be a
chance to return the wrong number of values to the caller.
`score` is None whenever no usable number was parsed, and `reviewed` is
False whenever the review never produced an answer at all. Neither case
invents a score: a diagram whose quality was not measured is reported as
unmeasured, not as passing.
"""
critique: str
score: Optional[float]
needs_improvement: bool
reviewed: bool
error: Optional[str] = None
# Markdown decoration the reviewer routinely wraps its answer in. Gemini writes
# "**SCORE:** 8.5" far more often than the bare "SCORE: 8.5" the rubric asks
# for, and a pattern that does not allow for it silently scores every diagram
# at whatever the default happens to be.
_MARKUP = re.compile(r"[*_`#]")
_SCORE_PATTERN = re.compile(r"\bSCORE\s*:?\s*(\d+(?:\.\d+)?)", re.IGNORECASE)
_LOOSE_SCORE_PATTERN = re.compile(
r"(?:score|rating|quality)\s*[:\s]\s*(\d+(?:\.\d+)?)\s*(?:/\s*10)?", re.IGNORECASE
)
# The underscore is optional because normalization strips it out of
# NEEDS_IMPROVEMENT along with the surrounding markdown.
_VERDICT_PATTERN = re.compile(
r"^\s*VERDICT\s*:?\s*(ACCEPTABLE|NEEDS[_ ]?IMPROVEMENT)", re.IGNORECASE | re.MULTILINE
)
def _normalize_review_text(text: str) -> str:
"""Strip markdown decoration so the rubric's fields can be found."""
return _MARKUP.sub("", text or "")
def _parse_score(text: str) -> Optional[float]:
"""Return the reviewer's 0-10 score, or None when there isn't a usable one.
None rather than a default: a fabricated score is indistinguishable from a
real one once it reaches the review log, and a default near the middle of
the range quietly passes lenient document types while failing strict ones.
"""
normalized = _normalize_review_text(text)
match = _SCORE_PATTERN.search(normalized) or _LOOSE_SCORE_PATTERN.search(normalized)
if not match:
return None
score = float(match.group(1))
# A number outside the rubric's range means something other than the score
# was matched -- a figure count, a percentage, an iteration number.
return score if 0.0 <= score <= 10.0 else None
def _parse_verdict(text: str) -> Optional[str]:
"""Return ACCEPTABLE / NEEDS_IMPROVEMENT from the verdict line, or None.
Anchored to the start of a line. The rubric prompt spells out both tokens
when it explains the response format, so a reviewer that echoes those
instructions back would fail a perfectly good diagram under a plain
substring search.
"""
match = _VERDICT_PATTERN.search(_normalize_review_text(text))
if not match:
return None
verdict = match.group(1).upper().replace(" ", "").replace("_", "")
return "NEEDS_IMPROVEMENT" if verdict == "NEEDSIMPROVEMENT" else "ACCEPTABLE"
def _resolve_api_key(explicit: Optional[str] = None) -> Optional[str]:
"""Resolve the OpenRouter key from --api-key, the environment, then any .env file.
The .env scan walks up from the working directory and finally checks the
script's own directory, so running from anywhere inside a project picks up
the key at its root. Only the standard library is used: python-dotenv is a
common omission, and a missing optional dependency should not read as a
missing credential.
"""
if explicit:
return explicit
from_env = os.environ.get("OPENROUTER_API_KEY", "").strip()
if from_env:
return from_env
cwd = Path.cwd()
for directory in [cwd, *cwd.parents, Path(__file__).resolve().parent]:
env_file = directory / ".env"
if not env_file.is_file():
continue
try:
content = env_file.read_text(encoding="utf-8", errors="replace")
except OSError:
continue
for raw in content.splitlines():
line = raw.strip()
if line.startswith("#") or "=" not in line:
continue
name, _, value = line.partition("=")
if name.strip() == "OPENROUTER_API_KEY":
value = value.strip().strip('"').strip("'")
if value:
return value
return None
class ScientificSchematicGenerator:
"""Generate scientific schematics using AI with smart iterative refinement.
Uses Gemini 3.7 Flash 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 = _resolve_api_key(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. The slug must
# be an image-output model; a text-only chat model is rejected with
# "No endpoints found that support the requested output modalities".
# https://openrouter.ai/google/gemini-3.1-flash-image
self.image_model = "google/gemini-3.1-flash-image"
# Gemini 3.7 Flash for quality review - excellent vision and reasoning
self.review_model = "google/gemini-3.7-flash"
def _log(self, message: str):
"""Log message if verbose mode is enabled."""
if self.verbose:
print(f"[{time.strftime('%H:%M:%S')}] {message}")
def _post_request(self, endpoint: str, payload: Dict[str, Any]) -> Dict[str, Any]:
"""Send one non-streaming request; never automatically replay a paid call."""
headers = {
"Authorization": f"Bearer {self.api_key}",
"Content-Type": "application/json",
"X-Title": "Scientific Schematic Generator",
}
self._log(f"POST {endpoint} using {payload['model']}")
try:
response = requests.post(
f"{self.base_url}/{endpoint}", headers=headers,
json=payload, timeout=120,
)
try:
response_json = response.json()
except ValueError:
raise RuntimeError(
f"API returned non-JSON data (HTTP {response.status_code})"
) from None
if not isinstance(response_json, dict):
raise RuntimeError("API response must be a JSON object")
if response.status_code != 200 or "error" in response_json:
error = response_json.get("error", {})
detail = error.get("message", "request rejected") if isinstance(error, dict) else str(error)
# Providers occasionally echo input; do not dump whole bodies or credentials.
detail = str(detail).replace(self.api_key, "[redacted]")[:500]
raise RuntimeError(f"API request failed (HTTP {response.status_code}): {detail}")
return response_json
except requests.exceptions.Timeout:
raise RuntimeError("API request timed out after 120 seconds") from None
except requests.exceptions.RequestException as exc:
detail = str(exc).replace(self.api_key, "[redacted]")
raise RuntimeError(f"API request failed: {detail}") from None
def _make_request(self, model: str, messages: List[Dict[str, Any]],
modalities: Optional[List[str]] = None) -> Dict[str, Any]:
"""Use chat completions for the text-and-image vision review."""
payload = {"model": model, "messages": messages}
if modalities:
payload["modalities"] = modalities
return self._post_request("chat/completions", payload)
def _extract_image_from_response(self, response: Dict[str, Any]) -> bytes:
"""Decode the dedicated Image API response and enforce this helper's PNG contract.
The provider may omit media_type; the PNG signature still has to match.
This is a format check, not a full image-decoder or scientific-content check.
"""
data = response.get("data")
if not isinstance(data, list) or not data or not isinstance(data[0], dict):
raise RuntimeError("Image API returned no data[0] image")
item = data[0]
if item.get("media_type") not in (None, "image/png"):
raise RuntimeError(f"Expected PNG output; received {item['media_type']}")
encoded = item.get("b64_json")
if not isinstance(encoded, str) or not encoded:
raise RuntimeError("Image API returned no b64_json image")
try:
image_data = base64.b64decode(encoded, validate=True)
except ValueError:
raise RuntimeError("Image API returned invalid base64 image data") from None
if not image_data.startswith(b"\x89PNG\r\n\x1a\n"):
raise RuntimeError("Image API output does not have a PNG signature")
return image_data
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
try:
# Image generation has its own body and response, distinct from chat.
# n=1 is supported by both current Gemini image-provider endpoints.
# output_format is absent from their capability maps: use the default
# and validate the returned MIME/signature rather than send that knob.
response = self._post_request("images", {
"model": self.image_model, "prompt": prompt, "n": 1,
})
image_data = self._extract_image_from_response(response)
self._log(f"[OK] Generated PNG ({len(image_data)} bytes)")
return image_data
except RuntimeError as exc:
self._last_error = str(exc)
self._log(f"[FAIL] Generation failed: {self._last_error}")
return None
def review_image(self, image_path: str, original_prompt: str,
iteration: int, doc_type: str = "default",
max_iterations: int = 2) -> ReviewResult:
"""
Review the generated image for quality, using the vision review model.
Args:
image_path: Path to the generated image
original_prompt: Original user prompt
iteration: Current iteration number
doc_type: Document type (journal, poster, presentation, etc.)
max_iterations: Maximum iterations allowed
Returns:
A ReviewResult. When the review cannot be completed -- the request
fails, or the model answers with nothing usable -- `reviewed` is
False and `score` is None rather than a stand-in number, and
`needs_improvement` is False: the fault is in the reviewer, not in
the diagram, so regenerating would not help.
"""
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:
response = self._make_request(
model=self.review_model,
messages=messages
)
# Extract text response
choices = response.get("choices", [])
if not choices:
# A normal enough outcome -- a rate limit, a content filter, a
# provider hiccup. The diagram itself is fine; only its review
# is missing, and saying so beats inventing a score.
reason = "the review model returned no choices"
self._log(f"[WARN] Review unavailable: {reason}")
return ReviewResult(
f"Review unavailable: {reason}.",
None, False, reviewed=False, error=reason,
)
message = choices[0].get("message", {})
content = message.get("content", "")
# Some models put their analysis in a separate reasoning field
reasoning = message.get("reasoning", "")
if reasoning and not content:
content = reasoning
if isinstance(content, list):
# Extract text from content blocks
text_parts = []
for block in content:
if isinstance(block, dict) and block.get("type") == "text":
text_parts.append(block.get("text", ""))
content = "\n".join(text_parts)
score = _parse_score(content)
verdict = _parse_verdict(content)
if score is None and verdict is None:
reason = "no score or verdict found in the review"
self._log(f"[WARN] Review unusable: {reason}")
return ReviewResult(
content if content else f"Review unusable: {reason}.",
None, False, reviewed=True, error=reason,
)
needs_improvement = verdict == "NEEDS_IMPROVEMENT" or (
score is not None and score < threshold
)
shown = f"{score}/10" if score is not None else "not stated"
self._log(f"[OK] Review complete (Score: {shown}, Threshold: {threshold}/10)")
self._log(f" Verdict: {'Needs improvement' if needs_improvement else 'Acceptable'}")
return ReviewResult(
content if content else "Review returned no text",
score,
needs_improvement,
reviewed=True,
error=None if score is not None else "no score found in the review",
)
except Exception as e:
# A failed review must not fail the run -- the image is already
# generated and saved -- but it must not read as a pass either.
self._log(f"[WARN] Review failed: {str(e)}")
return ReviewResult(
f"Review failed: {str(e)}",
None, False, reviewed=False, error=str(e),
)
def improve_prompt(self, original_prompt: str, critique: str,
iteration: int) -> str:
"""
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
"""
if isinstance(iterations, bool) or not isinstance(iterations, int) or not 1 <= iterations <= 2:
raise ValueError("iterations must be 1 or 2")
if doc_type.lower() not in self.QUALITY_THRESHOLDS:
raise ValueError(f"Unknown document type: {doc_type}")
output_path = Path(output_path)
if output_path.suffix.lower() != ".png":
raise ValueError("Output path must end in .png; format conversion is not supported")
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,
"image_model": self.image_model,
"review_model": self.review_model,
"quality_met": False,
"termination_reason": None,
"iterations": [],
"final_image": None,
# None, not 0.0 -- a run whose review never completed has no score,
# and a number here would be read as one the reviewer gave.
"final_score": None,
"final_reviewed": False,
"success": False,
"early_stop": False,
"early_stop_reason": None
}
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"[FAIL] Generation failed: {error_msg}")
results["iterations"].append({
"iteration": i,
"success": False,
"error": error_msg
})
# A failed refinement must not discard the earlier saved image.
# Stop here rather than replay a request after an ambiguous timeout.
results["termination_reason"] = "generation_failed"
break
# 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"[OK] Saved: {iter_path}")
# Review the image with the vision review model
print(f"Reviewing image with {self.review_model}...")
review = self.review_image(
str(iter_path), user_prompt, i, doc_type, iterations
)
if review.score is not None:
print(f"[OK] Score: {review.score}/10 (threshold: {threshold}/10)")
else:
print(f"[WARN] Review unavailable - image kept, quality not verified")
print(f" Reason: {review.error}")
# Save iteration results
iteration_result = {
"iteration": i,
"image_path": str(iter_path),
"prompt": current_prompt,
"critique": review.critique,
"score": review.score,
"reviewed": review.reviewed,
"review_error": review.error,
"needs_improvement": review.needs_improvement,
"success": True
}
results["iterations"].append(iteration_result)
# Preserve the latest successful image even if a later API call fails.
results["final_image"] = str(iter_path)
results["final_score"] = review.score
results["final_reviewed"] = review.reviewed and review.score is not None
results["success"] = True
results["quality_met"] = (
results["final_reviewed"] and review.score >= threshold
and not review.needs_improvement
)
# Check if quality is acceptable - STOP EARLY if so
if not review.needs_improvement:
if review.score is not None:
print(f"\n[OK] Quality meets {doc_type} threshold ({review.score} >= {threshold})")
print(f" No further iterations needed!")
reason = (f"Quality score {review.score} meets threshold "
f"{threshold} for {doc_type}")
else:
# Regenerating cannot fix a reviewer that did not answer.
print(f"\n[WARN] Stopping without a verified score - review the image yourself")
reason = f"Review did not produce a score: {review.error}"
results["final_image"] = str(iter_path)
results["final_score"] = review.score
results["final_reviewed"] = review.reviewed and review.score is not None
results["success"] = True
results["early_stop"] = True
results["early_stop_reason"] = reason
results["termination_reason"] = (
"quality_threshold_met" if results["quality_met"] else "review_unavailable"
)
break
# If this is the last iteration, we're done regardless
if i == iterations:
print(f"\n[WARN] Maximum iterations reached")
results["termination_reason"] = "max_iterations"
results["final_image"] = str(iter_path)
results["final_score"] = review.score
results["final_reviewed"] = review.reviewed and review.score is not None
results["success"] = True
break
# Quality below threshold - improve prompt for next iteration
print(f"\n[WARN] Review requests improvement (score: {review.score}; threshold: {threshold})")
print(f"Improving prompt based on feedback...")
current_prompt = self.improve_prompt(user_prompt, review.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[OK] Final image: {output_path}")
# Save review log
log_path = output_dir / f"{base_name}_review_log.json"
with open(log_path, "w", encoding="utf-8") as f:
json.dump(results, f, indent=2)
print(f"[OK] Review log: {log_path}")
print(f"\n{'='*60}")
print(f"Generation Complete!")
if results["final_score"] is not None:
print(f"Final Score: {results['final_score']}/10")
else:
print(f"Final Score: unavailable (the review did not produce one)")
if results["early_stop"]:
print(f"Iterations Used: {len([r for r in results['iterations'] if r.get('success')])}/{iterations} (early stop)")
print(f"{'='*60}\n")
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 — resolves --api-key, the environment, then any .env file
api_key = _resolve_api_key(args.api_key)
if not api_key:
print("Error: OPENROUTER_API_KEY not found")
print("\nSet it with:")
print(" export OPENROUTER_API_KEY='your_api_key'")
print("\nOr add OPENROUTER_API_KEY=your_api_key to a .env file")
print("Or 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[OK] Success! Image saved to: {args.output}")
used = len([r for r in results['iterations'] if r.get('success')])
if results.get("final_reviewed"):
if results.get("quality_met"):
print(f" (Completed in {used} iteration(s) - quality threshold met)")
else:
print(" (Image saved; review did not meet the quality criteria.)")
else:
# The image is real; the quality claim is not. Say which.
print(f" (Completed in {used} iteration(s) - quality NOT verified,"
f" the review produced no score. Check the image yourself.)")
sys.exit(0)
else:
print(f"\n[FAIL] Generation failed. Check review log for details.")
sys.exit(1)
except Exception as e:
print(f"\n[FAIL] Error: {str(e)}")
sys.exit(1)
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,266 @@
#!/usr/bin/env python3
"""
Literature Database Search Script
Processes normalized search records locally; does not query databases.
"""
import argparse
import json
import math
import re
import sys
from pathlib import Path
from urllib.parse import unquote
from typing import Dict, List
from datetime import datetime
def format_search_results(results: List[Dict], output_format: str = 'json') -> str:
"""
Format search results for output.
Args:
results: List of search results
output_format: Format (json, markdown, or bibtex)
Returns:
Formatted string
"""
if output_format == 'json':
return json.dumps(results, indent=2)
elif output_format == 'markdown':
md = f"# Literature Search Results\n\n"
md += f"**Export Generated**: {datetime.now().strftime('%Y-%m-%d %H:%M')}\n"
md += f"**Total Results**: {len(results)}\n\n"
for i, result in enumerate(results, 1):
md += f"## {i}. {result.get('title', 'Untitled')}\n\n"
md += f"**Authors**: {result.get('authors', 'Unknown')}\n\n"
md += f"**Year**: {result.get('year', 'N/A')}\n\n"
md += f"**Source**: {result.get('source', 'Unknown')}\n\n"
if result.get('abstract'):
md += f"**Abstract**: {result['abstract']}\n\n"
if result.get('doi'):
md += f"**DOI**: [{result['doi']}](https://doi.org/{result['doi']})\n\n"
if result.get('url'):
md += f"**URL**: {result['url']}\n\n"
if result.get('citations') is not None:
md += f"**Citations**: {result['citations']}\n\n"
md += "---\n\n"
return md
elif output_format == 'bibtex':
bibtex = ""
used_keys = set()
for i, result in enumerate(results, 1):
entry_type = result.get('type', 'article')
base_key = re.sub(r'[^a-zA-Z0-9_-]', '',
f"{result.get('first_author') or 'unknown'}{result.get('year') or '0000'}")
cite_key, suffix = base_key, 2
while cite_key in used_keys:
cite_key = f'{base_key}_{suffix}'
suffix += 1
used_keys.add(cite_key)
bibtex += f"@{entry_type}{{{cite_key},\n"
bibtex += f" title = {{{result.get('title', '')}}},\n"
bibtex += f" author = {{{result.get('authors', '')}}},\n"
bibtex += f" year = {{{result.get('year', '')}}},\n"
if result.get('journal'):
bibtex += f" journal = {{{result['journal']}}},\n"
if result.get('volume'):
bibtex += f" volume = {{{result['volume']}}},\n"
if result.get('pages'):
bibtex += f" pages = {{{result['pages']}}},\n"
if result.get('doi'):
bibtex += f" doi = {{{result['doi']}}},\n"
bibtex += "}\n\n"
return bibtex
else:
raise ValueError(f"Unknown format: {output_format}")
def deduplicate_results(results: List[Dict]) -> List[Dict]:
"""
Keep the first occurrence of a DOI; use title only among DOI-less records.
Exact title matches still require review. Preserve raw exports to recover
metadata from duplicate records; this helper does not identify studies.
Args:
results: List of search results
Returns:
Deduplicated list
"""
seen_dois = set()
seen_titles = set()
unique_results = []
for result in results:
doi = unquote(re.sub(r'^(?:https?://(?:dx\.)?doi\.org/|doi:\s*)', '',
str(result.get('doi') or '').strip(), flags=re.I)).lower()
title = str(result.get('title') or '').lower().strip()
# Check DOI first (more reliable)
if doi and doi in seen_dois:
continue
# Check title as fallback
if not doi and title in seen_titles:
continue
# Add to results
if doi:
seen_dois.add(doi)
if title and not doi:
seen_titles.add(title)
unique_results.append(result)
return unique_results
def rank_results(results: List[Dict], criteria: str = 'citations') -> List[Dict]:
"""
Rank results by specified criteria.
Args:
results: List of search results
criteria: Ranking criteria (citations, year, relevance)
Returns:
Ranked list
"""
field = {'citations': 'citations', 'year': 'year', 'relevance': 'relevance_score'}.get(criteria)
if field is None:
return results
def score(record):
try:
value = float(record.get(field))
return value if math.isfinite(value) else float('-inf')
except (ValueError, TypeError):
return float('-inf')
return sorted(results, key=score, reverse=True)
def filter_by_year(results: List[Dict], start_year: int = None, end_year: int = None) -> List[Dict]:
"""
Filter results by publication year range.
Args:
results: List of search results
start_year: Minimum year (inclusive)
end_year: Maximum year (inclusive)
Returns:
Filtered list
"""
filtered = []
for result in results:
try:
year = int(result.get('year'))
if start_year and year < start_year:
continue
if end_year and year > end_year:
continue
filtered.append(result)
except (ValueError, TypeError):
# Include if year parsing fails
filtered.append(result)
return filtered
def generate_search_summary(results: List[Dict]) -> Dict:
"""
Generate summary statistics for search results.
Args:
results: List of search results
Returns:
Summary dictionary
"""
summary = {
'total_results': len(results),
'sources': {},
'year_distribution': {},
'avg_citations': 0,
'total_citations': 0
}
citations = []
for result in results:
# Count by source
source = result.get('source', 'Unknown')
summary['sources'][source] = summary['sources'].get(source, 0) + 1
# Count by year
year = result.get('year', 'Unknown')
summary['year_distribution'][year] = summary['year_distribution'].get(year, 0) + 1
# Collect citations
if result.get('citations') is not None:
try:
value = int(result['citations'])
if value >= 0:
citations.append(value)
except (ValueError, TypeError):
pass
if citations:
summary['avg_citations'] = sum(citations) / len(citations)
summary['total_citations'] = sum(citations)
return summary
def main():
"""Process a JSON array; refuse raw provider envelopes and unknown options."""
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('results_file', type=Path)
parser.add_argument('--format', choices=['json', 'markdown', 'bibtex'], default='markdown')
parser.add_argument('--output', type=Path)
parser.add_argument('--rank', choices=['citations', 'year', 'relevance'])
parser.add_argument('--year-start', type=int)
parser.add_argument('--year-end', type=int)
parser.add_argument('--deduplicate', action='store_true')
parser.add_argument('--summary', action='store_true')
args = parser.parse_args()
if args.year_start and args.year_end and args.year_start > args.year_end:
parser.error('--year-start must not exceed --year-end')
try:
results = json.loads(args.results_file.read_text(encoding='utf-8'))
if not isinstance(results, list) or any(not isinstance(r, dict) for r in results):
raise ValueError('input must be a normalized JSON array of record objects, not a provider response')
if args.deduplicate:
results = deduplicate_results(results)
if args.year_start is not None or args.year_end is not None:
results = filter_by_year(results, args.year_start, args.year_end)
if args.rank:
results = rank_results(results, args.rank)
if args.summary:
print(json.dumps(generate_search_summary(results), indent=2), file=sys.stderr)
output = format_search_results(results, args.format)
if args.output:
args.output.write_text(output, encoding='utf-8')
print(f'[OK] Results saved to: {args.output}', file=sys.stderr)
else:
print(output)
except (OSError, ValueError, TypeError) as exc:
parser.exit(1, f'[FAIL] {exc}\n')
if __name__ == '__main__':
main()

View File

@@ -0,0 +1,198 @@
#!/usr/bin/env python3
"""Check DOI registration and retrieve Crossref metadata for manual citation review.
Registration does not establish that a citation supports a claim. Crossref does
not cover all DOI registration agencies; unavailable metadata needs manual review.
"""
import argparse
import json
import re
import time
from pathlib import Path
from typing import Dict, List, Tuple
from urllib.parse import quote, unquote
import requests
def normalize_doi(value: str) -> str:
"""Normalize a bare DOI or doi.org URL without stripping legal DOI punctuation."""
value = re.sub(r"^(?:https?://(?:dx\.)?doi\.org/|doi:\s*)", "", value.strip(), flags=re.I)
return unquote(value).lower()
class CitationVerifier:
def __init__(self, email: str = None):
self.email = email
self.session = requests.Session()
self.session.headers.update({'User-Agent': 'LiteratureReviewCitationVerifier/1.1'})
def extract_dois(self, text: str) -> List[str]:
"""Extract unique candidates; prose punctuation remains inherently ambiguous."""
found = []
for candidate in re.findall(r'10\.\d{4,9}/[^\s<>"{}]+', text, flags=re.I):
candidate = unquote(candidate).rstrip('.,;:')
# Keep balanced parentheses inside older DOI suffixes, remove Markdown closers.
while candidate and candidate[-1] in ')]':
closing = candidate[-1]
opening = '(' if closing == ')' else '['
if candidate.count(closing) <= candidate.count(opening):
break
candidate = candidate[:-1].rstrip('.,;:')
candidate = normalize_doi(candidate)
if candidate not in found:
found.append(candidate)
return found
def _get(self, url: str, **kwargs):
"""Retry only transient read failures, with bounded backoff."""
for attempt in range(3):
response = self.session.get(url, timeout=20, **kwargs)
if response.status_code not in (429, 500, 502, 503, 504) or attempt == 2:
return response
try:
delay = float(response.headers.get('Retry-After', 2 ** attempt))
except (TypeError, ValueError):
delay = 2 ** attempt
# Long server-directed delays need a later run, not an early retry.
if delay > 60:
return response
time.sleep(max(0, delay))
raise AssertionError('unreachable')
def verify_doi(self, doi: str) -> Tuple[bool, Dict]:
"""Return registration status and metadata; false includes inconclusive requests."""
doi = normalize_doi(doi)
if not re.fullmatch(r'10\.\d{4,9}/\S+', doi):
return False, {'doi': doi, 'status': 'invalid_syntax'}
try:
response = self._get(f"https://doi.org/api/handles/{quote(doi, safe='/')}")
payload = response.json()
code = payload.get('responseCode') if isinstance(payload, dict) else None
returned = payload.get('handle', '') if isinstance(payload, dict) else ''
if (code == 100 and response.status_code in (200, 404) and
isinstance(returned, str) and normalize_doi(returned) == doi):
return False, {'doi': doi, 'status': 'missing', 'handle_response_code': code}
if (response.status_code != 200 or code != 1 or
not isinstance(returned, str) or normalize_doi(returned) != doi):
return False, {'doi': doi, 'status': 'inconclusive',
'http_status': response.status_code, 'handle_response_code': code}
metadata = self._get_crossref_metadata(doi)
metadata.update({'doi': doi, 'status': 'registered'})
return True, metadata
except (requests.RequestException, ValueError) as exc:
return False, {'doi': doi, 'status': 'inconclusive', 'error': str(exc)}
def _get_crossref_metadata(self, doi: str) -> Dict:
"""Fetch one Crossref work; no list pagination or key is needed."""
try:
response = self._get(f"https://api.crossref.org/works/{quote(doi, safe='/')}",
params={'mailto': self.email} if self.email else {})
if response.status_code != 200:
return {'metadata_status': 'unavailable', 'crossref_http_status': response.status_code}
message = response.json().get('message')
if not isinstance(message, dict) or normalize_doi(message.get('DOI', '')) != doi:
return {'metadata_status': 'unavailable', 'error': 'Crossref response DOI missing or mismatched'}
def first(field):
values = message.get(field) or []
return values[0] if isinstance(values, list) and values else ''
authors = message.get('author') or []
return {
'metadata_status': 'retrieved', 'title': first('title'),
'authors': self._format_authors(authors), 'author': authors,
'year': self._extract_year(message), 'journal': first('container-title'),
'volume': message.get('volume', ''), 'issue': message.get('issue', ''),
'pages': message.get('page', ''), 'doi': doi,
'crossref_message': message,
}
except (requests.RequestException, ValueError, AttributeError) as exc:
return {'metadata_status': 'unavailable', 'error': str(exc)}
def _format_authors(self, authors: List[Dict]) -> str:
"""Preserve all authors for review; this is not a CSL citation formatter."""
names = []
for author in authors:
if not isinstance(author, dict):
continue
family, given = author.get('family', ''), author.get('given', '')
if family:
names.append(f'{family}, {given}' if given else family)
elif author.get('name'):
names.append(author['name'])
return '; '.join(names)
def _extract_year(self, message: Dict) -> str:
for field in ('published-print', 'published-online', 'published', 'issued'):
dates = (message.get(field) or {}).get('date-parts') or []
if dates and dates[0]:
return str(dates[0][0])
return ''
def verify_url(self, url: str) -> Tuple[bool, int]:
"""Check accessibility only; a 403/HEAD failure is not proof of an invalid URL."""
try:
response = self.session.head(url, timeout=20, allow_redirects=True)
return response.status_code < 400, response.status_code
except requests.RequestException:
return False, 0
def verify_citations_in_file(self, filepath: str) -> Dict:
dois = self.extract_dois(Path(filepath).read_text(encoding='utf-8'))
report = {'total_dois': len(dois), 'verified': [], 'failed': [],
'metadata_unavailable': [], 'metadata': {}, 'errors': {}, 'missing': [], 'inconclusive': [],
'verification_scope': 'DOI registration and Crossref metadata, not claim support or retraction screening'}
for doi in dois:
print(f'Checking DOI: {doi}')
registered, metadata = self.verify_doi(doi)
if registered:
report['verified'].append(doi)
report['metadata'][doi] = metadata
if metadata.get('metadata_status') != 'retrieved':
report['metadata_unavailable'].append(doi)
else:
report['failed'].append(doi)
report['errors'][doi] = metadata
bucket = 'missing' if metadata.get('status') == 'missing' else 'inconclusive'
report[bucket].append(doi)
time.sleep(0.5) # Sequential, <=2 Crossref single-work requests/s.
return report
def format_citation_apa(self, metadata: Dict) -> str:
"""Return a metadata preview, not a standards-compliant APA reference."""
return (f"{metadata.get('authors', '')} ({metadata.get('year') or 'n.d.'}). "
f"{metadata.get('title', '')}. {metadata.get('journal', '')}. "
f"https://doi.org/{metadata.get('doi', '')}")
def format_citation_nature(self, metadata: Dict) -> str:
"""Return a metadata preview; use CSL for final Nature formatting."""
return (f"{metadata.get('authors', '')} {metadata.get('title', '')}. "
f"{metadata.get('journal', '')} {metadata.get('volume', '')}, "
f"{metadata.get('pages', '')} ({metadata.get('year', '')}).")
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('markdown_file', type=Path)
parser.add_argument('--email', help='Your contact email for the Crossref polite pool')
parser.add_argument('-o', '--output', type=Path, help='JSON report path')
args = parser.parse_args()
output = args.output or args.markdown_file.with_name(args.markdown_file.stem + '_citation_report.json')
if output.resolve() == args.markdown_file.resolve():
parser.error('report path must differ from the input file')
try:
verifier = CitationVerifier(email=args.email)
report = verifier.verify_citations_in_file(str(args.markdown_file))
output.write_text(json.dumps(report, indent=2), encoding='utf-8')
except (OSError, ValueError) as exc:
parser.exit(1, f'[FAIL] {exc}\n')
print(f"Registered: {len(report['verified'])}; unresolved: {len(report['failed'])}; "
f"metadata unavailable: {len(report['metadata_unavailable'])}")
print(f'[OK] Report: {output}')
if not report['total_dois']:
print('[WARN] No DOIs found; review references manually.')
raise SystemExit(1 if report['failed'] else 0)
if __name__ == '__main__':
main()