-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
test_agent.py
663 lines (565 loc) · 23.6 KB
/
test_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
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
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
import os
import sys
from typing import Optional
from unittest.mock import MagicMock, Mock, PropertyMock, patch
import pandas as pd
import pytest
from langchain import OpenAI
from pandasai.agent import Agent
from pandasai.connectors.sql import (
PostgreSQLConnector,
SQLConnector,
SQLConnectorConfig,
)
from pandasai.constants import DEFAULT_FILE_PERMISSIONS
from pandasai.helpers.dataframe_serializer import DataframeSerializerType
from pandasai.llm.bamboo_llm import BambooLLM
from pandasai.llm.fake import FakeLLM
from pandasai.llm.langchain import LangchainLLM
from pandasai.pipelines.chat.code_cleaning import CodeCleaning
# from pandasai.pipelines.chat.code_cleaning import CodeManager
from pandasai.prompts.clarification_questions_prompt import ClarificationQuestionPrompt
from pandasai.prompts.explain_prompt import ExplainPrompt
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, "dataframe_serializer": DataframeSerializerType.CSV}
@pytest.fixture
def agent(self, sample_df: pd.DataFrame, config: dict) -> Agent:
return Agent(sample_df, config, vectorstore=MagicMock())
@pytest.fixture
@patch("pandasai.connectors.sql.create_engine", autospec=True)
def sql_connector(self, create_engine):
# Define your ConnectorConfig instance here
self.config = SQLConnectorConfig(
dialect="mysql",
driver="pymysql",
username="your_username",
password="your_password",
host="your_host",
port=443,
database="your_database",
table="your_table",
where=[["column_name", "=", "value"]],
).dict()
# Create an instance of SQLConnector
return SQLConnector(self.config)
@pytest.fixture
@patch("pandasai.connectors.sql.create_engine", autospec=True)
def pgsql_connector(self, create_engine):
# Define your ConnectorConfig instance here
self.config = SQLConnectorConfig(
dialect="mysql",
driver="pymysql",
username="your_username",
password="your_password",
host="your_host",
port=443,
database="your_database",
table="your_table",
where=[["column_name", "=", "value"]],
).dict()
# Create an instance of SQLConnector
return PostgreSQLConnector(self.config)
def test_constructor(self, sample_df, config):
agent_1 = Agent(sample_df, config)
agent_2 = Agent([sample_df], config)
# test multiple agents instances data overlap
agent_1.context.memory.add("Which country has the highest gdp?", True)
memory = agent_1.context.memory.all()
assert len(memory) == 1
memory = agent_2.context.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.chat = Mock()
agent.chat.return_value = "United States has the highest gdp"
# Test the chat function
response = agent.chat("Which country has the highest gdp?")
assert agent.chat.called
assert isinstance(response, str)
assert response == "United States has the highest gdp"
def test_code_generation(self, sample_df, config):
# Create an Agent instance for testing
agent = Agent(sample_df, config)
agent.pipeline.code_generation_pipeline.run = Mock()
agent.pipeline.code_generation_pipeline.run.return_value = (
"print(United States has the highest gdp)"
)
# Test the chat function
response = agent.generate_code("Which country has the highest gdp?")
assert agent.pipeline.code_generation_pipeline.run.called
assert isinstance(response, str)
assert response == "print(United States has the highest gdp)"
def test_code_generation_failure(self, sample_df, config):
# Create an Agent instance for testing
agent = Agent(sample_df, config)
agent.pipeline.code_generation_pipeline.run = Mock()
agent.pipeline.code_generation_pipeline.run.side_effect = Exception(
"Raise an exception"
)
# Test the chat function
response = agent.generate_code("Which country has the highest gdp?")
assert agent.pipeline.code_generation_pipeline.run.called
assert (
response
== "Unfortunately, I was not able to answer your question, because of the following error:\n\nRaise an exception\n"
)
def test_code_execution(self, sample_df, config):
# Create an Agent instance for testing
agent = Agent(sample_df, config)
agent.pipeline.code_execution_pipeline.run = Mock()
agent.pipeline.code_execution_pipeline.run.side_effect = Exception(
"Raise an exception"
)
response = agent.execute_code("print(United States has the highest gdp)")
assert agent.pipeline.code_execution_pipeline.run.called
assert (
response
== "Unfortunately, I was not able to answer your question, because of the following error:\n\nRaise an exception\n"
)
def test_code_execution_failure(self, sample_df, config):
# Create an Agent instance for testing
agent = Agent(sample_df, config)
agent.pipeline.code_execution_pipeline.run = Mock()
agent.pipeline.code_execution_pipeline.run.return_value = (
"United States has the highest gdp"
)
response = agent.execute_code("print(United States has the highest gdp)")
assert agent.pipeline.code_execution_pipeline.run.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.context.memory.add("Which country has the highest gdp?", True)
memory = agent.context.memory.all()
assert len(memory) == 1
agent.start_new_conversation()
memory = agent.context.memory.all()
assert len(memory) == 0
def test_clarification_questions(self, sample_df, config):
agent = Agent(sample_df, config, memory_size=10)
agent.context.config.llm.call = Mock()
clarification_response = (
'["What is happiest index for you?", "What is unit of measure for gdp?"]'
)
agent.context.config.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.context.config.llm.call = Mock()
agent.context.config.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.context.config.llm.call = Mock()
agent.context.config.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.context.config.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.context.config.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.context.config.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.context.config.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.context.config.llm.call = Mock()
clarification_response = """
What is expected Salary Increase?
"""
agent.context.config.llm.call.return_value = clarification_response
prompt = ExplainPrompt(
context=agent.context,
code="test code",
)
agent.call_llm_with_prompt(prompt)
assert agent.context.config.llm.call.call_count == 1
def test_call_prompt_max_retries_exceeds(self, agent: Agent):
# raises exception every time
agent.context.config.llm.call = Mock()
agent.context.config.llm.call.side_effect = Exception("Raise an exception")
with pytest.raises(Exception):
agent.call_llm_with_prompt("Test Prompt")
assert agent.context.config.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.context.config.llm.call = Mock()
agent.context.config.llm.call.side_effect = [
Exception(),
Exception(),
"LLM Result",
]
prompt = ExplainPrompt(
context=agent.context,
code="test code",
)
result = agent.call_llm_with_prompt(prompt)
assert result == "LLM Result"
assert agent.context.config.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.context.config.llm.call = Mock()
agent.context.config.llm.call.side_effect = [Exception(), "LLM Result"]
prompt = ExplainPrompt(
context=agent.context,
code="test code",
)
result = agent.call_llm_with_prompt(prompt)
assert result == "LLM Result"
assert agent.context.config.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.context.config.use_error_correction_framework = False
agent.context.config.llm.call = Mock()
agent.context.config.llm.call.side_effect = Exception()
with pytest.raises(Exception):
agent.call_llm_with_prompt("Test Prompt")
assert agent.context.config.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.context.config.max_retries = 5
agent.context.config.llm.call = Mock()
agent.context.config.llm.call.side_effect = Exception()
with pytest.raises(Exception):
agent.call_llm_with_prompt("Test Prompt")
assert agent.context.config.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.context.config.llm.call = Mock()
agent.context.config.llm.call.return_value = "This is not json"
prompt = ClarificationQuestionPrompt(
context=agent.context,
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.context.config.llm.call = Mock()
agent.context.config.llm.call.return_value = '["This is test question"]'
prompt = ClarificationQuestionPrompt(
context=agent.context,
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.context.config.llm.call = Mock()
clarification_response = """
How much has the total salary expense increased?
"""
agent.context.config.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?
"""
)
def test_load_llm_with_pandasai_llm(self, agent: Agent, llm):
assert agent.get_llm(llm) == llm
def test_load_llm_with_langchain_llm(self, agent: Agent, llm):
langchain_llm = OpenAI(openai_api_key="fake_key")
config = agent.get_config({"llm": langchain_llm})
assert isinstance(config.llm, LangchainLLM)
assert config.llm.langchain_llm == langchain_llm
def test_load_llm_none(self, agent: Agent, llm):
config = agent.get_config({"llm": None})
assert isinstance(config.llm, BambooLLM)
@pytest.mark.skip(reason="Removed CodeManager class")
@patch(
"pandasai.pipelines.chat.code_execution.CodeManager.last_code_executed",
new_callable=PropertyMock,
)
def test_last_code_executed(self, _mocked_property, agent: Agent):
expected_code = "result = {'type': 'string', 'value': 'There are 10 countries in the dataframe.'}"
_mocked_property.return_value = expected_code
agent.chat("How many countries are in the dataframe?")
assert agent.last_code_executed == expected_code
@pytest.mark.skip(reason="Removed CodeManager class")
# @patch.object(
# CodeManager,
# "execute_code",
# return_value={
# "type": "string",
# "value": "There are 10 countries in the dataframe.",
# },
# )
def test_last_result_is_saved(self, _mocked_method, agent: Agent):
assert agent.last_result is None
_mocked_method.__name__ = "execute_code"
agent.chat("How many countries are in the dataframe?")
assert agent.last_result == {
"type": "string",
"value": "There are 10 countries in the dataframe.",
}
@pytest.mark.skip(reason="Removed CodeManager class")
# @patch.object(
# CodeManager,
# "execute_code",
# return_value={
# "type": "string",
# "value": "There are 10 countries in the dataframe.",
# },
# )
@patch("pandasai.helpers.query_exec_tracker.QueryExecTracker.publish")
def test_query_tracker_publish_called_in_chat_method(
self, mock_query_tracker_publish, _mocked_method, agent: Agent
):
assert agent.last_result is None
_mocked_method.__name__ = "execute_code"
agent.chat("How many countries are in the dataframe?")
mock_query_tracker_publish.assert_called()
@pytest.mark.skip(reason="Removed CodeManager class")
@patch(
"pandasai.pipelines.chat.code_execution.CodeManager.execute_code",
autospec=True,
)
@patch(
"pandasai.pipelines.chat.code_generator.CodeGenerator.execute",
autospec=True,
)
@patch(
"pandasai.pipelines.chat.code_execution.traceback.format_exc",
autospec=True,
)
def test_retry_on_error_with_single_df(
self,
mock_traceback,
mock_generate,
mock_execute,
agent: Agent,
):
mock_traceback.return_value = "Test error"
mock_generate.return_value = (
"result = {'type': 'string', 'value': 'Hello World'}"
)
mock_execute.side_effect = [
Exception("Test error"),
{"type": "string", "value": "Hello World"},
]
agent.context.dfs[0].to_csv = Mock(
return_value="""country,gdp,happiness_index
China,654881226,6.66
Japan,9009692259,7.16
Spain,8446903488,6.38
"""
)
agent.chat("Hello world")
last_prompt = agent.last_prompt
if sys.platform.startswith("win"):
last_prompt = last_prompt.replace("\r\n", "\n")
print(last_prompt)
assert (
last_prompt
== """<dataframe>
dfs[0]:10x3
country,gdp,happiness_index
China,654881226,6.66
Japan,9009692259,7.16
Spain,8446903488,6.38
</dataframe>
The user asked the following question:
### QUERY
Hello world
You generated this python code:
result = {'type': 'string', 'value': 'Hello World'}
It fails with the following error:
Test error
Fix the python code above and return the new python code:""" # noqa: E501
)
@patch("os.makedirs")
def test_load_config_with_cache(self, mock_makedirs, agent):
# Modify the agent's configuration
agent.context.config.save_charts = True
agent.context.config.enable_cache = True
# Call the initialize method
agent.configure()
# Assertions for enabling cache
cache_dir = os.path.join(os.getcwd(), "cache")
mock_makedirs.assert_any_call(
cache_dir, mode=DEFAULT_FILE_PERMISSIONS, exist_ok=True
)
# Assertions for saving charts
charts_dir = os.path.join(os.getcwd(), agent.context.config.save_charts_path)
mock_makedirs.assert_any_call(
charts_dir, mode=DEFAULT_FILE_PERMISSIONS, exist_ok=True
)
@patch("os.makedirs")
def test_load_config_without_cache(self, mock_makedirs, agent):
# Modify the agent's configuration
agent.context.config.save_charts = True
agent.context.config.enable_cache = False
# Call the initialize method
agent.configure()
# Assertions for saving charts
charts_dir = os.path.join(os.getcwd(), agent.context.config.save_charts_path)
mock_makedirs.assert_called_once_with(
charts_dir, mode=DEFAULT_FILE_PERMISSIONS, exist_ok=True
)
def test_validate_true_direct_sql_with_non_connector(self, llm, sample_df):
# raise exception with non connector
Agent(
[sample_df],
config={"llm": llm, "enable_cache": False, "direct_sql": True},
)
def test_validate_direct_sql_with_connector(self, llm, sql_connector):
# not exception is raised using single connector
Agent(
[sql_connector],
config={"llm": llm, "enable_cache": False, "direct_sql": True},
)
def test_validate_false_direct_sql_with_connector(self, llm, sql_connector):
# not exception is raised using single connector
Agent(
[sql_connector],
config={"llm": llm, "enable_cache": False, "direct_sql": False},
)
def test_validate_false_direct_sql_with_two_different_connector(
self, llm, sql_connector, pgsql_connector
):
# not exception is raised using single connector
Agent(
[sql_connector, pgsql_connector],
config={"llm": llm, "enable_cache": False, "direct_sql": False},
)
def test_train_method_with_qa(self, agent):
queries = ["query1", "query2"]
codes = ["code1", "code2"]
agent.train(queries, codes)
agent._vectorstore.add_docs.assert_not_called()
agent._vectorstore.add_question_answer.assert_called_once_with(queries, codes)
def test_train_method_with_docs(self, agent):
docs = ["doc1"]
agent.train(docs=docs)
agent._vectorstore.add_question_answer.assert_not_called()
agent._vectorstore.add_docs.assert_called_once()
agent._vectorstore.add_docs.assert_called_once_with(docs)
def test_train_method_with_docs_and_qa(self, agent):
docs = ["doc1"]
queries = ["query1", "query2"]
codes = ["code1", "code2"]
agent.train(queries, codes, docs=docs)
agent._vectorstore.add_question_answer.assert_called_once()
agent._vectorstore.add_question_answer.assert_called_once_with(queries, codes)
agent._vectorstore.add_docs.assert_called_once()
agent._vectorstore.add_docs.assert_called_once_with(docs)
def test_train_method_with_queries_but_no_code(self, agent):
queries = ["query1", "query2"]
with pytest.raises(ValueError):
agent.train(queries)
def test_train_method_with_code_but_no_queries(self, agent):
codes = ["code1", "code2"]
with pytest.raises(ValueError):
agent.train(codes)
@patch.object(
CodeCleaning,
"execute",
return_value={
"type": "string",
"value": "There are 10 countries in the dataframe.",
},
)
@patch("pandasai.helpers.query_exec_tracker.QueryExecTracker.publish")
@patch(
"pandasai.helpers.query_exec_tracker.QueryExecTracker.last_log_id",
return_value="1234",
)
def test_query_tracker_last_log_id_property_called(
self,
mock_query_tracker_log_id,
mock_query_tracker_publish,
_mocked_method,
agent: Agent,
):
_mocked_method.__name__ = "execute_code"
agent.chat("How many countries are in the dataframe?")
agent.last_query_log_id()
mock_query_tracker_publish.assert_called()
mock_query_tracker_log_id.assert_called()