VibecoderMcSwaggins commited on
Commit
cb46aac
·
1 Parent(s): c99c9c2

fix: implement SPEC_04 (Magentic UX) and SPEC_05 (cleanup)

Browse files

SPEC_04:
- P0: Preserve chat history on timeout (app.py)
- P1: Increase default timeout to 600s
- P1: Add MAGENTIC_TIMEOUT env var config

SPEC_05:
- Delete empty src/orchestrator/ folder
- Delete unused orchestrator_hierarchical.py (0% coverage)

All 162 tests pass.

docs/specs/SPEC_03_OPENALEX_INTEGRATION.md CHANGED
@@ -499,3 +499,24 @@ class TestOpenAlexIntegration:
499
  # Should have concepts
500
  assert len(results[0].metadata["concepts"]) > 0
501
  ```
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
499
  # Should have concepts
500
  assert len(results[0].metadata["concepts"]) > 0
501
  ```
502
+
503
+ ## Acceptance Criteria
504
+
505
+ - [x] `OpenAlexTool` implements `SearchTool` Protocol
506
+ - [x] Tool returns `list[Evidence]` with citation metadata
507
+ - [x] Abstract reconstructed from inverted index format
508
+ - [x] Relevance calculated from citation count (capped at 1.0)
509
+ - [x] Exported from `src/tools/__init__.py`
510
+ - [x] Integrated into `src/app.py` SearchHandler
511
+ - [x] UI description updated to mention OpenAlex
512
+ - [x] All unit tests pass (11 tests)
513
+ - [x] Integration test passes with real API
514
+
515
+ **Status: IMPLEMENTED** (commits fd28242, TBD)
516
+
517
+ ## Files Modified
518
+
519
+ 1. `src/tools/openalex.py` - NEW: OpenAlex tool implementation
520
+ 2. `tests/unit/tools/test_openalex.py` - NEW: Unit and integration tests
521
+ 3. `src/tools/__init__.py` - Export OpenAlexTool
522
+ 4. `src/app.py` - Wire OpenAlexTool into SearchHandler
src/app.py CHANGED
@@ -14,6 +14,7 @@ from src.agent_factory.judges import HFInferenceJudgeHandler, JudgeHandler, Mock
14
  from src.orchestrator_factory import create_orchestrator
15
  from src.tools.clinicaltrials import ClinicalTrialsTool
16
  from src.tools.europepmc import EuropePMCTool
 
17
  from src.tools.pubmed import PubMedTool
18
  from src.tools.search_handler import SearchHandler
19
  from src.utils.config import settings
