You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

code_utils.py 29 kB

Code executors (#1405) * code executor * test * revert to main conversable agent * prepare for pr * kernel * run open ai tests only when it's out of draft status * update workflow file * revert workflow changes * ipython executor * check kernel installed; fix tests * fix tests * fix tests * update system prompt * Update notebook, more tests * notebook * raise instead of return None * allow user provided code executor. * fixing types * wip * refactoring * polishing * fixed failing tests * resolved merge conflict * fixing failing test * wip * local command line executor and embedded ipython executor * revert notebook * fix format * fix merged error * fix lmm test * fix lmm test * move warning * name and description should be part of the agent protocol, reset is not as it is only used for ConversableAgent; removing accidentally commited file * version for dependency * Update autogen/agentchat/conversable_agent.py Co-authored-by: Jack Gerrits <jackgerrits@users.noreply.github.com> * ordering of protocol * description * fix tests * make ipython executor dependency optional * update document optional dependencies * Remove exclude from Agent protocol * Make ConversableAgent consistent with Agent * fix tests * add doc string * add doc string * fix notebook * fix interface * merge and update agents * disable config usage in reply function * description field setter * customize system message update * update doc --------- Co-authored-by: Davor Runje <davor@airt.ai> Co-authored-by: Jack Gerrits <jackgerrits@users.noreply.github.com> Co-authored-by: Aaron <aaronlaptop12@hotmail.com> Co-authored-by: Chi Wang <wang.chi@microsoft.com>
2 years ago
2 years ago
raise error when msg is invalid; fix docstr; improve ResponsiveAgent; update doc and packaging; capture ipython output; find code blocks with llm when regex fails. (#1154) * autogen.agent -> autogen.agentchat * bug fix in portfolio * notebook * timeout * timeout * infer lang; close #1150 * timeout * message context * context handling * add sender to generate_reply * clean up the receive function * move mathchat to contrib * contrib * last_message * Add OptiGuide: agent and notebook * Optiguide notebook: add figures and URL 1. figures and code points to remote URL 2. simplify the prompt for the interpreter, because all information is already in the chat history. * Update name: Agent -> GenericAgent * Update notebook * Rename: GenericAgent -> ResponsiveAgent * Rebase to autogen.agentchat * OptiGuide: Comment, sytle, and notebook updates * simplify optiguide * raise error when msg is invalid; fix docstr * allow return None for generate_reply() * update_system_message * test update_system_message * simplify optiguide * simplify optiguide * simplify optiguide * simplify optiguide * move test * add test and fix bug * doc update * doc update * doc update * color * optiguide * prompt * test danger case * packaging * docker * remove path in traceback * capture ipython output * simplify * find code blocks with llm * find code with llm * order * order * fix bug in context handling * print executing msg * print executing msg * test find code * test find code * disable find_code * default_auto_reply * default auto reply * remove optiguide * remove -e --------- Co-authored-by: Beibin Li <beibin79@gmail.com>
3 years ago
raise error when msg is invalid; fix docstr; improve ResponsiveAgent; update doc and packaging; capture ipython output; find code blocks with llm when regex fails. (#1154) * autogen.agent -> autogen.agentchat * bug fix in portfolio * notebook * timeout * timeout * infer lang; close #1150 * timeout * message context * context handling * add sender to generate_reply * clean up the receive function * move mathchat to contrib * contrib * last_message * Add OptiGuide: agent and notebook * Optiguide notebook: add figures and URL 1. figures and code points to remote URL 2. simplify the prompt for the interpreter, because all information is already in the chat history. * Update name: Agent -> GenericAgent * Update notebook * Rename: GenericAgent -> ResponsiveAgent * Rebase to autogen.agentchat * OptiGuide: Comment, sytle, and notebook updates * simplify optiguide * raise error when msg is invalid; fix docstr * allow return None for generate_reply() * update_system_message * test update_system_message * simplify optiguide * simplify optiguide * simplify optiguide * simplify optiguide * move test * add test and fix bug * doc update * doc update * doc update * color * optiguide * prompt * test danger case * packaging * docker * remove path in traceback * capture ipython output * simplify * find code blocks with llm * find code with llm * order * order * fix bug in context handling * print executing msg * print executing msg * test find code * test find code * disable find_code * default_auto_reply * default auto reply * remove optiguide * remove -e --------- Co-authored-by: Beibin Li <beibin79@gmail.com>
3 years ago
Agent notebook example with human feedback; Support shell command and multiple code blocks; Improve the system message for assistant agent; Improve utility functions for config lists; reuse docker image (#1056) * add agent notebook and documentation * fix bug * set flush to True when printing msg in agent * add a math problem in agent notebook * remove * header * improve notebook doc * notebook update * improve notebook example * improve doc * agent notebook example with user feedback * log * log * improve notebook doc * improve print * doc * human_input_mode * human_input_mode str * indent * indent * Update flaml/autogen/agent/user_proxy_agent.py Co-authored-by: Chi Wang <wang.chi@microsoft.com> * shell command and multiple code blocks * Update notebook/autogen_agent.ipynb Co-authored-by: Chi Wang <wang.chi@microsoft.com> * Update notebook/autogen_agent.ipynb Co-authored-by: Chi Wang <wang.chi@microsoft.com> * Update notebook/autogen_agent.ipynb Co-authored-by: Chi Wang <wang.chi@microsoft.com> * coding agent * math notebook * renaming and doc format * typo * infer lang * sh * docker * docker * reset consecutive autoreply counter * fix explanation * paper talk * human feedback * web info * rename test * config list explanation * link to blogpost * installation * homepage features * features * features * rename agent * remove notebook * notebook test * docker command * notebook update * lang -> cmd * notebook * make it work for gpt-3.5 * return full log * quote * docker * docker * docker * docker * docker * docker image list * notebook * notebook * use_docker * use_docker * use_docker * doc * agent * doc * abs path * pandas * docker * reuse docker image * context window * news * print format * pyspark version in py3.8 * pyspark in py3.8 * pyspark and ray * quote * pyspark * pyspark * pyspark --------- Co-authored-by: Qingyun Wu <qingyun.wu@psu.edu>
3 years ago
raise error when msg is invalid; fix docstr; improve ResponsiveAgent; update doc and packaging; capture ipython output; find code blocks with llm when regex fails. (#1154) * autogen.agent -> autogen.agentchat * bug fix in portfolio * notebook * timeout * timeout * infer lang; close #1150 * timeout * message context * context handling * add sender to generate_reply * clean up the receive function * move mathchat to contrib * contrib * last_message * Add OptiGuide: agent and notebook * Optiguide notebook: add figures and URL 1. figures and code points to remote URL 2. simplify the prompt for the interpreter, because all information is already in the chat history. * Update name: Agent -> GenericAgent * Update notebook * Rename: GenericAgent -> ResponsiveAgent * Rebase to autogen.agentchat * OptiGuide: Comment, sytle, and notebook updates * simplify optiguide * raise error when msg is invalid; fix docstr * allow return None for generate_reply() * update_system_message * test update_system_message * simplify optiguide * simplify optiguide * simplify optiguide * simplify optiguide * move test * add test and fix bug * doc update * doc update * doc update * color * optiguide * prompt * test danger case * packaging * docker * remove path in traceback * capture ipython output * simplify * find code blocks with llm * find code with llm * order * order * fix bug in context handling * print executing msg * print executing msg * test find code * test find code * disable find_code * default_auto_reply * default auto reply * remove optiguide * remove -e --------- Co-authored-by: Beibin Li <beibin79@gmail.com>
3 years ago
Code executors (#1405) * code executor * test * revert to main conversable agent * prepare for pr * kernel * run open ai tests only when it's out of draft status * update workflow file * revert workflow changes * ipython executor * check kernel installed; fix tests * fix tests * fix tests * update system prompt * Update notebook, more tests * notebook * raise instead of return None * allow user provided code executor. * fixing types * wip * refactoring * polishing * fixed failing tests * resolved merge conflict * fixing failing test * wip * local command line executor and embedded ipython executor * revert notebook * fix format * fix merged error * fix lmm test * fix lmm test * move warning * name and description should be part of the agent protocol, reset is not as it is only used for ConversableAgent; removing accidentally commited file * version for dependency * Update autogen/agentchat/conversable_agent.py Co-authored-by: Jack Gerrits <jackgerrits@users.noreply.github.com> * ordering of protocol * description * fix tests * make ipython executor dependency optional * update document optional dependencies * Remove exclude from Agent protocol * Make ConversableAgent consistent with Agent * fix tests * add doc string * add doc string * fix notebook * fix interface * merge and update agents * disable config usage in reply function * description field setter * customize system message update * update doc --------- Co-authored-by: Davor Runje <davor@airt.ai> Co-authored-by: Jack Gerrits <jackgerrits@users.noreply.github.com> Co-authored-by: Aaron <aaronlaptop12@hotmail.com> Co-authored-by: Chi Wang <wang.chi@microsoft.com>
2 years ago
Agent notebook example with human feedback; Support shell command and multiple code blocks; Improve the system message for assistant agent; Improve utility functions for config lists; reuse docker image (#1056) * add agent notebook and documentation * fix bug * set flush to True when printing msg in agent * add a math problem in agent notebook * remove * header * improve notebook doc * notebook update * improve notebook example * improve doc * agent notebook example with user feedback * log * log * improve notebook doc * improve print * doc * human_input_mode * human_input_mode str * indent * indent * Update flaml/autogen/agent/user_proxy_agent.py Co-authored-by: Chi Wang <wang.chi@microsoft.com> * shell command and multiple code blocks * Update notebook/autogen_agent.ipynb Co-authored-by: Chi Wang <wang.chi@microsoft.com> * Update notebook/autogen_agent.ipynb Co-authored-by: Chi Wang <wang.chi@microsoft.com> * Update notebook/autogen_agent.ipynb Co-authored-by: Chi Wang <wang.chi@microsoft.com> * coding agent * math notebook * renaming and doc format * typo * infer lang * sh * docker * docker * reset consecutive autoreply counter * fix explanation * paper talk * human feedback * web info * rename test * config list explanation * link to blogpost * installation * homepage features * features * features * rename agent * remove notebook * notebook test * docker command * notebook update * lang -> cmd * notebook * make it work for gpt-3.5 * return full log * quote * docker * docker * docker * docker * docker * docker image list * notebook * notebook * use_docker * use_docker * use_docker * doc * agent * doc * abs path * pandas * docker * reuse docker image * context window * news * print format * pyspark version in py3.8 * pyspark in py3.8 * pyspark and ray * quote * pyspark * pyspark * pyspark --------- Co-authored-by: Qingyun Wu <qingyun.wu@psu.edu>
3 years ago
Agent notebook example with human feedback; Support shell command and multiple code blocks; Improve the system message for assistant agent; Improve utility functions for config lists; reuse docker image (#1056) * add agent notebook and documentation * fix bug * set flush to True when printing msg in agent * add a math problem in agent notebook * remove * header * improve notebook doc * notebook update * improve notebook example * improve doc * agent notebook example with user feedback * log * log * improve notebook doc * improve print * doc * human_input_mode * human_input_mode str * indent * indent * Update flaml/autogen/agent/user_proxy_agent.py Co-authored-by: Chi Wang <wang.chi@microsoft.com> * shell command and multiple code blocks * Update notebook/autogen_agent.ipynb Co-authored-by: Chi Wang <wang.chi@microsoft.com> * Update notebook/autogen_agent.ipynb Co-authored-by: Chi Wang <wang.chi@microsoft.com> * Update notebook/autogen_agent.ipynb Co-authored-by: Chi Wang <wang.chi@microsoft.com> * coding agent * math notebook * renaming and doc format * typo * infer lang * sh * docker * docker * reset consecutive autoreply counter * fix explanation * paper talk * human feedback * web info * rename test * config list explanation * link to blogpost * installation * homepage features * features * features * rename agent * remove notebook * notebook test * docker command * notebook update * lang -> cmd * notebook * make it work for gpt-3.5 * return full log * quote * docker * docker * docker * docker * docker * docker image list * notebook * notebook * use_docker * use_docker * use_docker * doc * agent * doc * abs path * pandas * docker * reuse docker image * context window * news * print format * pyspark version in py3.8 * pyspark in py3.8 * pyspark and ray * quote * pyspark * pyspark * pyspark --------- Co-authored-by: Qingyun Wu <qingyun.wu@psu.edu>
3 years ago
Agent notebook example with human feedback; Support shell command and multiple code blocks; Improve the system message for assistant agent; Improve utility functions for config lists; reuse docker image (#1056) * add agent notebook and documentation * fix bug * set flush to True when printing msg in agent * add a math problem in agent notebook * remove * header * improve notebook doc * notebook update * improve notebook example * improve doc * agent notebook example with user feedback * log * log * improve notebook doc * improve print * doc * human_input_mode * human_input_mode str * indent * indent * Update flaml/autogen/agent/user_proxy_agent.py Co-authored-by: Chi Wang <wang.chi@microsoft.com> * shell command and multiple code blocks * Update notebook/autogen_agent.ipynb Co-authored-by: Chi Wang <wang.chi@microsoft.com> * Update notebook/autogen_agent.ipynb Co-authored-by: Chi Wang <wang.chi@microsoft.com> * Update notebook/autogen_agent.ipynb Co-authored-by: Chi Wang <wang.chi@microsoft.com> * coding agent * math notebook * renaming and doc format * typo * infer lang * sh * docker * docker * reset consecutive autoreply counter * fix explanation * paper talk * human feedback * web info * rename test * config list explanation * link to blogpost * installation * homepage features * features * features * rename agent * remove notebook * notebook test * docker command * notebook update * lang -> cmd * notebook * make it work for gpt-3.5 * return full log * quote * docker * docker * docker * docker * docker * docker image list * notebook * notebook * use_docker * use_docker * use_docker * doc * agent * doc * abs path * pandas * docker * reuse docker image * context window * news * print format * pyspark version in py3.8 * pyspark in py3.8 * pyspark and ray * quote * pyspark * pyspark * pyspark --------- Co-authored-by: Qingyun Wu <qingyun.wu@psu.edu>
3 years ago
Agent notebook example with human feedback; Support shell command and multiple code blocks; Improve the system message for assistant agent; Improve utility functions for config lists; reuse docker image (#1056) * add agent notebook and documentation * fix bug * set flush to True when printing msg in agent * add a math problem in agent notebook * remove * header * improve notebook doc * notebook update * improve notebook example * improve doc * agent notebook example with user feedback * log * log * improve notebook doc * improve print * doc * human_input_mode * human_input_mode str * indent * indent * Update flaml/autogen/agent/user_proxy_agent.py Co-authored-by: Chi Wang <wang.chi@microsoft.com> * shell command and multiple code blocks * Update notebook/autogen_agent.ipynb Co-authored-by: Chi Wang <wang.chi@microsoft.com> * Update notebook/autogen_agent.ipynb Co-authored-by: Chi Wang <wang.chi@microsoft.com> * Update notebook/autogen_agent.ipynb Co-authored-by: Chi Wang <wang.chi@microsoft.com> * coding agent * math notebook * renaming and doc format * typo * infer lang * sh * docker * docker * reset consecutive autoreply counter * fix explanation * paper talk * human feedback * web info * rename test * config list explanation * link to blogpost * installation * homepage features * features * features * rename agent * remove notebook * notebook test * docker command * notebook update * lang -> cmd * notebook * make it work for gpt-3.5 * return full log * quote * docker * docker * docker * docker * docker * docker image list * notebook * notebook * use_docker * use_docker * use_docker * doc * agent * doc * abs path * pandas * docker * reuse docker image * context window * news * print format * pyspark version in py3.8 * pyspark in py3.8 * pyspark and ray * quote * pyspark * pyspark * pyspark --------- Co-authored-by: Qingyun Wu <qingyun.wu@psu.edu>
3 years ago
Agent notebook example with human feedback; Support shell command and multiple code blocks; Improve the system message for assistant agent; Improve utility functions for config lists; reuse docker image (#1056) * add agent notebook and documentation * fix bug * set flush to True when printing msg in agent * add a math problem in agent notebook * remove * header * improve notebook doc * notebook update * improve notebook example * improve doc * agent notebook example with user feedback * log * log * improve notebook doc * improve print * doc * human_input_mode * human_input_mode str * indent * indent * Update flaml/autogen/agent/user_proxy_agent.py Co-authored-by: Chi Wang <wang.chi@microsoft.com> * shell command and multiple code blocks * Update notebook/autogen_agent.ipynb Co-authored-by: Chi Wang <wang.chi@microsoft.com> * Update notebook/autogen_agent.ipynb Co-authored-by: Chi Wang <wang.chi@microsoft.com> * Update notebook/autogen_agent.ipynb Co-authored-by: Chi Wang <wang.chi@microsoft.com> * coding agent * math notebook * renaming and doc format * typo * infer lang * sh * docker * docker * reset consecutive autoreply counter * fix explanation * paper talk * human feedback * web info * rename test * config list explanation * link to blogpost * installation * homepage features * features * features * rename agent * remove notebook * notebook test * docker command * notebook update * lang -> cmd * notebook * make it work for gpt-3.5 * return full log * quote * docker * docker * docker * docker * docker * docker image list * notebook * notebook * use_docker * use_docker * use_docker * doc * agent * doc * abs path * pandas * docker * reuse docker image * context window * news * print format * pyspark version in py3.8 * pyspark in py3.8 * pyspark and ray * quote * pyspark * pyspark * pyspark --------- Co-authored-by: Qingyun Wu <qingyun.wu@psu.edu>
3 years ago
Agent notebook example with human feedback; Support shell command and multiple code blocks; Improve the system message for assistant agent; Improve utility functions for config lists; reuse docker image (#1056) * add agent notebook and documentation * fix bug * set flush to True when printing msg in agent * add a math problem in agent notebook * remove * header * improve notebook doc * notebook update * improve notebook example * improve doc * agent notebook example with user feedback * log * log * improve notebook doc * improve print * doc * human_input_mode * human_input_mode str * indent * indent * Update flaml/autogen/agent/user_proxy_agent.py Co-authored-by: Chi Wang <wang.chi@microsoft.com> * shell command and multiple code blocks * Update notebook/autogen_agent.ipynb Co-authored-by: Chi Wang <wang.chi@microsoft.com> * Update notebook/autogen_agent.ipynb Co-authored-by: Chi Wang <wang.chi@microsoft.com> * Update notebook/autogen_agent.ipynb Co-authored-by: Chi Wang <wang.chi@microsoft.com> * coding agent * math notebook * renaming and doc format * typo * infer lang * sh * docker * docker * reset consecutive autoreply counter * fix explanation * paper talk * human feedback * web info * rename test * config list explanation * link to blogpost * installation * homepage features * features * features * rename agent * remove notebook * notebook test * docker command * notebook update * lang -> cmd * notebook * make it work for gpt-3.5 * return full log * quote * docker * docker * docker * docker * docker * docker image list * notebook * notebook * use_docker * use_docker * use_docker * doc * agent * doc * abs path * pandas * docker * reuse docker image * context window * news * print format * pyspark version in py3.8 * pyspark in py3.8 * pyspark and ray * quote * pyspark * pyspark * pyspark --------- Co-authored-by: Qingyun Wu <qingyun.wu@psu.edu>
3 years ago
Agent notebook example with human feedback; Support shell command and multiple code blocks; Improve the system message for assistant agent; Improve utility functions for config lists; reuse docker image (#1056) * add agent notebook and documentation * fix bug * set flush to True when printing msg in agent * add a math problem in agent notebook * remove * header * improve notebook doc * notebook update * improve notebook example * improve doc * agent notebook example with user feedback * log * log * improve notebook doc * improve print * doc * human_input_mode * human_input_mode str * indent * indent * Update flaml/autogen/agent/user_proxy_agent.py Co-authored-by: Chi Wang <wang.chi@microsoft.com> * shell command and multiple code blocks * Update notebook/autogen_agent.ipynb Co-authored-by: Chi Wang <wang.chi@microsoft.com> * Update notebook/autogen_agent.ipynb Co-authored-by: Chi Wang <wang.chi@microsoft.com> * Update notebook/autogen_agent.ipynb Co-authored-by: Chi Wang <wang.chi@microsoft.com> * coding agent * math notebook * renaming and doc format * typo * infer lang * sh * docker * docker * reset consecutive autoreply counter * fix explanation * paper talk * human feedback * web info * rename test * config list explanation * link to blogpost * installation * homepage features * features * features * rename agent * remove notebook * notebook test * docker command * notebook update * lang -> cmd * notebook * make it work for gpt-3.5 * return full log * quote * docker * docker * docker * docker * docker * docker image list * notebook * notebook * use_docker * use_docker * use_docker * doc * agent * doc * abs path * pandas * docker * reuse docker image * context window * news * print format * pyspark version in py3.8 * pyspark in py3.8 * pyspark and ray * quote * pyspark * pyspark * pyspark --------- Co-authored-by: Qingyun Wu <qingyun.wu@psu.edu>
3 years ago
Agent notebook example with human feedback; Support shell command and multiple code blocks; Improve the system message for assistant agent; Improve utility functions for config lists; reuse docker image (#1056) * add agent notebook and documentation * fix bug * set flush to True when printing msg in agent * add a math problem in agent notebook * remove * header * improve notebook doc * notebook update * improve notebook example * improve doc * agent notebook example with user feedback * log * log * improve notebook doc * improve print * doc * human_input_mode * human_input_mode str * indent * indent * Update flaml/autogen/agent/user_proxy_agent.py Co-authored-by: Chi Wang <wang.chi@microsoft.com> * shell command and multiple code blocks * Update notebook/autogen_agent.ipynb Co-authored-by: Chi Wang <wang.chi@microsoft.com> * Update notebook/autogen_agent.ipynb Co-authored-by: Chi Wang <wang.chi@microsoft.com> * Update notebook/autogen_agent.ipynb Co-authored-by: Chi Wang <wang.chi@microsoft.com> * coding agent * math notebook * renaming and doc format * typo * infer lang * sh * docker * docker * reset consecutive autoreply counter * fix explanation * paper talk * human feedback * web info * rename test * config list explanation * link to blogpost * installation * homepage features * features * features * rename agent * remove notebook * notebook test * docker command * notebook update * lang -> cmd * notebook * make it work for gpt-3.5 * return full log * quote * docker * docker * docker * docker * docker * docker image list * notebook * notebook * use_docker * use_docker * use_docker * doc * agent * doc * abs path * pandas * docker * reuse docker image * context window * news * print format * pyspark version in py3.8 * pyspark in py3.8 * pyspark and ray * quote * pyspark * pyspark * pyspark --------- Co-authored-by: Qingyun Wu <qingyun.wu@psu.edu>
3 years ago
Agent notebook example with human feedback; Support shell command and multiple code blocks; Improve the system message for assistant agent; Improve utility functions for config lists; reuse docker image (#1056) * add agent notebook and documentation * fix bug * set flush to True when printing msg in agent * add a math problem in agent notebook * remove * header * improve notebook doc * notebook update * improve notebook example * improve doc * agent notebook example with user feedback * log * log * improve notebook doc * improve print * doc * human_input_mode * human_input_mode str * indent * indent * Update flaml/autogen/agent/user_proxy_agent.py Co-authored-by: Chi Wang <wang.chi@microsoft.com> * shell command and multiple code blocks * Update notebook/autogen_agent.ipynb Co-authored-by: Chi Wang <wang.chi@microsoft.com> * Update notebook/autogen_agent.ipynb Co-authored-by: Chi Wang <wang.chi@microsoft.com> * Update notebook/autogen_agent.ipynb Co-authored-by: Chi Wang <wang.chi@microsoft.com> * coding agent * math notebook * renaming and doc format * typo * infer lang * sh * docker * docker * reset consecutive autoreply counter * fix explanation * paper talk * human feedback * web info * rename test * config list explanation * link to blogpost * installation * homepage features * features * features * rename agent * remove notebook * notebook test * docker command * notebook update * lang -> cmd * notebook * make it work for gpt-3.5 * return full log * quote * docker * docker * docker * docker * docker * docker image list * notebook * notebook * use_docker * use_docker * use_docker * doc * agent * doc * abs path * pandas * docker * reuse docker image * context window * news * print format * pyspark version in py3.8 * pyspark in py3.8 * pyspark and ray * quote * pyspark * pyspark * pyspark --------- Co-authored-by: Qingyun Wu <qingyun.wu@psu.edu>
3 years ago
Code executors (#1405) * code executor * test * revert to main conversable agent * prepare for pr * kernel * run open ai tests only when it's out of draft status * update workflow file * revert workflow changes * ipython executor * check kernel installed; fix tests * fix tests * fix tests * update system prompt * Update notebook, more tests * notebook * raise instead of return None * allow user provided code executor. * fixing types * wip * refactoring * polishing * fixed failing tests * resolved merge conflict * fixing failing test * wip * local command line executor and embedded ipython executor * revert notebook * fix format * fix merged error * fix lmm test * fix lmm test * move warning * name and description should be part of the agent protocol, reset is not as it is only used for ConversableAgent; removing accidentally commited file * version for dependency * Update autogen/agentchat/conversable_agent.py Co-authored-by: Jack Gerrits <jackgerrits@users.noreply.github.com> * ordering of protocol * description * fix tests * make ipython executor dependency optional * update document optional dependencies * Remove exclude from Agent protocol * Make ConversableAgent consistent with Agent * fix tests * add doc string * add doc string * fix notebook * fix interface * merge and update agents * disable config usage in reply function * description field setter * customize system message update * update doc --------- Co-authored-by: Davor Runje <davor@airt.ai> Co-authored-by: Jack Gerrits <jackgerrits@users.noreply.github.com> Co-authored-by: Aaron <aaronlaptop12@hotmail.com> Co-authored-by: Chi Wang <wang.chi@microsoft.com>
2 years ago
Code executors (#1405) * code executor * test * revert to main conversable agent * prepare for pr * kernel * run open ai tests only when it's out of draft status * update workflow file * revert workflow changes * ipython executor * check kernel installed; fix tests * fix tests * fix tests * update system prompt * Update notebook, more tests * notebook * raise instead of return None * allow user provided code executor. * fixing types * wip * refactoring * polishing * fixed failing tests * resolved merge conflict * fixing failing test * wip * local command line executor and embedded ipython executor * revert notebook * fix format * fix merged error * fix lmm test * fix lmm test * move warning * name and description should be part of the agent protocol, reset is not as it is only used for ConversableAgent; removing accidentally commited file * version for dependency * Update autogen/agentchat/conversable_agent.py Co-authored-by: Jack Gerrits <jackgerrits@users.noreply.github.com> * ordering of protocol * description * fix tests * make ipython executor dependency optional * update document optional dependencies * Remove exclude from Agent protocol * Make ConversableAgent consistent with Agent * fix tests * add doc string * add doc string * fix notebook * fix interface * merge and update agents * disable config usage in reply function * description field setter * customize system message update * update doc --------- Co-authored-by: Davor Runje <davor@airt.ai> Co-authored-by: Jack Gerrits <jackgerrits@users.noreply.github.com> Co-authored-by: Aaron <aaronlaptop12@hotmail.com> Co-authored-by: Chi Wang <wang.chi@microsoft.com>
2 years ago
Agent notebook example with human feedback; Support shell command and multiple code blocks; Improve the system message for assistant agent; Improve utility functions for config lists; reuse docker image (#1056) * add agent notebook and documentation * fix bug * set flush to True when printing msg in agent * add a math problem in agent notebook * remove * header * improve notebook doc * notebook update * improve notebook example * improve doc * agent notebook example with user feedback * log * log * improve notebook doc * improve print * doc * human_input_mode * human_input_mode str * indent * indent * Update flaml/autogen/agent/user_proxy_agent.py Co-authored-by: Chi Wang <wang.chi@microsoft.com> * shell command and multiple code blocks * Update notebook/autogen_agent.ipynb Co-authored-by: Chi Wang <wang.chi@microsoft.com> * Update notebook/autogen_agent.ipynb Co-authored-by: Chi Wang <wang.chi@microsoft.com> * Update notebook/autogen_agent.ipynb Co-authored-by: Chi Wang <wang.chi@microsoft.com> * coding agent * math notebook * renaming and doc format * typo * infer lang * sh * docker * docker * reset consecutive autoreply counter * fix explanation * paper talk * human feedback * web info * rename test * config list explanation * link to blogpost * installation * homepage features * features * features * rename agent * remove notebook * notebook test * docker command * notebook update * lang -> cmd * notebook * make it work for gpt-3.5 * return full log * quote * docker * docker * docker * docker * docker * docker image list * notebook * notebook * use_docker * use_docker * use_docker * doc * agent * doc * abs path * pandas * docker * reuse docker image * context window * news * print format * pyspark version in py3.8 * pyspark in py3.8 * pyspark and ray * quote * pyspark * pyspark * pyspark --------- Co-authored-by: Qingyun Wu <qingyun.wu@psu.edu>
3 years ago
Code executors (#1405) * code executor * test * revert to main conversable agent * prepare for pr * kernel * run open ai tests only when it's out of draft status * update workflow file * revert workflow changes * ipython executor * check kernel installed; fix tests * fix tests * fix tests * update system prompt * Update notebook, more tests * notebook * raise instead of return None * allow user provided code executor. * fixing types * wip * refactoring * polishing * fixed failing tests * resolved merge conflict * fixing failing test * wip * local command line executor and embedded ipython executor * revert notebook * fix format * fix merged error * fix lmm test * fix lmm test * move warning * name and description should be part of the agent protocol, reset is not as it is only used for ConversableAgent; removing accidentally commited file * version for dependency * Update autogen/agentchat/conversable_agent.py Co-authored-by: Jack Gerrits <jackgerrits@users.noreply.github.com> * ordering of protocol * description * fix tests * make ipython executor dependency optional * update document optional dependencies * Remove exclude from Agent protocol * Make ConversableAgent consistent with Agent * fix tests * add doc string * add doc string * fix notebook * fix interface * merge and update agents * disable config usage in reply function * description field setter * customize system message update * update doc --------- Co-authored-by: Davor Runje <davor@airt.ai> Co-authored-by: Jack Gerrits <jackgerrits@users.noreply.github.com> Co-authored-by: Aaron <aaronlaptop12@hotmail.com> Co-authored-by: Chi Wang <wang.chi@microsoft.com>
2 years ago
2 years ago
Agent notebook example with human feedback; Support shell command and multiple code blocks; Improve the system message for assistant agent; Improve utility functions for config lists; reuse docker image (#1056) * add agent notebook and documentation * fix bug * set flush to True when printing msg in agent * add a math problem in agent notebook * remove * header * improve notebook doc * notebook update * improve notebook example * improve doc * agent notebook example with user feedback * log * log * improve notebook doc * improve print * doc * human_input_mode * human_input_mode str * indent * indent * Update flaml/autogen/agent/user_proxy_agent.py Co-authored-by: Chi Wang <wang.chi@microsoft.com> * shell command and multiple code blocks * Update notebook/autogen_agent.ipynb Co-authored-by: Chi Wang <wang.chi@microsoft.com> * Update notebook/autogen_agent.ipynb Co-authored-by: Chi Wang <wang.chi@microsoft.com> * Update notebook/autogen_agent.ipynb Co-authored-by: Chi Wang <wang.chi@microsoft.com> * coding agent * math notebook * renaming and doc format * typo * infer lang * sh * docker * docker * reset consecutive autoreply counter * fix explanation * paper talk * human feedback * web info * rename test * config list explanation * link to blogpost * installation * homepage features * features * features * rename agent * remove notebook * notebook test * docker command * notebook update * lang -> cmd * notebook * make it work for gpt-3.5 * return full log * quote * docker * docker * docker * docker * docker * docker image list * notebook * notebook * use_docker * use_docker * use_docker * doc * agent * doc * abs path * pandas * docker * reuse docker image * context window * news * print format * pyspark version in py3.8 * pyspark in py3.8 * pyspark and ray * quote * pyspark * pyspark * pyspark --------- Co-authored-by: Qingyun Wu <qingyun.wu@psu.edu>
3 years ago
Agent notebook example with human feedback; Support shell command and multiple code blocks; Improve the system message for assistant agent; Improve utility functions for config lists; reuse docker image (#1056) * add agent notebook and documentation * fix bug * set flush to True when printing msg in agent * add a math problem in agent notebook * remove * header * improve notebook doc * notebook update * improve notebook example * improve doc * agent notebook example with user feedback * log * log * improve notebook doc * improve print * doc * human_input_mode * human_input_mode str * indent * indent * Update flaml/autogen/agent/user_proxy_agent.py Co-authored-by: Chi Wang <wang.chi@microsoft.com> * shell command and multiple code blocks * Update notebook/autogen_agent.ipynb Co-authored-by: Chi Wang <wang.chi@microsoft.com> * Update notebook/autogen_agent.ipynb Co-authored-by: Chi Wang <wang.chi@microsoft.com> * Update notebook/autogen_agent.ipynb Co-authored-by: Chi Wang <wang.chi@microsoft.com> * coding agent * math notebook * renaming and doc format * typo * infer lang * sh * docker * docker * reset consecutive autoreply counter * fix explanation * paper talk * human feedback * web info * rename test * config list explanation * link to blogpost * installation * homepage features * features * features * rename agent * remove notebook * notebook test * docker command * notebook update * lang -> cmd * notebook * make it work for gpt-3.5 * return full log * quote * docker * docker * docker * docker * docker * docker image list * notebook * notebook * use_docker * use_docker * use_docker * doc * agent * doc * abs path * pandas * docker * reuse docker image * context window * news * print format * pyspark version in py3.8 * pyspark in py3.8 * pyspark and ray * quote * pyspark * pyspark * pyspark --------- Co-authored-by: Qingyun Wu <qingyun.wu@psu.edu>
3 years ago
Agent notebook example with human feedback; Support shell command and multiple code blocks; Improve the system message for assistant agent; Improve utility functions for config lists; reuse docker image (#1056) * add agent notebook and documentation * fix bug * set flush to True when printing msg in agent * add a math problem in agent notebook * remove * header * improve notebook doc * notebook update * improve notebook example * improve doc * agent notebook example with user feedback * log * log * improve notebook doc * improve print * doc * human_input_mode * human_input_mode str * indent * indent * Update flaml/autogen/agent/user_proxy_agent.py Co-authored-by: Chi Wang <wang.chi@microsoft.com> * shell command and multiple code blocks * Update notebook/autogen_agent.ipynb Co-authored-by: Chi Wang <wang.chi@microsoft.com> * Update notebook/autogen_agent.ipynb Co-authored-by: Chi Wang <wang.chi@microsoft.com> * Update notebook/autogen_agent.ipynb Co-authored-by: Chi Wang <wang.chi@microsoft.com> * coding agent * math notebook * renaming and doc format * typo * infer lang * sh * docker * docker * reset consecutive autoreply counter * fix explanation * paper talk * human feedback * web info * rename test * config list explanation * link to blogpost * installation * homepage features * features * features * rename agent * remove notebook * notebook test * docker command * notebook update * lang -> cmd * notebook * make it work for gpt-3.5 * return full log * quote * docker * docker * docker * docker * docker * docker image list * notebook * notebook * use_docker * use_docker * use_docker * doc * agent * doc * abs path * pandas * docker * reuse docker image * context window * news * print format * pyspark version in py3.8 * pyspark in py3.8 * pyspark and ray * quote * pyspark * pyspark * pyspark --------- Co-authored-by: Qingyun Wu <qingyun.wu@psu.edu>
3 years ago
raise error when msg is invalid; fix docstr; improve ResponsiveAgent; update doc and packaging; capture ipython output; find code blocks with llm when regex fails. (#1154) * autogen.agent -> autogen.agentchat * bug fix in portfolio * notebook * timeout * timeout * infer lang; close #1150 * timeout * message context * context handling * add sender to generate_reply * clean up the receive function * move mathchat to contrib * contrib * last_message * Add OptiGuide: agent and notebook * Optiguide notebook: add figures and URL 1. figures and code points to remote URL 2. simplify the prompt for the interpreter, because all information is already in the chat history. * Update name: Agent -> GenericAgent * Update notebook * Rename: GenericAgent -> ResponsiveAgent * Rebase to autogen.agentchat * OptiGuide: Comment, sytle, and notebook updates * simplify optiguide * raise error when msg is invalid; fix docstr * allow return None for generate_reply() * update_system_message * test update_system_message * simplify optiguide * simplify optiguide * simplify optiguide * simplify optiguide * move test * add test and fix bug * doc update * doc update * doc update * color * optiguide * prompt * test danger case * packaging * docker * remove path in traceback * capture ipython output * simplify * find code blocks with llm * find code with llm * order * order * fix bug in context handling * print executing msg * print executing msg * test find code * test find code * disable find_code * default_auto_reply * default auto reply * remove optiguide * remove -e --------- Co-authored-by: Beibin Li <beibin79@gmail.com>
3 years ago
Agent notebook example with human feedback; Support shell command and multiple code blocks; Improve the system message for assistant agent; Improve utility functions for config lists; reuse docker image (#1056) * add agent notebook and documentation * fix bug * set flush to True when printing msg in agent * add a math problem in agent notebook * remove * header * improve notebook doc * notebook update * improve notebook example * improve doc * agent notebook example with user feedback * log * log * improve notebook doc * improve print * doc * human_input_mode * human_input_mode str * indent * indent * Update flaml/autogen/agent/user_proxy_agent.py Co-authored-by: Chi Wang <wang.chi@microsoft.com> * shell command and multiple code blocks * Update notebook/autogen_agent.ipynb Co-authored-by: Chi Wang <wang.chi@microsoft.com> * Update notebook/autogen_agent.ipynb Co-authored-by: Chi Wang <wang.chi@microsoft.com> * Update notebook/autogen_agent.ipynb Co-authored-by: Chi Wang <wang.chi@microsoft.com> * coding agent * math notebook * renaming and doc format * typo * infer lang * sh * docker * docker * reset consecutive autoreply counter * fix explanation * paper talk * human feedback * web info * rename test * config list explanation * link to blogpost * installation * homepage features * features * features * rename agent * remove notebook * notebook test * docker command * notebook update * lang -> cmd * notebook * make it work for gpt-3.5 * return full log * quote * docker * docker * docker * docker * docker * docker image list * notebook * notebook * use_docker * use_docker * use_docker * doc * agent * doc * abs path * pandas * docker * reuse docker image * context window * news * print format * pyspark version in py3.8 * pyspark in py3.8 * pyspark and ray * quote * pyspark * pyspark * pyspark --------- Co-authored-by: Qingyun Wu <qingyun.wu@psu.edu>
3 years ago
Agent notebook example with human feedback; Support shell command and multiple code blocks; Improve the system message for assistant agent; Improve utility functions for config lists; reuse docker image (#1056) * add agent notebook and documentation * fix bug * set flush to True when printing msg in agent * add a math problem in agent notebook * remove * header * improve notebook doc * notebook update * improve notebook example * improve doc * agent notebook example with user feedback * log * log * improve notebook doc * improve print * doc * human_input_mode * human_input_mode str * indent * indent * Update flaml/autogen/agent/user_proxy_agent.py Co-authored-by: Chi Wang <wang.chi@microsoft.com> * shell command and multiple code blocks * Update notebook/autogen_agent.ipynb Co-authored-by: Chi Wang <wang.chi@microsoft.com> * Update notebook/autogen_agent.ipynb Co-authored-by: Chi Wang <wang.chi@microsoft.com> * Update notebook/autogen_agent.ipynb Co-authored-by: Chi Wang <wang.chi@microsoft.com> * coding agent * math notebook * renaming and doc format * typo * infer lang * sh * docker * docker * reset consecutive autoreply counter * fix explanation * paper talk * human feedback * web info * rename test * config list explanation * link to blogpost * installation * homepage features * features * features * rename agent * remove notebook * notebook test * docker command * notebook update * lang -> cmd * notebook * make it work for gpt-3.5 * return full log * quote * docker * docker * docker * docker * docker * docker image list * notebook * notebook * use_docker * use_docker * use_docker * doc * agent * doc * abs path * pandas * docker * reuse docker image * context window * news * print format * pyspark version in py3.8 * pyspark in py3.8 * pyspark and ray * quote * pyspark * pyspark * pyspark --------- Co-authored-by: Qingyun Wu <qingyun.wu@psu.edu>
3 years ago
Agent notebook example with human feedback; Support shell command and multiple code blocks; Improve the system message for assistant agent; Improve utility functions for config lists; reuse docker image (#1056) * add agent notebook and documentation * fix bug * set flush to True when printing msg in agent * add a math problem in agent notebook * remove * header * improve notebook doc * notebook update * improve notebook example * improve doc * agent notebook example with user feedback * log * log * improve notebook doc * improve print * doc * human_input_mode * human_input_mode str * indent * indent * Update flaml/autogen/agent/user_proxy_agent.py Co-authored-by: Chi Wang <wang.chi@microsoft.com> * shell command and multiple code blocks * Update notebook/autogen_agent.ipynb Co-authored-by: Chi Wang <wang.chi@microsoft.com> * Update notebook/autogen_agent.ipynb Co-authored-by: Chi Wang <wang.chi@microsoft.com> * Update notebook/autogen_agent.ipynb Co-authored-by: Chi Wang <wang.chi@microsoft.com> * coding agent * math notebook * renaming and doc format * typo * infer lang * sh * docker * docker * reset consecutive autoreply counter * fix explanation * paper talk * human feedback * web info * rename test * config list explanation * link to blogpost * installation * homepage features * features * features * rename agent * remove notebook * notebook test * docker command * notebook update * lang -> cmd * notebook * make it work for gpt-3.5 * return full log * quote * docker * docker * docker * docker * docker * docker image list * notebook * notebook * use_docker * use_docker * use_docker * doc * agent * doc * abs path * pandas * docker * reuse docker image * context window * news * print format * pyspark version in py3.8 * pyspark in py3.8 * pyspark and ray * quote * pyspark * pyspark * pyspark --------- Co-authored-by: Qingyun Wu <qingyun.wu@psu.edu>
3 years ago
raise error when msg is invalid; fix docstr; improve ResponsiveAgent; update doc and packaging; capture ipython output; find code blocks with llm when regex fails. (#1154) * autogen.agent -> autogen.agentchat * bug fix in portfolio * notebook * timeout * timeout * infer lang; close #1150 * timeout * message context * context handling * add sender to generate_reply * clean up the receive function * move mathchat to contrib * contrib * last_message * Add OptiGuide: agent and notebook * Optiguide notebook: add figures and URL 1. figures and code points to remote URL 2. simplify the prompt for the interpreter, because all information is already in the chat history. * Update name: Agent -> GenericAgent * Update notebook * Rename: GenericAgent -> ResponsiveAgent * Rebase to autogen.agentchat * OptiGuide: Comment, sytle, and notebook updates * simplify optiguide * raise error when msg is invalid; fix docstr * allow return None for generate_reply() * update_system_message * test update_system_message * simplify optiguide * simplify optiguide * simplify optiguide * simplify optiguide * move test * add test and fix bug * doc update * doc update * doc update * color * optiguide * prompt * test danger case * packaging * docker * remove path in traceback * capture ipython output * simplify * find code blocks with llm * find code with llm * order * order * fix bug in context handling * print executing msg * print executing msg * test find code * test find code * disable find_code * default_auto_reply * default auto reply * remove optiguide * remove -e --------- Co-authored-by: Beibin Li <beibin79@gmail.com>
3 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
raise error when msg is invalid; fix docstr; improve ResponsiveAgent; update doc and packaging; capture ipython output; find code blocks with llm when regex fails. (#1154) * autogen.agent -> autogen.agentchat * bug fix in portfolio * notebook * timeout * timeout * infer lang; close #1150 * timeout * message context * context handling * add sender to generate_reply * clean up the receive function * move mathchat to contrib * contrib * last_message * Add OptiGuide: agent and notebook * Optiguide notebook: add figures and URL 1. figures and code points to remote URL 2. simplify the prompt for the interpreter, because all information is already in the chat history. * Update name: Agent -> GenericAgent * Update notebook * Rename: GenericAgent -> ResponsiveAgent * Rebase to autogen.agentchat * OptiGuide: Comment, sytle, and notebook updates * simplify optiguide * raise error when msg is invalid; fix docstr * allow return None for generate_reply() * update_system_message * test update_system_message * simplify optiguide * simplify optiguide * simplify optiguide * simplify optiguide * move test * add test and fix bug * doc update * doc update * doc update * color * optiguide * prompt * test danger case * packaging * docker * remove path in traceback * capture ipython output * simplify * find code blocks with llm * find code with llm * order * order * fix bug in context handling * print executing msg * print executing msg * test find code * test find code * disable find_code * default_auto_reply * default auto reply * remove optiguide * remove -e --------- Co-authored-by: Beibin Li <beibin79@gmail.com>
3 years ago
2 years ago
raise error when msg is invalid; fix docstr; improve ResponsiveAgent; update doc and packaging; capture ipython output; find code blocks with llm when regex fails. (#1154) * autogen.agent -> autogen.agentchat * bug fix in portfolio * notebook * timeout * timeout * infer lang; close #1150 * timeout * message context * context handling * add sender to generate_reply * clean up the receive function * move mathchat to contrib * contrib * last_message * Add OptiGuide: agent and notebook * Optiguide notebook: add figures and URL 1. figures and code points to remote URL 2. simplify the prompt for the interpreter, because all information is already in the chat history. * Update name: Agent -> GenericAgent * Update notebook * Rename: GenericAgent -> ResponsiveAgent * Rebase to autogen.agentchat * OptiGuide: Comment, sytle, and notebook updates * simplify optiguide * raise error when msg is invalid; fix docstr * allow return None for generate_reply() * update_system_message * test update_system_message * simplify optiguide * simplify optiguide * simplify optiguide * simplify optiguide * move test * add test and fix bug * doc update * doc update * doc update * color * optiguide * prompt * test danger case * packaging * docker * remove path in traceback * capture ipython output * simplify * find code blocks with llm * find code with llm * order * order * fix bug in context handling * print executing msg * print executing msg * test find code * test find code * disable find_code * default_auto_reply * default auto reply * remove optiguide * remove -e --------- Co-authored-by: Beibin Li <beibin79@gmail.com>
3 years ago
Agent notebook example with human feedback; Support shell command and multiple code blocks; Improve the system message for assistant agent; Improve utility functions for config lists; reuse docker image (#1056) * add agent notebook and documentation * fix bug * set flush to True when printing msg in agent * add a math problem in agent notebook * remove * header * improve notebook doc * notebook update * improve notebook example * improve doc * agent notebook example with user feedback * log * log * improve notebook doc * improve print * doc * human_input_mode * human_input_mode str * indent * indent * Update flaml/autogen/agent/user_proxy_agent.py Co-authored-by: Chi Wang <wang.chi@microsoft.com> * shell command and multiple code blocks * Update notebook/autogen_agent.ipynb Co-authored-by: Chi Wang <wang.chi@microsoft.com> * Update notebook/autogen_agent.ipynb Co-authored-by: Chi Wang <wang.chi@microsoft.com> * Update notebook/autogen_agent.ipynb Co-authored-by: Chi Wang <wang.chi@microsoft.com> * coding agent * math notebook * renaming and doc format * typo * infer lang * sh * docker * docker * reset consecutive autoreply counter * fix explanation * paper talk * human feedback * web info * rename test * config list explanation * link to blogpost * installation * homepage features * features * features * rename agent * remove notebook * notebook test * docker command * notebook update * lang -> cmd * notebook * make it work for gpt-3.5 * return full log * quote * docker * docker * docker * docker * docker * docker image list * notebook * notebook * use_docker * use_docker * use_docker * doc * agent * doc * abs path * pandas * docker * reuse docker image * context window * news * print format * pyspark version in py3.8 * pyspark in py3.8 * pyspark and ray * quote * pyspark * pyspark * pyspark --------- Co-authored-by: Qingyun Wu <qingyun.wu@psu.edu>
3 years ago
Agent notebook example with human feedback; Support shell command and multiple code blocks; Improve the system message for assistant agent; Improve utility functions for config lists; reuse docker image (#1056) * add agent notebook and documentation * fix bug * set flush to True when printing msg in agent * add a math problem in agent notebook * remove * header * improve notebook doc * notebook update * improve notebook example * improve doc * agent notebook example with user feedback * log * log * improve notebook doc * improve print * doc * human_input_mode * human_input_mode str * indent * indent * Update flaml/autogen/agent/user_proxy_agent.py Co-authored-by: Chi Wang <wang.chi@microsoft.com> * shell command and multiple code blocks * Update notebook/autogen_agent.ipynb Co-authored-by: Chi Wang <wang.chi@microsoft.com> * Update notebook/autogen_agent.ipynb Co-authored-by: Chi Wang <wang.chi@microsoft.com> * Update notebook/autogen_agent.ipynb Co-authored-by: Chi Wang <wang.chi@microsoft.com> * coding agent * math notebook * renaming and doc format * typo * infer lang * sh * docker * docker * reset consecutive autoreply counter * fix explanation * paper talk * human feedback * web info * rename test * config list explanation * link to blogpost * installation * homepage features * features * features * rename agent * remove notebook * notebook test * docker command * notebook update * lang -> cmd * notebook * make it work for gpt-3.5 * return full log * quote * docker * docker * docker * docker * docker * docker image list * notebook * notebook * use_docker * use_docker * use_docker * doc * agent * doc * abs path * pandas * docker * reuse docker image * context window * news * print format * pyspark version in py3.8 * pyspark in py3.8 * pyspark and ray * quote * pyspark * pyspark * pyspark --------- Co-authored-by: Qingyun Wu <qingyun.wu@psu.edu>
3 years ago
Agent notebook example with human feedback; Support shell command and multiple code blocks; Improve the system message for assistant agent; Improve utility functions for config lists; reuse docker image (#1056) * add agent notebook and documentation * fix bug * set flush to True when printing msg in agent * add a math problem in agent notebook * remove * header * improve notebook doc * notebook update * improve notebook example * improve doc * agent notebook example with user feedback * log * log * improve notebook doc * improve print * doc * human_input_mode * human_input_mode str * indent * indent * Update flaml/autogen/agent/user_proxy_agent.py Co-authored-by: Chi Wang <wang.chi@microsoft.com> * shell command and multiple code blocks * Update notebook/autogen_agent.ipynb Co-authored-by: Chi Wang <wang.chi@microsoft.com> * Update notebook/autogen_agent.ipynb Co-authored-by: Chi Wang <wang.chi@microsoft.com> * Update notebook/autogen_agent.ipynb Co-authored-by: Chi Wang <wang.chi@microsoft.com> * coding agent * math notebook * renaming and doc format * typo * infer lang * sh * docker * docker * reset consecutive autoreply counter * fix explanation * paper talk * human feedback * web info * rename test * config list explanation * link to blogpost * installation * homepage features * features * features * rename agent * remove notebook * notebook test * docker command * notebook update * lang -> cmd * notebook * make it work for gpt-3.5 * return full log * quote * docker * docker * docker * docker * docker * docker image list * notebook * notebook * use_docker * use_docker * use_docker * doc * agent * doc * abs path * pandas * docker * reuse docker image * context window * news * print format * pyspark version in py3.8 * pyspark in py3.8 * pyspark and ray * quote * pyspark * pyspark * pyspark --------- Co-authored-by: Qingyun Wu <qingyun.wu@psu.edu>
3 years ago
Agent notebook example with human feedback; Support shell command and multiple code blocks; Improve the system message for assistant agent; Improve utility functions for config lists; reuse docker image (#1056) * add agent notebook and documentation * fix bug * set flush to True when printing msg in agent * add a math problem in agent notebook * remove * header * improve notebook doc * notebook update * improve notebook example * improve doc * agent notebook example with user feedback * log * log * improve notebook doc * improve print * doc * human_input_mode * human_input_mode str * indent * indent * Update flaml/autogen/agent/user_proxy_agent.py Co-authored-by: Chi Wang <wang.chi@microsoft.com> * shell command and multiple code blocks * Update notebook/autogen_agent.ipynb Co-authored-by: Chi Wang <wang.chi@microsoft.com> * Update notebook/autogen_agent.ipynb Co-authored-by: Chi Wang <wang.chi@microsoft.com> * Update notebook/autogen_agent.ipynb Co-authored-by: Chi Wang <wang.chi@microsoft.com> * coding agent * math notebook * renaming and doc format * typo * infer lang * sh * docker * docker * reset consecutive autoreply counter * fix explanation * paper talk * human feedback * web info * rename test * config list explanation * link to blogpost * installation * homepage features * features * features * rename agent * remove notebook * notebook test * docker command * notebook update * lang -> cmd * notebook * make it work for gpt-3.5 * return full log * quote * docker * docker * docker * docker * docker * docker image list * notebook * notebook * use_docker * use_docker * use_docker * doc * agent * doc * abs path * pandas * docker * reuse docker image * context window * news * print format * pyspark version in py3.8 * pyspark in py3.8 * pyspark and ray * quote * pyspark * pyspark * pyspark --------- Co-authored-by: Qingyun Wu <qingyun.wu@psu.edu>
3 years ago
Agent notebook example with human feedback; Support shell command and multiple code blocks; Improve the system message for assistant agent; Improve utility functions for config lists; reuse docker image (#1056) * add agent notebook and documentation * fix bug * set flush to True when printing msg in agent * add a math problem in agent notebook * remove * header * improve notebook doc * notebook update * improve notebook example * improve doc * agent notebook example with user feedback * log * log * improve notebook doc * improve print * doc * human_input_mode * human_input_mode str * indent * indent * Update flaml/autogen/agent/user_proxy_agent.py Co-authored-by: Chi Wang <wang.chi@microsoft.com> * shell command and multiple code blocks * Update notebook/autogen_agent.ipynb Co-authored-by: Chi Wang <wang.chi@microsoft.com> * Update notebook/autogen_agent.ipynb Co-authored-by: Chi Wang <wang.chi@microsoft.com> * Update notebook/autogen_agent.ipynb Co-authored-by: Chi Wang <wang.chi@microsoft.com> * coding agent * math notebook * renaming and doc format * typo * infer lang * sh * docker * docker * reset consecutive autoreply counter * fix explanation * paper talk * human feedback * web info * rename test * config list explanation * link to blogpost * installation * homepage features * features * features * rename agent * remove notebook * notebook test * docker command * notebook update * lang -> cmd * notebook * make it work for gpt-3.5 * return full log * quote * docker * docker * docker * docker * docker * docker image list * notebook * notebook * use_docker * use_docker * use_docker * doc * agent * doc * abs path * pandas * docker * reuse docker image * context window * news * print format * pyspark version in py3.8 * pyspark in py3.8 * pyspark and ray * quote * pyspark * pyspark * pyspark --------- Co-authored-by: Qingyun Wu <qingyun.wu@psu.edu>
3 years ago
Agent notebook example with human feedback; Support shell command and multiple code blocks; Improve the system message for assistant agent; Improve utility functions for config lists; reuse docker image (#1056) * add agent notebook and documentation * fix bug * set flush to True when printing msg in agent * add a math problem in agent notebook * remove * header * improve notebook doc * notebook update * improve notebook example * improve doc * agent notebook example with user feedback * log * log * improve notebook doc * improve print * doc * human_input_mode * human_input_mode str * indent * indent * Update flaml/autogen/agent/user_proxy_agent.py Co-authored-by: Chi Wang <wang.chi@microsoft.com> * shell command and multiple code blocks * Update notebook/autogen_agent.ipynb Co-authored-by: Chi Wang <wang.chi@microsoft.com> * Update notebook/autogen_agent.ipynb Co-authored-by: Chi Wang <wang.chi@microsoft.com> * Update notebook/autogen_agent.ipynb Co-authored-by: Chi Wang <wang.chi@microsoft.com> * coding agent * math notebook * renaming and doc format * typo * infer lang * sh * docker * docker * reset consecutive autoreply counter * fix explanation * paper talk * human feedback * web info * rename test * config list explanation * link to blogpost * installation * homepage features * features * features * rename agent * remove notebook * notebook test * docker command * notebook update * lang -> cmd * notebook * make it work for gpt-3.5 * return full log * quote * docker * docker * docker * docker * docker * docker image list * notebook * notebook * use_docker * use_docker * use_docker * doc * agent * doc * abs path * pandas * docker * reuse docker image * context window * news * print format * pyspark version in py3.8 * pyspark in py3.8 * pyspark and ray * quote * pyspark * pyspark * pyspark --------- Co-authored-by: Qingyun Wu <qingyun.wu@psu.edu>
3 years ago
Agent notebook example with human feedback; Support shell command and multiple code blocks; Improve the system message for assistant agent; Improve utility functions for config lists; reuse docker image (#1056) * add agent notebook and documentation * fix bug * set flush to True when printing msg in agent * add a math problem in agent notebook * remove * header * improve notebook doc * notebook update * improve notebook example * improve doc * agent notebook example with user feedback * log * log * improve notebook doc * improve print * doc * human_input_mode * human_input_mode str * indent * indent * Update flaml/autogen/agent/user_proxy_agent.py Co-authored-by: Chi Wang <wang.chi@microsoft.com> * shell command and multiple code blocks * Update notebook/autogen_agent.ipynb Co-authored-by: Chi Wang <wang.chi@microsoft.com> * Update notebook/autogen_agent.ipynb Co-authored-by: Chi Wang <wang.chi@microsoft.com> * Update notebook/autogen_agent.ipynb Co-authored-by: Chi Wang <wang.chi@microsoft.com> * coding agent * math notebook * renaming and doc format * typo * infer lang * sh * docker * docker * reset consecutive autoreply counter * fix explanation * paper talk * human feedback * web info * rename test * config list explanation * link to blogpost * installation * homepage features * features * features * rename agent * remove notebook * notebook test * docker command * notebook update * lang -> cmd * notebook * make it work for gpt-3.5 * return full log * quote * docker * docker * docker * docker * docker * docker image list * notebook * notebook * use_docker * use_docker * use_docker * doc * agent * doc * abs path * pandas * docker * reuse docker image * context window * news * print format * pyspark version in py3.8 * pyspark in py3.8 * pyspark and ray * quote * pyspark * pyspark * pyspark --------- Co-authored-by: Qingyun Wu <qingyun.wu@psu.edu>
3 years ago
raise error when msg is invalid; fix docstr; improve ResponsiveAgent; update doc and packaging; capture ipython output; find code blocks with llm when regex fails. (#1154) * autogen.agent -> autogen.agentchat * bug fix in portfolio * notebook * timeout * timeout * infer lang; close #1150 * timeout * message context * context handling * add sender to generate_reply * clean up the receive function * move mathchat to contrib * contrib * last_message * Add OptiGuide: agent and notebook * Optiguide notebook: add figures and URL 1. figures and code points to remote URL 2. simplify the prompt for the interpreter, because all information is already in the chat history. * Update name: Agent -> GenericAgent * Update notebook * Rename: GenericAgent -> ResponsiveAgent * Rebase to autogen.agentchat * OptiGuide: Comment, sytle, and notebook updates * simplify optiguide * raise error when msg is invalid; fix docstr * allow return None for generate_reply() * update_system_message * test update_system_message * simplify optiguide * simplify optiguide * simplify optiguide * simplify optiguide * move test * add test and fix bug * doc update * doc update * doc update * color * optiguide * prompt * test danger case * packaging * docker * remove path in traceback * capture ipython output * simplify * find code blocks with llm * find code with llm * order * order * fix bug in context handling * print executing msg * print executing msg * test find code * test find code * disable find_code * default_auto_reply * default auto reply * remove optiguide * remove -e --------- Co-authored-by: Beibin Li <beibin79@gmail.com>
3 years ago
raise error when msg is invalid; fix docstr; improve ResponsiveAgent; update doc and packaging; capture ipython output; find code blocks with llm when regex fails. (#1154) * autogen.agent -> autogen.agentchat * bug fix in portfolio * notebook * timeout * timeout * infer lang; close #1150 * timeout * message context * context handling * add sender to generate_reply * clean up the receive function * move mathchat to contrib * contrib * last_message * Add OptiGuide: agent and notebook * Optiguide notebook: add figures and URL 1. figures and code points to remote URL 2. simplify the prompt for the interpreter, because all information is already in the chat history. * Update name: Agent -> GenericAgent * Update notebook * Rename: GenericAgent -> ResponsiveAgent * Rebase to autogen.agentchat * OptiGuide: Comment, sytle, and notebook updates * simplify optiguide * raise error when msg is invalid; fix docstr * allow return None for generate_reply() * update_system_message * test update_system_message * simplify optiguide * simplify optiguide * simplify optiguide * simplify optiguide * move test * add test and fix bug * doc update * doc update * doc update * color * optiguide * prompt * test danger case * packaging * docker * remove path in traceback * capture ipython output * simplify * find code blocks with llm * find code with llm * order * order * fix bug in context handling * print executing msg * print executing msg * test find code * test find code * disable find_code * default_auto_reply * default auto reply * remove optiguide * remove -e --------- Co-authored-by: Beibin Li <beibin79@gmail.com>
3 years ago
Agent notebook example with human feedback; Support shell command and multiple code blocks; Improve the system message for assistant agent; Improve utility functions for config lists; reuse docker image (#1056) * add agent notebook and documentation * fix bug * set flush to True when printing msg in agent * add a math problem in agent notebook * remove * header * improve notebook doc * notebook update * improve notebook example * improve doc * agent notebook example with user feedback * log * log * improve notebook doc * improve print * doc * human_input_mode * human_input_mode str * indent * indent * Update flaml/autogen/agent/user_proxy_agent.py Co-authored-by: Chi Wang <wang.chi@microsoft.com> * shell command and multiple code blocks * Update notebook/autogen_agent.ipynb Co-authored-by: Chi Wang <wang.chi@microsoft.com> * Update notebook/autogen_agent.ipynb Co-authored-by: Chi Wang <wang.chi@microsoft.com> * Update notebook/autogen_agent.ipynb Co-authored-by: Chi Wang <wang.chi@microsoft.com> * coding agent * math notebook * renaming and doc format * typo * infer lang * sh * docker * docker * reset consecutive autoreply counter * fix explanation * paper talk * human feedback * web info * rename test * config list explanation * link to blogpost * installation * homepage features * features * features * rename agent * remove notebook * notebook test * docker command * notebook update * lang -> cmd * notebook * make it work for gpt-3.5 * return full log * quote * docker * docker * docker * docker * docker * docker image list * notebook * notebook * use_docker * use_docker * use_docker * doc * agent * doc * abs path * pandas * docker * reuse docker image * context window * news * print format * pyspark version in py3.8 * pyspark in py3.8 * pyspark and ray * quote * pyspark * pyspark * pyspark --------- Co-authored-by: Qingyun Wu <qingyun.wu@psu.edu>
3 years ago
raise error when msg is invalid; fix docstr; improve ResponsiveAgent; update doc and packaging; capture ipython output; find code blocks with llm when regex fails. (#1154) * autogen.agent -> autogen.agentchat * bug fix in portfolio * notebook * timeout * timeout * infer lang; close #1150 * timeout * message context * context handling * add sender to generate_reply * clean up the receive function * move mathchat to contrib * contrib * last_message * Add OptiGuide: agent and notebook * Optiguide notebook: add figures and URL 1. figures and code points to remote URL 2. simplify the prompt for the interpreter, because all information is already in the chat history. * Update name: Agent -> GenericAgent * Update notebook * Rename: GenericAgent -> ResponsiveAgent * Rebase to autogen.agentchat * OptiGuide: Comment, sytle, and notebook updates * simplify optiguide * raise error when msg is invalid; fix docstr * allow return None for generate_reply() * update_system_message * test update_system_message * simplify optiguide * simplify optiguide * simplify optiguide * simplify optiguide * move test * add test and fix bug * doc update * doc update * doc update * color * optiguide * prompt * test danger case * packaging * docker * remove path in traceback * capture ipython output * simplify * find code blocks with llm * find code with llm * order * order * fix bug in context handling * print executing msg * print executing msg * test find code * test find code * disable find_code * default_auto_reply * default auto reply * remove optiguide * remove -e --------- Co-authored-by: Beibin Li <beibin79@gmail.com>
3 years ago
2 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716
  1. import logging
  2. import os
  3. import pathlib
  4. import re
  5. import string
  6. import subprocess
  7. import sys
  8. import time
  9. from concurrent.futures import ThreadPoolExecutor, TimeoutError
  10. from hashlib import md5
  11. from typing import Any, Callable, Dict, List, Optional, Tuple, Union
  12. from autogen import oai
  13. import docker
  14. from .types import UserMessageImageContentPart, UserMessageTextContentPart
  15. SENTINEL = object()
  16. DEFAULT_MODEL = "gpt-4"
  17. FAST_MODEL = "gpt-3.5-turbo"
  18. # Regular expression for finding a code block
  19. # ```[ \t]*(\w+)?[ \t]*\r?\n(.*?)[ \t]*\r?\n``` Matches multi-line code blocks.
  20. # The [ \t]* matches the potential spaces before language name.
  21. # The (\w+)? matches the language, where the ? indicates it is optional.
  22. # The [ \t]* matches the potential spaces (not newlines) after language name.
  23. # The \r?\n makes sure there is a linebreak after ```.
  24. # The (.*?) matches the code itself (non-greedy).
  25. # The \r?\n makes sure there is a linebreak before ```.
  26. # The [ \t]* matches the potential spaces before closing ``` (the spec allows indentation).
  27. CODE_BLOCK_PATTERN = r"```[ \t]*(\w+)?[ \t]*\r?\n(.*?)\r?\n[ \t]*```"
  28. WORKING_DIR = os.path.join(os.path.dirname(os.path.realpath(__file__)), "extensions")
  29. UNKNOWN = "unknown"
  30. TIMEOUT_MSG = "Timeout"
  31. DEFAULT_TIMEOUT = 600
  32. WIN32 = sys.platform == "win32"
  33. PATH_SEPARATOR = WIN32 and "\\" or "/"
  34. logger = logging.getLogger(__name__)
  35. def content_str(content: Union[str, List[Union[UserMessageTextContentPart, UserMessageImageContentPart]], None]) -> str:
  36. """Converts the `content` field of an OpenAI merssage into a string format.
  37. This function processes content that may be a string, a list of mixed text and image URLs, or None,
  38. and converts it into a string. Text is directly appended to the result string, while image URLs are
  39. represented by a placeholder image token. If the content is None, an empty string is returned.
  40. Args:
  41. - content (Union[str, List, None]): The content to be processed. Can be a string, a list of dictionaries
  42. representing text and image URLs, or None.
  43. Returns:
  44. str: A string representation of the input content. Image URLs are replaced with an image token.
  45. Note:
  46. - The function expects each dictionary in the list to have a "type" key that is either "text" or "image_url".
  47. For "text" type, the "text" key's value is appended to the result. For "image_url", an image token is appended.
  48. - This function is useful for handling content that may include both text and image references, especially
  49. in contexts where images need to be represented as placeholders.
  50. """
  51. if content is None:
  52. return ""
  53. if isinstance(content, str):
  54. return content
  55. if not isinstance(content, list):
  56. raise TypeError(f"content must be None, str, or list, but got {type(content)}")
  57. rst = ""
  58. for item in content:
  59. if not isinstance(item, dict):
  60. raise TypeError("Wrong content format: every element should be dict if the content is a list.")
  61. assert "type" in item, "Wrong content format. Missing 'type' key in content's dict."
  62. if item["type"] == "text":
  63. rst += item["text"]
  64. elif item["type"] == "image_url":
  65. rst += "<image>"
  66. else:
  67. raise ValueError(f"Wrong content format: unknown type {item['type']} within the content")
  68. return rst
  69. def infer_lang(code: str) -> str:
  70. """infer the language for the code.
  71. TODO: make it robust.
  72. """
  73. if code.startswith("python ") or code.startswith("pip") or code.startswith("python3 "):
  74. return "sh"
  75. # check if code is a valid python code
  76. try:
  77. compile(code, "test", "exec")
  78. return "python"
  79. except SyntaxError:
  80. # not a valid python code
  81. return UNKNOWN
  82. # TODO: In the future move, to better support https://spec.commonmark.org/0.30/#fenced-code-blocks
  83. # perhaps by using a full Markdown parser.
  84. def extract_code(
  85. text: Union[str, List], pattern: str = CODE_BLOCK_PATTERN, detect_single_line_code: bool = False
  86. ) -> List[Tuple[str, str]]:
  87. """Extract code from a text.
  88. Args:
  89. text (str or List): The content to extract code from. The content can be
  90. a string or a list, as returned by standard GPT or multimodal GPT.
  91. pattern (str, optional): The regular expression pattern for finding the
  92. code block. Defaults to CODE_BLOCK_PATTERN.
  93. detect_single_line_code (bool, optional): Enable the new feature for
  94. extracting single line code. Defaults to False.
  95. Returns:
  96. list: A list of tuples, each containing the language and the code.
  97. If there is no code block in the input text, the language would be "unknown".
  98. If there is code block but the language is not specified, the language would be "".
  99. """
  100. text = content_str(text)
  101. if not detect_single_line_code:
  102. match = re.findall(pattern, text, flags=re.DOTALL)
  103. return match if match else [(UNKNOWN, text)]
  104. # Extract both multi-line and single-line code block, separated by the | operator
  105. # `([^`]+)`: Matches inline code.
  106. code_pattern = re.compile(CODE_BLOCK_PATTERN + r"|`([^`]+)`")
  107. code_blocks = code_pattern.findall(text)
  108. # Extract the individual code blocks and languages from the matched groups
  109. extracted = []
  110. for lang, group1, group2 in code_blocks:
  111. if group1:
  112. extracted.append((lang.strip(), group1.strip()))
  113. elif group2:
  114. extracted.append(("", group2.strip()))
  115. return extracted
  116. def generate_code(pattern: str = CODE_BLOCK_PATTERN, **config) -> Tuple[str, float]:
  117. """(openai<1) Generate code.
  118. Args:
  119. pattern (Optional, str): The regular expression pattern for finding the code block.
  120. The default pattern is for finding a code block in a markdown file.
  121. config (Optional, dict): The configuration for the API call.
  122. Returns:
  123. str: The generated code.
  124. float: The cost of the generation.
  125. """
  126. response = oai.Completion.create(**config)
  127. return extract_code(oai.Completion.extract_text(response)[0], pattern), response["cost"]
  128. _IMPROVE_FUNCTION_CONFIG = {
  129. "prompt": """Improve the function '{func_name}' to achieve the objective '{objective}'.
  130. The current implementation of the function is as follows:
  131. {file_string}""",
  132. "model": DEFAULT_MODEL,
  133. "request_timeout": 600,
  134. }
  135. def improve_function(file_name, func_name, objective, **config):
  136. """(openai<1) Improve the function to achieve the objective."""
  137. params = {**_IMPROVE_FUNCTION_CONFIG, **config}
  138. # read the entire file into a str
  139. with open(file_name, "r") as f:
  140. file_string = f.read()
  141. response = oai.Completion.create(
  142. {"func_name": func_name, "objective": objective, "file_string": file_string}, **params
  143. )
  144. return oai.Completion.extract_text(response)[0], response["cost"]
  145. _IMPROVE_CODE_CONFIG = {
  146. "prompt": """Analyze the code in the following files and return a list of suggestions for improvement{followup}, to achieve the objective of '{objective}'.
  147. {code}
  148. """,
  149. "model": DEFAULT_MODEL,
  150. "request_timeout": 900,
  151. }
  152. def improve_code(files, objective, suggest_only=True, **config):
  153. """(openai<1) Improve the code to achieve a given objective.
  154. Args:
  155. files (list): A list of file names containing the source code.
  156. objective (str): The objective to achieve.
  157. suggest_only (bool): Whether to return only the suggestions or the improved code.
  158. config (Optional, dict): The configuration for the API call.
  159. Returns:
  160. str: The improved code if suggest_only=False; a list of suggestions if suggest_only=True (default).
  161. float: The cost of the generation.
  162. """
  163. code = ""
  164. for file_name in files:
  165. # read the entire file into a string
  166. with open(file_name, "r") as f:
  167. file_string = f.read()
  168. code += f"""{file_name}:
  169. {file_string}
  170. """
  171. params = {**_IMPROVE_CODE_CONFIG, **config}
  172. followup = "" if suggest_only else " followed by the improved code"
  173. response = oai.Completion.create({"objective": objective, "code": code, "followup": followup}, **params)
  174. return oai.Completion.extract_text(response)[0], response["cost"]
  175. def timeout_handler(signum, frame):
  176. raise TimeoutError("Timed out!")
  177. def get_powershell_command():
  178. try:
  179. result = subprocess.run(["powershell", "$PSVersionTable.PSVersion.Major"], capture_output=True, text=True)
  180. if result.returncode == 0:
  181. return "powershell"
  182. except (FileNotFoundError, NotADirectoryError):
  183. # This means that 'powershell' command is not found so now we try looking for 'pwsh'
  184. try:
  185. result = subprocess.run(
  186. ["pwsh", "-Command", "$PSVersionTable.PSVersion.Major"], capture_output=True, text=True
  187. )
  188. if result.returncode == 0:
  189. return "pwsh"
  190. except FileExistsError as e:
  191. raise FileNotFoundError(
  192. "Neither powershell.exe nor pwsh.exe is present in the system. "
  193. "Please install PowerShell and try again. "
  194. ) from e
  195. except NotADirectoryError as e:
  196. raise NotADirectoryError(
  197. "PowerShell is either not installed or its path is not given "
  198. "properly in the environment variable PATH. Please check the "
  199. "path and try again. "
  200. ) from e
  201. except PermissionError as e:
  202. raise PermissionError("No permission to run powershell.") from e
  203. def _cmd(lang: str) -> str:
  204. if lang.startswith("python") or lang in ["bash", "sh"]:
  205. return lang
  206. if lang in ["shell"]:
  207. return "sh"
  208. if lang in ["ps1", "pwsh", "powershell"]:
  209. powershell_command = get_powershell_command()
  210. return powershell_command
  211. raise NotImplementedError(f"{lang} not recognized in code execution")
  212. def is_docker_running() -> bool:
  213. """Check if docker is running.
  214. Returns:
  215. bool: True if docker is running; False otherwise.
  216. """
  217. try:
  218. client = docker.from_env()
  219. client.ping()
  220. return True
  221. except docker.errors.DockerException:
  222. return False
  223. def in_docker_container() -> bool:
  224. """Check if the code is running in a docker container.
  225. Returns:
  226. bool: True if the code is running in a docker container; False otherwise.
  227. """
  228. return os.path.exists("/.dockerenv")
  229. def decide_use_docker(use_docker) -> bool:
  230. if use_docker is None:
  231. env_var_use_docker = os.environ.get("AUTOGEN_USE_DOCKER", "True")
  232. truthy_values = {"1", "true", "yes", "t"}
  233. falsy_values = {"0", "false", "no", "f"}
  234. # Convert the value to lowercase for case-insensitive comparison
  235. env_var_use_docker_lower = env_var_use_docker.lower()
  236. # Determine the boolean value based on the environment variable
  237. if env_var_use_docker_lower in truthy_values:
  238. use_docker = True
  239. elif env_var_use_docker_lower in falsy_values:
  240. use_docker = False
  241. elif env_var_use_docker_lower == "none": # Special case for 'None' as a string
  242. use_docker = None
  243. else:
  244. # Raise an error for any unrecognized value
  245. raise ValueError(
  246. f'Invalid value for AUTOGEN_USE_DOCKER: {env_var_use_docker}. Please set AUTOGEN_USE_DOCKER to "1/True/yes", "0/False/no", or "None".'
  247. )
  248. return use_docker
  249. def check_can_use_docker_or_throw(use_docker) -> None:
  250. if use_docker is not None:
  251. inside_docker = in_docker_container()
  252. docker_installed_and_running = is_docker_running()
  253. if use_docker and not inside_docker and not docker_installed_and_running:
  254. raise RuntimeError(
  255. "Code execution is set to be run in docker (default behaviour) but docker is not running.\n"
  256. "The options available are:\n"
  257. "- Make sure docker is running (advised approach for code execution)\n"
  258. '- Set "use_docker": False in code_execution_config\n'
  259. '- Set AUTOGEN_USE_DOCKER to "0/False/no" in your environment variables'
  260. )
  261. def _sanitize_filename_for_docker_tag(filename: str) -> str:
  262. """Convert a filename to a valid docker tag.
  263. See https://docs.docker.com/engine/reference/commandline/tag/ for valid tag
  264. format.
  265. Args:
  266. filename (str): The filename to be converted.
  267. Returns:
  268. str: The sanitized Docker tag.
  269. """
  270. # Replace any character not allowed with an underscore
  271. allowed_chars = set(string.ascii_letters + string.digits + "_.-")
  272. sanitized = "".join(char if char in allowed_chars else "_" for char in filename)
  273. # Ensure it does not start with a period or a dash
  274. if sanitized.startswith(".") or sanitized.startswith("-"):
  275. sanitized = "_" + sanitized[1:]
  276. # Truncate if longer than 128 characters
  277. return sanitized[:128]
  278. def execute_code(
  279. code: Optional[str] = None,
  280. timeout: Optional[int] = None,
  281. filename: Optional[str] = None,
  282. work_dir: Optional[str] = None,
  283. use_docker: Union[List[str], str, bool] = SENTINEL,
  284. lang: Optional[str] = "python",
  285. ) -> Tuple[int, str, Optional[str]]:
  286. """Execute code in a docker container.
  287. This function is not tested on MacOS.
  288. Args:
  289. code (Optional, str): The code to execute.
  290. If None, the code from the file specified by filename will be executed.
  291. Either code or filename must be provided.
  292. timeout (Optional, int): The maximum execution time in seconds.
  293. If None, a default timeout will be used. The default timeout is 600 seconds. On Windows, the timeout is not enforced when use_docker=False.
  294. filename (Optional, str): The file name to save the code or where the code is stored when `code` is None.
  295. If None, a file with a randomly generated name will be created.
  296. The randomly generated file will be deleted after execution.
  297. The file name must be a relative path. Relative paths are relative to the working directory.
  298. work_dir (Optional, str): The working directory for the code execution.
  299. If None, a default working directory will be used.
  300. The default working directory is the "extensions" directory under
  301. "path_to_autogen".
  302. use_docker (list, str or bool): The docker image to use for code execution.
  303. Default is True, which means the code will be executed in a docker container. A default list of images will be used.
  304. If a list or a str of image name(s) is provided, the code will be executed in a docker container
  305. with the first image successfully pulled.
  306. If False, the code will be executed in the current environment.
  307. Expected behaviour:
  308. - If `use_docker` is not set (i.e. left default to True) or is explicitly set to True and the docker package is available, the code will run in a Docker container.
  309. - If `use_docker` is not set (i.e. left default to True) or is explicitly set to True but the Docker package is missing or docker isn't running, an error will be raised.
  310. - If `use_docker` is explicitly set to False, the code will run natively.
  311. If the code is executed in the current environment,
  312. the code must be trusted.
  313. lang (Optional, str): The language of the code. Default is "python".
  314. Returns:
  315. int: 0 if the code executes successfully.
  316. str: The error message if the code fails to execute; the stdout otherwise.
  317. image: The docker image name after container run when docker is used.
  318. """
  319. if all((code is None, filename is None)):
  320. error_msg = f"Either {code=} or {filename=} must be provided."
  321. logger.error(error_msg)
  322. raise AssertionError(error_msg)
  323. running_inside_docker = in_docker_container()
  324. docker_running = is_docker_running()
  325. # SENTINEL is used to indicate that the user did not explicitly set the argument
  326. if use_docker is SENTINEL:
  327. use_docker = decide_use_docker(use_docker=None)
  328. check_can_use_docker_or_throw(use_docker)
  329. timeout = timeout or DEFAULT_TIMEOUT
  330. original_filename = filename
  331. if WIN32 and lang in ["sh", "shell"] and (not use_docker):
  332. lang = "ps1"
  333. if filename is None:
  334. code_hash = md5(code.encode()).hexdigest()
  335. # create a file with a automatically generated name
  336. filename = f"tmp_code_{code_hash}.{'py' if lang.startswith('python') else lang}"
  337. if work_dir is None:
  338. work_dir = WORKING_DIR
  339. filepath = os.path.join(work_dir, filename)
  340. file_dir = os.path.dirname(filepath)
  341. os.makedirs(file_dir, exist_ok=True)
  342. if code is not None:
  343. with open(filepath, "w", encoding="utf-8") as fout:
  344. fout.write(code)
  345. if not use_docker or running_inside_docker:
  346. # already running in a docker container
  347. cmd = [
  348. sys.executable if lang.startswith("python") else _cmd(lang),
  349. f".\\{filename}" if WIN32 else filename,
  350. ]
  351. with ThreadPoolExecutor(max_workers=1) as executor:
  352. future = executor.submit(
  353. subprocess.run,
  354. cmd,
  355. cwd=work_dir,
  356. capture_output=True,
  357. text=True,
  358. )
  359. try:
  360. result = future.result(timeout=timeout)
  361. except TimeoutError:
  362. if original_filename is None:
  363. os.remove(filepath)
  364. return 1, TIMEOUT_MSG, None
  365. if original_filename is None:
  366. os.remove(filepath)
  367. if result.returncode:
  368. logs = result.stderr
  369. if original_filename is None:
  370. abs_path = str(pathlib.Path(filepath).absolute())
  371. logs = logs.replace(str(abs_path), "").replace(filename, "")
  372. else:
  373. abs_path = str(pathlib.Path(work_dir).absolute()) + PATH_SEPARATOR
  374. logs = logs.replace(str(abs_path), "")
  375. else:
  376. logs = result.stdout
  377. return result.returncode, logs, None
  378. # create a docker client
  379. if use_docker and not docker_running:
  380. raise RuntimeError(
  381. "Docker package is missing or docker is not running. Please make sure docker is running or set use_docker=False."
  382. )
  383. client = docker.from_env()
  384. image_list = (
  385. ["python:3-slim", "python:3", "python:3-windowsservercore"]
  386. if use_docker is True
  387. else [use_docker] if isinstance(use_docker, str) else use_docker
  388. )
  389. for image in image_list:
  390. # check if the image exists
  391. try:
  392. client.images.get(image)
  393. break
  394. except docker.errors.ImageNotFound:
  395. # pull the image
  396. print("Pulling image", image)
  397. try:
  398. client.images.pull(image)
  399. break
  400. except docker.errors.DockerException:
  401. print("Failed to pull image", image)
  402. # get a randomized str based on current time to wrap the exit code
  403. exit_code_str = f"exitcode{time.time()}"
  404. abs_path = pathlib.Path(work_dir).absolute()
  405. cmd = [
  406. "sh",
  407. "-c",
  408. f'{_cmd(lang)} "{filename}"; exit_code=$?; echo -n {exit_code_str}; echo -n $exit_code; echo {exit_code_str}',
  409. ]
  410. # create a docker container
  411. container = client.containers.run(
  412. image,
  413. command=cmd,
  414. working_dir="/workspace",
  415. detach=True,
  416. # get absolute path to the working directory
  417. volumes={abs_path: {"bind": "/workspace", "mode": "rw"}},
  418. )
  419. start_time = time.time()
  420. while container.status != "exited" and time.time() - start_time < timeout:
  421. # Reload the container object
  422. container.reload()
  423. if container.status != "exited":
  424. container.stop()
  425. container.remove()
  426. if original_filename is None:
  427. os.remove(filepath)
  428. return 1, TIMEOUT_MSG, image
  429. # get the container logs
  430. logs = container.logs().decode("utf-8").rstrip()
  431. # commit the image
  432. tag = _sanitize_filename_for_docker_tag(filename)
  433. container.commit(repository="python", tag=tag)
  434. # remove the container
  435. container.remove()
  436. # check if the code executed successfully
  437. exit_code = container.attrs["State"]["ExitCode"]
  438. if exit_code == 0:
  439. # extract the exit code from the logs
  440. pattern = re.compile(f"{exit_code_str}(\\d+){exit_code_str}")
  441. match = pattern.search(logs)
  442. exit_code = 1 if match is None else int(match.group(1))
  443. # remove the exit code from the logs
  444. logs = logs if match is None else pattern.sub("", logs)
  445. if original_filename is None:
  446. os.remove(filepath)
  447. if exit_code:
  448. logs = logs.replace(f"/workspace/{filename if original_filename is None else ''}", "")
  449. # return the exit code, logs and image
  450. return exit_code, logs, f"python:{tag}"
  451. _GENERATE_ASSERTIONS_CONFIG = {
  452. "prompt": """Given the signature and docstring, write the exactly same number of assertion(s) for the provided example(s) in the docstring, without assertion messages.
  453. func signature:
  454. {definition}
  455. assertions:""",
  456. "model": FAST_MODEL,
  457. "max_tokens": 256,
  458. "stop": "\n\n",
  459. }
  460. def generate_assertions(definition: str, **config) -> Tuple[str, float]:
  461. """(openai<1) Generate assertions for a function.
  462. Args:
  463. definition (str): The function definition, including the signature and docstr.
  464. config (Optional, dict): The configuration for the API call.
  465. Returns:
  466. str: The generated assertions.
  467. float: The cost of the generation.
  468. """
  469. params = {**_GENERATE_ASSERTIONS_CONFIG, **config}
  470. response = oai.Completion.create(
  471. {"definition": definition},
  472. **params,
  473. )
  474. assertions = oai.Completion.extract_text(response)[0]
  475. return assertions, response["cost"]
  476. def _remove_check(response):
  477. """Remove the check function from the response."""
  478. # find the position of the check function
  479. pos = response.find("def check(")
  480. if pos == -1:
  481. return response
  482. return response[:pos]
  483. def eval_function_completions(
  484. responses: List[str],
  485. definition: str,
  486. test: Optional[str] = None,
  487. entry_point: Optional[str] = None,
  488. assertions: Optional[Union[str, Callable[[str], Tuple[str, float]]]] = None,
  489. timeout: Optional[float] = 3,
  490. use_docker: Optional[bool] = True,
  491. ) -> Dict:
  492. """(openai<1) Select a response from a list of responses for the function completion task (using generated assertions), and/or evaluate if the task is successful using a gold test.
  493. Args:
  494. responses (list): The list of responses.
  495. definition (str): The input definition.
  496. test (Optional, str): The test code.
  497. entry_point (Optional, str): The name of the function.
  498. assertions (Optional, str or Callable): The assertion code which serves as a filter of the responses, or an assertion generator.
  499. When provided, only the responses that pass the assertions will be considered for the actual test (if provided).
  500. timeout (Optional, float): The timeout for executing the code.
  501. Returns:
  502. dict: The success metrics.
  503. """
  504. n = len(responses)
  505. if assertions is None:
  506. # no assertion filter
  507. success_list = []
  508. for i in range(n):
  509. response = _remove_check(responses[i])
  510. code = (
  511. f"{response}\n{test}\ncheck({entry_point})"
  512. if response.startswith("def")
  513. else f"{definition}{response}\n{test}\ncheck({entry_point})"
  514. )
  515. success = execute_code(code, timeout=timeout, use_docker=use_docker)[0] == 0
  516. success_list.append(success)
  517. return {
  518. "expected_success": 1 - pow(1 - sum(success_list) / n, n),
  519. "success": any(s for s in success_list),
  520. }
  521. if callable(assertions) and n > 1:
  522. # assertion generator
  523. assertions, gen_cost = assertions(definition)
  524. else:
  525. assertions, gen_cost = None, 0
  526. if n > 1 or test is None:
  527. for i in range(n):
  528. response = responses[i] = _remove_check(responses[i])
  529. code = (
  530. f"{response}\n{assertions}" if response.startswith("def") else f"{definition}{response}\n{assertions}"
  531. )
  532. succeed_assertions = execute_code(code, timeout=timeout, use_docker=use_docker)[0] == 0
  533. if succeed_assertions:
  534. break
  535. else:
  536. # just test, no need to check assertions
  537. succeed_assertions = False
  538. i, response = 0, responses[0]
  539. if test is None:
  540. # no test code
  541. return {
  542. "index_selected": i,
  543. "succeed_assertions": succeed_assertions,
  544. "gen_cost": gen_cost,
  545. "assertions": assertions,
  546. }
  547. code_test = (
  548. f"{response}\n{test}\ncheck({entry_point})"
  549. if response.startswith("def")
  550. else f"{definition}{response}\n{test}\ncheck({entry_point})"
  551. )
  552. success = execute_code(code_test, timeout=timeout, use_docker=use_docker)[0] == 0
  553. return {
  554. "index_selected": i,
  555. "succeed_assertions": succeed_assertions,
  556. "success": success,
  557. "gen_cost": gen_cost,
  558. "assertions": assertions,
  559. }
  560. _FUNC_COMPLETION_PROMPT = "# Python 3{definition}"
  561. _FUNC_COMPLETION_STOP = ["\nclass", "\ndef", "\nif", "\nprint"]
  562. _IMPLEMENT_CONFIGS = [
  563. {"model": FAST_MODEL, "prompt": _FUNC_COMPLETION_PROMPT, "temperature": 0, "cache_seed": 0},
  564. {"model": FAST_MODEL, "prompt": _FUNC_COMPLETION_PROMPT, "stop": _FUNC_COMPLETION_STOP, "n": 7, "cache_seed": 0},
  565. {"model": DEFAULT_MODEL, "prompt": _FUNC_COMPLETION_PROMPT, "temperature": 0, "cache_seed": 1},
  566. {"model": DEFAULT_MODEL, "prompt": _FUNC_COMPLETION_PROMPT, "stop": _FUNC_COMPLETION_STOP, "n": 2, "cache_seed": 2},
  567. {"model": DEFAULT_MODEL, "prompt": _FUNC_COMPLETION_PROMPT, "stop": _FUNC_COMPLETION_STOP, "n": 1, "cache_seed": 2},
  568. ]
  569. class PassAssertionFilter:
  570. def __init__(self, assertions):
  571. self._assertions = assertions
  572. self.cost = 0
  573. self.metrics = self.responses = None
  574. def pass_assertions(self, context, response, **_):
  575. """(openai<1) Check if the response passes the assertions."""
  576. responses = oai.Completion.extract_text(response)
  577. metrics = eval_function_completions(responses, context["definition"], assertions=self._assertions)
  578. self._assertions = metrics["assertions"]
  579. self.cost += metrics["gen_cost"]
  580. self.metrics = metrics
  581. self.responses = responses
  582. return metrics["succeed_assertions"]
  583. def implement(
  584. definition: str,
  585. configs: Optional[List[Dict]] = None,
  586. assertions: Optional[Union[str, Callable[[str], Tuple[str, float]]]] = generate_assertions,
  587. ) -> Tuple[str, float]:
  588. """(openai<1) Implement a function from a definition.
  589. Args:
  590. definition (str): The function definition, including the signature and docstr.
  591. configs (list): The list of configurations for completion.
  592. assertions (Optional, str or Callable): The assertion code which serves as a filter of the responses, or an assertion generator.
  593. Returns:
  594. str: The implementation.
  595. float: The cost of the implementation.
  596. int: The index of the configuration which generates the implementation.
  597. """
  598. cost = 0
  599. configs = configs or _IMPLEMENT_CONFIGS
  600. if len(configs) > 1 and callable(assertions):
  601. assertions, cost = assertions(definition)
  602. assertion_filter = PassAssertionFilter(assertions)
  603. response = oai.Completion.create(
  604. {"definition": definition}, config_list=configs, filter_func=assertion_filter.pass_assertions
  605. )
  606. cost += assertion_filter.cost + response["cost"]
  607. return assertion_filter.responses[assertion_filter.metrics["index_selected"]], cost, response["config_id"]
  608. # for i, config in enumerate(configs):
  609. # response = oai.Completion.create({"definition": definition}, **config)
  610. # cost += oai.Completion.cost(response)
  611. # responses = oai.Completion.extract_text(response)
  612. # metrics = eval_function_completions(responses, definition, assertions=assertions)
  613. # assertions = metrics["assertions"]
  614. # cost += metrics["gen_cost"]
  615. # if metrics["succeed_assertions"] or i == len(configs) - 1:
  616. # return responses[metrics["index_selected"]], cost, i