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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
# Phase 15: OpenAlex Integration

**Priority**: HIGH - Biggest bang for buck
**Effort**: ~2-3 hours
**Dependencies**: None (existing codebase patterns sufficient)

---

## Prerequisites (COMPLETED)

The following model changes have been implemented to support this integration:

1. **`SourceName` Literal Updated** (`src/utils/models.py:9`)
   ```python
   SourceName = Literal["pubmed", "clinicaltrials", "europepmc", "preprint", "openalex"]
   ```
   - Without this, `source="openalex"` would fail Pydantic validation

2. **`Evidence.metadata` Field Added** (`src/utils/models.py:39-42`)
   ```python
   metadata: dict[str, Any] = Field(
       default_factory=dict,
       description="Additional metadata (e.g., cited_by_count, concepts, is_open_access)",
   )
   ```
   - Required for storing `cited_by_count`, `concepts`, etc.
   - Model is still frozen - metadata must be passed at construction time

3. **`__init__.py` Exports Updated** (`src/tools/__init__.py`)
   - All tools are now exported: `ClinicalTrialsTool`, `EuropePMCTool`, `PubMedTool`
   - OpenAlexTool should be added here after implementation

---

## Overview

Add OpenAlex as a 4th data source for comprehensive scholarly data including:
- Citation networks (who cites whom)
- Concept tagging (hierarchical topic classification)
- Author disambiguation
- 209M+ works indexed

**Why OpenAlex?**
- Free, no API key required
- Already implemented in reference repo
- Provides citation data we don't have
- Aggregates PubMed + preprints + more

---

## TDD Implementation Plan

### Step 1: Write the Tests First

**File**: `tests/unit/tools/test_openalex.py`

