AICodingLab
Claude Code лайфхаки · Урок 17 из 35

Deep-research: глубокие исследования в несколько фаз

🎯 Цель урока: Научиться проводить глубокие исследования с использованием Claude Code в несколько фаз, включая сбор данных, верификацию и синтез отчёта. Освоить production-ready методологию multi-agent research.

📖 Теория

Глубокие исследования (Deep-research) — это метод, позволяющий углубиться в изучение определённой темы, используя различные источники информации и подходы. В Claude Code этот процесс можно разбить на несколько ключевых фаз, автоматизированных через agent orchestration и parallel processing.

Архитектура Deep Research в Claude Code

Phase 1: Discovery (parallel)
├─ Agent A: Academic papers search
├─ Agent B: Industry reports search
├─ Agent C: Code repositories analysis
└─ Agent D: Social media sentiment

Phase 2: Verification (sequential)
├─ Cross-reference facts
├─ Check source credibility
└─ Identify conflicts

Phase 3: Synthesis (single agent)
└─ Generate comprehensive report

Phase 4: Review (parallel)
├─ Technical reviewer
├─ Fact checker
└─ Editor

Фазы глубокого исследования

  • Сбор данных (Discovery): Идентификация источников информации, включая статьи, книги, документы и интернет-ресурсы. Использование parallel agents для ускорения.
  • Анализ и верификация (Verification): Проверка достоверности собранной информации и её соответствия заданной теме. Cross-referencing между источниками.
  • Синтез отчёта (Synthesis): Обобщение и структурирование полученной информации в виде отчёта или презентации.
  • Обсуждение результатов (Review): Презентация полученных выводов и получение обратной связи.

Типы исследований

Тип Применение Длительность Агенты
Quick Research Быстрый обзор темы, FAQ 5-15 минут 1-2
Standard Research Техническая документация, конкурентный анализ 30-60 минут 3-5
Deep Research Белая книга, научная статья, стратегия 2-4 часа 5-10
Comprehensive Research Диссертация, market intelligence report 1-3 дня 10-20

🛠 Практика

Базовое исследование (Quick Research)

Шаг 1. Начните с выбора темы для исследования:

# Простой подход
"Research the current state of WebAssembly adoption in 2025"

# Claude выполнит:
# 1. WebSearch для статей
# 2. Анализ результатов
# 3. Синтез краткого отчёта

Standard Research с верификацией

Шаг 2. Используйте multi-phase подход:

# Phase 1: Data Collection
"Search for information about Rust web frameworks:
1. Official documentation
2. GitHub stars and activity
3. Performance benchmarks
4. Community feedback

Save findings to research-rust-frameworks.md"

# Phase 2: Verification
"Verify the claims in research-rust-frameworks.md:
- Cross-check performance numbers
- Validate GitHub statistics
- Check publication dates"

# Phase 3: Synthesis
"Create comprehensive comparison report of Rust web frameworks
based on verified data from research-rust-frameworks.md"

Deep Research с agent orchestration

Использование Workflow для параллельного исследования:

#!/usr/bin/env node
// research-workflow.js

export const meta = {
  name: 'deep-research',
  description: 'Multi-agent deep research on a topic',
  phases: [
    { title: 'Discovery', detail: 'Parallel data collection' },
    { title: 'Verification', detail: 'Cross-reference and fact-check' },
    { title: 'Synthesis', detail: 'Generate final report' }
  ]
};

const topic = args.topic || "AI coding assistants market 2025";

// Phase 1: Parallel Discovery
const discoveryAgents = await parallel([
  // Academic research
  () => agent(
    `Research academic papers on ${topic}. Focus on:
    - Recent publications (2024-2025)
    - Citation count
    - Key findings
    Save to discovery-academic.md`,
    { label: 'academic', phase: 'Discovery' }
  ),

  // Industry analysis
  () => agent(
    `Research industry reports on ${topic}. Focus on:
    - Market size and growth
    - Key players
    - Trends
    Save to discovery-industry.md`,
    { label: 'industry', phase: 'Discovery' }
  ),

  // Technical implementation
  () => agent(
    `Research technical implementations of ${topic}. Focus on:
    - GitHub repositories
    - Technologies used
    - Architecture patterns
    Save to discovery-technical.md`,
    { label: 'technical', phase: 'Discovery' }
  ),

  // User sentiment
  () => agent(
    `Research user opinions on ${topic}. Focus on:
    - Reddit discussions
    - Twitter sentiment
    - Product reviews
    Save to discovery-sentiment.md`,
    { label: 'sentiment', phase: 'Discovery' }
  )
]);

