
Deep Research
- 288 installs
- 340 repo stars
- Updated August 4, 2026
- glebis/claude-skills
deep-research is an agent research skill that investigates markets, APIs, regulations, or technical options with layered queries and synthesized citations before developers commit to scope or architecture.
About
deep-research is a Claude agent skill from glebis/claude-skills built for structured technical and market investigation before implementation commitments. It runs layered queries across APIs, regulations, competitive landscapes, and architectural alternatives, then synthesizes findings with citations developers can trace. The skill fits early discovery when choosing vendors, compliance paths, integration strategies, or build-versus-buy decisions. Developers reach for deep-research when a single web search is insufficient and they need an agent to compare options, surface risks, and produce a decision-ready brief instead of ad-hoc notes scattered across tabs.
- Multi-hop question plans
- Source-aware synthesis
- Competitive signal gathering
- Technical option comparison
- Decision-ready briefs
Deep Research by the numbers
- 288 all-time installs (skills.sh)
- Ranked #2,383 of 16,544 AI & Agent Building skills by installs in the Skillselion catalog
- Data as of Aug 6, 2026 (Skillselion catalog sync)
npx skills add https://github.com/glebis/claude-skills --skill deep-researchAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 288 |
|---|---|
| repo stars | ★ 340 |
| Last updated | August 4, 2026 |
| Repository | glebis/claude-skills ↗ |
How do you research APIs and regulations before choosing architecture?
Investigate markets, APIs, regulations, or technical options with layered queries and synthesized citations before committing to scope or architecture.
Who is it for?
Developers and tech leads evaluating integrations, compliance constraints, or build-versus-buy options who need cited synthesis before writing a PRD or ADR.
Skip if: Teams that already finalized architecture or only need code generation should skip deep-research because it targets pre-commitment investigation.
When should I use this skill?
The user must compare technical options, vendor APIs, regulations, or market context before locking scope, stack, or compliance approach.
What you get
Cited research brief, option comparison matrix, and risk summary with source references.
- cited research brief
- option comparison summary
Files
Deep Research Skill
Purpose
This skill enables comprehensive, internet-enabled research on any topic using OpenAI's Deep Research API (o4-mini-deep-research model). It intelligently enhances user research prompts through interactive clarifying questions, ensures research parameters are saved for reproducibility, and executes deep research with full web search capabilities.
When to Use This Skill
Trigger this skill when:
- User requests research on a specific topic
- User asks for analysis, investigation, or comprehensive information gathering
- User wants exploration of a subject with web search and reasoning
- User provides a brief research query that could be refined
- User wants to understand current state, trends, or comparisons in a field
Example user requests:
- "Research the most effective open-source RAG solutions with high benchmark performance"
- "What are the latest AI developments in 2025?"
- "I need a comprehensive analysis of distributed database systems"
- "Find best practices for implementing vector search"
- "Investigate how AI is impacting the software engineering industry"
Workflow Overview
User Input
↓
Assessment: Prompt too brief?
↓
YES → Ask Enhancement Questions → Collect Answers
↓ ↓
└───────→ Construct Enhanced Prompt ←──┘
↓
Save to Timestamped File
↓
Execute deep_research.py
↓
Output Report + Sources
↓
Present to UserHow Claude Should Use This Skill
Important for Token Efficiency: Deep research takes 10-20 minutes to complete. The skill is designed to run synchronously (blocking) without intermediate status checks. This approach minimizes token usage during the wait. Claude should: 1. Start the research 2. Wait for completion (subprocess blocks automatically) 3. Present final results once complete
No need for periodic polling or status updates during execution.
Step 1: Accept Research Request
Receive the user's research prompt. This can range from brief ("Latest AI trends") to highly detailed ("Impact of language models on developer productivity with focus on 2024-2025").
Step 2: Execute the Orchestration Script
Run the skill's main orchestration script with the user's research prompt:
python3 scripts/run_deep_research.py "Your research prompt here"The script is located at scripts/run_deep_research.py within the skill's installation.
Step 3: Script Execution Flow
The script automatically:
1. Assesses prompt completeness: Checks if prompt is too brief or generic (< 15 words or starts with "what is", "how to", etc.)
2. Asks clarifying questions (if needed):
- Presents 2-3 focused questions relevant to the research type
- Detects if research is technical or general based on keywords
- Allows users to select from predefined options (1-4) or provide custom text
- Questions cover: Scope/Timeframe, Depth level, Focus areas
3. Enhances the prompt: Combines original prompt with user's answers into structured research parameters
4. Saves prompt file: Writes enhanced prompt to research_prompt_YYYYMMDD_HHMMSS.txt for reproducibility
5. Executes deep research: Runs the core deep_research.py script with:
- Model: o4-mini-deep-research (configurable via
--model) - Timeout: 1800 seconds / 30 minutes (configurable via
--timeout) - Tools: Web search enabled by default
Step 4: Present Results to User
The script automatically:
- Saves markdown file: Research report with sources saved to
research_report_YYYYMMDD_HHMMSS.md - Prints to terminal: Complete research report with markdown formatting
- Lists web sources: Numbered URLs referenced in the research
- Confirms completion: Path where research files were saved
Token Efficiency Note: Deep research takes 10-20 minutes. The script runs synchronously (blocking) without intermediate polling, minimizing token usage during the wait.
Bundled Resources
Scripts
scripts/run_deep_research.py (Main Entry Point)
The orchestration script that handles:
- Prompt quality assessment
- Interactive enhancement questions (with smart detection for technical vs. general research)
- Prompt saving and timestamping
- Execution of core deep research
Key Features:
- Smart enhancement: Only asks questions if prompt is brief/generic
- Template-based questions: Different question sets for technical vs. general research
- Flexible input: Numbered options + custom text input
- Error handling: Helpful messages if deep_research.py is not found
Available options:
python3 run_deep_research.py <prompt> [OPTIONS]
--no-enhance Skip enhancement questions
--model <model> Model to use (default: o4-mini-deep-research)
--timeout <seconds> Timeout in seconds (default: 1800)
--output-dir <path> Where to save prompt fileassets/deep_research.py
Core script that interfaces with OpenAI's Deep Research API. Handles:
- API authentication via OPENAI_API_KEY
- Request creation and execution
- Automatic markdown saving: Saves timestamped report files by default
- Output formatting (report + sources with metadata)
- Error handling and retries
New command-line options:
--output-file <path> Custom output file path
--no-save Disable automatic markdown savingReferences
references/workflow.md
Detailed workflow documentation covering:
- Complete skill workflow with examples
- Prompt enhancement strategies
- Research parameters explanation
- Integration guidance for Claude
- Command-line interface reference
- Error handling and troubleshooting
- Tips for effective research
Key Behaviors
Smart Prompt Enhancement
The skill intelligently determines whether enhancement is needed:
- Triggers enhancement for prompts with < 15 words or generic starts
- Skips enhancement for detailed, specific prompts
- Allows users to disable with
--no-enhanceflag - Template-aware: Uses different questions for technical vs. general research
Research Parameters
Enhanced prompts include:
- Original user query with full context
- Scope and timeframe preferences
- Desired depth level (summary, technical, implementation, comparative)
- Specific focus areas (performance, cost, security, etc.)
These parameters help the deep research model deliver more targeted, relevant results.
Reproducibility
Every research execution:
- Saves the exact prompt used to a timestamped file
- Enables tracing research decisions
- Allows follow-up research using same/modified prompts
- Maintains audit trail of research parameters
Examples
Brief Prompt with Enhancement
User: "Research the most effective opensource RAG solutions"
Script behavior: 1. Detects brief prompt (12 words) + technical keywords ("opensource", "RAG") 2. Asks technical research questions:
- Technology scope: Open-source only? (User: Yes)
- Key metrics: Performance/benchmarks? (User: Speed and Accuracy)
- Use cases: Production deployment? (User: Multiple aspects)
3. Enhances to detailed prompt with parameters 4. Saves and executes deep research 5. Returns comprehensive report with comparative benchmarks and source URLs
Detailed Prompt Without Enhancement
User: "Analyze the impact of large language models on software developer productivity in 2024-2025, focusing on code generation tools, pair programming, and productivity metrics."
Script behavior: 1. Detects detailed prompt (24 words) with specific scope/focus 2. Skips enhancement questions 3. Saves and executes deep research immediately 4. Returns focused analysis aligned with user specifications
Requirements
- Python 3.7+
- OpenAI API key (set via
OPENAI_API_KEYenvironment variable or.envfile) - Internet connection (for web search)
- 30+ minutes for research completion (configurable timeout)
Token-Efficient Workflow
Long-Running Task Optimization
Deep research queries typically take 10-20 minutes to complete. This skill is optimized to minimize token usage during long waits:
How it works: 1. Synchronous execution: The script runs as a blocking subprocess (no background polling) 2. No intermediate checks: Claude waits silently for completion without status updates 3. Single output: Results are presented once at the end 4. Automatic saving: Markdown files are saved automatically, no manual intervention needed
Token savings:
- Traditional approach: Checking status every 30 seconds = ~40 checks × 500 tokens = ~20,000 tokens wasted
- This approach: Single wait = ~1,000 tokens total
Automatic File Management
The skill automatically generates and saves files:
Generated files:
research_prompt_YYYYMMDD_HHMMSS.txt- Enhanced research prompt with parametersresearch_report_YYYYMMDD_HHMMSS.md- Complete markdown report with:- Research sections (historical, cognitive, cultural, etc.)
- Numbered source citations
- Metadata footer (date, model)
Customization options:
# Custom output location
python3 deep_research.py --prompt-file prompt.txt --output-file my_research.md
# Disable automatic saving (terminal output only)
python3 deep_research.py --prompt-file prompt.txt --no-saveTroubleshooting
Missing OPENAI_API_KEY
Error: "Missing OPENAI_API_KEY"
Solution:
- Set environment variable:
export OPENAI_API_KEY="your-key" - Or create
.envfile in working directory withOPENAI_API_KEY=your-key
deep_research.py Not Found
Error: "Could not find deep_research.py"
Solution:
- Ensure skill is properly installed with assets
- Script searches in: skill assets folder → current directory → parent directory
Research Timeout
Error: Request times out after 30 minutes
Solution:
- Increase timeout:
--timeout 5400(90 minutes) - Simplify prompt to reduce research scope
- Run during off-peak hours for potentially faster API responses
{
"name": "deep-research",
"description": "This skill should be used when conducting comprehensive research on any topic using the OpenAI Deep Research API. It aut",
"author": {
"name": "Gleb Kalinin"
},
"repository": "https://github.com/glebis/claude-skills",
"license": "MIT"
}# OpenAI API Key
# Get your key from: https://platform.openai.com/api-keys
# Required for Deep Research API access
OPENAI_API_KEY=
#!/usr/bin/env python3
"""Simple CLI helper for the OpenAI Deep Research API."""
from __future__ import annotations
import argparse
import os
import sys
from datetime import datetime
from pathlib import Path
from typing import Iterable, List
from openai import OpenAI
from openai._exceptions import OpenAIError
from openai.types.responses.response import Response
try:
from openai.types.responses.response_function_web_search import (
Action,
ActionFind,
ActionOpenPage,
ActionSearch,
)
except ImportError: # pragma: no cover - SDK drift safety net
Action = ActionFind = ActionOpenPage = ActionSearch = None # type: ignore
DEFAULT_MODEL = "o4-mini-deep-research"
DEFAULT_TOOLS = [{"type": "web_search"}]
DEFAULT_TIMEOUT_SECONDS = 30 * 60 # 30 minutes runtime window
DEFAULT_ENV_PATH = Path(".env")
ENV_KEY = "OPENAI_API_KEY"
def load_env(path: Path = DEFAULT_ENV_PATH) -> None:
"""Populate os.environ from a .env file if the target key is missing."""
if os.environ.get(ENV_KEY) or not path.exists():
return
for raw_line in path.read_text().splitlines():
line = raw_line.strip()
if not line or line.startswith("#") or "=" not in line:
continue
key, value = line.split("=", 1)
key = key.strip()
if not key or key in os.environ:
continue
cleaned = value.strip().strip('"').strip("'")
os.environ[key] = cleaned
def extract_web_sources(response: Response) -> List[str]:
"""Extract unique URLs referenced by web search tool calls."""
urls: List[str] = []
for item in response.output:
item_type = getattr(item, "type", None)
if item_type != "web_search_call":
continue
action: Action | None = getattr(item, "action", None) # type: ignore[assignment]
if action is None:
continue
action_type = getattr(action, "type", "")
if action_type == "search":
sources: Iterable | None = getattr(action, "sources", None) # type: ignore[assignment]
for source in sources or []:
url = getattr(source, "url", None)
if url:
urls.append(url)
elif action_type in {"find", "open_page"}:
url = getattr(action, "url", None)
if url:
urls.append(url)
unique_urls: List[str] = []
seen = set()
for url in urls:
if url not in seen:
seen.add(url)
unique_urls.append(url)
return unique_urls
def run_research(
prompt: str,
*,
instructions: str | None,
model: str,
include_sources: bool,
timeout_seconds: float,
) -> Response:
load_env()
api_key = os.environ.get(ENV_KEY)
if not api_key:
raise SystemExit(
"Missing OPENAI_API_KEY. Set it via environment or .env file before running the script."
)
client = OpenAI(api_key=api_key, timeout=timeout_seconds)
request_payload: dict = {
"model": model,
"input": prompt,
"tools": DEFAULT_TOOLS,
}
if instructions:
request_payload["instructions"] = instructions
if include_sources:
request_payload["include"] = ["web_search_call.action.sources"]
try:
return client.responses.create(**request_payload)
except OpenAIError as exc:
raise SystemExit(f"Deep Research request failed: {exc}") from exc
def main(argv: list[str] | None = None) -> None:
parser = argparse.ArgumentParser(description="Run a Deep Research query using the OpenAI API")
parser.add_argument("prompt", nargs="?", help="The research question or task you want to run")
parser.add_argument(
"--instructions",
help="Optional system instructions to steer the researcher",
)
parser.add_argument(
"--model",
default=DEFAULT_MODEL,
help=f"Model to use (default: {DEFAULT_MODEL})",
)
parser.add_argument(
"--prompt-file",
type=Path,
help="Read the prompt text from a file instead of positional argument",
)
parser.add_argument(
"--no-sources",
action="store_true",
help="Disable best-effort extraction of web sources",
)
parser.add_argument(
"--timeout",
type=int,
default=DEFAULT_TIMEOUT_SECONDS,
help="Request timeout in seconds (default: 1800)",
)
parser.add_argument(
"--output-file",
type=Path,
help="Save research report to this markdown file (default: auto-generated timestamp)",
)
parser.add_argument(
"--no-save",
action="store_true",
help="Don't save the research report to a file",
)
args = parser.parse_args(argv)
if args.prompt_file and args.prompt:
parser.error("Specify either a positional prompt or --prompt-file, not both.")
prompt_text = args.prompt
if args.prompt_file:
if not args.prompt_file.exists():
parser.error(f"Prompt file not found: {args.prompt_file}")
prompt_text = args.prompt_file.read_text()
if not prompt_text:
parser.error("Provide a prompt via positional argument or --prompt-file.")
response = run_research(
prompt_text,
instructions=args.instructions,
model=args.model,
include_sources=not args.no_sources,
timeout_seconds=args.timeout,
)
report = (response.output_text or "").strip()
if not report:
print("No textual report returned. Full response follows:\n")
print(response.model_dump_json(indent=2))
return
# Extract sources
sources = extract_web_sources(response) if not args.no_sources else []
# Save to markdown file (unless --no-save is specified)
if not args.no_save:
output_file = args.output_file
if not output_file:
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
output_file = Path(f"research_report_{timestamp}.md")
# Build markdown content
markdown_content = report
# Append sources if available
if sources:
markdown_content += "\n\n## Sources\n\n"
for idx, url in enumerate(sources, start=1):
markdown_content += f"{idx}. {url}\n"
# Add metadata footer
markdown_content += f"\n\n---\n\n*Research conducted on: {datetime.now().strftime('%B %d, %Y')}* \n"
markdown_content += f"*Model: {args.model}* \n"
# Save file
output_file.write_text(markdown_content, encoding="utf-8")
print(f"✅ Research report saved to: {output_file.absolute()}\n")
# Print to terminal
print("=== Deep Research Report ===\n")
print(report)
if args.no_sources or not sources:
return
print("\n=== Sources ===")
for idx, url in enumerate(sources, start=1):
print(f"{idx}. {url}")
if __name__ == "__main__":
main(sys.argv[1:])
Deep Research Skill - Changelog
Version 2.0 - Token-Optimized with Automatic Markdown Saving
New Features
Automatic Markdown Saving
- Research reports are now automatically saved to timestamped markdown files
- Default filename:
research_report_YYYYMMDD_HHMMSS.md - Includes complete report, sources, and metadata footer
- No manual intervention needed
Token-Efficient Long-Running Task Handling
- Optimized for 10-20 minute deep research queries
- Synchronous execution (blocking subprocess, no polling)
- No intermediate status checks during wait
- Token savings: ~19,000 tokens per research query vs. polling approach
New Command-Line Options
--output-file <path> # Custom output file path
--no-save # Disable automatic markdown savingImprovements
deep_research.py Updates
- Added automatic file saving with timestamped filenames
- Enhanced markdown formatting with metadata footer
- Added datetime import for timestamp generation
- Success confirmation message with absolute file path
run_deep_research.py Updates
- Better progress messages with estimated time (10-20 minutes)
- Timeout display in both seconds and minutes
- Completion confirmation message
- Improved error handling
SKILL.md Updates
- Added "Token-Efficient Workflow" section explaining optimization
- Documented automatic markdown saving feature
- Added token savings calculations (~20K tokens saved)
- Updated all usage examples
- Enhanced troubleshooting section
Technical Details
Token Optimization Strategy:
- Traditional approach: 40 status checks × 500 tokens = 20,000 tokens
- Optimized approach: Single wait = ~1,000 tokens
- Savings: ~95% reduction in token usage during wait
File Generation:
research_prompt_YYYYMMDD_HHMMSS.txt- Enhanced prompt with parametersresearch_report_YYYYMMDD_HHMMSS.md- Complete markdown report
Usage Example
# Basic usage (auto-saves to research_report_20251025_150402.md)
python3 scripts/run_deep_research.py "Art as sense-making"
# Custom output location
python3 assets/deep_research.py --prompt-file prompt.txt --output-file my_research.md
# No automatic saving (terminal only)
python3 assets/deep_research.py --prompt-file prompt.txt --no-saveBreaking Changes
None - all changes are backward compatible. The skill maintains full compatibility with existing workflows.
Files Modified
assets/deep_research.py- Added automatic markdown savingscripts/run_deep_research.py- Enhanced progress messagesSKILL.md- Comprehensive documentation updates
---
Released: October 25, 2025
Deep Research Skill Workflow
Overview
This skill enables comprehensive research on any topic using the OpenAI Deep Research API (o4-mini-deep-research model). It automates the process of enhancing user prompts through interactive clarifying questions, saving the research parameters, and executing the deep research.
When to Use This Skill
Use this skill when:
- User requests in-depth research on a topic
- User asks for analysis, investigation, or comprehensive information gathering
- User wants to explore a subject with web search and structured reasoning
- User provides a brief or vague research query that needs refinement
Example triggers:
- "Research the most effective open-source RAG solutions"
- "I need to understand the current state of quantum computing"
- "Find information about emerging web frameworks"
- "Investigate best practices for distributed systems"
Skill Workflow
1. Receive User Research Prompt
Accept the user's research request. This can be:
- Brief/vague: "Latest AI trends"
- Detailed: "Impact of large language models on software engineering in 2025"
- Technical: "Comparison of vector databases for semantic search"
2. Assess Prompt Completeness
Determine if the prompt needs enhancement:
- Too brief (< 15 words): Ask clarifying questions
- Generic (starts with "what is", "how to", etc.): Ask clarifying questions
- Detailed/Specific: Proceed directly to research
3. Enhance Prompt (if needed)
Ask user 2-3 focused clarifying questions based on research type:
For General Research:
- Scope/Timeframe: Latest (2024-2025), Historical, Specific period?
- Depth level: Executive summary, Technical, Implementation guide, Comparative?
- Focus areas: Performance, Cost, Ease of use, Security, Multiple?
For Technical Research:
- Technology scope: Open-source only, Enterprise, Language-specific?
- Key metrics: Speed, Accuracy, Scalability, Resources?
- Use cases: Production, Research, Education, Exploration?
Allow users to:
- Select from predefined options (numbered list)
- Provide custom text input for more control
4. Construct Enhanced Prompt
Combine: 1. Original user prompt 2. User's answers to clarification questions as structured research parameters
Example:
Original: "Most effective opensource RAG solutions with highest benchmark performance"
Enhanced: "Most effective opensource RAG solutions with highest benchmark performance
Research parameters:
- Latest developments (2024-2025)
- Technical deep dive
- Performance/Benchmarks5. Save Research Prompt
Save the final research prompt to a timestamped file:
- Location: User's specified output directory or current working directory
- Format:
research_prompt_YYYYMMDD_HHMMSS.txt - Purpose: Reproducibility and audit trail of research parameters
Output: Display file path where prompt was saved
6. Execute Deep Research
Run deep_research.py with:
- Prompt file: The enhanced research prompt file
- Model: o4-mini-deep-research (configurable)
- Timeout: 1800 seconds / 30 minutes (configurable)
- Tools: Web search enabled by default
The script outputs:
- Deep Research Report: Comprehensive analysis with citations
- Web Sources: URLs extracted from search actions (numbered list)
7. Present Results
Output to user: 1. Research report (formatted markdown/text) 2. Referenced web sources (numbered list) 3. Path to saved research prompt file
File Structure
deep-research/
├── SKILL.md # Skill metadata and instructions
├── scripts/
│ ├── run_deep_research.py # Orchestration script (main entry point)
│ └── deep_research.py # Core deep research API client
├── references/
│ └── workflow.md # This file - detailed workflow
└── assets/
└── deep_research.py # Copy for easy skill accessKey Concepts
Prompt Enhancement
Enhancement is smart and optional:
- Only triggered for brief or generic prompts
- Users can skip with
--no-enhanceflag - Questions use closed-list options + custom text input
- Template-aware: Technical vs. General research questions
Research Parameters
The enhanced prompt includes:
- Original user query with context
- Explicit scope/timeframe
- Depth level expectations
- Specific focus areas
- Success criteria
This helps the deep research model deliver more targeted results.
Reproducibility
Each research run saves:
- Complete enhanced prompt used
- Timestamp for tracking
- Can be re-used or modified for follow-up research
Integration with Claude
When Claude uses this skill:
1. Receive research request → Accept user prompt 2. Check prompt quality → Determine if enhancement needed 3. Ask questions → Guide user to refine scope (if needed) 4. Execute script → Run run_deep_research.py with enhanced prompt 5. Present results → Show report + sources to user 6. Offer follow-ups → Suggest related research directions or refinements
Command-Line Interface
python3 run_deep_research.py "Your research prompt"
python3 run_deep_research.py "Brief prompt" --no-enhance
python3 run_deep_research.py "Prompt" --model o4-mini-deep-research
python3 run_deep_research.py "Prompt" --timeout 3600 --output-dir ./resultsError Handling
The skill handles:
- Missing deep_research.py → Helpful error message with location hints
- Invalid API key → Passes through to deep_research.py error handling
- Timeout exceeded → User can increase timeout parameter
- Interrupted research → Saved prompt file available for retry
Tips for Effective Research
1. Be specific: More specific prompts often yield better results even without enhancement 2. Define scope: Clarify timeframe and domain (e.g., "2025 trends in quantum computing") 3. Set expectations: Indicate desired output format (comparison table, timeline, etc.) 4. Review sources: Check URLs in results for credibility and relevance 5. Iterate: Use saved prompts as starting points for follow-up research
#!/usr/bin/env python3
"""
Deep Research Skill Orchestrator
This script enhances user research prompts through interactive questions,
saves the enhanced prompt, and executes deep_research.py to run the research.
"""
from __future__ import annotations
import argparse
import json
import os
import subprocess
import sys
import tempfile
from datetime import datetime
from pathlib import Path
from typing import Optional
# Prompt enhancement question templates by research type
ENHANCEMENT_TEMPLATES = {
"general": {
"scope": {
"question": "What is the scope/timeframe for this research?",
"options": [
"Latest developments (2024-2025)",
"Historical overview (all time)",
"Specific time period (please specify)",
"No preference"
]
},
"depth": {
"question": "What level of detail do you need?",
"options": [
"Executive summary",
"Technical deep dive",
"Implementation guide",
"Comparative analysis"
]
},
"focus": {
"question": "Any specific aspects or domains to focus on?",
"options": [
"Performance/Benchmarks",
"Cost/Efficiency",
"Ease of use/Adoption",
"Security/Privacy",
"Multiple aspects"
]
}
},
"technical": {
"scope": {
"question": "Technology scope?",
"options": [
"Open-source only",
"Open-source + enterprise",
"Language/framework specific",
"No restriction"
]
},
"metrics": {
"question": "What performance metrics matter most?",
"options": [
"Speed/Latency",
"Accuracy/Correctness",
"Scalability",
"Resource usage",
"Multiple metrics"
]
},
"use_case": {
"question": "Any specific use cases or applications?",
"options": [
"Production deployment",
"Research/Evaluation",
"Learning/Education",
"General exploration"
]
}
}
}
def is_prompt_too_brief(prompt: str) -> bool:
"""Check if prompt needs enhancement (too short or lacking detail)."""
# Prompts with less than 15 words or very generic are considered brief
word_count = len(prompt.split())
generic_patterns = ["what is", "how to", "tell me about"]
is_generic = any(prompt.lower().startswith(p) for p in generic_patterns)
return word_count < 15 or is_generic
def ask_enhancement_questions(prompt: str) -> str:
"""Ask user clarifying questions to enhance the prompt."""
# Detect if it's a technical research prompt
technical_keywords = ["algorithm", "framework", "benchmark", "api", "architecture", "library", "tool", "system"]
is_technical = any(kw in prompt.lower() for kw in technical_keywords)
template_type = "technical" if is_technical else "general"
template = ENHANCEMENT_TEMPLATES[template_type]
print(f"\n📋 Let's refine your research prompt...")
print(f"Original prompt: {prompt}\n")
enhanced_parts = []
for question_key, question_data in template.items():
print(f"\n{question_data['question']}")
for i, option in enumerate(question_data['options'], 1):
print(f" {i}. {option}")
while True:
response = input("Your choice (number or custom text): ").strip()
if response.isdigit() and 1 <= int(response) <= len(question_data['options']):
selected = question_data['options'][int(response) - 1]
if "specify" in selected.lower() or "custom" in selected.lower():
custom = input("Please specify: ").strip()
enhanced_parts.append(custom if custom else selected)
else:
enhanced_parts.append(selected)
break
elif response:
# Allow custom text input
enhanced_parts.append(response)
break
else:
print("Invalid input. Please try again.")
# Construct enhanced prompt
enhanced_prompt = f"{prompt}\n\nResearch parameters:\n"
enhanced_prompt += "\n".join(f"- {part}" for part in enhanced_parts)
return enhanced_prompt
def save_research_prompt(prompt: str, output_dir: Optional[Path] = None) -> Path:
"""Save the research prompt to a file."""
if output_dir is None:
output_dir = Path.cwd()
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
prompt_file = output_dir / f"research_prompt_{timestamp}.txt"
prompt_file.write_text(prompt, encoding="utf-8")
print(f"\n💾 Research prompt saved to: {prompt_file}")
return prompt_file
def get_deep_research_path() -> Path:
"""Get the path to deep_research.py."""
# Try relative to this script first (for skill assets)
script_dir = Path(__file__).parent
skill_assets = script_dir.parent / "assets" / "deep_research.py"
if skill_assets.exists():
return skill_assets
# Fall back to looking in common locations
cwd = Path.cwd()
if (cwd / "deep_research.py").exists():
return cwd / "deep_research.py"
if (cwd.parent / "deep_research.py").exists():
return cwd.parent / "deep_research.py"
raise FileNotFoundError(
"Could not find deep_research.py. Please ensure it's in the skill assets folder or current directory."
)
def run_deep_research(prompt_file: Path, model: str = "o4-mini-deep-research", timeout: int = 1800) -> None:
"""Execute deep_research.py with the research prompt."""
deep_research_py = get_deep_research_path()
print(f"\n🚀 Running Deep Research")
print(f" Model: {model}")
print(f" Timeout: {timeout} seconds ({timeout // 60} minutes)")
print(f" Estimated time: 10-20 minutes")
print(f"\n⏳ Research in progress... (this may take a while)\n")
cmd = [
sys.executable,
str(deep_research_py),
"--prompt-file",
str(prompt_file),
"--model",
model,
"--timeout",
str(timeout),
]
try:
subprocess.run(cmd, check=True)
print(f"\n✅ Deep Research completed successfully!")
except subprocess.CalledProcessError as exc:
print(f"\n❌ Deep Research execution failed with exit code {exc.returncode}")
raise SystemExit(f"Research execution failed") from exc
except FileNotFoundError as exc:
print(f"\n❌ Could not execute deep_research.py: {exc}")
raise SystemExit("Missing deep_research.py executable") from exc
def main(argv: list[str] | None = None) -> None:
parser = argparse.ArgumentParser(
description="Enhance a research prompt and run Deep Research API query"
)
parser.add_argument(
"prompt",
nargs="?",
help="The research question or task (can be brief, will be enhanced)",
)
parser.add_argument(
"--no-enhance",
action="store_true",
help="Skip prompt enhancement questions",
)
parser.add_argument(
"--model",
default="o4-mini-deep-research",
help="Model to use (default: o4-mini-deep-research)",
)
parser.add_argument(
"--timeout",
type=int,
default=1800,
help="Request timeout in seconds (default: 1800)",
)
parser.add_argument(
"--output-dir",
type=Path,
help="Directory to save the research prompt file",
)
args = parser.parse_args(argv)
if not args.prompt:
parser.error("Provide a research prompt as a positional argument.")
# Determine if enhancement is needed
prompt = args.prompt
if not args.no_enhance and is_prompt_too_brief(prompt):
prompt = ask_enhancement_questions(prompt)
elif not args.no_enhance:
print(f"\n✓ Prompt seems detailed enough, skipping enhancement questions.")
# Save the prompt
prompt_file = save_research_prompt(prompt, args.output_dir)
# Run deep research
run_deep_research(prompt_file, args.model, args.timeout)
if __name__ == "__main__":
main(sys.argv[1:])
Related skills
FAQ
What does deep-research produce for developers?
deep-research produces layered investigation output—option comparisons, risk notes, and synthesized citations—covering markets, APIs, regulations, or technical alternatives before scope or architecture is locked.
When should deep-research run in a project?
deep-research should run during early discovery when developers need evidence-backed comparisons of vendors, compliance paths, or technical choices rather than during implementation or deployment.
How is deep-research different from a quick web search?
deep-research chains layered queries and merges results into a cited synthesis aimed at architecture and scope decisions, whereas a quick search returns unstructured snippets without comparison framing.