-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
_tests_agent.py
287 lines (239 loc) · 10.5 KB
/
_tests_agent.py
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
from typing import Optional
from unittest.mock import Mock
import pandas as pd
import pytest
from pandasai.agent import Agent
from pandasai.llm.fake import FakeLLM
from pandasai.prompts.clarification_questions_prompt import ClarificationQuestionPrompt
from pandasai.prompts.explain_prompt import ExplainPrompt
from pandasai.smart_datalake import SmartDatalake
class TestAgent:
"Unit tests for Agent class"
@pytest.fixture
def sample_df(self):
return pd.DataFrame(
{
"country": [
"United States",
"United Kingdom",
"France",
"Germany",
"Italy",
"Spain",
"Canada",
"Australia",
"Japan",
"China",
],
"gdp": [
19294482071552,
2891615567872,
2411255037952,
3435817336832,
1745433788416,
1181205135360,
1607402389504,
1490967855104,
4380756541440,
14631844184064,
],
"happiness_index": [
6.94,
7.16,
6.66,
7.07,
6.38,
6.4,
7.23,
7.22,
5.87,
5.12,
],
}
)
@pytest.fixture
def llm(self, output: Optional[str] = None) -> FakeLLM:
return FakeLLM(output=output)
@pytest.fixture
def config(self, llm: FakeLLM) -> dict:
return {"llm": llm}
@pytest.fixture
def agent(self, sample_df: pd.DataFrame, config: dict) -> Agent:
return Agent(sample_df, config)
def test_constructor(self, sample_df, config):
agent_1 = Agent(sample_df, config)
assert isinstance(agent_1._lake, SmartDatalake)
agent_2 = Agent([sample_df], config)
assert isinstance(agent_2._lake, SmartDatalake)
# test multiple agents instances data overlap
agent_1._lake._memory.add("Which country has the highest gdp?", True)
memory = agent_1._lake._memory.all()
assert len(memory) == 1
memory = agent_2._lake._memory.all()
assert len(memory) == 0
def test_chat(self, sample_df, config):
# Create an Agent instance for testing
agent = Agent(sample_df, config)
agent._lake.chat = Mock()
agent._lake.chat.return_value = "United States has the highest gdp"
# Test the chat function
response = agent.chat("Which country has the highest gdp?")
assert agent._lake.chat.called
assert isinstance(response, str)
assert response == "United States has the highest gdp"
def test_start_new_conversation(self, sample_df, config):
agent = Agent(sample_df, config, memory_size=10)
agent._lake._memory.add("Which country has the highest gdp?", True)
memory = agent._lake._memory.all()
assert len(memory) == 1
agent.start_new_conversation()
memory = agent._lake._memory.all()
assert len(memory) == 0
def test_clarification_questions(self, sample_df, config):
agent = Agent(sample_df, config, memory_size=10)
agent._lake.llm.call = Mock()
clarification_response = (
'["What is happiest index for you?", "What is unit of measure for gdp?"]'
)
agent._lake.llm.call.return_value = clarification_response
questions = agent.clarification_questions("What is the happiest country?")
assert len(questions) == 2
assert questions[0] == "What is happiest index for you?"
assert questions[1] == "What is unit of measure for gdp?"
def test_clarification_questions_failure(self, sample_df, config):
agent = Agent(sample_df, config, memory_size=10)
agent._lake.llm.call = Mock()
agent._lake.llm.call.return_value = Exception("This is a mock exception")
with pytest.raises(Exception):
agent.clarification_questions("What is the happiest country?")
def test_clarification_questions_fail_non_json(self, sample_df, config):
agent = Agent(sample_df, config, memory_size=10)
agent._lake.llm.call = Mock()
agent._lake.llm.call.return_value = "This is not json response"
with pytest.raises(Exception):
agent.clarification_questions("What is the happiest country?")
def test_clarification_questions_max_3(self, sample_df, config):
agent = Agent(sample_df, config, memory_size=10)
agent._lake.llm.call = Mock()
clarification_response = (
'["What is happiest index for you", '
'"What is unit of measure for gdp", '
'"How many countries are involved in the survey", '
'"How do you want this data to be represented"]'
)
agent._lake.llm.call.return_value = clarification_response
questions = agent.clarification_questions("What is the happiest country?")
assert isinstance(questions, list)
assert len(questions) == 3
def test_explain(self, agent: Agent):
agent._lake.llm.call = Mock()
clarification_response = """
Combine the Data: To find out who gets paid the most,
I needed to match the names of people with the amounts of money they earn.
It's like making sure the right names are next to the right amounts.
I used a method to do this, like connecting pieces of a puzzle.
Find the Top Earner: After combining the data, I looked through it to find
the person with the most money.
It's like finding the person who has the most marbles in a game
"""
agent._lake.llm.call.return_value = clarification_response
response = agent.explain()
assert response == (
"""
Combine the Data: To find out who gets paid the most,
I needed to match the names of people with the amounts of money they earn.
It's like making sure the right names are next to the right amounts.
I used a method to do this, like connecting pieces of a puzzle.
Find the Top Earner: After combining the data, I looked through it to find
the person with the most money.
It's like finding the person who has the most marbles in a game
"""
)
def test_call_prompt_success(self, agent: Agent):
agent._lake.llm.call = Mock()
clarification_response = """
What is expected Salary Increase?
"""
agent._lake.llm.call.return_value = clarification_response
prompt = ExplainPrompt(
conversation="test conversation",
code="test code",
)
agent._call_llm_with_prompt(prompt)
assert agent._lake.llm.call.call_count == 1
def test_call_prompt_max_retries_exceeds(self, agent: Agent):
# raises exception every time
agent._lake.llm.call = Mock()
agent._lake.llm.call.side_effect = Exception("Raise an exception")
with pytest.raises(Exception):
agent._call_llm_with_prompt("Test Prompt")
assert agent._lake.llm.call.call_count == 3
def test_call_prompt_max_retry_on_error(self, agent: Agent):
# test the LLM call failed twice but succeed third time
agent._lake.llm.call = Mock()
agent._lake.llm.call.side_effect = [Exception(), Exception(), "LLM Result"]
prompt = ExplainPrompt(conversation="test conversation", code="")
result = agent._call_llm_with_prompt(prompt)
assert result == "LLM Result"
assert agent._lake.llm.call.call_count == 3
def test_call_prompt_max_retry_twice(self, agent: Agent):
# test the LLM call failed once but succeed second time
agent._lake.llm.call = Mock()
agent._lake.llm.call.side_effect = [Exception(), "LLM Result"]
prompt = ExplainPrompt(conversation="test conversation", code="")
result = agent._call_llm_with_prompt(prompt)
assert result == "LLM Result"
assert agent._lake.llm.call.call_count == 2
def test_call_llm_with_prompt_no_retry_on_error(self, agent: Agent):
# Test when LLM call raises an exception but retries are disabled
agent._lake.config.use_error_correction_framework = False
agent._lake.llm.call = Mock()
agent._lake.llm.call.side_effect = Exception()
with pytest.raises(Exception):
agent._call_llm_with_prompt("Test Prompt")
assert agent._lake.llm.call.call_count == 1
def test_call_llm_with_prompt_max_retries_check(self, agent: Agent):
# Test when LLM call raises an exception, but called call function
# 'max_retries' time
agent._lake.config.max_retries = 5
agent._lake.llm.call = Mock()
agent._lake.llm.call.side_effect = Exception()
with pytest.raises(Exception):
agent._call_llm_with_prompt("Test Prompt")
assert agent._lake.llm.call.call_count == 5
def test_clarification_prompt_validate_output_false_case(self, agent: Agent):
# Test whether the output is json or not
agent._lake.llm.call = Mock()
agent._lake.llm.call.return_value = "This is not json"
prompt = ClarificationQuestionPrompt(
dataframes=agent._lake.dfs,
conversation="test conversation",
query="test query",
)
with pytest.raises(Exception):
agent._call_llm_with_prompt(prompt)
def test_clarification_prompt_validate_output_true_case(self, agent: Agent):
# Test whether the output is json or not
agent._lake.llm.call = Mock()
agent._lake.llm.call.return_value = '["This is test question"]'
prompt = ClarificationQuestionPrompt(
dataframes=agent._lake.dfs,
conversation="test conversation",
query="test query",
)
result = agent._call_llm_with_prompt(prompt)
# Didn't raise any exception
assert isinstance(result, str)
def test_rephrase(self, sample_df, config):
agent = Agent(sample_df, config, memory_size=10)
agent._lake.llm.call = Mock()
clarification_response = """
How much has the total salary expense increased?
"""
agent._lake.llm.call.return_value = clarification_response
response = agent.rephrase_query("how much has the revenue increased?")
assert response == (
"""
How much has the total salary expense increased?
"""
)