// Phase 2: Verification
const verificationResults = await agent(
  `Verify findings from discovery phase:
  - Read all discovery-*.md files
  - Cross-reference facts between sources
  - Identify conflicts and resolve them
  - Flag unverified claims
  - Rate source credibility
  Save verified data to verified-findings.md`,
  { label: 'verification', phase: 'Verification' }
);

// Phase 3: Synthesis
const finalReport = await agent(
  `Create comprehensive research report on ${topic}:
  - Read verified-findings.md
  - Structure as executive summary + detailed sections
  - Include data visualizations (mermaid charts)
  - Add citations and references
  - Highlight key insights and recommendations
  Save to final-report-${topic.replace(/\\s+/g, '-')}.md`,
  { label: 'synthesis', phase: 'Synthesis' }
);

return {
  topic,
  sources_found: discoveryAgents.length,
  report_file: finalReport.output_file,
  insights: finalReport.key_insights
};

Запуск workflow:

Workflow --script research-workflow.js --args '{"topic": "AI coding assistants market 2025"}'

Production-Ready Research Framework

#!/usr/bin/env python3
"""
Deep Research Framework - structured research with Claude Code
"""
import os
import json
from pathlib import Path
from datetime import datetime
from typing import List, Dict, Optional

class ResearchProject:
    def __init__(self, topic: str, output_dir: str = "./research"):
        self.topic = topic
        self.output_dir = Path(output_dir)
        self.output_dir.mkdir(parents=True, exist_ok=True)

        self.project_id = f"{datetime.now().strftime('%Y%m%d_%H%M%S')}_{topic[:20]}"
        self.project_dir = self.output_dir / self.project_id
        self.project_dir.mkdir(exist_ok=True)

        self.sources = []
        self.findings = []
        self.metadata = {
            'topic': topic,
            'started_at': datetime.now().isoformat(),
            'phases_completed': []
        }

    def add_source(self, url: str, title: str, source_type: str, credibility: int = 3):
        """Добавить источник"""
        source = {
            'url': url,
            'title': title,
            'type': source_type,  # academic, industry, technical, social
            'credibility': credibility,  # 1-5 scale
            'added_at': datetime.now().isoformat()
        }
        self.sources.append(source)
        self._save_metadata()

    def add_finding(self, finding: str, source_urls: List[str], verified: bool = False):
        """Добавить находку"""
        finding_entry = {
            'text': finding,
            'sources': source_urls,
            'verified': verified,
            'added_at': datetime.now().isoformat()
        }
        self.findings.append(finding_entry)
        self._save_metadata()

    def phase_discovery(self, queries: List[str]) -> Dict:
        """Фаза 1: Discovery"""
        print(f"🔍 Phase 1: Discovery ({len(queries)} queries)")

        discovery_file = self.project_dir / "01-discovery.md"
        with open(discovery_file, 'w') as f:
            f.write(f"# Discovery Phase: {self.topic}\\n\\n")
            f.write(f"Queries:\\n")
            for q in queries:
                f.write(f"- {q}\\n")

        # Здесь интеграция с Claude Code
        # Для каждого query запустить поиск

        self.metadata['phases_completed'].append('discovery')
        self._save_metadata()

        return {'queries': len(queries), 'file': str(discovery_file)}

    def phase_verification(self) -> Dict:
        """Фаза 2: Verification"""
        print("✅ Phase 2: Verification")

        verification_file = self.project_dir / "02-verification.md"
        with open(verification_file, 'w') as f:
            f.write(f"# Verification Phase: {self.topic}\\n\\n")
            f.write(f"## Sources to verify ({len(self.sources)}):\\n\\n")

            for source in self.sources:
                f.write(f"### {source['title']}\\n")
                f.write(f"- URL: {source['url']}\\n")
                f.write(f"- Type: {source['type']}\\n")
                f.write(f"- Credibility: {source['credibility']}/5\\n\\n")

        self.metadata['phases_completed'].append('verification')
        self._save_metadata()

        return {'sources_verified': len(self.sources), 'file': str(verification_file)}

    def phase_synthesis(self, template: str = "standard") -> Dict:
        """Фаза 3: Synthesis"""
        print("📝 Phase 3: Synthesis")

        report_file = self.project_dir / "03-final-report.md"

        templates = {
            'standard': self._template_standard(),
            'executive': self._template_executive(),
            'technical': self._template_technical()
        }

        template_content = templates.get(template, templates['standard'])

        with open(report_file, 'w') as f:
            f.write(template_content)

        self.metadata['phases_completed'].append('synthesis')
        self.metadata['completed_at'] = datetime.now().isoformat()
        self._save_metadata()

        return {'report_file': str(report_file), 'template': template}

    def _template_standard(self) -> str:
        """Стандартный шаблон отчёта"""
        return f"""# Research Report: {self.topic}

## Executive Summary

[Brief overview of key findings]

## Methodology

- Research started: {self.metadata['started_at']}
- Sources collected: {len(self.sources)}
- Findings documented: {len(self.findings)}

## Sources

{self._format_sources()}

## Key Findings

{self._format_findings()}

## Detailed Analysis

[In-depth analysis of findings]

## Conclusions

[Summary of insights and recommendations]

## References

{self._format_references()}
"""

    def _template_executive(self) -> str:
        """Executive summary template"""
        return f"""# Executive Summary: {self.topic}

## Key Insights

[Top 3-5 insights]

## Recommendations

[Actionable recommendations]

## Supporting Data

[High-level statistics and trends]
"""

    def _template_technical(self) -> str:
        """Technical report template"""
        return f"""# Technical Analysis: {self.topic}

## Technical Overview

[Architecture, technologies, implementations]

## Performance Metrics

[Benchmarks, statistics]

## Code Examples

[Relevant code snippets]

## Technical Recommendations

[Technical best practices]
"""

    def _format_sources(self) -> str:
        """Форматировать список источников"""
        output = []
        for i, source in enumerate(self.sources, 1):
            output.append(f"{i}. **{source['title']}** ({source['type']}, credibility: {source['credibility']}/5)")
            output.append(f"   {source['url']}")
        return "\\n".join(output)

    def _format_findings(self) -> str:
        """Форматировать находки"""
        output = []
        for i, finding in enumerate(self.findings, 1):
            verified_mark = "✅" if finding['verified'] else "⚠️"
            output.append(f"{i}. {verified_mark} {finding['text']}")
            output.append(f"   Sources: {', '.join(finding['sources'][:3])}")
        return "\\n".join(output)

    def _format_references(self) -> str:
        """Форматировать библиографию"""
        output = []
        for i, source in enumerate(self.sources, 1):
            output.append(f"[{i}] {source['title']}. {source['url']} (Accessed {source['added_at']})")
        return "\\n".join(output)

    def _save_metadata(self):
        """Сохранить метаданные проекта"""
        metadata_file = self.project_dir / "metadata.json"
        with open(metadata_file, 'w') as f:
            json.dump({
                **self.metadata,
                'sources': self.sources,
                'findings': self.findings
            }, f, indent=2)

    def generate_summary(self) -> str:
        """Сгенерировать краткую сводку проекта"""
        duration = None
        if 'completed_at' in self.metadata:
            start = datetime.fromisoformat(self.metadata['started_at'])
            end = datetime.fromisoformat(self.metadata['completed_at'])
            duration = str(end - start)

        summary = f"""
Research Project Summary
========================
Topic: {self.topic}
Started: {self.metadata['started_at']}
Duration: {duration or 'In progress'}

Progress:
- Sources collected: {len(self.sources)}
- Findings documented: {len(self.findings)}
- Phases completed: {', '.join(self.metadata['phases_completed'])}

Output directory: {self.project_dir}
"""
        return summary