```python
"""Tests for OpenAlex search tool."""

import pytest
import respx
from httpx import Response

from src.tools.openalex import OpenAlexTool
from src.utils.models import Evidence


class TestOpenAlexTool:
    """Test suite for OpenAlex search functionality."""

    @pytest.fixture
    def tool(self) -> OpenAlexTool:
        return OpenAlexTool()

    def test_name_property(self, tool: OpenAlexTool) -> None:
        """Tool should identify itself as 'openalex'."""
        assert tool.name == "openalex"

    @respx.mock
    @pytest.mark.asyncio
    async def test_search_returns_evidence(self, tool: OpenAlexTool) -> None:
        """Search should return list of Evidence objects."""
        mock_response = {
            "results": [
                {
                    "id": "W2741809807",
                    "title": "Metformin and cancer: A systematic review",
                    "publication_year": 2023,
                    "cited_by_count": 45,
                    "type": "article",
                    "is_oa": True,
                    "primary_location": {
                        "source": {"display_name": "Nature Medicine"},
                        "landing_page_url": "https://doi.org/10.1038/example",
                        "pdf_url": None,
                    },
                    "abstract_inverted_index": {
                        "Metformin": [0],
                        "shows": [1],
                        "anticancer": [2],
                        "effects": [3],
                    },
                    "concepts": [
                        {"display_name": "Medicine", "score": 0.95},
                        {"display_name": "Oncology", "score": 0.88},
                    ],
                    "authorships": [
                        {
                            "author": {"display_name": "John Smith"},
                            "institutions": [{"display_name": "Harvard"}],
                        }
                    ],
                }
            ]
        }

        respx.get("https://api.openalex.org/works").mock(
            return_value=Response(200, json=mock_response)
        )

        results = await tool.search("metformin cancer", max_results=10)

        assert len(results) == 1
        assert isinstance(results[0], Evidence)
        assert "Metformin and cancer" in results[0].citation.title
        assert results[0].citation.source == "openalex"

    @respx.mock
    @pytest.mark.asyncio
    async def test_search_empty_results(self, tool: OpenAlexTool) -> None:
        """Search with no results should return empty list."""
        respx.get("https://api.openalex.org/works").mock(
            return_value=Response(200, json={"results": []})
        )

        results = await tool.search("xyznonexistentquery123")
        assert results == []

    @respx.mock
    @pytest.mark.asyncio
    async def test_search_handles_missing_abstract(self, tool: OpenAlexTool) -> None:
        """Tool should handle papers without abstracts."""
        mock_response = {
            "results": [
                {
                    "id": "W123",
                    "title": "Paper without abstract",
                    "publication_year": 2023,
                    "cited_by_count": 10,
                    "type": "article",
                    "is_oa": False,
                    "primary_location": {
                        "source": {"display_name": "Journal"},
                        "landing_page_url": "https://example.com",
                    },
                    "abstract_inverted_index": None,
                    "concepts": [],
                    "authorships": [],
                }
            ]
        }

        respx.get("https://api.openalex.org/works").mock(
            return_value=Response(200, json=mock_response)
        )

        results = await tool.search("test query")
        assert len(results) == 1
        assert results[0].content == ""  # No abstract

    @respx.mock
    @pytest.mark.asyncio
    async def test_search_extracts_citation_count(self, tool: OpenAlexTool) -> None:
        """Citation count should be in metadata."""
        mock_response = {
            "results": [
                {
                    "id": "W456",
                    "title": "Highly cited paper",
                    "publication_year": 2020,
                    "cited_by_count": 500,
                    "type": "article",
                    "is_oa": True,
                    "primary_location": {
                        "source": {"display_name": "Science"},
                        "landing_page_url": "https://example.com",
                    },
                    "abstract_inverted_index": {"Test": [0]},
                    "concepts": [],
                    "authorships": [],
                }
            ]
        }

        respx.get("https://api.openalex.org/works").mock(
            return_value=Response(200, json=mock_response)
        )

        results = await tool.search("highly cited")
        assert results[0].metadata["cited_by_count"] == 500

    @respx.mock
    @pytest.mark.asyncio
    async def test_search_extracts_concepts(self, tool: OpenAlexTool) -> None:
        """Concepts should be extracted for semantic discovery."""
        mock_response = {
            "results": [
                {
                    "id": "W789",
                    "title": "Drug repurposing study",
                    "publication_year": 2023,
                    "cited_by_count": 25,
                    "type": "article",
                    "is_oa": True,
                    "primary_location": {
                        "source": {"display_name": "PLOS ONE"},
                        "landing_page_url": "https://example.com",
                    },
                    "abstract_inverted_index": {"Drug": [0], "repurposing": [1]},
                    "concepts": [
                        {"display_name": "Pharmacology", "score": 0.92},
                        {"display_name": "Drug Discovery", "score": 0.85},
                        {"display_name": "Medicine", "score": 0.80},
                    ],
                    "authorships": [],
                }
            ]
        }

        respx.get("https://api.openalex.org/works").mock(
            return_value=Response(200, json=mock_response)
        )

        results = await tool.search("drug repurposing")
        assert "Pharmacology" in results[0].metadata["concepts"]
        assert "Drug Discovery" in results[0].metadata["concepts"]

    @respx.mock
    @pytest.mark.asyncio
    async def test_search_api_error_raises_search_error(
        self, tool: OpenAlexTool
    ) -> None:
        """API errors should raise SearchError."""
        from src.utils.exceptions import SearchError

        respx.get("https://api.openalex.org/works").mock(
            return_value=Response(500, text="Internal Server Error")
        )

        with pytest.raises(SearchError):
            await tool.search("test query")

    def test_reconstruct_abstract(self, tool: OpenAlexTool) -> None:
        """Test abstract reconstruction from inverted index."""
        inverted_index = {
            "Metformin": [0, 5],
            "is": [1],
            "a": [2],
            "diabetes": [3],
            "drug": [4],
            "effective": [6],
        }
        abstract = tool._reconstruct_abstract(inverted_index)
        assert abstract == "Metformin is a diabetes drug Metformin effective"
```

---

### Step 2: Create the Implementation

**File**: `src/tools/openalex.py`

