Adam Cseresznye commited on
Commit
6c3e8bb
·
1 Parent(s): a9ad71d

Add SynthesisAgent and update citations handling

Browse files
agents/__init__.py CHANGED
@@ -3,4 +3,4 @@
3
  This module exposes agent classes as they are implemented.
4
  """
5
 
6
- __all__ = ["SemanticScholarClient", "QueryOptimizationAgent"]
 
3
  This module exposes agent classes as they are implemented.
4
  """
5
 
6
+ __all__ = ["SemanticScholarClient", "QueryOptimizationAgent", "SynthesisAgent"]
agents/synthesis_agent.py ADDED
@@ -0,0 +1,169 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Synthesis agent for generating cited answers from retrieved passages.
2
+
3
+ This agent takes a list of retrieved passages (as LlamaIndex NodeWithScore objects)
4
+ and generates a final answer with inline citations (e.g., [1], [2]) using the
5
+ configured LLM via LiteLLM routing.
6
+
7
+ Usage:
8
+ from agents.synthesis_agent import SynthesisAgent
9
+ from llama_index.core.schema import NodeWithScore, TextNode
10
+
11
+ agent = SynthesisAgent()
12
+ answer = await agent.synthesize(
13
+ query="What are the cardiovascular risks of intermittent fasting?",
14
+ nodes=[node1, node2, node3]
15
+ )
16
+ # Returns: "Intermittent fasting may affect heart rate variability [1] and..."
17
+
18
+ Architecture:
19
+ - Uses LLMRouter for model selection with primary/fallback
20
+ - Enforces strict [N] citation format to prevent hallucinations
21
+ - Handles empty nodes gracefully with fallback message
22
+ """
23
+
24
+ from typing import List
25
+ from loguru import logger
26
+
27
+ from llama_index.core.schema import NodeWithScore
28
+
29
+ from utils.llm_router import LLMRouter
30
+
31
+
32
+ # Citation prompt template that enforces strict sourcing
33
+ CITATION_QA_TEMPLATE = (
34
+ "You are an AI research assistant. Your task is to answer the user's query "
35
+ "using ONLY the provided context passages.\n"
36
+ "---------------------\n"
37
+ "{context_str}\n"
38
+ "---------------------\n"
39
+ "Instructions:\n"
40
+ "1. Answer the query based ONLY on the context above.\n"
41
+ "2. Cite the source passage for every claim using the format [N], where N is the passage index provided in the text.\n"
42
+ "3. If the context does not contain the answer, say 'I cannot answer this based on the provided sources.'\n"
43
+ "4. Do not hallucinate external information.\n\n"
44
+ "User Query: {query_str}\n"
45
+ "Answer: "
46
+ )
47
+
48
+
49
+ class SynthesisAgent:
50
+ """Agent that synthesizes answers from retrieved passages with citations.
51
+
52
+ Uses LLMRouter to call the configured synthesis model (with fallback).
53
+ Formats passages with indices and enforces citation requirements via
54
+ a carefully crafted prompt template.
55
+
56
+ Attributes:
57
+ router: The LLMRouter instance for LLM calls.
58
+ temperature: Temperature for synthesis (default 0.3 for consistency).
59
+ """
60
+
61
+ INSUFFICIENT_CONTEXT_MESSAGE = "I cannot answer this based on the provided sources."
62
+
63
+ def __init__(self, temperature: float = 0.3) -> None:
64
+ """Initialize the synthesis agent.
65
+
66
+ Args:
67
+ temperature: LLM temperature for generation (0.3 = focused but not rigid).
68
+ """
69
+ self.router = LLMRouter()
70
+ self.temperature = temperature
71
+ logger.info(f"SynthesisAgent initialized with temperature={temperature}")
72
+
73
+ async def synthesize(self, query: str, nodes: List[NodeWithScore]) -> str:
74
+ """Synthesize a cited answer from query and retrieved nodes.
75
+
76
+ Args:
77
+ query: The user's original question.
78
+ nodes: List of NodeWithScore objects from retrieval (hybrid search results).
79
+
80
+ Returns:
81
+ A synthesized answer string containing inline [N] citations.
82
+ Returns fallback message if nodes are empty or synthesis fails.
83
+
84
+ Raises:
85
+ Exception: Re-raises LLM errors after logging (allows caller to handle).
86
+ """
87
+ logger.debug(
88
+ f"SynthesisAgent.synthesize called: query='{query[:50]}...' nodes_count={len(nodes)}"
89
+ )
90
+
91
+ # Handle empty nodes gracefully
92
+ if not nodes:
93
+ logger.warning(
94
+ "No nodes provided for synthesis, returning fallback message"
95
+ )
96
+ return self.INSUFFICIENT_CONTEXT_MESSAGE
97
+
98
+ # Build context string with passage indices
99
+ context_str = self._format_context(nodes)
100
+
101
+ # Build the full prompt
102
+ prompt = CITATION_QA_TEMPLATE.format(
103
+ context_str=context_str,
104
+ query_str=query,
105
+ )
106
+
107
+ logger.debug(
108
+ f"Synthesis prompt built: {len(prompt)} chars, {len(nodes)} passages"
109
+ )
110
+
111
+ try:
112
+ # Call LLM via router (handles primary/fallback)
113
+ response = await self.router.generate(prompt, model_type="synthesis")
114
+ logger.info(
115
+ f"Synthesis completed successfully: response_length={len(response)}"
116
+ )
117
+ return response.strip()
118
+ except Exception as e:
119
+ logger.exception(f"Synthesis failed with error: {e}")
120
+ # Re-raise to let caller decide how to handle
121
+ raise
122
+
123
+ def _format_context(self, nodes: List[NodeWithScore]) -> str:
124
+ """Format nodes into a context string with passage indices.
125
+
126
+ Each passage is formatted as:
127
+ [N] <passage text>
128
+ ---
129
+
130
+ Args:
131
+ nodes: List of NodeWithScore objects.
132
+
133
+ Returns:
134
+ Formatted context string for the prompt.
135
+ """
136
+ passages = []
137
+ for idx, node_with_score in enumerate(nodes):
138
+ # Extract text from the node
139
+ text = self._extract_text(node_with_score)
140
+ # Format with 1-based index for human readability
141
+ passage_idx = idx + 1
142
+ passages.append(f"[{passage_idx}] {text}")
143
+
144
+ return "\n---\n".join(passages)
145
+
146
+ def _extract_text(self, node_with_score: NodeWithScore) -> str:
147
+ """Extract text content from a NodeWithScore object.
148
+
149
+ Handles both direct text access and get_content() method.
150
+
151
+ Args:
152
+ node_with_score: A NodeWithScore from retrieval.
153
+
154
+ Returns:
155
+ The text content of the node.
156
+ """
157
+ node = node_with_score.node
158
+ # Try get_content() first (standard LlamaIndex method)
159
+ if hasattr(node, "get_content"):
160
+ return node.get_content()
161
+ # Fallback to text attribute
162
+ if hasattr(node, "text"):
163
+ return node.text
164
+ # Last resort: string conversion
165
+ logger.warning(f"Node has no text extraction method, using str(): {type(node)}")
166
+ return str(node)
167
+
168
+
169
+ __all__ = ["SynthesisAgent", "CITATION_QA_TEMPLATE"]
models/state.py CHANGED
@@ -44,7 +44,7 @@ class State(BaseModel):
44
 
45
  # Answer and citations (Week 3)
46
  answer: Optional[str] = None
47
- citations: Optional[List[Dict[str, Any]]] = None
48
 
49
  # Error tracking
50
  errors: List[str] = Field(default_factory=list)
 
44
 
45
  # Answer and citations (Week 3)
46
  answer: Optional[str] = None
47
+ citations: List[int] = Field(default_factory=list)
48
 
49
  # Error tracking
50
  errors: List[str] = Field(default_factory=list)
requirements.txt CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:d836bc5134e1bcf7f24d7d6db111245f4fbba2ee84b2a5afcaff280a8ddcbfe3
3
- size 334
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f1b9ca86fcceb7e407a843868b3fe61f6aa4f47b978f114bef8abd1588ac579e
3
+ size 359
scripts/validate_synthesis_manual.py ADDED
@@ -0,0 +1,151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Manual validation script for SynthesisAgent.
2
+
3
+ This is a developer tool to verify the Synthesis Agent works correctly
4
+ with the real LLM API. It is NOT a CI/CD test.
5
+
6
+ Usage:
7
+ python scripts/validate_synthesis_manual.py
8
+
9
+ Prerequisites:
10
+ - Set GOOGLE_API_KEY and/or GROQ_API_KEY in .env
11
+ - Set SYNTHESIS_MODEL and SYNTHESIS_FALLBACK in .env
12
+
13
+ Expected Output:
14
+ - Query and context passages displayed
15
+ - Synthesized answer with [1], [2], [3] citations
16
+ """
17
+
18
+ import asyncio
19
+ import sys
20
+ from pathlib import Path
21
+
22
+ # Add project root to path for imports
23
+ project_root = Path(__file__).parent.parent
24
+ sys.path.insert(0, str(project_root))
25
+
26
+ from llama_index.core.schema import NodeWithScore, TextNode
27
+ from agents.synthesis_agent import SynthesisAgent
28
+
29
+
30
+ def create_test_nodes() -> list[NodeWithScore]:
31
+ """Create mock nodes with known content about intermittent fasting."""
32
+ passages = [
33
+ {
34
+ "text": (
35
+ "Intermittent fasting has been shown to promote autophagy, "
36
+ "a cellular cleaning process that removes damaged proteins and "
37
+ "organelles. Studies in mice have demonstrated that fasting for "
38
+ "16-24 hours activates autophagy pathways, potentially reducing "
39
+ "the risk of age-related diseases."
40
+ ),
41
+ "source": "Cell Biology Review, 2023",
42
+ },
43
+ {
44
+ "text": (
45
+ "Research indicates that intermittent fasting can improve insulin "
46
+ "sensitivity by 20-30% in overweight adults. A randomized controlled "
47
+ "trial with 100 participants showed significant reductions in fasting "
48
+ "blood glucose levels after 8 weeks of time-restricted eating."
49
+ ),
50
+ "source": "Diabetes Care Journal, 2022",
51
+ },
52
+ {
53
+ "text": (
54
+ "Cardiovascular benefits of intermittent fasting include reduced "
55
+ "blood pressure, improved cholesterol profiles, and decreased "
56
+ "inflammatory markers. A meta-analysis of 12 studies found that "
57
+ "fasting protocols reduced LDL cholesterol by an average of 10%."
58
+ ),
59
+ "source": "Cardiology Research, 2024",
60
+ },
61
+ ]
62
+
63
+ nodes = []
64
+ for i, passage in enumerate(passages):
65
+ node = TextNode(
66
+ text=passage["text"],
67
+ metadata={"source": passage["source"], "index": i + 1},
68
+ )
69
+ nodes.append(NodeWithScore(node=node, score=0.9 - i * 0.1))
70
+
71
+ return nodes
72
+
73
+
74
+ def print_separator(title: str = "") -> None:
75
+ """Print a visual separator."""
76
+ print("\n" + "=" * 60)
77
+ if title:
78
+ print(f" {title}")
79
+ print("=" * 60)
80
+
81
+
82
+ async def main() -> None:
83
+ """Run manual validation of SynthesisAgent."""
84
+ print_separator("SYNTHESIS AGENT MANUAL VALIDATION")
85
+
86
+ # Create test data
87
+ query = "What are the health benefits of intermittent fasting?"
88
+ nodes = create_test_nodes()
89
+
90
+ # Display query
91
+ print_separator("QUERY")
92
+ print(f" {query}")
93
+
94
+ # Display context passages
95
+ print_separator("CONTEXT PASSAGES")
96
+ for i, node_with_score in enumerate(nodes):
97
+ node = node_with_score.node
98
+ source = node.metadata.get("source", "Unknown")
99
+ text_preview = node.text[:100] + "..." if len(node.text) > 100 else node.text
100
+ print(f"\n [{i + 1}] (score: {node_with_score.score:.2f})")
101
+ print(f" Source: {source}")
102
+ print(f" Text: {text_preview}")
103
+
104
+ # Initialize agent and synthesize
105
+ print_separator("CALLING SYNTHESIS AGENT")
106
+ print(" Initializing SynthesisAgent...")
107
+
108
+ agent = SynthesisAgent(temperature=0.3)
109
+
110
+ print(" Calling synthesize()... (waiting for LLM response)")
111
+ print()
112
+
113
+ try:
114
+ answer = await agent.synthesize(query=query, nodes=nodes)
115
+
116
+ print_separator("SYNTHESIZED ANSWER")
117
+ print()
118
+ print(answer)
119
+ print()
120
+
121
+ # Check for citations
122
+ print_separator("CITATION CHECK")
123
+ citations_found = []
124
+ for i in range(1, len(nodes) + 1):
125
+ if f"[{i}]" in answer:
126
+ citations_found.append(i)
127
+ print(f" ✓ Citation [{i}] found in answer")
128
+ else:
129
+ print(f" ✗ Citation [{i}] NOT found in answer")
130
+
131
+ if len(citations_found) == len(nodes):
132
+ print("\n ✅ All citations present - synthesis looks correct!")
133
+ elif len(citations_found) > 0:
134
+ print(f"\n ⚠️ {len(citations_found)}/{len(nodes)} citations found")
135
+ else:
136
+ print("\n ❌ No citations found - check prompt template")
137
+
138
+ except Exception as e:
139
+ print_separator("ERROR")
140
+ print(f" Synthesis failed: {e}")
141
+ print("\n Check your .env file for:")
142
+ print(" - GOOGLE_API_KEY or GROQ_API_KEY")
143
+ print(" - SYNTHESIS_MODEL (e.g., gemini/gemini-1.5-flash)")
144
+ print(" - SYNTHESIS_FALLBACK (e.g., groq/llama3-8b-8192)")
145
+ raise
146
+
147
+ print_separator("VALIDATION COMPLETE")
148
+
149
+
150
+ if __name__ == "__main__":
151
+ asyncio.run(main())
tests/unit/test_state.py CHANGED
@@ -54,3 +54,32 @@ def test_error_tracking_and_defaults():
54
  # defaults regenerated per instance