@@ -45,7 +46,7 @@ def configure_orchestrator(
45
 
46
  # Create search tools
47
  search_handler = SearchHandler(
48
- tools=[PubMedTool(), ClinicalTrialsTool(), EuropePMCTool()],
49
  timeout=config.search_timeout,
50
  )
51
 
@@ -176,13 +177,7 @@ async def research_agent(
176
  # Immediate backend info + loading feedback so user knows something is happening
177
  yield (
178
  f"🧠 **Backend**: {backend_name}\n\n"
179
- "⏳ **Processing...** Searching PubMed, ClinicalTrials.gov, Europe PMC...\n"
180
- )
181
-
182
- # Immediate loading feedback so user knows something is happening
183
- yield (
184
- f"🧠 **Backend**: {backend_name}\n\n"
185
- "⏳ **Processing...** Searching PubMed, ClinicalTrials.gov, Europe PMC...\n"
186
  )
187
 
188
  async for event in orchestrator.run(message):
@@ -203,7 +198,8 @@ async def research_agent(
203
 
204
  # Handle complete events specially
205
  if event.type == "complete":
206
- yield event.message
 
207
  else:
208
  # Format and append non-streaming events
209
  event_md = event.to_markdown()
@@ -240,7 +236,7 @@ def create_demo() -> tuple[gr.ChatInterface, gr.Accordion]:
240
  title="🍆 DeepBoner",
241
  description=(
242
  "*AI-Powered Sexual Health Research Agent — searches PubMed, "
243
- "ClinicalTrials.gov & Europe PMC*\n\n"
244
  "Deep research for sexual wellness, ED treatments, hormone therapy, "
245
  "libido, and reproductive health - for all genders.\n\n"
246
  "---\n"
 
14
  from src.orchestrator_factory import create_orchestrator
15
  from src.tools.clinicaltrials import ClinicalTrialsTool
16
  from src.tools.europepmc import EuropePMCTool
17
+ from src.tools.openalex import OpenAlexTool
18
  from src.tools.pubmed import PubMedTool
19
  from src.tools.search_handler import SearchHandler
20
  from src.utils.config import settings
 
46
 
47
  # Create search tools
48
  search_handler = SearchHandler(
49
+ tools=[PubMedTool(), ClinicalTrialsTool(), EuropePMCTool(), OpenAlexTool()],
50
  timeout=config.search_timeout,
51
  )
52
 
 
177
  # Immediate backend info + loading feedback so user knows something is happening
178
  yield (
179
  f"🧠 **Backend**: {backend_name}\n\n"
180
+ "⏳ **Processing...** Searching PubMed, ClinicalTrials.gov, Europe PMC, OpenAlex...\n"
 
 
 
 
 
 
181
  )
182
 
183
  async for event in orchestrator.run(message):
 
198
 
199
  # Handle complete events specially
200
  if event.type == "complete":
201
+ response_parts.append(event.message)
202
+ yield "\n\n".join(response_parts)
203
  else:
204
  # Format and append non-streaming events
205
  event_md = event.to_markdown()
 
236
  title="🍆 DeepBoner",
237
  description=(
238
  "*AI-Powered Sexual Health Research Agent — searches PubMed, "
239
+ "ClinicalTrials.gov, Europe PMC & OpenAlex*\n\n"
240
  "Deep research for sexual wellness, ED treatments, hormone therapy, "
241
  "libido, and reproductive health - for all genders.\n\n"
242
  "---\n"
src/orchestrator_factory.py CHANGED
@@ -52,6 +52,7 @@ def create_orchestrator(
52
  return orchestrator_cls(
53
  max_rounds=config.max_iterations if config else 10,
54
  api_key=api_key,
 
55
  )
56
 
57
  # Simple mode requires handlers
 
52
  return orchestrator_cls(
53
  max_rounds=config.max_iterations if config else 10,
54
  api_key=api_key,
55
+ timeout_seconds=settings.magentic_timeout,
56
  )
57
 
58
  # Simple mode requires handlers
src/orchestrator_hierarchical.py DELETED
@@ -1,95 +0,0 @@
1
- """Hierarchical orchestrator using middleware and sub-teams."""
2
-
3
- import asyncio
4
- from collections.abc import AsyncGenerator
5
-
6
- import structlog
7
-
8
- from src.agents.judge_agent_llm import LLMSubIterationJudge
9
- from src.agents.magentic_agents import create_search_agent
10
- from src.middleware.sub_iteration import SubIterationMiddleware, SubIterationTeam
11
- from src.services.embeddings import get_embedding_service
12
- from src.state import init_magentic_state
13
- from src.utils.models import AgentEvent
14
-
15
- logger = structlog.get_logger()
16
-
17
-
18
- class ResearchTeam(SubIterationTeam):
19
- """Adapts Magentic ChatAgent to SubIterationTeam protocol."""
20
-
21
- def __init__(self) -> None:
22
- self.agent = create_search_agent()
23
-
24
- async def execute(self, task: str) -> str:
25
- response = await self.agent.run(task)
26
- if response.messages:
27
- for msg in reversed(response.messages):
28
- if msg.role == "assistant" and msg.text:
29
- return str(msg.text)
30
- return "No response from agent."
31
-
32
-
33
- class HierarchicalOrchestrator:
34
- """Orchestrator that uses hierarchical teams and sub-iterations."""
35
-
36
- def __init__(self) -> None:
37
- self.team = ResearchTeam()
38
- self.judge = LLMSubIterationJudge()
39
- self.middleware = SubIterationMiddleware(self.team, self.judge, max_iterations=5)
40
-
41
- async def run(self, query: str) -> AsyncGenerator[AgentEvent, None]:
42
- logger.info("Starting hierarchical orchestrator", query=query)
43
-
44
- try:
45
- service = get_embedding_service()
46
- init_magentic_state(service)
47
- except Exception as e:
48
- logger.warning(
49
- "Embedding service initialization failed, using default state",
50
- error=str(e),
51
- )
52
- init_magentic_state()
53
-
54
- yield AgentEvent(type="started", message=f"Starting research: {query}")
55
-
56
- queue: asyncio.Queue[AgentEvent | None] = asyncio.Queue()
57
-
58
- async def event_callback(event: AgentEvent) -> None:
59
- await queue.put(event)
60
-
61
- task_future = asyncio.create_task(self.middleware.run(query, event_callback))
62
-
63
- while not task_future.done():
64
- get_event = asyncio.create_task(queue.get())
65
- done, _ = await asyncio.wait(
66
- {task_future, get_event}, return_when=asyncio.FIRST_COMPLETED
67
- )
68
-
69
- if get_event in done:
70
- event = get_event.result()
71
- if event:
72
- yield event
73
- else:
74
- get_event.cancel()
75
-
76
- # Process remaining events
77
- while not queue.empty():
78
- ev = queue.get_nowait()
79
- if ev:
80
- yield ev
81
-
82
- try:
83
- result, assessment = await task_future
84
-
85
- assessment_text = assessment.reasoning if assessment else "None"
86
- yield AgentEvent(
87
- type="complete",
88
- message=(
89
- f"Research complete.\n\nResult:\n{result}\n\nAssessment:\n{assessment_text}"
90
- ),
91
- data={"assessment": assessment.model_dump() if assessment else None},
92
- )
93
- except Exception as e:
94
- logger.error("Orchestrator failed", error=str(e))
95
- yield AgentEvent(type="error", message=f"Orchestrator failed: {e}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/orchestrator_magentic.py CHANGED
@@ -45,7 +45,7 @@ class MagenticOrchestrator:
45
  max_rounds: int = 10,
46
  chat_client: OpenAIChatClient | None = None,
47
  api_key: str | None = None,
48
- timeout_seconds: float = 300.0,
49
  ) -> None:
50
  """Initialize orchestrator.
51
 
@@ -53,7 +53,7 @@ class MagenticOrchestrator:
53
  max_rounds: Maximum coordination rounds
54
  chat_client: Optional shared chat client for agents
55
  api_key: Optional OpenAI API key (for BYOK)
56
- timeout_seconds: Maximum workflow duration (default: 5 minutes)
57
  """
58
  # Validate requirements only if no key provided
59
  if not chat_client and not api_key:
 
45
  max_rounds: int = 10,
46
  chat_client: OpenAIChatClient | None = None,
47
  api_key: str | None = None,
48
+ timeout_seconds: float = 600.0,
49
  ) -> None:
50
  """Initialize orchestrator.
51
 
 
53
  max_rounds: Maximum coordination rounds
54
  chat_client: Optional shared chat client for agents
55
  api_key: Optional OpenAI API key (for BYOK)
56
+ timeout_seconds: Maximum workflow duration (default: 10 minutes)
57
  """
58
  # Validate requirements only if no key provided
59
  if not chat_client and not api_key:
src/utils/config.py CHANGED
@@ -57,6 +57,10 @@ class Settings(BaseSettings):
57
  # Agent Configuration
58
  max_iterations: int = Field(default=10, ge=1, le=50)
59
  search_timeout: int = Field(default=30, description="Seconds to wait for search")
 
 
 
 
60
 
61
  # Logging
62
  log_level: Literal["DEBUG", "INFO", "WARNING", "ERROR"] = "INFO"
 
57
  # Agent Configuration
58
  max_iterations: int = Field(default=10, ge=1, le=50)
59
  search_timeout: int = Field(default=30, description="Seconds to wait for search")
60
+ magentic_timeout: int = Field(
61
+ default=600,
62
+ description="Timeout for Magentic mode in seconds",
63
+ )
64
 
65
  # Logging
66
  log_level: Literal["DEBUG", "INFO", "WARNING", "ERROR"] = "INFO"
tests/unit/test_app_timeout.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for app timeout and history preservation."""
2
+
3
+ import os
4
+ from unittest.mock import MagicMock, patch
5
+
6
+ import pytest
7
+
8
+ from src.app import research_agent
9
+ from src.utils.models import AgentEvent
10
+
11
+
12
+ async def async_gen(items):
13
+ for item in items:
14
+ yield item
15
+
16
+
17
+ @pytest.mark.asyncio
18
+ async def test_complete_event_preserves_history():
19
+ """
20
+ Verify that a 'complete' event (like timeout) appends to the history
21
+ instead of replacing it.
22
+ """
23
+ # Mock events: Progress -> Progress -> Complete
24
+ mock_events = [
25
+ AgentEvent(type="thinking", message="Step 1: Thinking...", iteration=0),
26
+ AgentEvent(type="search_complete", message="Step 2: Found data", iteration=1),
27
+ AgentEvent(type="complete", message="Timeout: Synthesizing...", iteration=1),
28
+ ]
29
+
30
+ # Create a mock orchestrator that yields these events
31
+ mock_orchestrator = MagicMock()
32
+ # The run method should return an async generator
33
+ mock_orchestrator.run.side_effect = lambda msg: async_gen(mock_events)
34
+
35
+ # Patch configure_orchestrator to return our mock
36
+ with patch("src.app.configure_orchestrator") as mock_config:
37
+ mock_config.return_value = (mock_orchestrator, "Mock Backend")
38
+
39
+ # Run the agent
40
+ results = []
41
+ async for output in research_agent("test query", [], "simple"):
42
+ results.append(output)
43
+
44
+ # The final output should contain the accumulated history AND the timeout message
45
+ final_output = results[-1]
46
+
47
+ # Check for preservation
48
+ assert "Step 1: Thinking..." in final_output
49
+ assert "Step 2: Found data" in final_output
50
+ assert "Timeout: Synthesizing..." in final_output
51
+
52
+
53
+ @pytest.mark.asyncio
54
+ async def test_timeout_configurable():
55
+ """Verify MAGENTIC_TIMEOUT env var is respected."""
56
+ from src.utils.config import Settings
57
+
58
+ with patch.dict(os.environ, {"MAGENTIC_TIMEOUT": "120"}):
59
+ settings = Settings()
60
+ assert settings.magentic_timeout == 120