```python
"""OpenAlex search tool for comprehensive scholarly data."""

from typing import Any

import httpx
from tenacity import retry, stop_after_attempt, wait_exponential

from src.utils.exceptions import SearchError
from src.utils.models import Citation, Evidence


class OpenAlexTool:
    """
    Search OpenAlex for scholarly works with rich metadata.

    OpenAlex provides:
    - 209M+ scholarly works
    - Citation counts and networks
    - Concept tagging (hierarchical)
    - Author disambiguation
    - Open access links

    API Docs: https://docs.openalex.org/
    """

    BASE_URL = "https://api.openalex.org/works"

    def __init__(self, email: str | None = None) -> None:
        """
        Initialize OpenAlex tool.

        Args:
            email: Optional email for polite pool (faster responses)
        """
        self.email = email or "deepcritical@example.com"

    @property
    def name(self) -> str:
        return "openalex"

    @retry(
        stop=stop_after_attempt(3),
        wait=wait_exponential(multiplier=1, min=1, max=10),
        reraise=True,
    )
    async def search(self, query: str, max_results: int = 10) -> list[Evidence]:
        """
        Search OpenAlex for scholarly works.

        Args:
            query: Search terms
            max_results: Maximum results to return (max 200 per request)

        Returns:
            List of Evidence objects with citation metadata

        Raises:
            SearchError: If API request fails
        """
        params = {
            "search": query,
            "filter": "type:article",  # Only peer-reviewed articles
            "sort": "cited_by_count:desc",  # Most cited first
            "per_page": min(max_results, 200),
            "mailto": self.email,  # Polite pool for faster responses
        }

        async with httpx.AsyncClient(timeout=30.0) as client:
            try:
                response = await client.get(self.BASE_URL, params=params)
                response.raise_for_status()

                data = response.json()
                results = data.get("results", [])

                return [self._to_evidence(work) for work in results[:max_results]]

            except httpx.HTTPStatusError as e:
                raise SearchError(f"OpenAlex API error: {e}") from e
            except httpx.RequestError as e:
                raise SearchError(f"OpenAlex connection failed: {e}") from e

    def _to_evidence(self, work: dict[str, Any]) -> Evidence:
        """Convert OpenAlex work to Evidence object."""
        title = work.get("title", "Untitled")
        pub_year = work.get("publication_year", "Unknown")
        cited_by = work.get("cited_by_count", 0)
        is_oa = work.get("is_oa", False)

        # Reconstruct abstract from inverted index
        abstract_index = work.get("abstract_inverted_index")
        abstract = self._reconstruct_abstract(abstract_index) if abstract_index else ""

        # Extract concepts (top 5)
        concepts = [
            c.get("display_name", "")
            for c in work.get("concepts", [])[:5]
            if c.get("display_name")
        ]

        # Extract authors (top 5)
        authorships = work.get("authorships", [])
        authors = [
            a.get("author", {}).get("display_name", "")
            for a in authorships[:5]
            if a.get("author", {}).get("display_name")
        ]

        # Get URL
        primary_loc = work.get("primary_location") or {}
        url = primary_loc.get("landing_page_url", "")
        if not url:
            # Fallback to OpenAlex page
            work_id = work.get("id", "").replace("https://openalex.org/", "")
            url = f"https://openalex.org/{work_id}"

        return Evidence(
            content=abstract[:2000],
            citation=Citation(
                source="openalex",
                title=title[:500],
                url=url,
                date=str(pub_year),
                authors=authors,
            ),
            relevance=min(0.9, 0.5 + (cited_by / 1000)),  # Boost by citations
            metadata={
                "cited_by_count": cited_by,
                "is_open_access": is_oa,
                "concepts": concepts,
                "pdf_url": primary_loc.get("pdf_url"),
            },
        )

    def _reconstruct_abstract(
        self, inverted_index: dict[str, list[int]]
    ) -> str:
        """
        Reconstruct abstract from OpenAlex inverted index format.

        OpenAlex stores abstracts as {"word": [position1, position2, ...]}.
        This rebuilds the original text.
        """
        if not inverted_index:
            return ""

        # Build position -> word mapping
        position_word: dict[int, str] = {}
        for word, positions in inverted_index.items():
            for pos in positions:
                position_word[pos] = word

        # Reconstruct in order
        if not position_word:
            return ""

        max_pos = max(position_word.keys())
        words = [position_word.get(i, "") for i in range(max_pos + 1)]
        return " ".join(w for w in words if w)
```

---

### Step 3: Register in Search Handler

**File**: `src/tools/search_handler.py` (add to imports and tool list)

