Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Integrate CodeIntepreter #736

Merged
merged 477 commits into from
Feb 5, 2024
Merged
Show file tree
Hide file tree
Changes from 20 commits
Commits
Show all changes
477 commits
Select commit Hold shift + click to select a range
3bb445b
fix: no returns function tools.
orange-crow Dec 19, 2023
6895e74
update parse No Args function.
orange-crow Dec 19, 2023
52b8ba8
update globals with function tools.
orange-crow Dec 19, 2023
cb31ede
add udf in ML_MODULE_MAP.
orange-crow Dec 19, 2023
c733541
fix: BaseWriteAnalysisCode now do not install packages or check packa…
orange-crow Dec 19, 2023
6ed4322
feat: add use_udfs with WriteCodeWithTools.
orange-crow Dec 19, 2023
0f3c0c2
update JUDGE_PROMPT_TEMPLATE in ml_engineer_simple.py
mannaandpoem Dec 19, 2023
8afac01
set the plan.current_task.task_type to udf when use udfs.
orange-crow Dec 20, 2023
19b0120
restore task_type value.
orange-crow Dec 20, 2023
a0d2f9b
update: rm async, mv to utils
stellaHSR Dec 20, 2023
0c42d55
rm comments
stellaHSR Dec 20, 2023
9135386
feat:
orange-crow Dec 20, 2023
7b8c15b
feat: add make_tools and feat function.
orange-crow Dec 20, 2023
48ef61c
change format
stellaHSR Dec 20, 2023
2d56265
Merge branch 'dev_tool_selection_resume' into 'dev'
garylin2099 Dec 20, 2023
72e550b
minor update: move action, fix circular import, add entry parameters
garylin2099 Dec 20, 2023
c473763
Merge branch 'no_plan' into 'dev'
garylin2099 Dec 20, 2023
99945e3
update default_system_msg in BaseWriteAnalysisCode.
orange-crow Dec 20, 2023
aa5c42f
use self.DEFAULT_SYSTEM_MSG in process_msg.
orange-crow Dec 20, 2023
1145641
update
orange-crow Dec 20, 2023
5af4f6b
add new test for aask_code about write code by steps.
orange-crow Dec 20, 2023
a39cc30
add test for ml_engineer.
orange-crow Dec 21, 2023
c43e2be
update condition for DebugCode.
orange-crow Dec 21, 2023
d72b457
Merge branch 'dev' into dev_make_tools
orange-crow Dec 21, 2023
1160f07
update reset.
orange-crow Dec 21, 2023
b716c6d
Merge branch 'generalize' into 'dev'
garylin2099 Dec 21, 2023
4700000
Merge branch 'dev' into dev_make_tools
orange-crow Dec 21, 2023
82dce58
update DEFAULT_SYSTEM_MSG.
orange-crow Dec 21, 2023
e8f5ce0
update use_udfs.
orange-crow Dec 21, 2023
94b352c
update MakeTools DEFAULT_SYSTEM_MSG.
orange-crow Dec 21, 2023
6d36511
update make tools: code -> remove_comments(code).
orange-crow Dec 21, 2023
01fe23b
update ml ops
Dec 21, 2023
bb7f4c3
update code prompt for make tools.
orange-crow Dec 21, 2023
e0903fe
refine ml prompt
Dec 21, 2023
7806013
update: use WriteCodeByGenerate conditions.
orange-crow Dec 22, 2023
5ff1a74
Merge branch 'dev_tool_selection_new' into 'dev'
garylin2099 Dec 26, 2023
be47f61
resolve CR in MR17.
orange-crow Dec 26, 2023
b43cdb2
update make_tools.
orange-crow Dec 26, 2023
b49db2d
resolve cr in MR17.
orange-crow Dec 26, 2023
c76c176
Merge branch 'dev' into 'dev_make_tools'
orange-crow Dec 26, 2023
a2743d2
resolve cr in MR17.
orange-crow Dec 26, 2023
a51e5d7
Merge branch 'dev_make_tools' of https://gitlab.deepwisdomai.com/agen…
orange-crow Dec 26, 2023
a93173d
Merge branch 'dev_make_tools' into 'dev'
garylin2099 Dec 26, 2023
263595b
support load tools from file or file list
Dec 27, 2023
fe6e46d
Merge branch 'load_tools' into 'dev'
garylin2099 Dec 27, 2023
db4e334
general planner, code interpreter
garylin2099 Dec 28, 2023
0b6b3a0
support plan and act in role
garylin2099 Dec 28, 2023
fd9f241
add timeout and retry when code execution
Jan 9, 2024
851ec41
fix task type issue; add TaskResult data type
garylin2099 Jan 9, 2024
3eee6ef
drop retry
Jan 9, 2024
bbc23c3
Merge branch 'dev_code_exec_timeout' into 'dev'
garylin2099 Jan 10, 2024
7603a1a
Merge branch 'general_new' into 'dev'
garylin2099 Jan 10, 2024
8530869
Merge branch 'main' into dev_updated
garylin2099 Jan 10, 2024
767c993
format using precommit
garylin2099 Jan 10, 2024
4ec6151
format using precommit
garylin2099 Jan 10, 2024
cd990fd
code adapted to v0.6
garylin2099 Jan 10, 2024
3a31200
Merge branch 'dev_updated' into 'dev'
garylin2099 Jan 10, 2024
e12ab25
generalize write code with tools, simplify ml_engineer
garylin2099 Jan 10, 2024
4ecd427
formatting
garylin2099 Jan 10, 2024
437bbca
make tool ask review
garylin2099 Jan 11, 2024
17aeb9f
formatting
garylin2099 Jan 11, 2024
9e0b974
default tool_config and module_name
garylin2099 Jan 11, 2024
e56caa6
update
stellaHSR Jan 11, 2024
a98edad
增加非异步接口
stellaHSR Jan 11, 2024
af26fe0
update debug_code ut
stellaHSR Jan 11, 2024
3be26cf
add sd ut
stellaHSR Jan 11, 2024
12bc010
add asyn sd ut
stellaHSR Jan 11, 2024
e99c5f2
tool management at one place, add aask_code mock, azure mock
garylin2099 Jan 11, 2024
39915ec
add comments to clarify tool_type prompts
garylin2099 Jan 12, 2024
45e2d6c
Merge branch 'tool_manage' into 'code_intepreter'
garylin2099 Jan 12, 2024
9946280
update locally
stellaHSR Jan 12, 2024
a957538
update test for write_code_with_tools
Jan 12, 2024
99675a5
add unittest and remove old code
Jan 12, 2024
8827048
fix libs path
garylin2099 Jan 12, 2024
a46d3d5
Merge branch 'tool_manage' into 'code_intepreter'
garylin2099 Jan 12, 2024
75134d2
Merge branch 'code_intepreter' of https://gitlab.deepwisdomai.com/age…
stellaHSR Jan 12, 2024
d06dc0f
Merge branch 'code_intepreter' of https://gitlab.deepwisdomai.com/age…
stellaHSR Jan 12, 2024
192e2aa
Merge branch 'code_intepreter' into sd_and_debugcode_ut
stellaHSR Jan 12, 2024
13010f6
add async function for sd tool
stellaHSR Jan 12, 2024
d9ad3a6
update
stellaHSR Jan 12, 2024
3fded9b
fix timeout
Jan 12, 2024
40f5d5e
add vision tool for code_interpreter
mannaandpoem Jan 12, 2024
e079b8b
remove sensitive and recover rsp_cache.json
garylin2099 Jan 13, 2024
4b09ffd
pre-commit format
garylin2099 Jan 13, 2024
4a28d66
Merge branch 'sd_and_debugcode_ut' into 'code_intepreter'
garylin2099 Jan 13, 2024
4eb366c
Merge branch 'add_test_for_ml_tools' into 'code_intepreter'
garylin2099 Jan 13, 2024
932a26c
update unittest
Jan 15, 2024
7f0c752
Merge branch 'fix_code_timeout' into 'code_intepreter'
garylin2099 Jan 15, 2024
f45a368
1. add vision config in config.yaml
mannaandpoem Jan 15, 2024
2678413
update config.yaml
mannaandpoem Jan 15, 2024
23fdf90
Merge branch 'code_intepreter' into code_intepreter_add_vision
mannaandpoem Jan 15, 2024
38929dc
update imitate_webpage.py
mannaandpoem Jan 15, 2024
9eee30b
update config.yaml and vision.py for configuration of vision
mannaandpoem Jan 15, 2024
841f69d
update config.yaml and vision.py for configuration of vision
mannaandpoem Jan 15, 2024
4671a03
Merge remote-tracking branch 'origin/code_intepreter_add_vision' into…
mannaandpoem Jan 15, 2024
c927991
update get_choice_function_arguments.
orange-crow Jan 15, 2024
bb356fb
update truncate.
orange-crow Jan 15, 2024
ec07513
support for markdown.
orange-crow Jan 15, 2024
b69f2be
delete type.
orange-crow Jan 15, 2024
4f93c5f
add only_code arg for WriteCodeByGenerate.
orange-crow Jan 15, 2024
7f1584d
1. add test_vision.py
mannaandpoem Jan 15, 2024
00f7f93
add scrape_web.
orange-crow Jan 15, 2024
75628ca
add scrape_web.py
orange-crow Jan 15, 2024
a7e0888
update scrape_web docstring.
orange-crow Jan 15, 2024
66db86a
update test_vision.py for mock
mannaandpoem Jan 15, 2024
559a160
restore.
orange-crow Jan 15, 2024
b430e2c
update scrape_web module.
orange-crow Jan 15, 2024
d1666c3
update get_choice_function_arguments.
orange-crow Jan 15, 2024
f9b1cce
update code-intepreter by auto aask.
orange-crow Jan 15, 2024
29fd711
update module.
orange-crow Jan 16, 2024
eef77d1
display markdown.
orange-crow Jan 16, 2024
95ce190
feature: display markdown content.
orange-crow Jan 16, 2024
43558c2
doc: add ipywidgets.
orange-crow Jan 16, 2024
42a106c
Merge branch 'code_intepreter_add_vision' into 'code_intepreter'
garylin2099 Jan 17, 2024
ff10c9b
change name: _display_markdown -> display_markdown.
orange-crow Jan 17, 2024
20f31fa
pre-commit.
orange-crow Jan 17, 2024
02a81ab
Merge branch 'code_intepreter' into 'update-code-intepreter-by-auto-a…
orange-crow Jan 18, 2024
10129c6
update scrape_web.
orange-crow Jan 18, 2024
f3612f8
add only_code arg for WriteCodeByGenerate.
orange-crow Jan 18, 2024
d78db89
delete arg only_code.
orange-crow Jan 18, 2024
224bf82
Merge branch 'update-code-intepreter-by-auto-aask' into 'code_intepre…
garylin2099 Jan 18, 2024
46cd219
add tool registry
garylin2099 Jan 12, 2024
d7ab4d3
renaming and integrate sd tool, fix import issue
garylin2099 Jan 13, 2024
c8da839
moving files
garylin2099 Jan 15, 2024
638dda3
add unit tests for tool registry
garylin2099 Jan 15, 2024
8a14dde
tool_type renaming
garylin2099 Jan 16, 2024
c8858cd
minimize ml_engineer
garylin2099 Jan 16, 2024
9dc421b
rename schema to schemas to avoid pydantic warning
garylin2099 Jan 16, 2024
1cabf2c
change register arg name, integrate image2web tool
garylin2099 Jan 18, 2024
c32dcca
fix schema reading bug
garylin2099 Jan 18, 2024
88c4c8c
integrate web scraping tool
garylin2099 Jan 18, 2024
3faa094
fix aask_code issues in ml_engineer
garylin2099 Jan 18, 2024
23fccdd
update mock llm aask_code
garylin2099 Jan 18, 2024
c7d46d0
Merge branch 'tool_manage_new' into 'code_intepreter'
garylin2099 Jan 18, 2024
06b35a3
fix bug of save file and update prompt for gpt_v_generator tool
mannaandpoem Jan 19, 2024
c6695a3
fix: keep same return value in get_choice_function_arguments.
orange-crow Jan 19, 2024
c4a60d8
make tool yaml from class or func docstring
garylin2099 Jan 19, 2024
2ccfe31
unittest for tool convert
garylin2099 Jan 19, 2024
5405428
allow select tool at role initialization & restructure writecodewitht…
garylin2099 Jan 20, 2024
9661c3c
update IMAGE2WEBPAGE_PROMPT for gpt_v_generator tool
mannaandpoem Jan 22, 2024
e1a37ca
Merge branch 'code_intepreter_fix_gpt_v_generator' into 'code_intepre…
garylin2099 Jan 22, 2024
8084fca
change default value of language_value.
orange-crow Jan 22, 2024
8ed51b1
Merge branch 'fix-openai-return-bug' into 'code_intepreter'
garylin2099 Jan 22, 2024
0f245f5
logging
garylin2099 Jan 22, 2024
5ddaaaa
add test: test_get_choice_function_arguments_for_aask_code.
orange-crow Jan 22, 2024
9b3987f
add docstring parser
garylin2099 Jan 22, 2024
33e13b6
typo
garylin2099 Jan 22, 2024
6cb2910
fix: now present the results of failure and success code in different…
orange-crow Jan 22, 2024
c96b517
add test.
orange-crow Jan 22, 2024
1793a5f
update function_rsps.
orange-crow Jan 22, 2024
64a296a
update logger warning for JSONDecodeError.
orange-crow Jan 22, 2024
7f5f95d
Merge branch 'tool_manage_new' into 'code_intepreter'
garylin2099 Jan 22, 2024
3bfd0c8
update truncate.
orange-crow Jan 22, 2024
1bf9e02
add new test.
orange-crow Jan 22, 2024
0ad3de6
update _process_code.
orange-crow Jan 22, 2024
93538cc
Merge branch 'add-test-for-aask_code-executecode' into 'code_intepreter'
garylin2099 Jan 22, 2024
987eb6d
fix: now support parsing code in message.content when using tools_call.
orange-crow Jan 23, 2024
31813f2
add new test for tool_calls_rsp.
orange-crow Jan 23, 2024
a06d802
update CodeParser.parse_code.
orange-crow Jan 23, 2024
cff4eff
update CodeParser.parse_code.
orange-crow Jan 23, 2024
0cc0a16
add new test for tool_calls_rsp.
orange-crow Jan 23, 2024
bcda7ac
add comments for openai tools_call respond bug.
orange-crow Jan 23, 2024
519f22f
update CodeInterpreter._write_and_exec_code
orange-crow Jan 23, 2024
2d9a6c3
Merge branch 'fix-openai-tools_call-respond-bug' into 'code_intepreter'
garylin2099 Jan 23, 2024
d60a4c1
Merge branch 'update-CodeInterpreter._write_and_exec_code' into 'code…
garylin2099 Jan 23, 2024
ff5e7de
add strip for result.
orange-crow Jan 24, 2024
dfe49a3
update return value.
orange-crow Jan 24, 2024
3f2b512
new file: tests/metagpt/tools/libs/test_web_scraping.py
orange-crow Jan 24, 2024
0c8a844
add strip for result.
orange-crow Jan 24, 2024
0353f36
new file: examples/crawle_webpage.py
orange-crow Jan 24, 2024
f1a4197
rm make tools in ci for now
garylin2099 Jan 25, 2024
5f62484
Merge branch 'tool_manage_new' into 'code_intepreter'
garylin2099 Jan 25, 2024
526025b
change file name: crawle_webpage.py -> crawl_webpage.py
orange-crow Jan 25, 2024
54a0874
chore
orange-crow Jan 25, 2024
1fb7712
Merge branch 'add-web-scraping-test' into 'code_intepreter'
garylin2099 Jan 25, 2024
7aa89a3
minor update
garylin2099 Jan 25, 2024
606f1b8
accept goal during run; move more logic from role to planner
garylin2099 Jan 30, 2024
31a9410
Merge branch 'tool_manage_new' into 'code_intepreter'
garylin2099 Jan 30, 2024
4a7929d
rm immature code, improve naming, add unittest test rsp cache
garylin2099 Jan 30, 2024
ede04f2
fix test_write_analysis_code
garylin2099 Jan 30, 2024
274747e
fix test_debug_code
garylin2099 Jan 30, 2024
5dde5a8
rm unused & format
garylin2099 Jan 30, 2024
a8b4dfb
Merge branch 'add_unittest' into 'code_intepreter'
garylin2099 Jan 30, 2024
2fcb2a1
Merge branch 'dev' into code_intepreter
garylin2099 Jan 30, 2024
f9519ca
change ways of using config
garylin2099 Jan 30, 2024
56f5dc9
fix planner serialization bug, add test data
garylin2099 Jan 31, 2024
a9ef85b
add gptv config
garylin2099 Jan 31, 2024
7cead19
fix: add arg for OpenAILLM in test_get_choice_function_arguments_for_…
orange-crow Jan 31, 2024
56f640d
delete test_make_client_kwargs_without_proxy_azure.
orange-crow Jan 31, 2024
b8d0547
Merge branch 'update-test_get_choice_function_arguments_for_aask_code…
garylin2099 Jan 31, 2024
30de3b4
fix message init bug
garylin2099 Jan 31, 2024
b585064
rm redundant
garylin2099 Jan 31, 2024
d74dab9
update sd ut
stellaHSR Jan 31, 2024
7d38181
Merge branch 'code_intepreter' of https://gitlab.deepwisdomai.com/age…
stellaHSR Jan 31, 2024
28b0323
add package for test_sd_engine
stellaHSR Jan 31, 2024
c44d08c
rm config get in dev
stellaHSR Jan 31, 2024
a1b16b7
fix ml_engineer test
garylin2099 Jan 31, 2024
f8d69ed
Merge branch 'dev' into code_intepreter
garylin2099 Jan 31, 2024
487169e
rm mle_simple for now
garylin2099 Jan 31, 2024
b9663ce
fix parse_code bug.
orange-crow Jan 31, 2024
15e72ca
chore.
orange-crow Jan 31, 2024
df58d55
Merge branch 'fix-parse_code' into 'code_intepreter'
garylin2099 Jan 31, 2024
6656ebf
add ask_review, write plan, ci test
garylin2099 Jan 31, 2024
c3d4af6
rm unnecessary
garylin2099 Jan 31, 2024
37a606d
rm unfinished
garylin2099 Jan 31, 2024
ff970ab
Merge branch 'dev' into code_intepreter
garylin2099 Jan 31, 2024
45acde0
use pytest to mock, rm dependency
garylin2099 Feb 1, 2024
e85f749
Merge branch 'ci_sd_ut_new' into 'code_intepreter'
garylin2099 Feb 1, 2024
b1da79c
refine naming and some details
garylin2099 Feb 1, 2024
afb702c
Merge branch 'dev' into code_intepreter
garylin2099 Feb 1, 2024
2897981
task utils etc.
garylin2099 Feb 1, 2024
e7ae79b
Merge branch 'dev' into code_intepreter
garylin2099 Feb 1, 2024
4cd09e7
file read write utils
garylin2099 Feb 1, 2024
1a1610a
add more comments
garylin2099 Feb 1, 2024
35438e7
role pydantic init
garylin2099 Feb 2, 2024
f605fc4
Add type annotations, describe function return values, and remove unu…
orange-crow Feb 2, 2024
e71755e
add docstring
Feb 2, 2024
fab4d73
add optional flag
Feb 2, 2024
1da50f1
remove ToolTypesEnum
garylin2099 Feb 2, 2024
188f7aa
Remove unused code.
orange-crow Feb 2, 2024
29baea4
Merge branch 'fe_docstring' into 'code_intepreter'
garylin2099 Feb 2, 2024
c9f6b7c
1. merge run and run_reflection; 2. remove useless code
stellaHSR Feb 2, 2024
0336010
Merge branch 'code_intepreter' of https://gitlab.deepwisdomai.com/age…
garylin2099 Feb 2, 2024
32fb353
Merge branch 'update-execute_nb_code.py' into 'code_intepreter'
garylin2099 Feb 2, 2024
3894334
Merge branch 'code_intepreter' of https://gitlab.deepwisdomai.com/age…
garylin2099 Feb 2, 2024
4938896
rm yaml, add docstring
garylin2099 Feb 2, 2024
a74afd6
Merge branch 'ci_debugcode_modify' into 'code_intepreter'
garylin2099 Feb 2, 2024
6754d89
update ci cache
garylin2099 Feb 2, 2024
891e35b
Merge branch 'dev' into code_intepreter
garylin2099 Feb 2, 2024
c6ac7ef
fix web scrape init
garylin2099 Feb 2, 2024
2a096ad
rm unnecessary test datasets
garylin2099 Feb 2, 2024
3648669
fix test_ut_writer failure due to aask_code mock
garylin2099 Feb 4, 2024
24d2c5c
isolate codes to be restructured in the future
garylin2099 Feb 4, 2024
b7d0379
rm experimental code
garylin2099 Feb 4, 2024
d1deb0f
Remove _parse_arguments function and comment out handle_exception dec…
orange-crow Feb 4, 2024
4caa1ec
Revert CodeParser.parse_code function to version 0.6.6.
orange-crow Feb 4, 2024
4b912cc
update test.
orange-crow Feb 4, 2024
b4d032c
chore.
orange-crow Feb 4, 2024
321a4c0
rm redundant function and docstring in libs
garylin2099 Feb 4, 2024
55dac10
fix bug and update cache
garylin2099 Feb 4, 2024
4cfee3b
rm code steps, mv planner, mv ci mle
garylin2099 Feb 4, 2024
8c65ed0
rm redundant docstring
garylin2099 Feb 4, 2024
9af2508
Merge branch 'simplify_tools' into 'code_intepreter'
garylin2099 Feb 4, 2024
ca6749b
Merge branch 'del-_parse_arguments-in-openai_api.py' into code_intepr…
garylin2099 Feb 4, 2024
a609946
mv tool_type def
garylin2099 Feb 4, 2024
a35f536
raise error directly if invalid json
garylin2099 Feb 4, 2024
20393e9
rename tool type
garylin2099 Feb 5, 2024
748aabc
add future; rename writecodebygenerate tools
garylin2099 Feb 5, 2024
9343a6b
mv pip success logic, rm redundant prompt
garylin2099 Feb 5, 2024
4027043
improve details
garylin2099 Feb 5, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -178,3 +178,4 @@ cov.xml
*.faiss
*-structure.csv
*-structure.json
metagpt/tools/schemas
6 changes: 3 additions & 3 deletions metagpt/actions/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,9 @@
from metagpt.actions.write_prd import WritePRD
from metagpt.actions.write_prd_review import WritePRDReview
from metagpt.actions.write_test import WriteTest
from metagpt.actions.execute_nb_code import ExecuteNbCode
from metagpt.actions.write_analysis_code import WriteCodeByGenerate
from metagpt.actions.write_plan import WritePlan
from metagpt.actions.ci.execute_nb_code import ExecuteNbCode
from metagpt.actions.ci.write_analysis_code import WriteCodeByGenerate
from metagpt.actions.ci.write_plan import WritePlan


