File size: 8,380 Bytes
0efdc2f
 
5d12635
0efdc2f
89f1173
9d21bf8
cfb473d
 
 
 
 
 
0efdc2f
 
fa696e8
 
0efdc2f
cfb473d
0efdc2f
 
 
 
 
 
 
 
cfb473d
0efdc2f
 
 
 
0a480cb
0efdc2f
0a480cb
0efdc2f
 
 
 
 
 
 
 
cfb473d
0efdc2f
 
cfb473d
 
 
 
 
 
0efdc2f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cd11dad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0a480cb
cd11dad
 
 
cfb473d
 
5d12635
0efdc2f
 
cfb473d
0efdc2f
 
 
 
 
 
8625ded
2f8ae1f
0efdc2f
 
 
cfb473d
 
0efdc2f
8625ded
2f8ae1f
8625ded
0efdc2f
 
 
 
 
 
 
 
 
cfb473d
2f8ae1f
0efdc2f
 
 
 
cfb473d
 
 
 
 
0efdc2f
cfb473d
0efdc2f
 
cfb473d
0efdc2f
cfb473d
cd11dad
 
 
 
0efdc2f
 
cfb473d
 
0efdc2f
 
 
 
cfb473d
0efdc2f
 
 
 
 
 
 
5d12635
0efdc2f
 
cfb473d
cd004e1
cfb473d
 
 
 
0efdc2f
cfb473d
fa696e8
 
 
0efdc2f
 
 
 
89f1173
0efdc2f
 
 
 
 
 
 
 
 
 
 
cd11dad
 
 
 
cfb473d
 
 
 
 
 
 
 
 
 
 
 
0efdc2f
cfb473d
0efdc2f
 
5d12635
cfb473d
 
9d21bf8
cfb473d
 
 
0efdc2f
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
#!/usr/bin/env python3
"""
Demo: Full Stack DeepBoner Agent (Phases 1-8).

This script demonstrates the COMPLETE REAL sexual health research pipeline:
- Phase 2: REAL Search (PubMed + ClinicalTrials + Europe PMC)
- Phase 6: REAL Embeddings (sentence-transformers + ChromaDB)
- Phase 7: REAL Hypothesis (LLM mechanistic reasoning)
- Phase 3: REAL Judge (LLM evidence assessment)
- Phase 8: REAL Report (LLM structured scientific report)

NO MOCKS. NO FAKE DATA. REAL SCIENCE.

Usage:
    uv run python examples/full_stack_demo/run_full.py "testosterone libido"
    uv run python examples/full_stack_demo/run_full.py "sildenafil erectile dysfunction" -i 3

Requires: OPENAI_API_KEY or ANTHROPIC_API_KEY
"""

import argparse
import asyncio
import os
import sys
from typing import Any

from src.utils.models import Evidence


def print_header(title: str) -> None:
    """Print a formatted section header."""
    print(f"\n{'=' * 70}")
    print(f"  {title}")
    print(f"{'=' * 70}\n")


def print_step(step: int, name: str) -> None:
    """Print a step indicator."""
    print(f"\n[Step {step}] {name}")
    print("-" * 50)


_MAX_DISPLAY_LEN = 600


def _print_truncated(text: str) -> None:
    """Print text, truncating if too long."""
    if len(text) > _MAX_DISPLAY_LEN:
        print(text[:_MAX_DISPLAY_LEN] + "\n... [truncated for display]")
    else:
        print(text)


async def _run_search_iteration(
    query: str,
    iteration: int,
    evidence_store: dict[str, Any],
    all_evidence: list[Evidence],
    search_handler: Any,
    embedding_service: Any,
) -> list[Evidence]:
    """Run a single search iteration with deduplication."""
    search_queries = [query]
    if evidence_store.get("hypotheses"):
        for h in evidence_store["hypotheses"][-2:]:
            search_queries.extend(h.search_suggestions[:1])

    for q in search_queries[:2]:
        result = await search_handler.execute(q, max_results_per_tool=5)
        print(f"  '{q}' -> {result.total_found} results")
        new_unique = await embedding_service.deduplicate(result.evidence)
        print(f"  After dedup: {len(new_unique)} unique")
        all_evidence.extend(new_unique)

    evidence_store["current"] = all_evidence
    evidence_store["iteration_count"] = iteration
    return all_evidence


async def _handle_judge_step(
    judge_handler: Any, query: str, all_evidence: list[Evidence], evidence_store: dict[str, Any]
) -> tuple[bool, str]:
    """Handle the judge assessment step. Returns (should_stop, next_query)."""
    print("\n[Judge] Assessing evidence quality (REAL LLM)...")
    assessment = await judge_handler.assess(query, all_evidence)
    print(f"  Mechanism Score: {assessment.details.mechanism_score}/10")
    print(f"  Clinical Score:  {assessment.details.clinical_evidence_score}/10")
    print(f"  Confidence:      {assessment.confidence:.0%}")
    print(f"  Recommendation:  {assessment.recommendation.upper()}")

    if assessment.recommendation == "synthesize":
        print("\n[Judge] Evidence sufficient! Proceeding to report generation...")
        evidence_store["last_assessment"] = assessment.details.model_dump()
        return True, query

    next_queries = assessment.next_search_queries[:2] if assessment.next_search_queries else []
    if next_queries:
        print(f"\n[Judge] Need more evidence. Next queries: {next_queries}")
        return False, next_queries[0]

    print("\n[Judge] Need more evidence but no suggested queries. Continuing with original query.")
    return False, query