# Использование
if __name__ == "__main__":
    # Создать исследовательский проект
    project = ResearchProject("WebAssembly adoption in enterprise 2025")

    # Phase 1: Discovery
    project.phase_discovery([
        "WebAssembly enterprise case studies",
        "WASM performance benchmarks",
        "Companies using WebAssembly in production"
    ])

    # Добавить источники
    project.add_source(
        "https://example.com/wasm-study",
        "Enterprise WebAssembly Study 2025",
        "industry",
        credibility=4
    )

    # Добавить находки
    project.add_finding(
        "75% of surveyed enterprises report using WASM in production",
        ["https://example.com/wasm-study"],
        verified=True
    )

    # Phase 2: Verification
    project.phase_verification()

    # Phase 3: Synthesis
    project.phase_synthesis(template="executive")

    # Показать сводку
    print(project.generate_summary())

Интеграция с gstack /browse

Для web research используйте gstack browser:

# Открыть browser для исследования
/open-gstack-browser

# Исследовать тему
/browse "search for WebAssembly enterprise adoption"

# Собрать данные с нескольких страниц
/browse "navigate to each result and extract key statistics"

# Сохранить findings
/browse "compile findings into research-notes.md"

⚠️ Troubleshooting

Проблема 1: Источники низкого качества

Решение: Используйте credibility scoring и приоритизируйте академические источники, official documentation, peer-reviewed papers.