class ActionType(Enum):
Expand Down
File renamed without changes.
50 changes: 21 additions & 29 deletions metagpt/actions/debug_code.py → metagpt/actions/ci/debug_code.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from typing import List

from metagpt.actions.write_analysis_code import BaseWriteAnalysisCode
from metagpt.actions.ci.write_analysis_code import BaseWriteAnalysisCode
from metagpt.logs import logger
from metagpt.schema import Message
from metagpt.utils.common import create_func_call_config
Expand Down Expand Up @@ -47,7 +47,7 @@ def add(a: int, b: int) -> int:
[runtime Error]
{runtime_result}

Analysis the error step by step, provide me improve method and code. Remember to follow [context] rerquirement. Don't forget write code for steps behind the error step.
Analysis the error step by step, provide me improve method and code. Remember to follow [context] requirement. Don't forget write code for steps behind the error step.
[reflection on previous impl]:
xxx
"""
Expand All @@ -72,19 +72,25 @@ def add(a: int, b: int) -> int:
}


def messages_to_str(messages: List[Message]) -> str:
return "\n".join([str(message) for message in messages])
class DebugCode(BaseWriteAnalysisCode):
async def run(
self,
context: List[Message] = None,
code: str = "",
runtime_result: str = "",
) -> str:
"""
Execute the debugging process based on the provided context, code, and runtime_result.

