File size: 10,082 Bytes
4c0b7eb
 
e7b4937
4c0b7eb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59f3cce
4c0b7eb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
LLM Integration Tests - Stage 3 Validation
Author: @mangubee
Date: 2026-01-02

Tests for Stage 3 LLM integration:
- Planning with LLM
- Tool selection via function calling
- Answer synthesis from evidence
- Full workflow with mocked LLM responses
"""

import pytest
from unittest.mock import patch, MagicMock
from src.agent.llm_client import (
    plan_question,
    select_tools_with_function_calling,
    synthesize_answer
)
from src.tools import TOOLS


class TestPlanningFunction:
    """Test LLM-based planning function."""

    @patch('src.agent.llm_client.Anthropic')
    def test_plan_question_basic(self, mock_anthropic):
        """Test planning with simple question."""
        # Mock LLM response
        mock_client = MagicMock()
        mock_response = MagicMock()
        mock_response.content = [MagicMock(text="1. Search for information\n2. Analyze results")]
        mock_client.messages.create.return_value = mock_response
        mock_anthropic.return_value = mock_client

        # Test planning
        plan = plan_question(
            question="What is the capital of France?",
            available_tools=TOOLS
        )

        assert isinstance(plan, str)
        assert len(plan) > 0
        print(f"βœ“ Generated plan: {plan[:50]}...")

    @patch('src.agent.llm_client.Anthropic')
    def test_plan_with_files(self, mock_anthropic):
        """Test planning with file context."""
        # Mock LLM response
        mock_client = MagicMock()
        mock_response = MagicMock()
        mock_response.content = [MagicMock(text="1. Parse file\n2. Extract data\n3. Calculate answer")]
        mock_client.messages.create.return_value = mock_response
        mock_anthropic.return_value = mock_client

        # Test planning with files
        plan = plan_question(
            question="What is the total in the spreadsheet?",
            available_tools=TOOLS,
            file_paths=["data.xlsx"]
        )

        assert isinstance(plan, str)
        assert len(plan) > 0
        print(f"βœ“ Generated plan with files: {plan[:50]}...")


class TestToolSelection:
    """Test LLM function calling for tool selection."""

    @patch('src.agent.llm_client.Anthropic')
    def test_select_single_tool(self, mock_anthropic):
        """Test selecting single tool with parameters."""
        # Mock LLM response with function call
        mock_client = MagicMock()
        mock_response = MagicMock()

        # Mock tool_use content block
        mock_tool_use = MagicMock()
        mock_tool_use.type = "tool_use"
        mock_tool_use.name = "search"
        mock_tool_use.input = {"query": "capital of France"}
        mock_tool_use.id = "call_001"

        mock_response.content = [mock_tool_use]
        mock_client.messages.create.return_value = mock_response
        mock_anthropic.return_value = mock_client

        # Test tool selection
        tool_calls = select_tools_with_function_calling(
            question="What is the capital of France?",
            plan="1. Search for capital of France",
            available_tools=TOOLS
        )

        assert isinstance(tool_calls, list)
        assert len(tool_calls) == 1
        assert tool_calls[0]["tool"] == "search"
        assert "query" in tool_calls[0]["params"]
        print(f"βœ“ Selected tool: {tool_calls[0]}")

    @patch('src.agent.llm_client.Anthropic')
    def test_select_multiple_tools(self, mock_anthropic):
        """Test selecting multiple tools in sequence."""
        # Mock LLM response with multiple function calls
        mock_client = MagicMock()
        mock_response = MagicMock()

        # Mock multiple tool_use blocks
        mock_tool1 = MagicMock()
        mock_tool1.type = "tool_use"
        mock_tool1.name = "parse_file"
        mock_tool1.input = {"file_path": "data.xlsx"}
        mock_tool1.id = "call_001"

        mock_tool2 = MagicMock()
        mock_tool2.type = "tool_use"
        mock_tool2.name = "safe_eval"
        mock_tool2.input = {"expression": "sum(values)"}
        mock_tool2.id = "call_002"

        mock_response.content = [mock_tool1, mock_tool2]
        mock_client.messages.create.return_value = mock_response
        mock_anthropic.return_value = mock_client

        # Test tool selection
        tool_calls = select_tools_with_function_calling(
            question="What is the sum in data.xlsx?",
            plan="1. Parse file\n2. Calculate sum",
            available_tools=TOOLS
        )

        assert isinstance(tool_calls, list)
        assert len(tool_calls) == 2
        assert tool_calls[0]["tool"] == "parse_file"
        assert tool_calls[1]["tool"] == "safe_eval"
        print(f"βœ“ Selected {len(tool_calls)} tools")


class TestAnswerSynthesis:
    """Test LLM-based answer synthesis."""

    @patch('src.agent.llm_client.Anthropic')
    def test_synthesize_simple_answer(self, mock_anthropic):
        """Test synthesizing answer from single evidence."""
        # Mock LLM response
        mock_client = MagicMock()
        mock_response = MagicMock()
        mock_response.content = [MagicMock(text="Paris")]
        mock_client.messages.create.return_value = mock_response
        mock_anthropic.return_value = mock_client

        # Test answer synthesis
        answer = synthesize_answer(
            question="What is the capital of France?",
            evidence=["[search] Paris is the capital and most populous city of France"]
        )

        assert isinstance(answer, str)
        assert len(answer) > 0
        assert answer == "Paris"
        print(f"βœ“ Synthesized answer: {answer}")

    @patch('src.agent.llm_client.Anthropic')
    def test_synthesize_from_multiple_evidence(self, mock_anthropic):
        """Test synthesizing answer from multiple evidence sources."""
        # Mock LLM response
        mock_client = MagicMock()
        mock_response = MagicMock()
        mock_response.content = [MagicMock(text="42")]
        mock_client.messages.create.return_value = mock_response
        mock_anthropic.return_value = mock_client

        # Test answer synthesis with multiple evidence
        answer = synthesize_answer(
            question="What is the answer?",
            evidence=[
                "[search] The answer to life is 42",
                "[safe_eval] 6 * 7 = 42",
                "[parse_file] Result: 42"
            ]
        )

        assert isinstance(answer, str)
        assert answer == "42"
        print(f"βœ“ Synthesized answer from {3} evidence items: {answer}")

    @patch('src.agent.llm_client.Anthropic')
    def test_synthesize_with_conflicts(self, mock_anthropic):
        """Test synthesizing answer when evidence conflicts."""
        # Mock LLM response - should resolve conflict
        mock_client = MagicMock()
        mock_response = MagicMock()
        mock_response.content = [MagicMock(text="Paris")]
        mock_client.messages.create.return_value = mock_response
        mock_anthropic.return_value = mock_client

        # Test answer synthesis with conflicting evidence
        answer = synthesize_answer(
            question="What is the capital of France?",
            evidence=[
                "[search] Paris is the capital of France (source: Wikipedia, 2024)",
                "[search] Lyon was briefly capital during revolution (source: old text, 1793)"
            ]
        )

        assert isinstance(answer, str)
        assert answer == "Paris"  # Should pick more recent/credible source
        print(f"βœ“ Resolved conflict, answer: {answer}")


class TestEndToEndWorkflow:
    """Test full agent workflow with mocked LLM."""

    @patch('src.agent.llm_client.Anthropic')
    @patch('src.tools.web_search.tavily_search')
    def test_full_search_workflow(self, mock_tavily, mock_anthropic):
        """Test complete workflow: plan β†’ search β†’ answer."""
        from src.agent import GAIAAgent

        # Mock tool execution
        mock_tavily.return_value = "Paris is the capital and most populous city of France"

        # Mock LLM responses
        mock_client = MagicMock()

        # Response 1: Planning
        # Response 2: Tool selection (function calling)
        # Response 3: Answer synthesis

        mock_plan_response = MagicMock()
        mock_plan_response.content = [MagicMock(text="1. Search for capital of France")]

        mock_tool_response = MagicMock()
        mock_tool_use = MagicMock()
        mock_tool_use.type = "tool_use"
        mock_tool_use.name = "web_search"
        mock_tool_use.input = {"query": "capital of France"}
        mock_tool_use.id = "call_001"
        mock_tool_response.content = [mock_tool_use]

        mock_answer_response = MagicMock()
        mock_answer_response.content = [MagicMock(text="Paris")]

        # Set up mock to return different responses for each call
        mock_client.messages.create.side_effect = [
            mock_plan_response,
            mock_tool_response,
            mock_answer_response
        ]

        mock_anthropic.return_value = mock_client

        # Test full workflow
        agent = GAIAAgent()
        answer = agent("What is the capital of France?")

        assert isinstance(answer, str)
        assert answer == "Paris"
        print(f"βœ“ Full workflow completed, answer: {answer}")


if __name__ == "__main__":
    print("\n" + "="*70)
    print("GAIA Agent - Stage 3 LLM Integration Tests")
    print("="*70 + "\n")

    # Run tests manually for quick validation
    test_plan = TestPlanningFunction()
    test_plan.test_plan_question_basic()
    test_plan.test_plan_with_files()

    test_tools = TestToolSelection()
    test_tools.test_select_single_tool()
    test_tools.test_select_multiple_tools()

    test_answer = TestAnswerSynthesis()
    test_answer.test_synthesize_simple_answer()
    test_answer.test_synthesize_from_multiple_evidence()
    test_answer.test_synthesize_with_conflicts()

    test_e2e = TestEndToEndWorkflow()
    test_e2e.test_full_search_workflow()

    print("\n" + "="*70)
    print("βœ“ All Stage 3 LLM integration tests passed!")
    print("="*70 + "\n")