Open-source, secure environment with real-world tools for enterprise-grade agents.
Python agentaiai-agentai-agentscode-interpretercopilotdevelopmentdevtoolsgptgpt-4javascriptllmnextjsopenaipythonreactsoftwaretypescript
commit
Vasek Mlejnsky7b509f142716
diff --git a/api-service/codegen/agent/base.py b/api-service/codegen/agent/base.pyindex e0871bf27..4153c937e 100644--- a/api-service/codegen/agent/base.py+++ b/api-service/codegen/agent/base.py@@ -1,5 +1,4 @@from typing import Optional, Tuple, List, Dict, Union-import jsonimport xml.etree.ElementTree as ETfrom langchain.agents.tools import InvalidTool@@ -9,7 +8,8 @@ from langchain.schema import AgentAction, AgentFinishfrom langchain.tools.base import BaseToolFINAL_ANSWER_ACTION = "Final Answer:"-+ACTIONS_QUEUE = "action_queue"+MALFORMED_ANSWER = "malformed_answer"# class ActionRouter(BaseTool):# name = "action_router"@@ -17,51 +17,57 @@ FINAL_ANSWER_ACTION = "Final Answer:"class CodegenAgent(ChatAgent):- def _construct_scratchpad(- self, intermediate_steps: List[Tuple[AgentAction, str]]- ) -> str:- # print("CONSTRUCTING SCRATCHPAD before:")- # print(len(intermediate_steps))-- # Leave only the latest element in the `intermediate_steps` list- # if len(intermediate_steps) > 4:- # intermediate_steps = intermediate_steps[len(intermediate_steps) - 2 :]- # print(intermediate_steps)-- # print("CONSTRUCTING SCRATCHPAD after:")- # print(len(intermediate_steps))-- agent_scratchpad = super()._construct_scratchpad(intermediate_steps)- # print("=======================SCRATCHPAD:", agent_scratchpad)- # print("=======================")- if not isinstance(agent_scratchpad, str):- raise ValueError("agent_scratchpad should be of type string.")- if agent_scratchpad:- return (- f"This was your previous work "- f"(but I haven't seen any of it! I only see what "- f"you return as final answer):\n{agent_scratchpad}"- )- else:- return agent_scratchpad+ # def _construct_scratchpad(+ # self, intermediate_steps: List[Tuple[AgentAction, str]]+ # ) -> str:+ # # print("CONSTRUCTING SCRATCHPAD before:")+ # # print(len(intermediate_steps))++ # # Leave only the latest element in the `intermediate_steps` list+ # # if len(intermediate_steps) > 4:+ # # intermediate_steps = intermediate_steps[len(intermediate_steps) - 2 :]+ # # print(intermediate_steps)++ # # print("CONSTRUCTING SCRATCHPAD after:")+ # # print(len(intermediate_steps))++ # agent_scratchpad = super()._construct_scratchpad(intermediate_steps)+ # # print("=======================SCRATCHPAD:", agent_scratchpad)+ # # print("=======================")+ # if not isinstance(agent_scratchpad, str):+ # raise ValueError("agent_scratchpad should be of type string.")+ # if agent_scratchpad:+ # return (+ # f"This was your previous work "+ # f"(but I haven't seen any of it! I only see what "+ # f"you return as final answer):\n{agent_scratchpad}"+ # )+ # else:+ # return agent_scratchpaddef _extract_tool_and_input(self, text: str) -> Optional[Tuple[str, str]]:if FINAL_ANSWER_ACTION in text:return "Final Answer", text.split(FINAL_ANSWER_ACTION)[-1].strip()try:- # TODO: Here we can change the JSON formated `action` + `action_input` to something- # more suited to our use-case so the model doesn't need to escape the generated code._, action, _ = text.split("```")root = ET.fromstring(f"<root>{action.strip()}</root>")actions = root.findall("action")++ # We handle the case when the LLM starts specifying multiple actions in a single response.if len(actions) > 1:- return "action_router", action.strip()+ return ACTIONS_QUEUE, action.strip()else:return actions[0].attrib["tool"], actions[0].text-- # response = json.loads(action.strip())- # return response["action"], response["action_input"]except Exception as e:+ # Sometimes the agent just completely messed up the output format.+ # We want to remind it that the last answer was wrong and it should+ # follow the format.+ return (+ MALFORMED_ANSWER,+ """I just tried to parse your last reponse and received this error:+ {e}+ Reminder, that you should follow the format I told you!""",+ )# TODO: I think this is buggy. I haven't really had a chance to properly test it and debug the model's behavior.print(f"====== Got exception '{str(e)}'\n text:\n{text}")# input = response["action_input"]@@ -122,6 +128,8 @@ class CodegenAgentExecutor(AgentExecutor):if isinstance(output, AgentFinish):return output# Sometimes the LLM decides to pass the value of `FINAL_ANSWER_ACTION` as a tool name.+ # Instead of trying to "force" the LLM to don't do that, we can just write a bit of+ # code and handle this case.elif output.tool == FINAL_ANSWER_ACTION:return AgentFinish({"output": action.tool_input}, action.log)@@ -129,8 +137,16 @@ class CodegenAgentExecutor(AgentExecutor):output, verbose=self.verbose, color="green")- #- if output.tool == "action_router":+ # Sometimes the agent just completely messed up the output format.+ # We want to remind it that the last answer was wrong and it should+ # follow the format.+ if output.tool == MALFORMED_ANSWER:+ return output, output.tool_input++ # The `ACTIONS_QUEUE` isn't really a name of a tool.+ # It's a way for us to specify that the LLM passed multiple actions in a single response.+ # We handle this case by running each action one by one.+ if output.tool == ACTIONS_QUEUE:observation = ""# The `output.tool_input` is a XML tree with multiple actions# Go through each action and run it.diff --git a/api-service/codegen/callback_handler.py b/api-service/codegen/callback_handler.pynew file mode 100644index 000000000..e8100593b--- /dev/null+++ b/api-service/codegen/callback_handler.py@@ -0,0 +1,86 @@+from typing import Dict, Any, List, Union+import sys++from langchain.callbacks.base import BaseCallbackHandler+from langchain.schema import AgentAction, AgentFinish, LLMResult+++class CustomCallbackHandler(BaseCallbackHandler):+ def on_llm_start(+ self, serialized: Dict[str, Any], prompts: List[str], **kwargs: Any+ ) -> None:+ """Run when LLM starts running."""+ pass++ def on_llm_new_token(self, token: str, **kwargs: Any) -> None:+ """Run on new LLM token. Only available when streaming is enabled."""+ pass++ def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None:+ """Run when LLM ends running."""+ pass++ def on_llm_error(+ self, error: Union[Exception, KeyboardInterrupt], **kwargs: Any+ ) -> None:+ """Run when LLM errors."""+ pass++ def on_chain_start(+ self, serialized: Dict[str, Any], inputs: Dict[str, Any], **kwargs: Any+ ) -> None:+ """Run when chain starts running."""+ pass++ def on_chain_end(self, outputs: Dict[str, Any], **kwargs: Any) -> None:+ """Run when chain ends running."""+ pass++ def on_chain_error(+ self, error: Union[Exception, KeyboardInterrupt], **kwargs: Any+ ) -> None:+ """Run when chain errors."""+ pass++ def on_tool_start(+ self, serialized: Dict[str, Any], input_str: str, **kwargs: Any+ ) -> None:+ """Run when tool starts running."""+ print("[+CustomCallbackHandler] TOOL START", flush=True)+ print(serialized)+ print(input_str)+ print("[-CustomCallbackHandler]")+ sys.stdout.flush()++ def on_tool_end(self, output: str, **kwargs: Any) -> None:+ """Run when tool ends running."""+ print("[+CustomCallbackHandler] TOOL END", flush=True)+ print(output)+ print("[-CustomCallbackHandler]")+ sys.stdout.flush()++ def on_tool_error(+ self, error: Union[Exception, KeyboardInterrupt], **kwargs: Any+ ) -> None:+ """Run when tool errors."""+ print("[+CustomCallbackHandler] TOOL ERROR")+ print(error)+ print("[-CustomCallbackHandler]")+ sys.stdout.flush()++ def on_agent_action(self, action: AgentAction, **kwargs: Any) -> Any:+ """Run on agent action."""+ print("[+CustomCallbackHandler] AGENT ACTION", flush=True)+ print(action.tool)+ print(action.log)+ print(action.tool_input)+ print("[-CustomCallbackHandler]")+ sys.stdout.flush()++ def on_text(self, text: str, **kwargs: Any) -> None:+ """Run on arbitrary text."""+ pass++ def on_agent_finish(self, finish: AgentFinish, **kwargs: Any) -> None:+ """Run on agent end."""+ passdiff --git a/api-service/codegen/codegen.py b/api-service/codegen/codegen.pyindex aa15bc53e..317c8c50b 100644--- a/api-service/codegen/codegen.py+++ b/api-service/codegen/codegen.py@@ -7,13 +7,12 @@ from typing import (Optional,)import subprocess+from time import sleepfrom pydantic import BaseModel-from langchain.llms.openai import OpenAIChat, OpenAIfrom langchain.chat_models import ChatOpenAIfrom langchain.callbacks.base import CallbackManagerfrom langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandler-from langchain.agents import AgentExecutorfrom langchain.tools import BaseTool# from codegen.tools.documentation import ReadDocumentation@@ -33,17 +32,36 @@ from codegen.prompt import (HUMAN_INSTRUCTIONS_PREFIX,HUMAN_INSTRUCTIONS_SUFFIX,)+from .callback_handler import CustomCallbackHandler-class OutputFinalCode(BaseTool):- name = "OutputFinalCode"- description = "This is the last tool you would use. You use it when you know the final server code and you want to output it. The input should be the final server code that does what the user required."+class AskHuman(BaseTool):+ name = "AskHuman"+ description = "You can ask a human for guidance when you think you got stuck or you are not sure what to do next. The input should be a question for the human."++ def _run(self, question: str) -> str:+ print(question)+ sleep(60)+ with open(+ "/Users/vasekmlejnsky/Developer/ai-api/api-service/codegen/human_input.txt"+ ) as f:+ human_input = f.read()+ print("human_input:", human_input)+ return human_input++ async def _arun(self, question: str) -> str:+ return NotImplementedError("AskHuman does not support async")- def _run(self, final_code: str) -> str:- return final_code- async def _arun(self, final_code: str) -> str:- return NotImplementedError("OutputFinalCode does not support async")+# class OutputFinalCode(BaseTool):+# name = "OutputFinalCode"+# description = "This is the last tool you would use. You use it when you know the final server code and you want to output it. The input should be the final server code that does what the user required."++# def _run(self, final_code: str) -> str:+# return final_code++# async def _arun(self, final_code: str) -> str:+# return NotImplementedError("OutputFinalCode does not support async")class WriteCodeToFile(BaseTool):@@ -106,6 +124,9 @@ class DeployCode(BaseTool):# 6. Once all works without any bugs and errors, write the code to the file.# 7. Deploy the code.# """+cm = CallbackManager([StreamingStdOutCallbackHandler(), CustomCallbackHandler()])++class Codegen(BaseModel):agent: Optional[CodegenAgent]agent_executor: Optional[CodegenAgentExecutor]@@ -114,12 +135,14 @@ class Codegen(BaseModel):temperature=0,max_tokens=2056,verbose=True,- callback_manager=CallbackManager([StreamingStdOutCallbackHandler()]),+ callback_manager=cm,+ # callback_manager=CallbackManager([CustomCallbackHandler()]),)input_variables = ["input", "agent_scratchpad", "method"]tools = [# InvalidTool(),# OutputFinalCode(),+ AskHuman(),WriteCodeToFile(),DeployCode(),]diff --git a/api-service/codegen/human_input.txt b/api-service/codegen/human_input.txtnew file mode 100644index 000000000..21cb523e3--- /dev/null+++ b/api-service/codegen/human_input.txt@@ -0,0 +1 @@+I just set it, you are good to go\ No newline at end of filediff --git a/api-service/codegen/prompt.py b/api-service/codegen/prompt.pyindex 4aea32834..ce31ec9c6 100644--- a/api-service/codegen/prompt.py+++ b/api-service/codegen/prompt.py@@ -3,6 +3,7 @@PREFIX = """You are an AI JavaScript/Nodejs assistant.- Follow the user's instructions carefully & to the letter.- Minimize any other prose.+- NEVER deploy code before you run it and are sure it is working.- You are building an Express server that handles REST API.- You have access to the following tools:"""@@ -12,14 +13,15 @@ PREFIX = """You are an AI JavaScript/Nodejs assistant.# "action_input": $INPUT# }}}}FORMAT_INSTRUCTIONS = """"The way you use the tools is by specifying a XML snippet.-Specifically, this XML snippet MUST have a `<action tool="$TOOL_NAME">$INPUT</action>` element (with the name of the tool in the `tool` attribute and input for the tool inside the XML tag).-The XML snippect CANNOT HAVE MORE THAN ONE ACTION. Do NOT use multiple actions at once. Here is an example of a valid XML code snippet:+Specifically, this XML snippet MUST have a `<action tool="$TOOL_NAME">$INPUT</action>` element with the name of the tool in the `tool` attribute and input for the tool inside the XML tag.++Here is an example of a valid XML code snippet:```<action tool="$TOOL_NAME">$INPUT</action>```-ALWAYS use the following format and NEVER specify more than ONE ACTION AT THE TIME:+ALWAYS use the following format:Instructions: the input instructions you must implement