### Install NanoResearch with Development Dependencies Source: https://github.com/openraiser/nanoresearch/blob/main/README.md Clones the NanoResearch repository and installs it with development dependencies, preparing the environment for use and contribution. ```bash git clone https://github.com/OpenRaiser/NanoResearch.git cd NanoResearch pip install -e ".[dev]" ``` -------------------------------- ### Codex Integration Setup Source: https://github.com/openraiser/nanoresearch/blob/main/README.md Initializes the repository for use with Codex, leveraging existing CLI and manifest logic for autonomous research tasks. ```bash git clone https://github.com/OpenRaiser/NanoResearch.git cd NanoResearch ``` -------------------------------- ### Configure Lark (Feishu) Integration Source: https://github.com/openraiser/nanoresearch/blob/main/README.md Install dependencies, configure credentials via environment variables or JSON, and launch the bot. ```bash pip install lark-oapi export FEISHU_APP_ID="cli_xxx" export FEISHU_APP_SECRET="xxx" nanoresearch feishu ``` ```json { "feishu": { "app_id": "cli_xxx", "app_secret": "xxx" } } ``` -------------------------------- ### Install LaTeX Compiler Source: https://github.com/openraiser/nanoresearch/blob/main/README.md Install the Tectonic compiler, which is recommended for NanoResearch to automatically handle missing TeX packages. ```bash conda install -c conda-forge tectonic ``` -------------------------------- ### NanoResearch Configuration Example Source: https://github.com/openraiser/nanoresearch/blob/main/README.md Provides a detailed JSON configuration for NanoResearch, specifying API endpoints, model parameters, and execution profiles for various stages of the research pipeline. This configuration can be customized for different research needs. ```json { "research": { "base_url": "https://your-openai-compatible-endpoint/v1/", "api_key": "your-api-key", "template_format": "neurips2025", "execution_profile": "local_quick", "writing_mode": "hybrid", "max_retries": 2, "auto_create_env": true, "auto_download_resources": true, "ideation": { "model": "your-model", "temperature": 0.5, "max_tokens": 16384, "timeout": 600.0 }, "planning": { "model": "your-model", "temperature": 0.2, "max_tokens": 16384, "timeout": 600.0 }, "code_gen": { "model": "your-model", "temperature": 0.1, "max_tokens": 16384, "timeout": 600.0 }, "writing": { "model": "your-model", "temperature": 0.4, "max_tokens": 16384, "timeout": 600.0 }, "figure_gen": { "model": "gemini-3.1-flash-image-preview", "image_backend": "gemini", "temperature": null, "timeout": 300.0 }, "review": { "model": "your-model", "temperature": 0.3, "max_tokens": 16384, "timeout": 300.0 } } } ``` -------------------------------- ### Cloning NanoResearch and Running Research Pipeline via Claude CLI Source: https://github.com/openraiser/nanoresearch/blob/main/README_en.md This snippet demonstrates how to clone the NanoResearch repository and initiate a research project using the command-line interface with Claude Code. It outlines the basic commands for starting a new research topic and navigating the project. ```bash git clone https://github.com/OpenRaiser/NanoResearch.git cd NanoResearch claude /project:research "Your Research Topic Here" ``` -------------------------------- ### Search Literature using MCP Server Tools Source: https://context7.com/openraiser/nanoresearch/llms.txt Demonstrates how to use MCP server tools for literature retrieval from arXiv and Semantic Scholar. It includes functions for searching papers, getting paper details, batch retrieval, and searching by title. ```Python import asyncio from mcp_server.tools.arxiv_search import search_arxiv from mcp_server.tools.semantic_scholar import ( search_semantic_scholar, get_paper_details, get_papers_batch, search_paper_by_title, ) async def search_literature(): # 搜索 arXiv arxiv_papers = await search_arxiv( query="transformer attention mechanism", max_results=20, categories=["cs.LG", "cs.AI"], ) for paper in arxiv_papers[:3]: print(f"[arXiv] {paper['title']} ({paper['year']})") print(f" ID: {paper['paper_id']}") print(f" Authors: {', '.join(paper['authors'][:3])}") # 搜索 Semantic Scholar s2_papers = await search_semantic_scholar( query="graph neural network molecular", max_results=20, ) for paper in s2_papers[:3]: print(f"[S2] {paper['title']} ({paper['year']})") print(f" Citations: {paper['citation_count']}") # 获取论文详情(包含引用和参考文献) details = await get_paper_details("arXiv:2106.01345") print(f"论文: {details['title']}") print(f"引用数: {len(details.get('citations', []))}") print(f"参考文献数: {len(details.get('references', []))}") # 批量获取论文信息(高效 API) paper_ids = ["arXiv:2106.01345", "arXiv:2005.12872"] batch_results = await get_papers_batch(paper_ids) # 按标题精确匹配 matched = await search_paper_by_title("Attention Is All You Need") if matched: print(f"匹配到: {matched['title']}") asyncio.run(search_literature()) ``` -------------------------------- ### Generate Experimental Blueprint with PlanningAgent Source: https://context7.com/openraiser/nanoresearch/llms.txt Uses the PlanningAgent to generate a detailed experimental blueprint based on ideation output. It requires research configuration and workspace setup, and outputs details about datasets, baselines, metrics, proposed methods, and compute requirements. ```Python import asyncio from nanoresearch.config import ResearchConfig from nanoresearch.pipeline.workspace import Workspace from nanoresearch.agents.planning import PlanningAgent from nanoresearch.schemas.manifest import PipelineMode async def run_planning(ideation_output: dict): config = ResearchConfig.load() workspace = Workspace.create( topic="Efficient Attention", config_snapshot=config.snapshot(), pipeline_mode=PipelineMode.DEEP, ) agent = PlanningAgent(workspace, config) # 基于 ideation 输出生成实验蓝图 blueprint = await agent.run(ideation_output=ideation_output) # 蓝图包含: print(f"实验标题: {blueprint.get('title')}") print(f"数据集: {[d['name'] for d in blueprint.get('datasets', [])]}") print(f"基线方法: {[b['name'] for b in blueprint.get('baselines', [])]}") print(f"评估指标: {[m['name'] for m in blueprint.get('metrics', [])]}") # 提出的方法 method = blueprint.get("proposed_method", {}) print(f"提出方法: {method.get('name')}") print(f"关键组件: {method.get('key_components')}") # 消融实验组 ablations = blueprint.get("ablation_groups", []) print(f"消融实验组数: {len(ablations)}") # 计算资源需求 compute = blueprint.get("compute_requirements", {}) print(f"GPU 类型: {compute.get('gpu_type')}") print(f"预估时间: {compute.get('estimated_hours')} 小时") return blueprint # blueprint = asyncio.run(run_planning(ideation_result)) ``` -------------------------------- ### Get Data Root Directories Source: https://github.com/openraiser/nanoresearch/blob/main/nanoresearch/agents/_runner_script_template.py.txt Returns a list of unique Path objects for the project's data directories. It specifically looks for 'data' and 'datasets' subdirectories within the PROJECT_ROOT. ```python def _data_roots() -> list[Path]: return _unique_existing_paths( [ PROJECT_ROOT / "data", PROJECT_ROOT / "datasets", ] ) ``` -------------------------------- ### Get Model Root Directories Source: https://github.com/openraiser/nanoresearch/blob/main/nanoresearch/agents/_runner_script_template.py.txt Returns a list of unique Path objects for the project's model directories. It specifically looks for 'models' and 'checkpoints' subdirectories within the PROJECT_ROOT. ```python def _model_roots() -> list[Path]: return _unique_existing_paths( [ PROJECT_ROOT / "models", PROJECT_ROOT / "checkpoints", ] ) ``` -------------------------------- ### Configure Execution Profiles in NanoResearch Source: https://context7.com/openraiser/nanoresearch/llms.txt This Python snippet demonstrates how to configure the execution profile for the NanoResearch project using the `ExecutionProfile` enum. It shows examples for setting the profile to `FAST_DRAFT` for rapid iteration or `LOCAL_QUICK` for prioritizing local execution with optional SLURM upgrades. ```python from nanoresearch.config import ExecutionProfile # fast_draft: 轻量级草稿模式,快速迭代 config.execution_profile = ExecutionProfile.FAST_DRAFT # local_quick: 优先本地执行,需要时可升级到 SLURM(默认) config.execution_profile = ExecutionProfile.LOCAL_QUICK ``` -------------------------------- ### Generate Research Code with CodingAgent Source: https://context7.com/openraiser/nanoresearch/llms.txt Utilizes the CodingAgent to generate executable research code based on an experimental blueprint. It requires the topic, blueprint, and setup output, and returns generated files, code directory, training commands, SLURM scripts, and dependency information. ```Python import asyncio from nanoresearch.config import ResearchConfig from nanoresearch.pipeline.workspace import Workspace from nanoresearch.agents.coding import CodingAgent from nanoresearch.schemas.manifest import PipelineMode async def run_coding(topic: str, blueprint: dict, setup_output: dict): config = ResearchConfig.load() workspace = Workspace.create( topic=topic, config_snapshot=config.snapshot(), pipeline_mode=PipelineMode.DEEP, ) agent = CodingAgent(workspace, config) # 生成实验代码 result = await agent.run( topic=topic, experiment_blueprint=blueprint, setup_output=setup_output, ) # 结果包含: print(f"生成文件: {result.get('generated_files')}") print(f"代码目录: {result.get('code_dir')}") print(f"训练命令: {result.get('train_command')}") print(f"SLURM 脚本: {result.get('slurm_script')}") print(f"依赖文件: {result.get('requirements_path')}") # 代码计划详情 code_plan = result.get("code_plan", {}) print(f"项目名称: {code_plan.get('project_name')}") print(f"Python 版本: {code_plan.get('python_version')}") print(f"依赖包: {code_plan.get('dependencies')}") return result # result = asyncio.run(run_coding("Attention", blueprint, setup_output)) ``` -------------------------------- ### CLI Help and Usage Source: https://github.com/openraiser/nanoresearch/blob/main/README.md Display the help menu for all available NanoResearch CLI commands. ```bash nanoresearch --help ``` -------------------------------- ### GET /papers/sota Source: https://context7.com/openraiser/nanoresearch/llms.txt Retrieves state-of-the-art results for specific machine learning tasks from Papers With Code. ```APIDOC ## GET /papers/sota ### Description Queries the Papers With Code API to retrieve benchmark rankings and SOTA models for a given task. ### Method GET ### Endpoint /papers/sota ### Parameters #### Query Parameters - **task_id** (string) - Required - The ID of the ML task. - **dataset** (string) - Required - The dataset name. - **max_results** (integer) - Optional - Limit for returned entries. ### Response #### Success Response (200) - **model_name** (string) - Name of the model. - **score** (float) - Performance metric. - **paper_title** (string) - Title of the associated paper. ``` -------------------------------- ### Cloning NanoResearch and Opening in Codex Source: https://github.com/openraiser/nanoresearch/blob/main/README_en.md This snippet shows the initial steps to set up NanoResearch for use with Codex. It involves cloning the repository and then opening it within the Codex environment, with instructions to have Codex read the AGENTS.md file first. ```bash # 1. Clone the project git clone https://github.com/OpenRaiser/NanoResearch.git cd NanoResearch # 2. Open the repo in Codex # 3. Ask Codex to read AGENTS.md first ``` -------------------------------- ### Main Entry Point for NanoResearch Runner Source: https://github.com/openraiser/nanoresearch/blob/main/nanoresearch/agents/_runner_script_template.py.txt The main function that initializes the argument parser, handles command-line arguments including '--dry-run' and '--quick-eval', ensures output directories are created, and validates the mutual exclusivity of '--dry-run' and '--quick-eval'. It serves as the primary entry point for the runner script. ```Python def main() -> int: parser = argparse.ArgumentParser(description="NanoResearch deterministic runner") parser.add_argument("--dry-run", action="store_true") parser.add_argument("--quick-eval", action="store_true") args, passthrough = parser.parse_known_args() if args.dry_run and args.quick_eval: print("Only one of --dry-run/--quick-eval may be used.", file=sys.stderr) return 2 _ensure_output_dirs() ``` -------------------------------- ### Load and Access Workspace - Python Source: https://context7.com/openraiser/nanoresearch/llms.txt Demonstrates how to load an existing NanoResearch workspace and access its various directories for papers, plans, drafts, figures, code, and logs. It also shows how to read and write JSON and text files within the workspace. ```python from nanoresearch.pipeline.workspace import Workspace from pathlib import Path # 加载已有工作空间 workspace = Workspace.load(Path("~/.nanoresearch/workspace/research/abc123def456").expanduser()) # 访问工作空间目录 papers_dir = workspace.papers_dir # 文献检索产物 plans_dir = workspace.plans_dir # 实验方案 drafts_dir = workspace.drafts_dir # 论文草稿 figures_dir = workspace.figures_dir # 生成的配图 code_dir = workspace.code_dir # 实验代码 logs_dir = workspace.logs_dir # 运行日志 # 读写 JSON 数据 workspace.write_json("plans/experiment_config.json", { "learning_rate": 0.001, "batch_size": 32, "epochs": 100 }) config_data = workspace.read_json("plans/experiment_config.json") # 读写文本文件 workspace.write_text("logs/training.log", "Epoch 1: loss=0.5\nEpoch 2: loss=0.3") log_content = workspace.read_text("logs/training.log") ``` -------------------------------- ### Run NanoResearch Pipeline Source: https://github.com/openraiser/nanoresearch/blob/main/README.md Demonstrates commands to run the NanoResearch pipeline. Includes a dry-run option to validate configurations without execution, a full pipeline run with verbose output, and resuming a pipeline from a specific workspace after a failure. ```bash # 验证配置 nanoresearch run --topic "Adaptive Sparse Attention Mechanisms" --dry-run # 启动完整流水线 nanoresearch run --topic "Adaptive Sparse Attention Mechanisms" --format neurips2025 --verbose # 从断点恢复(若某阶段失败) nanoresearch resume --workspace ~/.nanobot/workspace/research/{session_id} --verbose ``` -------------------------------- ### Search GitHub Repositories with MCP Server Source: https://context7.com/openraiser/nanoresearch/llms.txt Demonstrates how to use the MCP server's GitHub search tool to find repositories based on a query, maximum results, and programming language. It outputs repository name, URL, stars, and a truncated description. ```Python import asyncio from mcp_server.tools.github_search import search_repos async def search_github(): repos = await search_repos( query="transformer pytorch implementation", max_results=5, language="Python", ) for repo in repos: print(f"Repo: {repo['name']}") print(f" URL: {repo['url']}") print(f" Stars: {repo.get('stars', 'N/A')}") print(f" Description: {repo.get('description', '')[:100]}") asyncio.run(search_github()) ``` -------------------------------- ### Build Quick Evaluation Tokens Source: https://github.com/openraiser/nanoresearch/blob/main/nanoresearch/agents/_runner_script_template.py.txt Constructs a list of command-line tokens optimized for quick evaluation runs. It intelligently adds flags like '--quick-eval' and speed-up options (e.g., reducing epochs, increasing batch size) if they are not already present or blocked. It also incorporates passthrough arguments. ```Python def _build_quick_eval_tokens( target_tokens: list[str], entry_script: Path | None, passthrough: list[str], blocked_options: set[str] | None = None, ) -> list[str]: tokens = list(target_tokens) blocked = set(blocked_options or set()) actual_qe = _detect_flag_form(entry_script, "--quick-eval") if ( actual_qe and "--quick-eval" not in blocked and "--quick_eval" not in blocked and not _token_present(tokens, "--quick-eval") and not _token_present(tokens, "--quick_eval") ): tokens.append(actual_qe) speedups = [ ("--epochs", "1"), ("--num-epochs", "1"), ("--max-steps", "2"), ("--steps", "2"), ("--batch-size", "8"), ("--num-workers", "0"), ("--workers", "0"), ("--subset-size", "64"), ("--train-size", "64"), ("--quick-eval-train-size", "64"), ("--limit-train-batches", "2"), ("--limit-val-batches", "1"), ] seen_bare: set[str] = set() for option, value in speedups: bare = option.lstrip("-").replace("-", "_") if bare in seen_bare: continue actual = _detect_flag_form(entry_script, option) if ( actual and option not in blocked and not _token_present(tokens, actual) and not _token_present(passthrough, actual) and not _token_present(tokens, option) and not _token_present(passthrough, option) ): tokens.extend([actual, value]) seen_bare.add(bare) return [*tokens, *passthrough] ``` -------------------------------- ### Use IdeationAgent for Literature Review - Python Source: https://context7.com/openraiser/nanoresearch/llms.txt Demonstrates the usage of the IdeationAgent for performing literature reviews, analyzing research gaps, and generating hypotheses. It shows how to initialize the agent, run it with a specific topic, and access the structured results including papers, gaps, hypotheses, and evidence. ```python import asyncio from nanoresearch.config import ResearchConfig from nanoresearch.pipeline.workspace import Workspace from nanoresearch.agents.ideation import IdeationAgent from nanoresearch.schemas.manifest import PipelineMode async def run_ideation(): config = ResearchConfig.load() workspace = Workspace.create( topic="Efficient Transformers", config_snapshot=config.snapshot(), pipeline_mode=PipelineMode.DEEP, ) agent = IdeationAgent(workspace, config) # 运行文献检索和假说生成 result = await agent.run(topic="Efficient Attention Mechanisms for Long Context") # 结果包含: print(f"检索到 {len(result.get('papers', []))} 篇相关论文") print(f"识别出 {len(result.get('gaps', []))} 个研究空白") print(f"生成了 {len(result.get('hypotheses', []))} 个假说") print(f"选定假说: {result.get('selected_hypothesis')}") print(f"选定理由: {result.get('rationale')}") # 访问提取的量化证据 evidence = result.get("evidence", {}) metrics = evidence.get("extracted_metrics", []) print(f"提取了 {len(metrics)} 个量化指标") # 访问 GitHub 参考实现 repos = result.get("reference_repos", []) print(f"找到 {len(repos)} 个参考代码仓库") return result result = asyncio.run(run_ideation()) ``` -------------------------------- ### Configuration File Loading (Python) Source: https://github.com/openraiser/nanoresearch/blob/main/nanoresearch/agents/_runner_script_template.py.txt Identifies and loads configuration files based on preferred locations and project file discovery. Supports multiple formats like YAML, JSON, TOML, and Python files. ```Python from pathlib import Path import re import ast PROJECT_ROOT = Path(".") def _project_files(max_depth: int = 3) -> list[Path]: files: list[Path] = [] for path in PROJECT_ROOT.rglob("*"): if not path.is_file(): continue try: rel_parts = path.relative_to(PROJECT_ROOT).parts except ValueError: continue if any(part.startswith(".") or part == "__pycache__" for part in rel_parts): continue if len(rel_parts) > max_depth: continue files.append(path) return files def _unique_existing_paths(paths: list[Path]) -> list[Path]: unique: list[Path] = [] seen: set[str] = set() for path in paths: try: resolved = path.resolve() except OSError: resolved = path key = str(resolved) if not path.exists() or key in seen: continue seen.add(key) unique.append(path) return unique def _existing_config_files() -> list[Path]: preferred = _unique_existing_paths( [ PROJECT_ROOT / "config.py", PROJECT_ROOT / "config.yaml", PROJECT_ROOT / "config.yml", PROJECT_ROOT / "config.json", PROJECT_ROOT / "config.toml", PROJECT_ROOT / "config" / "default.yaml", PROJECT_ROOT / "config" / "default.yml", PROJECT_ROOT / "config" / "default.json", PROJECT_ROOT / "config" / "default.toml", PROJECT_ROOT / "configs" / "default.yaml", PROJECT_ROOT / "configs" / "default.yml", PROJECT_ROOT / "configs" / "default.json", PROJECT_ROOT / "configs" / "default.toml", ] ) if preferred: return preferred return _unique_existing_paths( [ path for path in _project_files() if path.suffix.lower() in {'.py', '.yaml', '.yml', '.json', '.toml'} and "config" in path.stem.lower() ] ) def _load_config_mapping(path: Path) -> dict[str, object] | None: suffix = path.suffix.lower() # ... (implementation depends on suffix) ``` -------------------------------- ### Run Full Research Pipeline - Python Source: https://context7.com/openraiser/nanoresearch/llms.txt Shows how to orchestrate and run a complete research pipeline using the UnifiedPipelineOrchestrator. This involves loading configurations, creating a workspace, defining progress callbacks, and executing the pipeline, followed by exporting the final paper. ```python import asyncio from nanoresearch.config import ResearchConfig from nanoresearch.pipeline.workspace import Workspace from nanoresearch.pipeline.unified_orchestrator import UnifiedPipelineOrchestrator from nanoresearch.schemas.manifest import PipelineMode, PaperMode async def run_research_pipeline(): # 加载配置 config = ResearchConfig.load() # 创建工作空间 workspace = Workspace.create( topic="Graph Neural Networks for Molecular Property Prediction", config_snapshot=config.snapshot(), pipeline_mode=PipelineMode.DEEP, paper_mode=PaperMode.ORIGINAL_RESEARCH, ) # 定义进度回调 def progress_callback(stage: str, status: str, message: str): icons = {"started": ">>>", "completed": " OK", "failed": "ERR"} print(f" {icons.get(status, ' ')} [{stage}] {message}") # 创建并运行编排器 orchestrator = UnifiedPipelineOrchestrator( workspace, config, progress_callback=progress_callback ) try: result = await orchestrator.run("Graph Neural Networks for Molecular Property Prediction") print("Pipeline completed successfully!") # 导出论文 export_path = workspace.export() print(f"Paper exported to: {export_path}") return result finally: await orchestrator.close() # 运行 result = asyncio.run(run_research_pipeline()) ``` -------------------------------- ### Execute Target Command with Environment Source: https://github.com/openraiser/nanoresearch/blob/main/nanoresearch/agents/_runner_script_template.py.txt Runs a command specified by tokens within a given execution mode ('quick-eval' or other). It sets up the environment variables, including NANORESEARCH_EXECUTION_MODE and NANORESEARCH_QUICK_EVAL, and configures WANDB and TOKENIZERS_PARALLELISM for quick eval. It returns the return code of the completed subprocess. ```Python def _run_target(tokens: list[str], mode: str, target_env: dict[str, str] | None = None) -> int: env = {**os.environ} if target_env: env.update(target_env) env["NANORESEARCH_EXECUTION_MODE"] = mode if mode == "quick-eval": env["NANORESEARCH_QUICK_EVAL"] = "1" env.setdefault("WANDB_MODE", "disabled") env.setdefault("TOKENIZERS_PARALLELISM", "false") command = _materialize_command(tokens) completed = subprocess.run( command, cwd=str(PROJECT_ROOT), env=env, check=False, ) return int(completed.returncode or 0) ``` -------------------------------- ### Programmatic Configuration and Workspace Management Source: https://context7.com/openraiser/nanoresearch/llms.txt Using the Python API to load configurations, inspect stage-specific settings, and initialize new research workspaces. ```python from nanoresearch.config import ResearchConfig from nanoresearch.pipeline.workspace import Workspace from nanoresearch.schemas.manifest import PipelineMode, PaperMode config = ResearchConfig.load() ideation_config = config.for_stage("ideation") workspace = Workspace.create( topic="Efficient Attention Mechanisms for Long Sequences", config_snapshot={"template_format": "neurips2025"}, pipeline_mode=PipelineMode.DEEP, paper_mode=PaperMode.ORIGINAL_RESEARCH ) ``` -------------------------------- ### Initialize Claude Code Research Pipeline Source: https://github.com/openraiser/nanoresearch/blob/main/README.md Clones the repository and initiates the research pipeline using Claude Code, allowing for autonomous research without manual API key configuration. ```bash git clone https://github.com/OpenRaiser/NanoResearch.git cd NanoResearch claude /project:research "你的研究课题" ``` -------------------------------- ### Load Configuration from Various File Types Source: https://github.com/openraiser/nanoresearch/blob/main/nanoresearch/agents/_runner_script_template.py.txt Parses configuration from files with .py, .json, .yaml, .yml, or .toml extensions. It attempts to load the content as text and then parse it based on the file suffix. For Python files, it calls a specific parser. For JSON, it uses `json.loads`. For YAML, it uses a helper function. For TOML, it uses `tomllib` if available. Returns None if parsing fails or the file type is unsupported. ```python def _load_config_mapping(path: Path) -> object | None: suffix = path.suffix.lower() try: text = path.read_text(encoding="utf-8", errors="replace") except OSError: return None if suffix == ".py": return _parse_python_config(path) if suffix == ".json": try: parsed = json.loads(text) except json.JSONDecodeError: return None return parsed if isinstance(parsed, dict) else None if suffix in {".yaml", ".yml"}: return _parse_yaml_like_text(text) if suffix == ".toml": if tomllib is None: return None try: parsed = tomllib.loads(text) except Exception: return None return parsed if isinstance(parsed, dict) else None return None ``` -------------------------------- ### Run Research Pipeline via CLI Source: https://github.com/openraiser/nanoresearch/blob/main/README.md Execute a new research pipeline for a specific topic with a chosen LaTeX template format. ```bash nanoresearch run --topic "Graph Foundation Models for Biology" --format neurips2025 ``` -------------------------------- ### Claude Code Integration: Project Research Commands Source: https://context7.com/openraiser/nanoresearch/llms.txt This section details the command-line interface (CLI) commands for interacting with the NanoResearch project within Claude Code. It covers cloning the repository, initiating the project, running the full research pipeline, and executing specific stages like ideation, planning, experiment, analysis, writing, and review. ```bash # 进入项目目录 git clone https://github.com/OpenRaiser/NanoResearch.git cd NanoResearch claude # 运行完整 9 阶段流水线 /project:research "Efficient Attention Mechanisms" # 分阶段运行 /project:ideation "Neural Architecture Search" # Stage 1: 文献检索 /project:planning # Stage 2: 实验规划 /project:experiment # Stages 3-5: 环境准备+代码+执行 /project:analysis # Stage 6: 结果分析 /project:writing # Stages 7-8: 配图+论文 /project:review # Stage 9: 审稿修订 # 工具命令 /project:status # 查看当前状态 /project:resume # 断点续跑 ``` -------------------------------- ### Manage Research Pipelines via CLI Source: https://context7.com/openraiser/nanoresearch/llms.txt Commands to initiate research pipelines, resume interrupted sessions, check status, list sessions, and export completed research papers. ```bash nanoresearch run --topic "Adaptive Sparse Attention Mechanisms" --format neurips2025 --verbose nanoresearch resume --workspace ~/.nanoresearch/workspace/research/abc123def456 --verbose nanoresearch status --workspace ~/.nanoresearch/workspace/research/abc123def456 nanoresearch list nanoresearch export --workspace ~/.nanoresearch/workspace/research/abc123 --output ./my_paper ``` -------------------------------- ### Ensure Output Directories Exist Source: https://github.com/openraiser/nanoresearch/blob/main/nanoresearch/agents/_runner_script_template.py.txt Creates essential output directories ('results', 'checkpoints', 'logs') within the project root if they do not already exist. This function ensures that the project has the necessary structure for storing outputs. ```Python def _ensure_output_dirs() -> None: for dirname in ("results", "checkpoints", "logs"): (PROJECT_ROOT / dirname).mkdir(exist_ok=True) ``` -------------------------------- ### Project File Discovery (Python) Source: https://github.com/openraiser/nanoresearch/blob/main/nanoresearch/agents/_runner_script_template.py.txt Recursively finds files within a project directory up to a specified depth, excluding hidden files and __pycache__ directories. Useful for locating configuration files. ```Python from pathlib import Path PROJECT_ROOT = Path(".") def _project_files(max_depth: int = 3) -> list[Path]: files: list[Path] = [] for path in PROJECT_ROOT.rglob("*"): if not path.is_file(): continue try: rel_parts = path.relative_to(PROJECT_ROOT).parts except ValueError: continue if any(part.startswith(".") or part == "__pycache__" for part in rel_parts): continue if len(rel_parts) > max_depth: continue files.append(path) return files ``` -------------------------------- ### Materialize Normalized Configuration to File Source: https://github.com/openraiser/nanoresearch/blob/main/nanoresearch/agents/_runner_script_template.py.txt Writes a normalized configuration dictionary to a file in the specified format (YAML, JSON, or TOML). It creates the `AUTO_CONFIG_DIR` if it doesn't exist and determines the target filename based on the format. For TOML, it uses `_dump_toml`. For JSON, it uses `json.dumps` with indentation. Returns the Path object of the created file or None if an OSError occurs. ```python def _materialize_config(mapping: dict[str, object], fmt: str) -> Path | None: AUTO_CONFIG_DIR.mkdir(exist_ok=True) target = AUTO_CONFIG_DIR / { "yaml": "config_auto.yaml", "json": "config_auto.json", "toml": "config_auto.toml", }.get(fmt, "config_auto.json") normalized = _normalize_config_mapping(mapping) try: if fmt == "toml": target.write_text("\n".join(_dump_toml(normalized)) + "\n", encoding="utf-8") else: target.write_text(json.dumps(normalized, indent=2, ensure_ascii=False), encoding="utf-8") except OSError: return None return target ``` -------------------------------- ### Configuration Format Detection (Python) Source: https://github.com/openraiser/nanoresearch/blob/main/nanoresearch/agents/_runner_script_template.py.txt Determines the expected configuration file format (YAML, JSON, TOML, Python) by analyzing the source code of an entry script. This helps in selecting the appropriate parser. ```Python from pathlib import Path def _entry_script_source(entry_script: Path | None) -> str: # Placeholder for actual source code retrieval return "" def _expected_config_format(entry_script: Path | None) -> str: source = _entry_script_source(entry_script).lower() if not source: return "unknown" if any(token in source for token in ("yaml.safe_load", "yaml.load", "omegaconf", "hydra", ".yaml", ".yml")): return "yaml" if any(token in source for token in ("json.load", "json.loads", ".json")): return "json" if any(token in source for token in ("tomllib.load", "toml.load", ".toml")): return "toml" if any(token in source for token in ("import config", "from config import")): return "python" return "unknown" ``` -------------------------------- ### Generate and Compile LaTeX Documents Source: https://context7.com/openraiser/nanoresearch/llms.txt This Python script demonstrates how to generate LaTeX content from a template and then compile it into a PDF. It utilizes `generate_latex` for content creation and `compile_pdf` for the compilation process. The script handles template rendering with provided data and supports BibTeX for citations. ```python import asyncio from mcp_server.tools.latex_gen import generate_latex, generate_full_paper from mcp_server.tools.pdf_compile import compile_pdf # 使用模板生成 LaTeX latex_content = generate_latex( template_name="paper.tex.j2", data={ "title": "Efficient Attention for Long Sequences", "authors": ["Author One", "Author Two"], "abstract": "We propose a novel attention mechanism...", "sections": [ {"heading": "Introduction", "content": "..."}, {"heading": "Method", "content": "..."}, ], }, template_format="neurips2025", ) # 编译 PDF async def compile_paper(): result = await compile_pdf( tex_path="/path/to/paper.tex", bibtex=True, ) print(f"PDF 路径: {result.get('pdf_path')}") print(f"编译成功: {result.get('success')}") asyncio.run(compile_paper()) ``` -------------------------------- ### Determine Configuration File Candidate Source: https://github.com/openraiser/nanoresearch/blob/main/nanoresearch/agents/_runner_script_template.py.txt Identifies a single, unambiguous configuration file based on the expected format derived from an entry script and existing configuration files. It prioritizes files matching the expected format. If multiple files exist for the expected format, it attempts to materialize a configuration in the expected format from other available config files. Finally, if only one configuration file exists overall, it returns that file. ```python def _config_candidate(entry_script: Path | None) -> str | None: expected_format = _expected_config_format(entry_script) config_files = _existing_config_files() if expected_format in {"yaml", "json", "toml", "python"}: matching = [ path for path in config_files if ( expected_format == "python" and path.suffix.lower() == ".py" ) or ( expected_format == "yaml" and path.suffix.lower() in {".yaml", ".yml"} ) or ( expected_format == "json" and path.suffix.lower() == ".json" ) or ( expected_format == "toml" and path.suffix.lower() == ".toml" ) ] matching = _unique_existing_paths(matching) if len(matching) == 1: return str(matching[0].resolve()) if expected_format in {"yaml", "json", "toml"}: source_candidates: list[Path] = [] for suffix in (".py", ".json", ".yaml", ".yml", ".toml"): source_candidates.extend([path for path in config_files if path.suffix.lower() == suffix]) for source_path in _unique_existing_paths(source_candidates): mapping = _load_config_mapping(source_path) if not isinstance(mapping, dict): continue materialized = _materialize_config(mapping, expected_format) if materialized is not None: return str(materialized.resolve()) unique_files = _unique_existing_paths(config_files) if len(unique_files) == 1: return str(unique_files[0].resolve()) return None ``` -------------------------------- ### System Configuration Management Source: https://context7.com/openraiser/nanoresearch/llms.txt Configuration structure for NanoResearch using JSON and environment variables to define model endpoints, API keys, and execution profiles. ```json { "research": { "base_url": "https://your-openai-compatible-endpoint/v1/", "api_key": "your-api-key", "template_format": "neurips2025", "ideation": { "model": "deepseek-ai/DeepSeek-V3.2", "temperature": 0.5 } } } ``` ```bash export NANORESEARCH_BASE_URL="https://api.openai.com/v1/" export NANORESEARCH_API_KEY="sk-xxx" export OPENALEX_API_KEY="your-openalex-key" ``` -------------------------------- ### Dump Configuration Dictionary to TOML Lines Source: https://github.com/openraiser/nanoresearch/blob/main/nanoresearch/agents/_runner_script_template.py.txt Generates a list of strings representing a TOML configuration file from a Python dictionary. It handles nested dictionaries by creating TOML sections. Values are converted using the `_toml_value` helper function. Empty lines are inserted between top-level keys and nested sections for readability. ```python def _dump_toml(mapping: dict[str, object], prefix: str = "") -> list[str]: lines: list[str] = [] nested: list[tuple[str, dict[str, object]]] = [] for key, value in mapping.items(): if isinstance(value, dict): nested.append((key, value)) continue lines.append(f"{key} = {_toml_value(value)}") for key, value in nested: section = f"{prefix}.{key}" if prefix else key if lines: lines.append("") lines.append(f"[{section}]") lines.extend(_dump_toml(value, section)) return lines ``` -------------------------------- ### Track Pipeline Stages - Python Source: https://context7.com/openraiser/nanoresearch/llms.txt Illustrates how to use the PipelineStage enum to track the progress of different stages within a research pipeline. This includes marking stages as running, completed, or failed, handling exceptions, incrementing retry counts, and registering artifacts. ```python from nanoresearch.schemas.manifest import PipelineStage # 标记阶段状态 workspace.mark_stage_running(PipelineStage.IDEATION) # ... 执行阶段逻辑 ... workspace.mark_stage_completed(PipelineStage.IDEATION, output_path="papers/ideation_output.json") # 处理失败情况 try: # 执行代码... pass except Exception as e: workspace.mark_stage_failed(PipelineStage.CODING, error=str(e)) # 重试计数 retry_count = workspace.increment_retry(PipelineStage.EXECUTION) print(f"Retry attempt: {retry_count}") # 注册产物 artifact = workspace.register_artifact( name="experiment_blueprint", file_path=workspace.plans_dir / "experiment_blueprint.json", stage=PipelineStage.PLANNING, ) print(f"Artifact checksum: {artifact.checksum}") # 查看 manifest 状态 manifest = workspace.manifest print(f"Current stage: {manifest.current_stage}") print(f"Total artifacts: {len(manifest.artifacts)}") for stage_name, record in manifest.stages.items(): print(f" {stage_name}: {record.status}") ``` -------------------------------- ### Advanced Pipeline Execution and Export Source: https://github.com/openraiser/nanoresearch/blob/main/README.md Run a pipeline with verbose logging enabled and export the results from a specific workspace to a local directory. ```bash nanoresearch run --topic "Adaptive Sparse Attention" --format neurips2025 --verbose nanoresearch export --workspace ~/.nanobot/workspace/research/{session_id} --output ./paper_out ``` -------------------------------- ### POST /latex/generate Source: https://context7.com/openraiser/nanoresearch/llms.txt Generates LaTeX content from templates and compiles it into a PDF document. ```APIDOC ## POST /latex/generate ### Description Generates a LaTeX document based on a provided template and data, then compiles the resulting file into a PDF. ### Method POST ### Endpoint /latex/generate ### Parameters #### Request Body - **template_name** (string) - Required - The name of the Jinja2 template file. - **data** (object) - Required - Content data including title, authors, abstract, and sections. - **template_format** (string) - Required - The target format (e.g., neurips2025). - **bibtex** (boolean) - Optional - Whether to include BibTeX processing during compilation. ### Request Example { "template_name": "paper.tex.j2", "data": { "title": "Efficient Attention", "authors": ["Author A"], "sections": [{"heading": "Intro", "content": "..."}] }, "template_format": "neurips2025" } ### Response #### Success Response (200) - **pdf_path** (string) - Path to the generated PDF file. - **success** (boolean) - Status of the compilation process. ``` -------------------------------- ### Export Research Paper via CLI Source: https://github.com/openraiser/nanoresearch/blob/main/README.md Uses the nanoresearch CLI to export a completed research workspace into a structured paper format. ```bash nanoresearch export --workspace ~/.nanobot/workspace/research/{session_id} --output ./my_paper ``` -------------------------------- ### Materialize Command from Tokens Source: https://github.com/openraiser/nanoresearch/blob/main/nanoresearch/agents/_runner_script_template.py.txt Converts a list of command-line tokens into an executable command list. It handles different scenarios, such as Python scripts, module execution (-m), or direct commands, prepending the Python executable where necessary. ```Python def _materialize_command(tokens: list[str]) -> list[str]: if not tokens: return [sys.executable, "main.py"] first = tokens[0] if _is_python_launcher(first): return [sys.executable, *tokens[1:]] if first in {"-m", "-c"} or first.endswith(".py"): return [sys.executable, *tokens] return list(tokens) ``` -------------------------------- ### Integrate with Papers With Code for SOTA Benchmarks Source: https://context7.com/openraiser/nanoresearch/llms.txt This Python script demonstrates how to interact with the Papers With Code API to search for machine learning tasks and retrieve State-of-the-Art (SOTA) results. It uses `search_tasks` to find relevant tasks and `get_sota` to fetch benchmark leaderboards, providing model names, scores, and paper titles. ```python import asyncio from mcp_server.tools.paperswithcode import search_tasks, get_sota async def query_benchmarks(): # 搜索 ML 任务 tasks = await search_tasks( query="image classification", max_results=10, ) for task in tasks[:3]: print(f"Task: {task['name']}") print(f" ID: {task['id']}") # 获取 SOTA 排行榜 sota = await get_sota( task_id="image-classification", dataset="ImageNet", max_results=10, ) for entry in sota[:5]: print(f"Method: {entry.get('model_name')}") print(f" Score: {entry.get('score')}") print(f" Paper: {entry.get('paper_title')}") asyncio.run(query_benchmarks()) ``` -------------------------------- ### Path Resolution and Existence Check (Python) Source: https://github.com/openraiser/nanoresearch/blob/main/nanoresearch/agents/_runner_script_template.py.txt Functions to resolve paths, check if they exist, and find unique existing paths within a project. Handles absolute and relative paths, and resolves potential OS errors. ```Python from pathlib import Path import re import ast PROJECT_ROOT = Path(".") def _path_exists(path_value: str) -> bool: normalized = str(path_value or "").strip() if not normalized: return False return _resolved_path(normalized).exists() def _resolved_path(path_value: str) -> Path: candidate = Path(path_value) return candidate if candidate.is_absolute() else PROJECT_ROOT / candidate def _unique_existing_paths(paths: list[Path]) -> list[Path]: unique: list[Path] = [] seen: set[str] = set() for path in paths: try: resolved = path.resolve() except OSError: resolved = path key = str(resolved) if not path.exists() or key in seen: continue seen.add(key) unique.append(path) return unique ``` -------------------------------- ### Workspace Management API Source: https://context7.com/openraiser/nanoresearch/llms.txt Methods for loading workspaces, managing file system directories, and performing I/O operations on research artifacts. ```APIDOC ## POST /workspace/load ### Description Loads an existing research workspace from the local file system. ### Method POST ### Endpoint /workspace/load ### Parameters #### Request Body - **path** (string) - Required - The absolute or relative path to the workspace directory. ### Request Example { "path": "~/.nanoresearch/workspace/research/abc123def456" } ### Response #### Success Response (200) - **workspace_id** (string) - Unique identifier for the loaded workspace. - **directories** (object) - Map of workspace subdirectories (papers, plans, drafts, etc.). ``` -------------------------------- ### Execute and Manage Research Pipeline Source: https://github.com/openraiser/nanoresearch/blob/main/README_en.md Command-line interface commands for running, validating, resuming, and exporting research projects. ```bash # Validate config nanoresearch run --topic "Adaptive Sparse Attention Mechanisms" --dry-run # Run the full pipeline nanoresearch run --topic "Adaptive Sparse Attention Mechanisms" --format neurips2025 --verbose # Resume from checkpoint (if a stage fails) nanoresearch resume --workspace ~/.nanobot/workspace/research/{session_id} --verbose # Export paper nanoresearch export --workspace ~/.nanobot/workspace/research/{session_id} --output ./my_paper ```