Open-source, secure environment with real-world tools for enterprise-grade agents.
Python agentaiai-agentai-agentscode-interpretercopilotdevelopmentdevtoolsgptgpt-4javascriptllmnextjsopenaipythonreactsoftwaretypescript
commit
Vasek Mlejnsky8c58d6b60c6d
diff --git a/api-service/app.py b/api-service/app.pyindex fdb08033f..9d116bf8d 100644--- a/api-service/app.py+++ b/api-service/app.py@@ -7,9 +7,13 @@ from flask import Flask, abort, requestfrom flask_cors import CORSfrom codegen.env import EnvVar-from codegen import generate_req_handler++# from codegen import generate_req_handler+from codegen import Codegen+from codegen.tools.playground import create_playground_toolsfrom database import Database, DeploymentState+url = os.environ.get("SUPABASE_URL")key = os.environ.get("SUPABASE_KEY")@@ -54,62 +58,94 @@ def generate():route = body["route"]envs: List[EnvVar] = body["envs"]- db.create_deployment(run_id=run_id, project_id=project_id, route_id=route_id)+ request_body_blocks = [+ block for block in blocks if block.get("type") == "RequestBody"+ ]+ request_body_template = (+ request_body_blocks[0]["prompt"] if len(request_body_blocks) > 0 else None+ )- final_prompt, js_code = generate_req_handler(- db=db,- run_id=run_id,- blocks=blocks,- method=method,- route=route,+ playground_tools, playground = create_playground_tools(envs=envs,+ route=route,+ method=method,+ request_body_template=request_body_template,)- db.update_state(run_id=run_id, state=DeploymentState.Deploying)-- cf_worker_dir_path = (- os.path.abspath(os.path.dirname(__file__)) + "/cf-worker-template"- )- index_js_path = cf_worker_dir_path + "/index.js"- wrangler_template_path = cf_worker_dir_path + "/wrangler.template.toml"- wrangler_path = cf_worker_dir_path + "/wrangler.toml"-- # TODO: Inject code to cf-worker-template/index.js- code = js_code.strip("`").strip()- with open(index_js_path, "w") as file:- file.write(code)-- # Convert envs to the env vars string that looks like this:- # KEY_1 = VALUE_1- # KEY_2 = VALUE_2- envs_str = ""- for env in envs:- if env["key"]:- envs_str += f'{env["key"]} = "{env["value"]}"\n'- # TODO: Update name in cf-worker-template/wrangler.template.toml- replace_file_content(- wrangler_template_path,- wrangler_path,- {"<NAME>": f'"{project_id}"', "<VARS>": envs_str},+ cg = Codegen.from_playground_tools(playground_tools)+ cg.generate(+ route=route,+ envs=envs,+ method=method,+ blocks=blocks,)- # TODO: Call npm run deploy- cmd = ["npm", "run", "deploy", "--prefix", cf_worker_dir_path]- with subprocess.Popen(cmd, stdout=subprocess.PIPE) as proc:- print(proc.stdout.read().decode())-- db.update_state(run_id=run_id, state=DeploymentState.Finished)+ playground.close()- api_url = f"https://{project_id}.devbook.workers.dev"- db.update_url(run_id=run_id, url=api_url)-- # TODO: Report back the URL of deployed APIreturn {- "code": js_code.strip("`").strip(),- "prompt": final_prompt,- "url": api_url,+ "code": "",+ "prompt": "",+ "url": "",}+ ##################++ # db.create_deployment(run_id=run_id, project_id=project_id, route_id=route_id)++ # final_prompt, js_code = generate_req_handler(+ # db=db,+ # run_id=run_id,+ # blocks=blocks,+ # method=method,+ # route=route,+ # envs=envs,+ # )++ # db.update_state(run_id=run_id, state=DeploymentState.Deploying)++ # cf_worker_dir_path = (+ # os.path.abspath(os.path.dirname(__file__)) + "/cf-worker-template"+ # )+ # index_js_path = cf_worker_dir_path + "/index.js"+ # wrangler_template_path = cf_worker_dir_path + "/wrangler.template.toml"+ # wrangler_path = cf_worker_dir_path + "/wrangler.toml"++ # # TODO: Inject code to cf-worker-template/index.js+ # code = js_code.strip("`").strip()+ # with open(index_js_path, "w") as file:+ # file.write(code)++ # # Convert envs to the env vars string that looks like this:+ # # KEY_1 = VALUE_1+ # # KEY_2 = VALUE_2+ # envs_str = ""+ # for env in envs:+ # if env["key"]:+ # envs_str += f'{env["key"]} = "{env["value"]}"\n'+ # # TODO: Update name in cf-worker-template/wrangler.template.toml+ # replace_file_content(+ # wrangler_template_path,+ # wrangler_path,+ # {"<NAME>": f'"{project_id}"', "<VARS>": envs_str},+ # )++ # # TODO: Call npm run deploy+ # cmd = ["npm", "run", "deploy", "--prefix", cf_worker_dir_path]+ # with subprocess.Popen(cmd, stdout=subprocess.PIPE) as proc:+ # print(proc.stdout.read().decode())++ # db.update_state(run_id=run_id, state=DeploymentState.Finished)++ # api_url = f"https://{project_id}.devbook.workers.dev"+ # db.update_url(run_id=run_id, url=api_url)++ # # TODO: Report back the URL of deployed API+ # return {+ # "code": js_code.strip("`").strip(),+ # "prompt": final_prompt,+ # "url": api_url,+ # }+if __name__ == "__main__":app.run(debug=True, host="0.0.0.0", port=int(os.environ.get("PORT", 8080)))diff --git a/api-service/codegen/__init__.py b/api-service/codegen/__init__.pyindex e69de29bb..ee2367881 100644--- a/api-service/codegen/__init__.py+++ b/api-service/codegen/__init__.py@@ -0,0 +1 @@+from .codegen import Codegendiff --git a/api-service/codegen/agent/base.py b/api-service/codegen/agent/base.pyindex f4919b157..5dfa95f59 100644--- a/api-service/codegen/agent/base.py+++ b/api-service/codegen/agent/base.py@@ -39,20 +39,19 @@ class CodegenAgent(ChatAgent):def _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()- _, action, _ = text.split("```")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("```")response = json.loads(action.strip())return response["action"], response["action_input"]except Exception as e:# 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)}' when parsing json:\n{action.strip()}"- )+ print(f"====== Got exception '{str(e)}'\n text:\n{text}")# input = response["action_input"]return ("InvalidTool",- f"I just ran your response via json.loads and received this error\n{str(e)}\nPlease try again",+ f"[{text[:50]}...]",+ # f"You are not following the response format as I told you. I just ran your response via json.loads and received this error\n{str(e)}\nPlease try again and change your response.",)# raise ValueError(f"Could not parse LLM output: {text}")diff --git a/api-service/codegen/codegen.py b/api-service/codegen/codegen.pyindex 40986285d..a0fe3f4d3 100644--- a/api-service/codegen/codegen.py+++ b/api-service/codegen/codegen.py@@ -1,4 +1,12 @@-from typing import List, Tuple, List, Any, Dict+from typing import (+ List,+ Tuple,+ List,+ Any,+ Dict,+ Optional,+)+import subprocessfrom pydantic import BaseModelfrom langchain.llms.openai import OpenAIChat, OpenAI@@ -6,22 +14,112 @@ from langchain.chat_models import ChatOpenAIfrom langchain.callbacks.base import CallbackManagerfrom langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandlerfrom langchain.agents import AgentExecutor+from langchain.tools import BaseTool# from codegen.tools.documentation import ReadDocumentation-from codegen.env import EnvVar-from codegen.js_agent import create_js_agent-from codegen.prompt import PREFIX, SUFFIX, FORMAT_INSTRUCTIONS-from codegen.tools.playground import create_playground_tools-from database import Database+# from codegen.env import EnvVar+# from codegen.js_agent import create_js_agent+# from codegen.prompt import PREFIX, SUFFIX, FORMAT_INSTRUCTIONS+# from codegen.tools.playground import create_playground_tools+# from database import Database-from codegen.tools.playground import create_playground_tools+# from codegen.tools.playground import create_playground_tools+from codegen.env import EnvVarfrom codegen.agent import CodegenAgent-from codegen.prompt import PREFIX, SUFFIX, FORMAT_INSTRUCTIONS+from codegen.prompt import (+ PREFIX,+ SUFFIX,+ FORMAT_INSTRUCTIONS,+ HUMAN_INSTRUCTIONS_PREFIX,+ HUMAN_INSTRUCTIONS_SUFFIX,+)+++class InvalidTool(BaseTool):+ name = "InvalidTool"+ description = "Do not use this tool! It is for human system admin only!"++ def _run(self, err: str) -> str:+ return err++ async def _arun(self, err: str) -> str:+ return err+++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):+ name = "WriteCodeToFile"+ description = """Writes code to the index.js file. The input should be the code to be written."""+ def _run(self, code: str) -> str:+ print(f"Writing code to file: \n{code}")+ with open(+ "/Users/vasekmlejnsky/Developer/nodejs-express-server/index.js", "w"+ ) as f:+ f.write(+ f"""+ import {{ createRequire }} from "module";+ const require = createRequire(import.meta.url);+ {code}"""+ )+ return "wrote code to index.js"+ async def _arun(self, err: str) -> str:+ return NotImplementedError("WriteCodeToFile does not support async")+++class DeployCode(BaseTool):+ name = "DeployCode"+ description = """Deploys the code."""++ def _run(self, empty: str) -> str:+ print("Deploying...")+ p = subprocess.Popen(+ ["git", "add", "."],+ cwd="/Users/vasekmlejnsky/Developer/nodejs-express-server",+ )+ p.wait()+ p = subprocess.Popen(+ ["git", "commit", "-m", "Deploy"],+ cwd="/Users/vasekmlejnsky/Developer/nodejs-express-server",+ )+ p.wait()+ p = subprocess.Popen(+ [+ "git",+ "push",+ ],+ cwd="/Users/vasekmlejnsky/Developer/nodejs-express-server",+ )+ p.wait()+ return f"deployed server"++ async def _arun(self, empty: str) -> str:+ return NotImplementedError("DeployCode does not support async")+++# testing_instructions = """Here are your instructions:+# 1. Extract `email` from the incoming POST request.+# 2. If there's no email, respond back with an error.+# 3. Otherwise, respond back with the part of the email before the '@' sign.+# 4. Generate the full required server code and make sure it starts without any errors.+# 5. Test that the generated server from the previous step behaves as is required by making mock `curl` requests to the server.+# 6. Once all works without any bugs and errors, write the code to the file.+# 7. Deploy the code.+# """class Codegen(BaseModel):- agent: CodegenAgent- agent_executor: AgentExecutor+ agent: Optional[CodegenAgent]+ agent_executor: Optional[AgentExecutor]llm = ChatOpenAI(streaming=True,temperature=0,@@ -30,25 +128,16 @@ class Codegen(BaseModel):callback_manager=CallbackManager([StreamingStdOutCallbackHandler()]),)input_variables = ["input", "agent_scratchpad", "method"]- tools = []+ tools = [+ # InvalidTool(),+ # OutputFinalCode(),+ WriteCodeToFile(),+ DeployCode(),+ ]@classmethoddef from_playground_tools(cls, playground_tools: Tuple[List[Any]]):c = cls()- print(c.input_variables)- print(c.tools)-- # Create prompt- prompt = CodegenAgent.create_prompt(- tools=[- *playground_tools,- *c.tools,- ],- prefix=PREFIX,- suffix=SUFFIX,- format_instructions=FORMAT_INSTRUCTIONS,- input_variables=c.input_variables,- )# Create CodegenAgent and its executorc.agent = CodegenAgent.from_llm_and_tools(@@ -73,84 +162,122 @@ class Codegen(BaseModel):return c- def generate():- # TODO- pass+ def generate(+ self,+ envs: List[EnvVar],+ route: str,+ method: str,+ blocks: List[Dict],+ ):+ input_vars = {+ "route": route,+ "method": method,+ }+ instructions = "Here are the instructions:"+ inst_idx = 0+ # Append the premade prefix instructions.+ for instruction in HUMAN_INSTRUCTIONS_PREFIX:+ inst_idx += 1-cg = Codegen()+ values = []+ # Extract the correct values from `input_vars` based on the keys.+ for k, v in input_vars.items():+ if k in instruction["variables"]:+ values.append(v)+ # Use the values to format the instruction string.+ inst = instruction["content"].format(*values)+ instructions = instructions + "\n" + f"{inst_idx}. {inst}"-def generate_req_handler(- db: Database,- run_id: str,- blocks: List[Dict],- method: str,- route: str,- envs: List[EnvVar],-):- request_body_blocks = [- block for block in blocks if block.get("type") == "RequestBody"- ]- request_body_template = (- request_body_blocks[0]["prompt"] if len(request_body_blocks) > 0 else None- )- playground_tools, playground = create_playground_tools(- envs=envs,- route=route,- method=method,- request_body_template=request_body_template,- )+ for block in blocks:+ if block.get("type") == "Basic":+ inst_idx += 1+ instructions = instructions + "\n" + f"{inst_idx}. " + block["prompt"]- steps = ""- for idx, block in enumerate(blocks):- if block.get("type") == "Basic":- steps = steps + "\n" + "{}. ".format(idx + 1) + block["prompt"] + "\n"- tool_names = ["InstallNPMDependencies", "RunJavaScriptCode"]- prefix = PREFIX.format(- method=method,- tool_names=tool_names,- steps=steps,- request_body=request_body_template,- )- format_instructions = FORMAT_INSTRUCTIONS.format(- tool_names=tool_names,- )- executor = create_js_agent(- db=db,- run_id=run_id,- llm=OpenAI(temperature=0, max_tokens=1000),- # llm=OpenAI(temperature=0, model_name='code-davinci-002', max_tokens=1000),- # llm=OpenAIChat(temperature=0, max_tokens=1000),- tools=[- # ReadDocumentation()- *playground_tools,- ],- verbose=True,- prefix=prefix,- format_instructions=format_instructions,- )+ # Append the premade suffix instructions.+ for inst in HUMAN_INSTRUCTIONS_SUFFIX:+ inst_idx += 1+ instructions = instructions + "\n" + f"{inst_idx}. {inst}"++ self.agent_executor.run(+ agent_scratchpad="",+ # input=testing_instructions+ input=instructions,+ method=method,+ )+++# def generate_req_handler(+# db: Database,+# run_id: str,+# blocks: List[Dict],+# method: str,+# route: str,+# envs: List[EnvVar],+# ):+# request_body_blocks = [+# block for block in blocks if block.get("type") == "RequestBody"+# ]+# request_body_template = (+# request_body_blocks[0]["prompt"] if len(request_body_blocks) > 0 else None+# )+# playground_tools, playground = create_playground_tools(+# envs=envs,+# route=route,+# method=method,+# request_body_template=request_body_template,+# )++# steps = ""+# for idx, block in enumerate(blocks):+# if block.get("type") == "Basic":+# steps = steps + "\n" + "{}. ".format(idx + 1) + block["prompt"] + "\n"+# tool_names = ["InstallNPMDependencies", "RunJavaScriptCode"]+# prefix = PREFIX.format(+# method=method,+# tool_names=tool_names,+# steps=steps,+# request_body=request_body_template,+# )+# format_instructions = FORMAT_INSTRUCTIONS.format(+# tool_names=tool_names,+# )+# executor = create_js_agent(+# db=db,+# run_id=run_id,+# llm=OpenAI(temperature=0, max_tokens=1000),+# # llm=OpenAI(temperature=0, model_name='code-davinci-002', max_tokens=1000),+# # llm=OpenAIChat(temperature=0, max_tokens=1000),+# tools=[+# # ReadDocumentation()+# *playground_tools,+# ],+# verbose=True,+# prefix=prefix,+# format_instructions=format_instructions,+# )- # Convert env vars to Javascript comments, each on its on line for each env var.- # envs_str = ""- # for env in envs:- # envs_str += f'// const {env["key"]} = `env.{env["key"]}`\n'+# # Convert env vars to Javascript comments, each on its on line for each env var.+# # envs_str = ""+# # for env in envs:+# # envs_str += f'// const {env["key"]} = `env.{env["key"]}`\n'- # prompt = PREFIX.format(- # method=method, envs=envs_str, request_body=request_body_template- # )+# # prompt = PREFIX.format(+# # method=method, envs=envs_str, request_body=request_body_template+# # )- # for idx, block in enumerate(blocks):- # if block.get("type") == "Basic":- # prompt = prompt + "\n" + "{}. ".format(idx + 1) + block["prompt"] + "\n"+# # for idx, block in enumerate(blocks):+# # if block.get("type") == "Basic":+# # prompt = prompt + "\n" + "{}. ".format(idx + 1) + block["prompt"] + "\n"- # prompt = prompt + "\n" + SUFFIX.format(method=method)+# # prompt = prompt + "\n" + SUFFIX.format(method=method)- # handler_code = executor.run(prompt).strip("`").strip()- handler_code = executor.run(f"Requirement:").strip("`").strip()- print("CODE")- print(handler_code)+# # handler_code = executor.run(prompt).strip("`").strip()+# handler_code = executor.run(f"Requirement:").strip("`").strip()+# print("CODE")+# print(handler_code)- playground.close()+# playground.close()- return "", handler_code+# return "", handler_codediff --git a/api-service/codegen/prompt.py b/api-service/codegen/prompt.pyindex ed09fdcb3..c59444314 100644--- a/api-service/codegen/prompt.py+++ b/api-service/codegen/prompt.py@@ -1,9 +1,9 @@+# - ALWAYS use `import` to import packages.PREFIX = """You are an AI JavaScript/Nodejs assistant.- Follow the user's instructions carefully & to the letter.- Minimize any other prose.- You are building an Express server that handles REST API.-- ALWAYS use `import` to import packages.-- Make sure any code you generate is JSON escaped+- Make sure any code you generate is JSON escaped.- You have access to the following tools:"""FORMAT_INSTRUCTIONS = """"The way you use the tools is by specifying a json blob.@@ -30,7 +30,26 @@ Action:```Observation: the result of the action... (this Thought/Action/Observation can repeat N times)-Thought: I now know the final answer-Final Answer: the final code that satisfies all the input instructions. THE FINAL ANSWER IT MUST BE JUST THE CODE."""+Thought: I now know the final server code and can show it.+Final Answer: the final server code"""-SUFFIX = """Begin! Reminder to NEVER use tools you don't have access to and ALWAYS use the exact characters `Final Answer` when responding."""+SUFFIX = """Begin! Reminder to NEVER use tools you don't have access to and ALWAYS use the exact the action `OutputFinalCode` when you know the final server code."""++HUMAN_INSTRUCTIONS_PREFIX = [+ {+ "variables": ["method"],+ "content": """The HTTP request handler is of type {0}""",+ },+ {+ "variables": ["route"],+ "content": """The request handler MUST be on the route `{0}`""",+ },+ # """The request handler must be on the route `{route}`""",+]++HUMAN_INSTRUCTIONS_SUFFIX = [+ "Generate the full required server code and make sure it starts without any errors.",+ "Test that the generated server from the previous step behaves as is required by making mock `curl` requests to the server.",+ "Once all works without any bugs and errors, write the code to the file.",+ "Deploy the code.",+]diff --git a/api-service/codegen/tools/playground/mock/request.py b/api-service/codegen/tools/playground/mock/request.pyindex 7973dae2f..03948e839 100644--- a/api-service/codegen/tools/playground/mock/request.py+++ b/api-service/codegen/tools/playground/mock/request.py@@ -1,6 +1,7 @@import jsonfrom codegen.tools.playground.playground import Playground+class MockRequestFactory:def __init__(self,@@ -23,7 +24,7 @@ class MockRequestFactory:def generate_body_data(self):if self.body_template is None:- return '{}'+ return "{}"body_interface_name = "RequestBody"request_body_template = f"""interface {body_interface_name} {{@@ -31,5 +32,7 @@ class MockRequestFactory:}}"""- body = json.loads(self.playground.mock_body_data(request_body_template, body_interface_name))[body_interface_name]+ body = json.loads(+ self.playground.mock_body_data(request_body_template, body_interface_name)+ )[body_interface_name]return json.dumps(body)diff --git a/api-service/codegen/tools/playground/tools/code.py b/api-service/codegen/tools/playground/tools/code.pyindex 20433497b..8e805e1ec 100644--- a/api-service/codegen/tools/playground/tools/code.py+++ b/api-service/codegen/tools/playground/tools/code.py@@ -26,6 +26,7 @@ def create_code_tools(playground: NodeJSPlayground, mock: MockRequestFactory):yield install_dependencieslast_javascript_code: str | None+# This tool is just for executing JavaScript without doing the request to server@tool("RunJavaScriptCode")def run_javascript_code(code: str) -> str:@@ -33,10 +34,16 @@ def create_code_tools(playground: NodeJSPlayground, mock: MockRequestFactory):Run JavaScript code and return errors and output.Input should be a valid JavaScript code."""++ with_require = f"""+ import {{ createRequire }} from "module";+ const require = createRequire(import.meta.url);+ {extract_code(code)}+ """nonlocal last_javascript_code- last_javascript_code = code+ last_javascript_code = with_require- output = playground.run_javascript_code(extract_code(code))+ output = playground.run_javascript_code(with_require)result = encode_command_output(output)return result if len(result) > 0 else "Code execution finished without error"diff --git a/api-service/test.py b/api-service/test.pyindex e39b34217..ed00b4c14 100644--- a/api-service/test.py+++ b/api-service/test.py@@ -84,7 +84,9 @@ class CustomChatAgent(ChatAgent):def _construct_scratchpad(self, intermediate_steps: List[Tuple[AgentAction, str]]) -> str:- # print("CONSTRUCTING SCRATCHPAD before:")+ print(+ "CONSTRUCTING SCRATCHPAD len(intermediate_steps):", len(intermediate_steps)+ )# print(len(intermediate_steps))# Leave only the latest element in the `intermediate_steps` list@@ -109,26 +111,26 @@ class CustomChatAgent(ChatAgent):else:return agent_scratchpad- def _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()- _, action, _ = text.split("```")- 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.- response = json.loads(action.strip())- return response["action"], response["action_input"]- except Exception as e:- # 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)}' when parsing json:\n{action.strip()}"- )- # input = response["action_input"]- return (- "InvalidTool",- f"I just ran your response via json.loads and received this error\n{str(e)}\nPlease try again",- )- # raise ValueError(f"Could not parse LLM output: {text}")+ # def _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()+ # _, action, _ = text.split("```")+ # 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.+ # response = json.loads(action.strip())+ # return response["action"], response["action_input"]+ # except Exception as e:+ # # 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)}' when parsing json:\n{action.strip()}"+ # )+ # # input = response["action_input"]+ # return (+ # "InvalidTool",+ # f"I just ran your response via json.loads and received this error\n{str(e)}\nPlease try again",+ # )+ # # raise ValueError(f"Could not parse LLM output: {text}")OPENAI_API_KEY = "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"@@ -246,6 +248,7 @@ prompt = CustomChatAgent.create_prompt(invalid_tool = InvalidTool()# Create agent and it's executor# agent = ChatAgent.from_llm_and_tools(+memory = ConversationBufferWindowMemory(k=1, return_messages=True)agent = CustomChatAgent.from_llm_and_tools(llm=chat,tools=[@@ -260,6 +263,7 @@ agent = CustomChatAgent.from_llm_and_tools(input_variables=input_variables,# verbose=True,# memory=ConversationBufferWindowMemory(k=2),+ memory=memory,)ae = AgentExecutor.from_agent_and_tools(agent=agent,@@ -269,7 +273,7 @@ ae = AgentExecutor.from_agent_and_tools(WriteCodeToFile(),DeployCode(),],- # memory=ConversationBufferWindowMemory(k=2),+ memory=memory,verbose=True,)@@ -387,5 +391,8 @@ except ValueError as e:# # chat([*chat_messages, instruct1_prompt])+print("=========== MEMORY")+for message in memory.buffer:+ print(message.content)playground.close()