Args:
context (List[Message]): A list of Message objects representing the context.
code (str): The code to be debugged.
runtime_result (str): The result of the code execution.

class DebugCode(BaseWriteAnalysisCode):
name: str = "debugcode"
Returns:
str: The improved implementation based on the debugging process.
"""

async def run_reflection(
self,
context: list[Message],
code: str,
runtime_result: str,
) -> dict:
info = []
reflection_prompt = REFLECTION_PROMPT.format(
debug_example=DEBUG_REFLECTION_EXAMPLE,
Expand All @@ -96,22 +102,8 @@ async def run_reflection(
info.append(Message(role="system", content=system_prompt))
info.append(Message(role="user", content=reflection_prompt))

resp = await self.llm.aask_code(messages=info, **create_func_call_config(CODE_REFLECTION))
logger.info(f"reflection is {resp}")
return resp
tool_config = create_func_call_config(CODE_REFLECTION)
reflection = await self.llm.aask_code(messages=info, **tool_config)
logger.info(f"reflection is {reflection}")

async def run(
self,
context: List[Message] = None,
code: str = "",
runtime_result: str = "",
) -> str:
"""
use reflection to debug, based on current code and the execution errors
"""
reflection = await self.run_reflection(
code=code,
context=context,
runtime_result=runtime_result,
)
return {"code": reflection["improved_impl"]}
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,7 @@
import base64
import re
import traceback
from pathlib import Path
from typing import Any, Dict, List, Tuple, Union
from typing import List, Literal, Tuple

import nbformat
from nbclient import NotebookClient
Expand All @@ -25,14 +24,13 @@

from metagpt.actions import Action
from metagpt.logs import logger
from metagpt.schema import Message


class ExecuteNbCode(Action):
"""execute notebook code block, return result to llm, and display it."""

nb: Any
nb_client: Any
nb: NotebookNode
nb_client: NotebookClient
console: Console
interaction: str
timeout: int = 600
Expand Down Expand Up @@ -70,13 +68,13 @@ async def reset(self):
await self.build()
self.nb_client = NotebookClient(self.nb, timeout=self.timeout)

def add_code_cell(self, code):
def add_code_cell(self, code: str):
self.nb.cells.append(new_code_cell(source=code))

def add_markdown_cell(self, markdown):
def add_markdown_cell(self, markdown: str):
self.nb.cells.append(new_markdown_cell(source=markdown))

def _display(self, code, language: str = "python"):
def _display(self, code: str, language: Literal["python", "markdown"] = "python"):
if language == "python":
code = Syntax(code, "python", theme="paraiso-dark", line_numbers=True)
self.console.print(code)
Expand All @@ -85,21 +83,18 @@ def _display(self, code, language: str = "python"):
else:
raise ValueError(f"Only support for python, markdown, but got {language}")

def add_output_to_cell(self, cell, output):
def add_output_to_cell(self, cell: NotebookNode, output: str):
"""add outputs of code execution to notebook cell."""
if "outputs" not in cell:
cell["outputs"] = []
# TODO: show figures
else:
cell["outputs"].append(new_output(output_type="stream", name="stdout", text=str(output)))

def parse_outputs(self, outputs: List) -> str:
def parse_outputs(self, outputs: List[str]) -> str:
"""Parses the outputs received from notebook execution."""
assert isinstance(outputs, list)
parsed_output = ""

# empty outputs: such as 'x=1\ny=2'
if not outputs:
return parsed_output

for i, output in enumerate(outputs):
if output["output_type"] == "stream" and not any(
tag in output["text"]
Expand All @@ -117,7 +112,7 @@ def parse_outputs(self, outputs: List) -> str:
parsed_output += output["data"]["text/plain"]
return parsed_output

def show_bytes_figure(self, image_base64: str, interaction_type: str = "ipython"):
def show_bytes_figure(self, image_base64: str, interaction_type: Literal["ipython", None]):
image_bytes = base64.b64decode(image_base64)
if interaction_type == "ipython":
from IPython.display import Image, display
Expand All @@ -141,25 +136,12 @@ def is_ipython(self) -> bool:
else:
return False
except NameError:
# 如果在Python脚本中运行,__file__ 变量存在
return False

def _process_code(self, code: Union[str, Dict], language: str = "python") -> Tuple:
"""handle different code response formats, support str or dict"""
if isinstance(code, str) and Path(code).suffix in (".py", ".txt"):
code = Path(code).read_text(encoding="utf-8")
return code, language

if isinstance(code, str):
return code, language

if isinstance(code, dict):
assert "code" in code
code = code["code"]
return code, language

async def run_cell(self, cell: NotebookNode, cell_index: int) -> Tuple[bool, str]:
"""set timeout for run code"""
"""set timeout for run code.
returns the success or failure of the cell execution, and an optional error message.
"""
try:
await self.nb_client.async_execute_cell(cell, cell_index)
return True, ""
Expand All @@ -175,9 +157,10 @@ async def run_cell(self, cell: NotebookNode, cell_index: int) -> Tuple[bool, str
except Exception:
return False, f"{traceback.format_exc()}"

async def run(self, code: Union[str, Dict, Message], language: str = "python") -> Tuple[str, bool]:
code, language = self._process_code(code, language)

async def run(self, code: str, language: Literal["python", "markdown"] = "python") -> Tuple[str, bool]:
"""
return the output of code execution, and a success indicator (bool) of code execution.
"""
self._display(code, language)

if language == "python":
Expand All @@ -198,8 +181,9 @@ async def run(self, code: Union[str, Dict, Message], language: str = "python") -
outputs = self.parse_outputs(self.nb.cells[-1].outputs)
return truncate(remove_escape_and_color_codes(outputs), is_success=success)
elif language == "markdown":
# markdown
# add markdown content to markdown cell in a notebook.
self.add_markdown_cell(code)
# return True, beacuse there is no execution failure for markdown cell.
return code, True
else:
raise ValueError(f"Only support for language: python, markdown, but got {language}, ")
Expand Down Expand Up @@ -230,7 +214,7 @@ def truncate(result: str, keep_len: int = 2000, is_success: bool = True):
return result if not is_same_desc else desc + result, is_success


def remove_escape_and_color_codes(input_str):
def remove_escape_and_color_codes(input_str: str):
# 使用正则表达式去除转义字符和颜色代码
pattern = re.compile(r"\x1b\[[0-9;]*[mK]")
result = pattern.sub("", input_str)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
from typing import List, Tuple

from metagpt.actions import Action
from metagpt.actions.write_analysis_code import WriteCodeWithTools
from metagpt.prompts.ml_action import (
from metagpt.actions.ci.write_analysis_code import WriteCodeWithTools
from metagpt.prompts.ci.ml_action import (
GENERATE_CODE_PROMPT,
ML_TOOL_USAGE_PROMPT,
PRINT_DATA_COLUMNS,
UPDATE_DATA_COLUMNS,
)
from metagpt.prompts.write_analysis_code import CODE_GENERATOR_WITH_TOOLS
from metagpt.prompts.ci.write_analysis_code import CODE_GENERATOR_WITH_TOOLS
from metagpt.schema import Message, Plan
from metagpt.utils.common import create_func_call_config, remove_comments

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,17 @@
@Author : orange-crow
@File : write_analysis_code.py
"""
from typing import Dict, Tuple, Union
from typing import Tuple

