Open-source, secure environment with real-world tools for enterprise-grade agents.
Python agentaiai-agentai-agentscode-interpretercopilotdevelopmentdevtoolsgptgpt-4javascriptllmnextjsopenaipythonreactsoftwaretypescript
Fix logging and smol dev logs
Tomas Valentaa8612a292214
diff --git a/api-service/agent/smol_agent.py b/api-service/agent/smol_agent.pyindex 9363af56b..246f282cb 100644--- a/api-service/agent/smol_agent.py+++ b/api-service/agent/smol_agent.py@@ -73,7 +73,8 @@ class SmolAgent(AgentBase):await self.on_logs({- "message": f"hi its me, 🐣the smol developer🐣! you said you wanted:\n{user_prompt}"+ "message": f"hi its me, 🐣the smol developer🐣! you said you wanted:\n{user_prompt}",+ "type": "info",})playground = None@@ -84,18 +85,39 @@ class SmolAgent(AgentBase):playground = Playground(env_id="PPSrlH5TIvFx", get_envs=self.get_envs)await playground.open()+ await self.on_logs(+ {+ "message": f"Created playground",+ "properties": {+ "playground": "created",+ "id": playground.id,+ },+ "type": "playground",+ }+ )+fixClockDrift = asyncio.ensure_future(playground.sync_clock())rootdir = "/repo"await playground.change_rootdir(rootdir)await playground.make_dir(rootdir)+await playground.clone_repo(repo_address=repo_address,rootdir=rootdir,branch=branch,)- await self.on_logs({"message": f"Cloned repository"})+ await self.on_logs(+ {+ "message": f"Cloned repository",+ "properties": {+ "tool": "git",+ "repository": f"{owner}/{repo}",+ },+ "type": "tool",+ }+ )extensions_to_skip = [".png",@@ -182,6 +204,18 @@ Begin generating the code now.""",)+ await self.on_logs(+ {+ "message": f"Generated file",+ "properties": {+ "content": filecode,+ "filename": filename,+ "model": "gpt-4",+ },+ "type": "model",+ }+ )+return filename, filecodefilepaths_string = await generate_response(@@ -195,6 +229,18 @@ do not add any other explanation, only return a python list of strings.user_prompt,)+ await self.on_logs(+ {+ "message": f"Generating filepaths",+ "properties": {+ "prompt": user_prompt,+ "result": filepaths_string,+ "model": "gpt-4",+ },+ "type": "model",+ }+ )+# parse the result into a python listlist_actual = ast.literal_eval(filepaths_string)@@ -215,10 +261,45 @@ do not add any other explanation, only return a python list of strings.prompt=user_prompt,)+ await self.on_logs(+ {+ "message": f"Generated file",+ "properties": {+ "filename": filename,+ "result": filecode,+ "model": "gpt-4",+ },+ "type": "model",+ }+ )+await playground.write_file(os.path.join(rootdir, filename), filecode)++ await self.on_logs(+ {+ "message": f"Saved file",+ "properties": {+ "filename": filename,+ "content": filecode,+ "tool": "filesystem",+ },+ "type": "tool",+ }+ )+else:await clean_dir()+ await self.on_logs(+ {+ "message": f"Cleaned root directory",+ "properties": {+ "tool": "filesystem",+ },+ "type": "tool",+ }+ )+# understand shared dependenciesshared_dependencies = await generate_response("""You are an AI developer who is trying to write a program that will generate code for the user based on their intent.@@ -237,6 +318,18 @@ Exclusively focus on the names of the shared dependencies, and do not add any ot""",user_prompt,)++ await self.on_logs(+ {+ "message": f"Generated shared dependencies",+ "properties": {+ "result": shared_dependencies,+ "model": "gpt-4",+ },+ "type": "model",+ }+ )+print(shared_dependencies)# write shared dependencies as a md file inside the generated directoryawait playground.write_file(@@ -244,6 +337,18 @@ Exclusively focus on the names of the shared dependencies, and do not add any otshared_dependencies,)+ await self.on_logs(+ {+ "message": f"Saved shared dependencies",+ "properties": {+ "filename": "shared_dependencies.md",+ "content": shared_dependencies,+ "tool": "filesystem",+ },+ "type": "tool",+ }+ )+# execute the file generation in paralell and wait for all of them to finish. Use list comprehension to generate the taskstasks = [generate_file(@@ -262,7 +367,19 @@ Exclusively focus on the names of the shared dependencies, and do not add any otgenerated_files = await asyncio.gather(*tasks)for name, content in generated_files:- await playground.write_file(os.path.join(rootdir, name), content)+ filepath = os.path.join(rootdir, name)+ await playground.write_file(filepath, content)+ await self.on_logs(+ {+ "message": f"Saved file",+ "properties": {+ "filename": filepath,+ "content": content,+ "tool": "filesystem",+ },+ "type": "tool",+ }+ )await fixClockDriftawait playground.push_repo(@@ -272,6 +389,20 @@ Exclusively focus on the names of the shared dependencies, and do not add any otgit_email=git_app_email,git_name=git_app_name,)++ await self.on_logs(+ {+ "message": f"Pushed repository",+ "properties": {+ "repository_url": f"https://github.com/{owner}/{repo}",+ "branch": branch,+ "commit_message": commit_message,+ "tool": "git",+ },+ "type": "tool",+ }+ )+await self.on_interaction_request(AgentInteractionRequest(interaction_id=str(uuid.uuid4()),@@ -286,6 +417,15 @@ Exclusively focus on the names of the shared dependencies, and do not add any otfinally:if playground is not None:playground.close()+ await self.on_logs(+ {+ "message": f"Closed playground",+ "properties": {+ "playground": "closed",+ },+ "type": "playground",+ }+ )async def _dev_in_background(self, instructions: Any):print("Start agent run", self._dev_loop)diff --git a/api-service/app.py b/api-service/app.pyindex 40f9bd71a..70e1d8e3d 100644--- a/api-service/app.py+++ b/api-service/app.py@@ -28,28 +28,8 @@ def check_token(token: str | None):raise HTTPException(status_code=401, detail="Invalid token")-@asynccontextmanager-async def lifespan(app: FastAPI):- # deployments = await db.get_deployments()- # for deployment in deployments:- # if (- # deployment["enabled"]- # and deployment.get("config", None)- # and deployment.get("project_id", None)- # ):- # print("Restarting deployment", deployment["id"])- # await deployment_manager.create_deployment(- # deployment["id"],- # deployment["project_id"],- # deployment["config"],- # )- yield---# TODO: Fix proxying - https://fastapi.tiangolo.com/advanced/behind-a-proxy/app = FastAPI(title="e2b-api",- lifespan=lifespan,)app.add_middleware(CORSMiddleware,@@ -90,6 +70,7 @@ async def create_agent_deployment(db_deployment["id"],project_id,body.config,+ db_deployment.get("logs") or [],)return {"id": deployment.id}else:@@ -98,6 +79,7 @@ async def create_agent_deployment(id,project_id,body.config,+ [],)return {"id": deployment.id}@@ -137,35 +119,24 @@ async def interact_with_agent_deployment(check_token(token)deployment = await deployment_manager.get_deployment(id)if not deployment:- raise HTTPException(status_code=404, detail="Deployment not found")+ # Get deployment from db if enabled+ db_deployment = await db.get_deployment(id)+ if (+ db_deployment+ and db_deployment["enabled"]+ and db_deployment.get("config", None)+ and db_deployment.get("project_id", None)+ ):+ deployment = await deployment_manager.create_deployment(+ db_deployment["id"],+ db_deployment["project_id"],+ db_deployment["config"],+ db_deployment.get("logs") or [],+ )+ else:+ raise HTTPException(status_code=404, detail="Deployment not found")result = await deployment.agent.interaction(body)if body.interaction_id:deployment.event_handler.remove_interaction_request(body.interaction_id)return result--[email protected]("/deployments/{id}/interaction_requests")-async def get_agent_intereaction_requests(- id: str,- token: Annotated[str, Depends(oauth2_scheme)],-):- check_token(token)- deployment = await deployment_manager.get_deployment(id)- if not deployment:- raise HTTPException(status_code=404, detail="Deployment not found")-- return {"interaction_requests": deployment.event_handler.interaction_requests}--[email protected]("/deployments/{id}/logs")-async def get_agent_deployment_status(- id: str,- token: Annotated[str, Depends(oauth2_scheme)],-):- check_token(token)- deployment = await deployment_manager.get_deployment(id)- if not deployment:- raise HTTPException(status_code=404, detail="Deployment not found")-- return {"logs": deployment.event_handler.logs}diff --git a/api-service/database/database.py b/api-service/database/database.pyindex 5783fcad6..508454697 100644--- a/api-service/database/database.py+++ b/api-service/database/database.py@@ -69,20 +69,6 @@ class Database:on_conflict="id",).execute()- async def update_project_developent_logs(- self,- id: str,- logs: List[Step],- ) -> None:- await self.client.table(TABLE_PROJECTS).update(- {- "development_logs": logs,- }- ).eq(- "id",- id,- ).execute()-async def get_env_vars(self, project_id: str) -> List[EnvVar]:"""The return value is a list of dicts with the following keys:- key: The name of an env vardiff --git a/api-service/deployment/in_memory.py b/api-service/deployment/in_memory.pyindex a68d15e18..a36517a8c 100644--- a/api-service/deployment/in_memory.py+++ b/api-service/deployment/in_memory.py@@ -1,4 +1,4 @@-from typing import Any, Dict+from typing import Any, Dict, Listfrom database.base import dbfrom deployment.manager import AgentDeploymentManager, AgentDeployment@@ -16,12 +16,15 @@ class InMemoryDeploymentManager(AgentDeploymentManager):id: str,project_id: str,config: Any,+ logs: List[Any],):+ print("Creating deployment", config, logs)deployment = await AgentDeployment.from_factory(id,get_agent_factory_from_template(config["templateID"]),project_id,config,+ logs,)try:await db.create_deployment(deployment.id, project_id, config)@@ -37,7 +40,9 @@ class InMemoryDeploymentManager(AgentDeploymentManager):id: str,project_id: str,config: Any,+ logs: List[Any],):+ print(">>>> Updating deployment", id, config, logs)try:await self.remove_deployment(id)except:@@ -47,6 +52,7 @@ class InMemoryDeploymentManager(AgentDeploymentManager):id,project_id,config,+ logs,)async def remove_deployment(self, id: str):diff --git a/api-service/deployment/manager.py b/api-service/deployment/manager.pyindex f89535c6b..07783ae0b 100644--- a/api-service/deployment/manager.py+++ b/api-service/deployment/manager.py@@ -1,4 +1,6 @@import os+from re import L+from agent.output.work_queue import WorkQueueimport aiohttpimport json@@ -59,17 +61,21 @@ async def agent_run_cancelled(deployment_id: str):class AgentEvents:- def __init__(self, id: str) -> None:+ def __init__(self, id: str, logs: List[Any]) -> None:self.id = id- self.logs: List[Any] = []+ self.logs: List[Any] = logsself.interaction_requests: List[AgentInteractionRequest] = []+ self.log_que = WorkQueue[List[Any]](+ lambda logs: db.update_deployment_logs(self.id, logs)+ )- async def overwrite_logs(self, logs: List[Any]):- self.logs = logs- await db.update_deployment_logs(self.id, logs)+ async def add_log(self, log: Any):+ self.logs.append(log)+ self.log_que.schedule(self.logs)async def add_interaction_request(- self, interaction_request: AgentInteractionRequest+ self,+ interaction_request: AgentInteractionRequest,):self.interaction_requests.append(interaction_request)match interaction_request.type:@@ -99,12 +105,13 @@ class AgentDeployment:factory: AgentFactory,project_id: str,config: Any,+ logs: List[Any],):- event_handler = AgentEvents(deployment_id)+ event_handler = AgentEvents(deployment_id, logs)agent = await factory(config,lambda: db.get_env_vars(project_id),- event_handler.overwrite_logs,+ event_handler.add_log,event_handler.add_interaction_request,)return cls(deployment_id, agent, event_handler)