```python
# Add import
from src.tools.openalex import OpenAlexTool

# Add to _create_tools method
def _create_tools(self) -> list[SearchTool]:
    return [
        PubMedTool(),
        ClinicalTrialsTool(),
        EuropePMCTool(),
        OpenAlexTool(),  # NEW
    ]
```

---

### Step 4: Update `__init__.py`

**File**: `src/tools/__init__.py`

```python
from src.tools.openalex import OpenAlexTool

__all__ = [
    "PubMedTool",
    "ClinicalTrialsTool",
    "EuropePMCTool",
    "OpenAlexTool",  # NEW
    # ...
]
```

---

## Demo Script

**File**: `examples/openalex_demo.py`

```python
#!/usr/bin/env python3
"""Demo script to verify OpenAlex integration."""

import asyncio
from src.tools.openalex import OpenAlexTool


async def main():
    """Run OpenAlex search demo."""
    tool = OpenAlexTool()

    print("=" * 60)
    print("OpenAlex Integration Demo")
    print("=" * 60)

    # Test 1: Basic drug repurposing search
    print("\n[Test 1] Searching for 'metformin cancer drug repurposing'...")
    results = await tool.search("metformin cancer drug repurposing", max_results=5)

    for i, evidence in enumerate(results, 1):
        print(f"\n--- Result {i} ---")
        print(f"Title: {evidence.citation.title}")
        print(f"Year: {evidence.citation.date}")
        print(f"Citations: {evidence.metadata.get('cited_by_count', 'N/A')}")
        print(f"Concepts: {', '.join(evidence.metadata.get('concepts', []))}")
        print(f"Open Access: {evidence.metadata.get('is_open_access', False)}")
        print(f"URL: {evidence.citation.url}")
        if evidence.content:
            print(f"Abstract: {evidence.content[:200]}...")

    # Test 2: High-impact papers
    print("\n" + "=" * 60)
    print("[Test 2] Finding highly-cited papers on 'long COVID treatment'...")
    results = await tool.search("long COVID treatment", max_results=3)

    for evidence in results:
        print(f"\n- {evidence.citation.title}")
        print(f"  Citations: {evidence.metadata.get('cited_by_count', 0)}")

    print("\n" + "=" * 60)
    print("Demo complete!")


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

---

## Verification Checklist

### Unit Tests
```bash
# Run just OpenAlex tests
uv run pytest tests/unit/tools/test_openalex.py -v

# Expected: All tests pass
```

### Integration Test (Manual)
```bash
# Run demo script with real API
uv run python examples/openalex_demo.py

# Expected: Real results from OpenAlex API
```

### Full Test Suite
```bash
# Ensure nothing broke
make check

# Expected: All 110+ tests pass, mypy clean
```

---

## Success Criteria

1. **Unit tests pass**: All mocked tests in `test_openalex.py` pass
2. **Integration works**: Demo script returns real results
3. **No regressions**: `make check` passes completely
4. **SearchHandler integration**: OpenAlex appears in search results alongside other sources
5. **Citation metadata**: Results include `cited_by_count`, `concepts`, `is_open_access`

---

## Future Enhancements (P2)

Once basic integration works:

1. **Citation Network Queries**
   ```python
   # Get papers citing a specific work
   async def get_citing_works(self, work_id: str) -> list[Evidence]:
       params = {"filter": f"cites:{work_id}"}
       ...
   ```

2. **Concept-Based Search**
   ```python
   # Search by OpenAlex concept ID
   async def search_by_concept(self, concept_id: str) -> list[Evidence]:
       params = {"filter": f"concepts.id:{concept_id}"}
       ...
   ```

3. **Author Tracking**
   ```python
   # Find all works by an author
   async def search_by_author(self, author_id: str) -> list[Evidence]:
       params = {"filter": f"authorships.author.id:{author_id}"}
       ...
   ```

---

## Notes

- OpenAlex is **very generous** with rate limits (no documented hard limit)
- Adding `mailto` parameter gives priority access (polite pool)
- Abstract is stored as inverted index - must reconstruct
- Citation count is a good proxy for paper quality/impact
- Consider caching responses for repeated queries