async def run_full_demo(query: str, max_iterations: int) -> None:
    """Run the REAL full stack pipeline."""
    print_header("DeepBoner Full Stack Demo (REAL)")
    print(f"Query: {query}")
    print(f"Max iterations: {max_iterations}")
    print("Mode: REAL (All live API calls - no mocks)\n")

    # Import real components
    from src.agent_factory.judges import JudgeHandler
    from src.agents.hypothesis_agent import HypothesisAgent
    from src.agents.report_agent import ReportAgent
    from src.services.embeddings import EmbeddingService
    from src.tools.clinicaltrials import ClinicalTrialsTool
    from src.tools.europepmc import EuropePMCTool
    from src.tools.pubmed import PubMedTool
    from src.tools.search_handler import SearchHandler

    # Initialize REAL services
    print("[Init] Loading embedding model...")
    embedding_service = EmbeddingService()
    search_handler = SearchHandler(
        tools=[PubMedTool(), ClinicalTrialsTool(), EuropePMCTool()], timeout=30.0
    )
    judge_handler = JudgeHandler()

    # Shared evidence store
    evidence_store: dict[str, Any] = {"current": [], "hypotheses": [], "iteration_count": 0}
    all_evidence: list[Evidence] = []

    for iteration in range(1, max_iterations + 1):
        print_step(iteration, f"ITERATION {iteration}/{max_iterations}")

        # Step 1: REAL Search
        print("\n[Search] Querying PubMed + ClinicalTrials + Europe PMC (REAL API calls)...")
        all_evidence = await _run_search_iteration(
            query, iteration, evidence_store, all_evidence, search_handler, embedding_service
        )

        if not all_evidence:
            print("\nNo evidence found. Try a different query.")
            return

        # Step 2: REAL Hypothesis generation (first iteration only)
        if iteration == 1:
            print("\n[Hypothesis] Generating mechanistic hypotheses (REAL LLM)...")
            hypothesis_agent = HypothesisAgent(evidence_store, embedding_service)
            hyp_response = await hypothesis_agent.run(query)
            _print_truncated(hyp_response.messages[0].text)

        # Step 3: REAL Judge
        should_stop, query = await _handle_judge_step(
            judge_handler, query, all_evidence, evidence_store
        )
        if should_stop:
            break

    # Step 4: REAL Report generation
    print_step(iteration + 1, "REPORT GENERATION (REAL LLM)")
    report_agent = ReportAgent(evidence_store, embedding_service)
    report_response = await report_agent.run(query)

    print("\n" + "=" * 70)
    print("  FINAL RESEARCH REPORT")
    print("=" * 70)
    print(report_response.messages[0].text)


async def main() -> None:
    """Entry point."""
    parser = argparse.ArgumentParser(
        description="DeepBoner Full Stack Demo - REAL, No Mocks",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
This demo runs the COMPLETE pipeline with REAL API calls:
  1. REAL search: Actual PubMed queries
  2. REAL embeddings: Actual sentence-transformers model
  3. REAL hypothesis: Actual LLM generating mechanistic chains
  4. REAL judge: Actual LLM assessing evidence quality
  5. REAL report: Actual LLM generating structured report

Examples:
    uv run python examples/full_stack_demo/run_full.py "testosterone libido"
    uv run python examples/full_stack_demo/run_full.py "sildenafil erectile dysfunction" -i 3
    uv run python examples/full_stack_demo/run_full.py "flibanserin mechanism"
        """,
    )
    parser.add_argument(
        "query",
        help="Research query (e.g., 'testosterone libido')",
    )
    parser.add_argument(
        "-i",
        "--iterations",
        type=int,
        default=2,
        help="Max search iterations (default: 2)",
    )

    args = parser.parse_args()

    if args.iterations < 1:
        print("Error: iterations must be at least 1")
        sys.exit(1)

    # Fail fast: require API key
    if not (os.getenv("OPENAI_API_KEY") or os.getenv("ANTHROPIC_API_KEY")):
        print("=" * 70)
        print("ERROR: This demo requires a real LLM.")
        print()
        print("Set one of the following in your .env file:")
        print("  OPENAI_API_KEY=sk-...")
        print("  ANTHROPIC_API_KEY=sk-ant-...")
        print()
        print("This is a REAL demo. No mocks. No fake data.")
        print("=" * 70)
        sys.exit(1)

    await run_full_demo(args.query, args.iterations)

    print("\n" + "=" * 70)
    print("  DeepBoner Full Stack Demo Complete!")
    print("  ")
    print("  Everything you just saw was REAL:")
    print("    - Real PubMed + ClinicalTrials + Europe PMC searches")
    print("    - Real embedding computations")
    print("    - Real LLM reasoning")
    print("    - Real scientific report")
    print("=" * 70 + "\n")


if __name__ == "__main__":
    asyncio.run(main())