Проблема 2: Conflicting information

Решение: Cross-reference между источниками, проверяйте даты публикаций, используйте verification phase для разрешения конфликтов.

Проблема 3: Research takes too long

Решение: Используйте parallel agents через Workflow, ограничьте scope исследования, используйте time-boxing (2h max per phase).

Проблема 4: Information overload

Решение: Фильтруйте источники по relevance score, используйте structured templates для организации данных, делайте промежуточные summaries.

Проблема 5: Unable to verify claims

Решение: Помечайте unverified claims с ⚠️ , ищите multiple independent sources, при невозможности верификации — исключайте из final report.

📝 Домашнее задание

  1. Quick Research: Выберите техническую тему и проведите 15-минутное исследование. Используйте WebSearch и создайте краткую сводку.
  2. Multi-phase Research: Проведите standard research (30-60 мин) с тремя фазами: discovery, verification, synthesis. Соберите минимум 5 источников.
  3. Workflow Research: Создайте research workflow с параллельными agents для разных типов источников (academic, industry, technical, social).
  4. Research Framework: Используйте ResearchProject class для организации исследования. Добавьте credibility scoring для источников.
  5. Verification: Для одной из находок проведите deep verification: найдите 3+ независимых источника, подтверждающих факт.
  6. Report Generation: Создайте итоговый отчёт используя один из templates (standard/executive/technical). Добавьте visualizations через mermaid.
  7. Presentation: Подготовьте 5-минутную презентацию результатов вашего исследования с ключевыми insights и recommendations.

🎓 После урока вы умеете

  • Проводить глубокие исследования в несколько фаз с использованием Claude Code
  • Организовывать parallel research через workflow с multiple agents
  • Собирать и анализировать информацию из различных источников
  • Верифицировать данные и оценивать credibility источников
  • Создавать structured research projects с метаданными
  • Генерировать comprehensive отчёты по различным templates
  • Использовать gstack /browse для web research
  • Диагностировать и решать типичные проблемы research
  • Презентовать результаты своих исследований и получать обратную связь
  • Масштабировать research процесс от quick (15min) до comprehensive (multi-day)

🔗 Дополнительные ресурсы

Рекомендуемые курсы

Продолжите обучение по смежным темам

ИИ-наставник по этому уроку

Задайте вопрос по теме урока «Deep-research: глубокие исследования в несколько фаз» — наставник ответит, опираясь на его содержание. Он помогает понять, но не делает домашку за вас.

Привет! Я наставник по этому уроку. Спросите что угодно по теме — объясню простыми словами. 🙂
Ответы генерирует ИИ и может ошибаться — сверяйтесь с уроком.
ИИ-консультант
Помогу выбрать курс