55
  s2 = State(query="err2")
56
  assert s2.request_id != s.request_id
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54
  # defaults regenerated per instance
55
  s2 = State(query="err2")
56
  assert s2.request_id != s.request_id
57
+
58
+
59
+ @pytest.mark.unit
60
+ def test_synthesis_fields_defaults():
61
+ """Test that answer and citations fields default correctly."""
62
+ s = State(query="synthesis test")
63
+ # answer defaults to None
64
+ assert s.answer is None
65
+ # citations defaults to empty list
66
+ assert s.citations == []
67
+ assert isinstance(s.citations, list)
68
+
69
+
70
+ @pytest.mark.unit
71
+ def test_synthesis_fields_assignment():
72
+ """Test that answer and citations can be assigned and updated."""
73
+ s = State(query="synthesis test")
74
+
75
+ # Set answer
76
+ s.update_fields(answer="The evidence suggests...")
77
+ assert s.answer == "The evidence suggests..."
78
+
79
+ # Set citations as list of integers (paper indices)
80
+ s.update_fields(citations=[0, 2, 5])
81
+ assert s.citations == [0, 2, 5]
82
+
83
+ # Verify other existing fields remain intact
84
+ assert s.finalists is None
85
+ assert s.passages is None
tests/unit/test_synthesis_agent.py ADDED
@@ -0,0 +1,255 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Unit tests for the SynthesisAgent.
2
+
3
+ Tests cover:
4
+ - Happy path: Valid nodes return synthesized answer with citations
5
+ - Empty nodes: Returns fallback message gracefully
6
+ - LLM errors: Exception handling and logging
7
+ - Context formatting: Proper passage indexing
8
+ """
9
+
10
+ import pytest
11
+ from unittest.mock import AsyncMock, patch, MagicMock
12
+
13
+ from llama_index.core.schema import NodeWithScore, TextNode
14
+
15
+ from agents.synthesis_agent import SynthesisAgent, CITATION_QA_TEMPLATE
16
+
17
+
18
+ # Helper to create mock NodeWithScore objects
19
+ def create_mock_node(text: str, score: float = 0.9) -> NodeWithScore:
20
+ """Create a mock NodeWithScore for testing."""
21
+ node = TextNode(text=text)
22
+ return NodeWithScore(node=node, score=score)
23
+
24
+
25
+ @pytest.mark.unit
26
+ @pytest.mark.asyncio
27
+ async def test_synthesize_happy_path():
28
+ """Synthesize should return LLM response with citations for valid nodes."""
29
+ agent = SynthesisAgent()
30
+
31
+ nodes = [
32
+ create_mock_node("Intermittent fasting can affect heart rate variability."),
33
+ create_mock_node("Studies show metabolic benefits of time-restricted eating."),
34
+ create_mock_node("Some patients report fatigue during fasting periods."),
35
+ ]
36
+
37
+ expected_response = (
38
+ "Intermittent fasting can affect heart rate variability [1]. "
39
+ "Studies have also shown metabolic benefits [2], though some patients "
40
+ "report fatigue during fasting periods [3]."
41
+ )
42
+
43
+ with patch.object(
44
+ agent.router, "generate", new_callable=AsyncMock
45
+ ) as mock_generate:
46
+ mock_generate.return_value = expected_response
47
+
48
+ result = await agent.synthesize(
49
+ query="What are the cardiovascular effects of intermittent fasting?",
50
+ nodes=nodes,
51
+ )
52
+
53
+ assert result == expected_response
54
+ mock_generate.assert_called_once()
55
+ # Verify the prompt contains all passages
56
+ call_args = mock_generate.call_args
57
+ prompt = call_args[0][0] # First positional arg is the prompt
58
+ assert "[1]" in prompt
59
+ assert "[2]" in prompt
60
+ assert "[3]" in prompt
61
+ assert "heart rate variability" in prompt
62
+
63
+
64
+ @pytest.mark.unit
65
+ @pytest.mark.asyncio
66
+ async def test_synthesize_empty_nodes():
67
+ """Synthesize should return fallback message for empty node list."""
68
+ agent = SynthesisAgent()
69
+
70
+ result = await agent.synthesize(
71
+ query="What are the risks of fasting?",
72
+ nodes=[],
73
+ )
74
+
75
+ assert result == SynthesisAgent.INSUFFICIENT_CONTEXT_MESSAGE
76
+
77
+
78
+ @pytest.mark.unit
79
+ @pytest.mark.asyncio
80
+ async def test_synthesize_llm_error():
81
+ """Synthesize should re-raise LLM errors after logging."""
82
+ agent = SynthesisAgent()
83
+
84
+ nodes = [
85
+ create_mock_node("Some passage about fasting."),
86
+ ]
87
+
88
+ with patch.object(
89
+ agent.router, "generate", new_callable=AsyncMock
90
+ ) as mock_generate:
91
+ mock_generate.side_effect = Exception("LLM API timeout")
92
+
93
+ with pytest.raises(Exception) as exc_info:
94
+ await agent.synthesize(
95
+ query="What is fasting?",
96
+ nodes=nodes,
97
+ )
98
+
99
+ assert "LLM API timeout" in str(exc_info.value)
100
+ mock_generate.assert_called_once()
101
+
102
+
103
+ @pytest.mark.unit
104
+ @pytest.mark.asyncio
105
+ async def test_synthesize_single_node():
106
+ """Synthesize should work correctly with a single node."""
107
+ agent = SynthesisAgent()
108
+
109
+ nodes = [
110
+ create_mock_node("Fasting promotes autophagy in cells."),
111
+ ]
112
+
113
+ expected_response = "Fasting promotes autophagy in cells [1]."
114
+
115
+ with patch.object(
116
+ agent.router, "generate", new_callable=AsyncMock
117
+ ) as mock_generate:
118
+ mock_generate.return_value = expected_response
119
+
120
+ result = await agent.synthesize(
121
+ query="What is autophagy?",
122
+ nodes=nodes,
123
+ )
124
+
125
+ assert result == expected_response
126
+
127
+
128
+ @pytest.mark.unit
129
+ @pytest.mark.asyncio
130
+ async def test_synthesize_calls_synthesis_model_type():
131
+ """Synthesize should call LLM router with 'synthesis' model type."""
132
+ agent = SynthesisAgent()
133
+
134
+ nodes = [create_mock_node("Test passage.")]
135
+
136
+ with patch.object(
137
+ agent.router, "generate", new_callable=AsyncMock
138
+ ) as mock_generate:
139
+ mock_generate.return_value = "Answer [1]."
140
+
141
+ await agent.synthesize(query="Test query", nodes=nodes)
142
+
143
+ # Verify generate was called with correct arguments
144
+ mock_generate.assert_called_once()
145
+ args, kwargs = mock_generate.call_args
146
+ # Check if model_type is passed as positional or keyword arg
147
+ if len(args) >= 2:
148
+ assert args[1] == "synthesis"
149
+ else:
150
+ assert kwargs.get("model_type") == "synthesis"
151
+
152
+
153
+ @pytest.mark.unit
154
+ def test_format_context_multiple_passages():
155
+ """_format_context should format passages with 1-based indices."""
156
+ agent = SynthesisAgent()
157
+
158
+ nodes = [
159
+ create_mock_node("First passage."),
160
+ create_mock_node("Second passage."),
161
+ create_mock_node("Third passage."),
162
+ ]
163
+
164
+ context = agent._format_context(nodes)
165
+
166
+ assert "[1] First passage." in context
167
+ assert "[2] Second passage." in context
168
+ assert "[3] Third passage." in context
169
+ assert "---" in context # Separator is present
170
+
171
+
172
+ @pytest.mark.unit
173
+ def test_format_context_empty_list():
174
+ """_format_context should return empty string for empty list."""
175
+ agent = SynthesisAgent()
176
+
177
+ context = agent._format_context([])
178
+
179
+ assert context == ""
180
+
181
+
182
+ @pytest.mark.unit
183
+ def test_extract_text_from_node():
184
+ """_extract_text should get text from NodeWithScore."""
185
+ agent = SynthesisAgent()
186
+
187
+ node = create_mock_node("Extracted text content.")
188
+
189
+ text = agent._extract_text(node)
190
+
191
+ assert text == "Extracted text content."
192
+
193
+
194
+ @pytest.mark.unit
195
+ def test_citation_prompt_template_format():
196
+ """CITATION_QA_TEMPLATE should be properly formatted with placeholders."""
197
+ assert "{context_str}" in CITATION_QA_TEMPLATE
198
+ assert "{query_str}" in CITATION_QA_TEMPLATE
199
+ assert "ONLY" in CITATION_QA_TEMPLATE # Emphasis on using only context
200
+ assert "[N]" in CITATION_QA_TEMPLATE # Citation format instruction
201
+
202
+
203
+ @pytest.mark.unit
204
+ def test_agent_initialization():
205
+ """SynthesisAgent should initialize with default temperature."""
206
+ agent = SynthesisAgent()
207
+
208
+ assert agent.temperature == 0.3
209
+ assert agent.router is not None
210
+
211
+
212
+ @pytest.mark.unit
213
+ def test_agent_custom_temperature():
214
+ """SynthesisAgent should accept custom temperature."""
215
+ agent = SynthesisAgent(temperature=0.7)
216
+
217
+ assert agent.temperature == 0.7
218
+
219
+
220
+ @pytest.mark.unit
221
+ @pytest.mark.asyncio
222
+ async def test_synthesize_strips_whitespace():
223
+ """Synthesize should strip leading/trailing whitespace from response."""
224
+ agent = SynthesisAgent()
225
+
226
+ nodes = [create_mock_node("Test passage.")]
227
+
228
+ with patch.object(
229
+ agent.router, "generate", new_callable=AsyncMock
230
+ ) as mock_generate:
231
+ mock_generate.return_value = " Answer with whitespace [1]. \n"
232
+
233
+ result = await agent.synthesize(query="Test query", nodes=nodes)
234
+
235
+ assert result == "Answer with whitespace [1]."
236
+
237
+
238
+ @pytest.mark.unit
239
+ @pytest.mark.asyncio
240
+ async def test_synthesize_preserves_multiline_response():
241
+ """Synthesize should preserve internal newlines in response."""
242
+ agent = SynthesisAgent()
243
+
244
+ nodes = [create_mock_node("Test passage.")]
245
+
246
+ multiline_response = "Point 1 [1].\n\nPoint 2 [1]."
247
+
248
+ with patch.object(
249
+ agent.router, "generate", new_callable=AsyncMock
250
+ ) as mock_generate:
251
+ mock_generate.return_value = multiline_response
252
+
253
+ result = await agent.synthesize(query="Test query", nodes=nodes)
254
+
255
+ assert result == multiline_response