Skip to content

armgit / E2B

Public Imported from GitHub
0

Open-source, secure environment with real-world tools for enterprise-grade agents.

Agent demo [WIP]

Tomas Valenta64d241c6c150
diff --git a/api-service/agent/basic_agent.py b/api-service/agent/basic_agent.py
index 9c3431caf..37ade79d5 100644
--- a/api-service/agent/basic_agent.py
+++ b/api-service/agent/basic_agent.py
@@ -1,4 +1,5 @@
import asyncio
+import math
import uuid
import chevron
@@ -147,7 +148,7 @@ class BasicAgent(AgentBase):
AIMessagePromptTemplate.from_template("{agent_scratchpad}"),
]
return ChatPromptTemplate(
- input_variables=["agent_scratchpad"],
+ input_variables=["agent_scratchpad", "repo_context"],
messages=messages,
)
@@ -165,9 +166,7 @@ class BasicAgent(AgentBase):
# Create playground for code tools
playground = NodeJSPlayground(get_envs=self.get_envs)
- if "RepoURL" in instructions:
- await playground.checkout_repo(instructions["RepoURL"])
- await playground.run_command("npm install", rootdir="/code")
+ await playground.checkout_repo(instructions["RepoURL"], "/repo")
tools = list(create_tools(playground=playground))
self.tool_names = [tool.name for tool in tools]
@@ -188,15 +187,23 @@ class BasicAgent(AgentBase):
)
repo_files: List[Tuple[str, str]] = []
- async for file in playground.get_files("/code", ["node_modules"]):
+ async for file in playground.get_files(
+ "/repo",
+ ["node_modules", ".git", "package-lock.json", ".next"],
+ ):
repo_files.append(file)
vectordb = await get_memory(self.config, repo_files)
async def get_repo_context(prompt: str):
- docs = await vectordb.asimilarity_search(prompt, k=4)
+ docs = await vectordb.asimilarity_search(
+ prompt,
+ k=min(5, len(repo_files)),
+ )
+
+ print("getting docs >>>", [doc.metadata["path"] for doc in docs])
- return "Relevant files in the codebase:\n\n" + "\n".join(
+ return "Relevant files in the initial codebase:\n\n" + "\n".join(
[
f"{doc.metadata['path']}\n```\n({doc.page_content})\n```\n"
for doc in docs
@@ -256,7 +263,9 @@ class BasicAgent(AgentBase):
# Query the LLM in background
scratchpad = get_agent_scratchpad()
repo_context = await get_repo_context(
- prompt=prompt.format_prompt(scratchpad=scratchpad).to_string(),
+ prompt=prompt.format_prompt(
+ agent_scratchpad=scratchpad, repo_context=""
+ ).to_string(),
)
self.llm_generation = asyncio.create_task(
@@ -308,7 +317,7 @@ class BasicAgent(AgentBase):
except RewriteStepsException:
print("REWRITING")
continue
-
+ # await playground.push_repo()
except:
raise
finally:
diff --git a/api-service/agent/memory.py b/api-service/agent/memory.py
index 8c91df82f..c13aef587 100644
--- a/api-service/agent/memory.py
+++ b/api-service/agent/memory.py
@@ -1,4 +1,4 @@
-from typing import AsyncIterator, Callable, List, Tuple
+from typing import List, Tuple
from langchain.embeddings.openai import OpenAIEmbeddings
from langchain.text_splitter import CharacterTextSplitter
from langchain.vectorstores import Chroma, VectorStore
@@ -7,7 +7,7 @@ from models.base import ModelConfig
async def get_memory(config: ModelConfig, files: List[Tuple[str, str]]) -> VectorStore:
- splitter = CharacterTextSplitter()
+ splitter = CharacterTextSplitter(chunk_size=2000)
documents = splitter.create_documents(
[file for _, file in files],
[{"path": path} for path, _ in files],
diff --git a/api-service/agent/tools/base.py b/api-service/agent/tools/base.py
index cddb1fc4c..79e6113ab 100644
--- a/api-service/agent/tools/base.py
+++ b/api-service/agent/tools/base.py
@@ -6,6 +6,7 @@ from session.playground.nodejs import NodeJSPlayground
from .human.tools import create_human_tools
from .playground.tools.code import create_code_tools
from .playground.tools.filesystem import create_filesystem_tools
+from .playground.tools.process import create_process_tools
def create_tools(
@@ -19,7 +20,7 @@ def create_tools(
for tools in (
tool_factory(playground=playground)
for tool_factory in [
- # create_process_tools,
+ create_process_tools,
create_filesystem_tools,
create_code_tools,
]
diff --git a/api-service/agent/tools/playground/tools/code.py b/api-service/agent/tools/playground/tools/code.py
index dd3042dc8..75592d53d 100644
--- a/api-service/agent/tools/playground/tools/code.py
+++ b/api-service/agent/tools/playground/tools/code.py
@@ -32,7 +32,7 @@ def create_code_tools(playground: NodeJSPlayground):
output = await playground.run_saved_javascript_code()
return encode_command_output(output)
- yield run_saved_code
+ # yield run_saved_code
# A tool for writing JavaScript code specifically to the index.mjs file
@async_tool("WriteJavaScriptCode")
@@ -44,7 +44,7 @@ def create_code_tools(playground: NodeJSPlayground):
await playground.write_javascript_code(extract_code(code))
return "Code written to index.mjs"
- yield write_javascript_code
+ # yield write_javascript_code
# # This tool is just for executing JavaScript without doing the request to server
# @async_tool("RunJavaScriptCode")
diff --git a/api-service/agent/tools/playground/tools/filesystem.py b/api-service/agent/tools/playground/tools/filesystem.py
index 6f5fd7847..2c834e9f9 100644
--- a/api-service/agent/tools/playground/tools/filesystem.py
+++ b/api-service/agent/tools/playground/tools/filesystem.py
@@ -3,6 +3,7 @@ from typing import List
from agent.tools.async_tool import async_tool
from session.playground import NodeJSPlayground
from playground_client.models.entry_info import EntryInfo
+from playground_client.exceptions import NotFoundException
def encode_directory_listing(entries: List[EntryInfo]) -> str:
@@ -20,27 +21,30 @@ def create_filesystem_tools(playground: NodeJSPlayground):
@async_tool("ReadFile")
async def read_file(path: str) -> str:
- """Read content of the file from filesystem."""
- return await playground.read_file(path)
+ """Read content of the file from filesystem. The input should be an absolute path to a file."""
+ try:
+ return await playground.read_file(path.strip())
+ except NotFoundException:
+ return "File not found"
yield read_file
@async_tool("SaveFile")
async def save_file(input: str) -> str:
"""Save content to a file in the filesystem.
- The input should be a path to a file followed by the content of the file.
+ The input should be an absolute path to a file followed by the content of the file.
Separate the path and content by a newline character.
"""
path, content = input.lstrip().split("\n", 1)
- await playground.write_file(path, content)
+ await playground.write_file(path.strip(), content)
return "File saved"
yield save_file
@async_tool("DeleteFile")
async def delete_file(path: str) -> str:
- """Delete the file."""
+ """Delete the file. The input should be an absolute path to a file."""
await playground.delete_file(path)
return "File deleted"
@@ -48,16 +52,19 @@ def create_filesystem_tools(playground: NodeJSPlayground):
@async_tool("ListDirectory")
async def list_directory(path: str) -> str:
- """List all files and subdirectories from the directory."""
- entries = await playground.list_dir(path)
- return encode_directory_listing(entries)
+ """List all files and subdirectories from the directory. The input should be an absolute path to a directory."""
+ try:
+ entries = await playground.list_dir(path.strip())
+ return encode_directory_listing(entries)
+ except NotFoundException:
+ return "Directory not found"
yield list_directory
@async_tool("DeleteDirectory")
async def delete_directory(path: str) -> str:
- """Delete the directory."""
- await playground.delete_dir(path)
+ """Delete the directory. The input should be an absolute path to a directory."""
+ await playground.delete_dir(path.strip())
return "Directory deleted"
yield delete_directory
diff --git a/api-service/agent/tools/playground/tools/process.py b/api-service/agent/tools/playground/tools/process.py
index 1777279fb..3a7cd76ff 100644
--- a/api-service/agent/tools/playground/tools/process.py
+++ b/api-service/agent/tools/playground/tools/process.py
@@ -39,7 +39,7 @@ def create_process_tools(playground: NodeJSPlayground):
The returned result will be the output and errors returned when running the command.
"""
await playground.update_envs()
- output = await playground.run_command(command)
+ output = await playground.run_command(command, rootdir="/repo")
result = encode_command_output(output)
return result if len(result) > 0 else "Process finished without error"
diff --git a/api-service/playground/src/sessions/filesystemController.ts b/api-service/playground/src/sessions/filesystemController.ts
index ecc09bde8..c28ff5cfa 100644
--- a/api-service/playground/src/sessions/filesystemController.ts
+++ b/api-service/playground/src/sessions/filesystemController.ts
@@ -82,10 +82,15 @@ export class FilesystemController extends Controller {
@Query() path: string,
@BodyProp() content: string,
) {
- await CachedSession
- .findSession(sessionID)
- .session
- .filesystem!
- .write(path, content)
+ try {
+ await CachedSession
+ .findSession(sessionID)
+ .session
+ .filesystem!
+ .write(path, content)
+ } catch (err) {
+ console.error(err)
+ throw err
+ }
}
}
diff --git a/api-service/session/playground/base.py b/api-service/session/playground/base.py
index 78ecede4b..1cc872f01 100644
--- a/api-service/session/playground/base.py
+++ b/api-service/session/playground/base.py
@@ -39,11 +39,34 @@ class Playground(Session):
for open_port in open_ports
)
- async def checkout_repo(self, repo_url: str):
- await self.run_command(f"git clone {repo_url} .")
-
- # async def push_repo(self, repo_url: str):
- # await self.run_command(f"git push")
+ async def checkout_repo(self, repo_url: str, rootdir: str):
+ # WIP
+ await self.make_dir("/repo")
+ await self.run_command(
+ """
+apk add \
+ --no-cache \
+ --allow-untrusted \
+ --repository http://dl-cdn.alpinelinux.org/alpine/v3.15/main git
+ """
+ )
+ await self.run_command('git config --global http.sslVerify "false"')
+ res = await self.run_command(
+ f"git clone {repo_url} /repo && npm install --prefix /repo",
+ rootdir="/",
+ )
+ print("res", res)
+
+ async def push_repo(self, repo_url: str):
+ await self.run_command(
+ """
+apk add \
+ --no-cache \
+ --allow-untrusted \
+ --repository http://dl-cdn.alpinelinux.org/alpine/v3.15/main github-cli
+ """
+ )
+ await self.run_command(f"git push")
async def change_rootdir(self, rootdir: str):
self.rootdir = rootdir
diff --git a/api-service/session/playground/nodejs.py b/api-service/session/playground/nodejs.py
index 652d97a5e..16bfd5ec5 100644
--- a/api-service/session/playground/nodejs.py
+++ b/api-service/session/playground/nodejs.py
@@ -5,8 +5,8 @@ from session.session import GetEnvs
class NodeJSPlayground(Playground):
- node_js_env_id = "dCeMnVVxu01L"
- rootdir = "/code"
+ node_js_env_id = "QFNlQVCzcKxD"
+ rootdir = "/repo"
default_javascript_code_file = os.path.join(rootdir, "index.mjs")
run_code_timeout = 3 # 3s
diff --git a/components/Editor/Sidebar/Agent/Tool/RunTerminalCommand.tsx b/components/Editor/Sidebar/Agent/Tool/RunTerminalCommand.tsx
new file mode 100644
index 000000000..8ef54f4d2
--- /dev/null
+++ b/components/Editor/Sidebar/Agent/Tool/RunTerminalCommand.tsx
@@ -0,0 +1,43 @@
+import {
+ Code2,
+} from 'lucide-react'
+
+import { ToolName, ToolLog } from 'db/types'
+
+import Base from './Base'
+
+
+export interface Props {
+ log: ToolLog
+ isRunning?: boolean
+}
+
+function RunTerminalCommand({
+ log,
+ isRunning,
+}: Props) {
+ if (log.tool_name !== ToolName.RunTerminalCommand) throw new Error(`'${log.tool_name}': This component supports only logs for '${ToolName.WriteJavaScriptCode}' tool`)
+
+ const body = log.tool_input.trim()
+ ? (
+ <div className="
+ pt-2
+ ">
+ <pre>
+ {log.tool_input.trim()}
+ </pre>
+ </div>
+ )
+ : null
+
+ return (
+ <Base
+ isRunning={isRunning}
+ log={log}
+ icon={<Code2 size="16px" />}
+ body={body}
+ />
+ )
+}
+
+export default RunTerminalCommand
diff --git a/components/Editor/Sidebar/Agent/Tool/index.tsx b/components/Editor/Sidebar/Agent/Tool/index.tsx
index 4f372707e..3c7fdf52d 100644
--- a/components/Editor/Sidebar/Agent/Tool/index.tsx
+++ b/components/Editor/Sidebar/Agent/Tool/index.tsx
@@ -11,6 +11,7 @@ import SaveFile from './SaveFile'
import DeleteFile from './DeleteFile'
import ListDirectory from './ListDirectory'
import DeleteDirectory from './DeleteDirectory'
+import RunTerminalCommand from './RunTerminalCommand'
export interface Props {
log: ToolLog
@@ -32,6 +33,8 @@ function Tool({
return <WriteCode log={log} isRunning={isRunning} />
case ToolName.RunSavedCode:
return <RunSavedCode log={log} isRunning={isRunning} />
+ case ToolName.RunTerminalCommand:
+ return <RunTerminalCommand log={log} isRunning={isRunning} />
case ToolName.ReadFile:
return <ReadFile log={log} isRunning={isRunning} />
case ToolName.SaveFile:
diff --git a/db/types.ts b/db/types.ts
index 15417cdeb..430c8d14a 100644
--- a/db/types.ts
+++ b/db/types.ts
@@ -15,6 +15,7 @@ export enum ToolName {
DeleteFile = 'DeleteFile',
DeleteDirectory = 'DeleteDirectory',
ListDirectory = 'ListDirectory',
+ RunTerminalCommand = 'RunTerminalCommand',
}
interface BaseLog {