from metagpt.actions import Action
from metagpt.logs import logger
from metagpt.prompts.write_analysis_code import (
from metagpt.prompts.ci.write_analysis_code import (
CODE_GENERATOR_WITH_TOOLS,
SELECT_FUNCTION_TOOLS,
TOOL_RECOMMENDATION_PROMPT,
TOOL_USAGE_PROMPT,
)
from metagpt.schema import Message, Plan
from metagpt.schema import Message, Plan, SystemMessage
from metagpt.tools import TOOL_REGISTRY
from metagpt.tools.tool_registry import validate_tool_names
from metagpt.utils.common import create_func_call_config
Expand All @@ -24,34 +24,10 @@ class BaseWriteAnalysisCode(Action):
DEFAULT_SYSTEM_MSG: str = """You are Code Interpreter, a world-class programmer that can complete any goal by executing code. Strictly follow the plan and generate code step by step. Each step of the code will be executed on the user's machine, and the user will provide the code execution results to you.**Notice: The code for the next step depends on the code for the previous step. Must reuse variables in the lastest other code directly, dont creat it again, it is very import for you. Use !pip install in a standalone block to install missing packages.Usually the libraries you need are already installed.Dont check if packages already imported.**""" # prompt reference: https://github.com/KillianLucas/open-interpreter/blob/v0.1.4/interpreter/system_message.txt
# REUSE_CODE_INSTRUCTION = """ATTENTION: DONT include codes from previous tasks in your current code block, include new codes only, DONT repeat codes!"""

def process_msg(self, prompt: Union[str, list[Dict], Message, list[Message]], system_msg: str = None):
default_system_msg = system_msg or self.DEFAULT_SYSTEM_MSG
# 全部转成list
if not isinstance(prompt, list):
prompt = [prompt]
assert isinstance(prompt, list)
# 转成list[dict]
messages = []
for p in prompt:
if isinstance(p, str):
messages.append({"role": "user", "content": p})
elif isinstance(p, dict):
messages.append(p)
elif isinstance(p, Message):
if isinstance(p.content, str):
messages.append(p.to_dict())
elif isinstance(p.content, dict) and "code" in p.content:
messages.append(p.content["code"])

# 添加默认的提示词
if default_system_msg not in messages[0]["content"] and messages[0]["role"] != "system":
messages.insert(0, {"role": "system", "content": default_system_msg})
elif default_system_msg not in messages[0]["content"] and messages[0]["role"] == "system":
messages[0] = {
"role": "system",
"content": messages[0]["content"] + default_system_msg,
}
return messages
def insert_system_message(self, context: list[Message], system_msg: str = None):
system_msg = system_msg or self.DEFAULT_SYSTEM_MSG
context.insert(0, SystemMessage(content=system_msg)) if context[0].role != "system" else None
return context

async def run(self, context: list[Message], plan: Plan = None) -> dict:
"""Run of a code writing action, used in data analysis or modeling
Expand All @@ -69,16 +45,9 @@ async def run(self, context: list[Message], plan: Plan = None) -> dict:
class WriteCodeByGenerate(BaseWriteAnalysisCode):
"""Ask LLM to generate codes purely by itself without local user-defined tools"""

async def run(
self,
context: [list[Message]],
plan: Plan = None,
system_msg: str = None,
**kwargs,
) -> dict:
# context.append(Message(content=self.REUSE_CODE_INSTRUCTION, role="user"))
prompt = self.process_msg(context, system_msg)
rsp = await self.llm.aask_code(prompt, **kwargs)
async def run(self, context: list[Message], plan: Plan = None, system_msg: str = None, **kwargs) -> dict:
messages = self.insert_system_message(context, system_msg)
rsp = await self.llm.aask_code(messages, **kwargs)
return rsp


Expand Down Expand Up @@ -184,7 +153,7 @@ async def run(
context.append(Message(content=tools_instruction, role="user"))

# prepare prompt & LLM call
prompt = self.process_msg(context)
prompt = self.insert_system_message(context)
tool_config = create_func_call_config(CODE_GENERATOR_WITH_TOOLS)
rsp = await self.llm.aask_code(prompt, **tool_config)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@

from metagpt.actions import Action
from metagpt.logs import logger
from metagpt.prompts.write_analysis_code import (
from metagpt.prompts.ci.write_analysis_code import (
ASSIGN_TASK_TYPE_CONFIG,
ASSIGN_TASK_TYPE_PROMPT,
)
Expand Down
4 changes: 2 additions & 2 deletions metagpt/plan/planner.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@

from pydantic import BaseModel, Field

from metagpt.actions.ask_review import AskReview, ReviewConst
from metagpt.actions.write_plan import (
from metagpt.actions.ci.ask_review import AskReview, ReviewConst
from metagpt.actions.ci.write_plan import (
WritePlan,
precheck_update_plan_from_rsp,
update_plan_from_rsp,
Expand Down
File renamed without changes.
2 changes: 1 addition & 1 deletion metagpt/provider/openai_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
from metagpt.provider.constant import GENERAL_FUNCTION_SCHEMA
from metagpt.provider.llm_provider_registry import register_provider
from metagpt.schema import Message
from metagpt.utils.common import CodeParser
from metagpt.utils.common import CodeParser, decode_image
from metagpt.utils.cost_manager import CostManager, Costs
from metagpt.utils.exceptions import handle_exception
from metagpt.utils.token_counter import (
Expand Down
Loading
Loading