Skip to content

armgit / E2B

Public Imported from GitHub
0

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

Remove unused Python API code

Tomas Valentaa88dc82323c0
diff --git a/api-service/agent/output/__init__.py b/api-service/agent/output/__init__.py
deleted file mode 100644
index e69de29bb..000000000
diff --git a/api-service/agent/output/output_stream_parser.py b/api-service/agent/output/output_stream_parser.py
deleted file mode 100644
index af88939e2..000000000
--- a/api-service/agent/output/output_stream_parser.py
+++ /dev/null
@@ -1,172 +0,0 @@
-import datetime
-import uuid
-
-from typing import List, TypedDict
-
-from agent.output.parse_output import (
- Log,
- ThoughtLog,
- ToolLog,
- merge_logs,
- parse_output,
-)
-
-
-class Step(TypedDict):
- output: str
- logs: List[ToolLog | ThoughtLog]
-
-
-class ToolOutput(TypedDict):
- finish_at: str
- tool_output: str
-
-
-class LogMeta(TypedDict):
- id: str
- created_at: str
-
-
-class OutputStreamParser:
- """
- We receive a stream of tokens and want to parse this stream of tokens to thought and tool logs
- even if we haven't yet received all tokens we need to execute the action.
-
- We call the self._parse every time we receive new token or tool output.
- This method takes the token buffer and tries to transform it to thought and tool logs.
- It can also create tool logs even if we haven't received all the tokens we need to execute the action yet.
-
- // Example token buffer content:
- Thought:
- This is a thought
-
- Action:
- <action type="CurlJavaScriptServer">
- </ac
- // End of example
-
- This is parsed as following buffered logs:
- [
- {
- "id": "id1",
- "created_at": "2023-03-22 13:46:52.561854",
- "type": "thought",
- "content": "This is a thought",
- },
- {
- "id": "id2",
- "created_at": "2023-03-22 13:46:52.561854",
- "type": "tool",
- "tool_name": "CurlJavaScriptServer,
- "tool_input": "",
- }
- ]
-
- Buffered logs are thought logs or tool logs for which we haven't received outputs yet.
-
- We can keep track of the buffered logs because there will always be more tool logs than tool outputs - we must parse the actions from tokens before they executed.
- We are matching the tools' logs and tools' outputs by the order in which they are parsed and ingested (if we need to support asynchronous execution of tools we need to change this matching)
- and the buffered can be flushed to finished logs when we receive output for the last tool in the buffered logs.
- """
-
- def __init__(
- self,
- tool_names: List[str],
- steps: List[Step] = [],
- buffered_step=Step(output="", logs=[]),
- ) -> None:
- self._tool_names = tool_names
-
- # All "finished" logs that the parser saved.
- self._steps = steps[:]
-
- self._token_buffer: str = buffered_step["output"]
-
- # Logs have both `thought` logs and `tool` logs.
- # These logs can be partially parsed or they can have missing outputs.
- # They are flushed to self._logs after outputs for all tools in self._logs.buffer are ingested.
- self._logs_buffer: List[ToolLog | ThoughtLog] = buffered_step["logs"]
- self._logs_meta_buffer: List[LogMeta] = [
- LogMeta(created_at=log.get("created_at", ""), id=log.get("id", ""))
- for log in self._logs_buffer
- ]
-
- # This is a list of tools' outputs that corresponds to the tool logs in the self._logs.buffer.
- self._tools_output_buffer: List[ToolOutput] = [
- ToolOutput(
- finish_at=log.get("finish_at", ""),
- tool_output=log.get("tool_output", ""),
- )
- for log in self._logs_buffer
- if log.get("tool_output")
- ]
-
- def _parse(self):
- """This function should be called only after ingesting new token or tool output to update the buffered logs."""
- # We overwrite the current buffered logs with their newer version.
- # If you ingested token or tool output this will save the change so you can call self.get_logs and get the new logs.
- self._logs_buffer = [
- log
- for log in parse_output(self._token_buffer)
- if log["type"] == "thought"
- or log["type"] == "tool"
- and log.get("tool_name") in self._tool_names
- ]
-
- # Add a new uuids to id buffer if we have less ids that there are logs in the logs buffer.
- self._logs_meta_buffer.extend(
- LogMeta(id=str(uuid.uuid4()), created_at=str(datetime.datetime.now()))
- for _ in range(len(self._logs_buffer) - len(self._logs_meta_buffer))
- )
-
- # Assign the stable ids and timestamps to logs
- for log, meta in zip(self._logs_buffer, self._logs_meta_buffer):
- merge_logs(log, meta)
-
- # Update tools' logs with the information from ingested tools' outputs.
- for tool_log, output in zip(
- (tool_log for tool_log in self._logs_buffer if tool_log["type"] == "tool"),
- self._tools_output_buffer,
- ):
- merge_logs(tool_log, output)
-
- def ingest_complete_llm_output(self, output: str):
- """Ingest whole output of an LLM overwriting the current buffer."""
- self._token_buffer = output
- self._parse()
- return self
-
- def ingest_token(self, token: str):
- """Ingest token and update the logs."""
- self._token_buffer += token
- self._parse()
- return self
-
- def ingest_tool_output(self, output: str):
- """Ingest output from tool and update the logs."""
- self._tools_output_buffer.append(
- {
- "finish_at": str(datetime.datetime.now()),
- "tool_output": output,
- }
- )
- self._parse()
-
- # If we received output for the last tool in the buffered logs we save the buffered logs to logs and reset all buffers.
- # We know this is is the output for the last tool if the number of tool logs in buffered logs is equal to the number of buffered outputs.
- if len(self._tools_output_buffer) == len(
- [log for log in self._logs_buffer if log["type"] == "tool"]
- ):
- self._steps.append(self.get_current_step())
- self._token_buffer = ""
- self._logs_buffer = []
- self._tools_output_buffer = []
- self._logs_meta_buffer = []
-
- return self
-
- def get_steps(self) -> List[Step]:
- return [*self._steps, self.get_current_step()]
-
- def get_current_step(self):
- return Step(output=self._token_buffer, logs=self._logs_buffer)
diff --git a/api-service/agent/output/parse_output.py b/api-service/agent/output/parse_output.py
deleted file mode 100644
index cb299796c..000000000
--- a/api-service/agent/output/parse_output.py
+++ /dev/null
@@ -1,72 +0,0 @@
-import xml.etree.ElementTree as ET
-import re
-from typing_extensions import NotRequired
-from typing import TypedDict
-from typing import Literal
-from lxml import etree
-
-escape_table = str.maketrans({
- "<": "&lt;",
- ">": "&gt;",
- "&": "&amp;",
- "'": "&apos;",
- '"': "&quot;",
-})
-
-def xml_escape(text: str):
- return text.translate(escape_table)
-
-
-class Log(TypedDict):
- id: NotRequired[str]
- type: Literal["thought"] | Literal["tool"]
- created_at: NotRequired[str]
-
-class ThoughtLog(Log):
- content: str
-
-class ToolLog(Log):
- tool_name: str
- tool_input: str
- tool_output: NotRequired[str]
- finish_at: NotRequired[str]
-
-def merge_logs(log: TypedDict, other: TypedDict):
- log.update(other)
-
-
-action_tag_open = "<action(?:\\s+tool=\".+?\")?\\s*/?>?"
-action_tag_close = "</\\s*action\\s*>?"
-
-action_tag_split_pattern = re.compile(f"({action_tag_open})|({action_tag_close})|(.+?)")
-action_tag_check_pattern = re.compile(f"{action_tag_open}|{action_tag_close}")
-
-def parse_output(text: str):
- escaped = "".join(
- # If the text part is not action tag escape it.
- part if action_tag_check_pattern.match(part) else xml_escape(part)
- for part
- # Split the text by action opening and closing tags.
- in re.split(action_tag_split_pattern, text)
- if part
- )
-
- root = ET.fromstring(
- f"<root>{escaped}</root>",
- # Use Parser with C binding for libxml2+libxslt, with recovery mode that allows to parse incomplete XML.
- etree.XMLParser(recover=True),
- )
-
- leading_thought = root.text.strip() if root.text else None
- if leading_thought:
- yield ThoughtLog(type="thought", content=leading_thought)
-
- for action in root.findall("action"):
- tool_name = action.attrib.get("tool", "")
- if tool_name:
- yield ToolLog(type="tool", tool_name=tool_name, tool_input=action.text or "")
-
- # Create thoughts from text between and after actions.
- trailing_thought = action.tail.strip() if action.tail else None
- if trailing_thought:
- yield ThoughtLog(type="thought", content=trailing_thought)
diff --git a/api-service/agent/output/token_callback_handler.py b/api-service/agent/output/token_callback_handler.py
deleted file mode 100644
index 7b3092f44..000000000
--- a/api-service/agent/output/token_callback_handler.py
+++ /dev/null
@@ -1,28 +0,0 @@
-from typing import Any
-from langchain.callbacks.base import AsyncCallbackHandler
-from langchain.schema import LLMResult
-from asyncio import Queue
-
-
-class TokenCallbackHandler(AsyncCallbackHandler):
- def __init__(self, **kwargs) -> None:
- super().__init__(**kwargs)
- self._queue: Queue[str | None] = Queue(1)
-
- async def on_llm_new_token(self, token: str, **kwargs: Any) -> None:
- """Run on new LLM token. Only available when streaming is enabled."""
- await self._ingest_token(token)
-
- async def on_llm_end(self, response: LLMResult, **kwargs: Any):
- await self._close_token_stream()
-
- async def retrieve_token(self):
- token = await self._queue.get()
- self._queue.task_done()
- return token
-
- async def _ingest_token(self, token: str):
- await self._queue.put(token)
-
- async def _close_token_stream(self):
- await self._queue.put(None)
diff --git a/api-service/agent/output/work_queue.py b/api-service/agent/output/work_queue.py
deleted file mode 100644
index 29ed47a12..000000000
--- a/api-service/agent/output/work_queue.py
+++ /dev/null
@@ -1,50 +0,0 @@
-from asyncio import Queue, ensure_future
-from typing import Any, Callable, Coroutine, Generic, TypeVar
-
-from typing import Coroutine
-
-T = TypeVar("T")
-
-
-class WorkQueue(Generic[T]):
- """Queue that tries to always process only the most recently scheduled workload."""
-
- def __init__(self, on_workload: Callable[[T], Coroutine[Any, Any, Any]]) -> None:
- self._queue: Queue[Coroutine] = Queue()
- self._on_workload = on_workload
- # Start the worker that saves logs from queue to the db.
- self._worker = ensure_future(self._start())
-
- async def _work(self):
- # Remove all logs except the newest one from the queue.
- for _ in range(self._queue.qsize() - 1):
- old_coro = self._queue.get_nowait()
- try:
- old_coro.close()
- except Exception as e:
- print(e)
- finally:
- self._queue.task_done()
-
- # Save the newest log to the db or wait until a log is pushed to the queue and then save it to the db.
- task = await self._queue.get()
- try:
- await ensure_future(task)
- except Exception as e:
- print(e)
- finally:
- self._queue.task_done()
-
- async def _start(self):
- while True:
- await self._work()
-
- async def flush(self):
- await self._queue.join()
-
- def schedule(self, workload: T):
- task = self._on_workload(workload)
- self._queue.put_nowait(task)
-
- def close(self):
- self._worker.cancel()
diff --git a/api-service/agent/tools/__init__.py b/api-service/agent/tools/__init__.py
deleted file mode 100644
index 1776c5916..000000000
--- a/api-service/agent/tools/__init__.py
+++ /dev/null
@@ -1,2 +0,0 @@
-from .base import create_tools
-from .async_tool import async_tool
diff --git a/api-service/agent/tools/async_tool.py b/api-service/agent/tools/async_tool.py
deleted file mode 100644
index e46db78fb..000000000
--- a/api-service/agent/tools/async_tool.py
+++ /dev/null
@@ -1,55 +0,0 @@
-from typing import Awaitable, Callable, Optional, cast
-from langchain.agents import Tool
-from langchain.tools.base import BaseTool
-
-from agent.output.parse_output import ToolLog, parse_output
-
-
-def func(_: str):
- raise NotImplementedError()
-
-
-def async_tool(name: str | None = None) -> Callable:
- """You don't have to specify tool's name if there is an example of the tool use in the docstring."""
-
- def _make_tool(arun: Optional[Callable[[str], Awaitable[str]]]) -> BaseTool:
- nonlocal name
- if arun.__doc__ is None:
- raise NotImplementedError(f"Missing docstring for {name} async tool")
-
- # Check if the tool name in an example in tool description matches with the name of the tool.
- # This error is hard to detect because the model still sometimes uses the correct name
- # and not the incorrect name from the example.
- tool_example = next(
- (
- cast(ToolLog, tool)
- for tool in parse_output(arun.__doc__.strip())
- if tool["type"] == "tool"
- ),
- None,
- )
-
- if tool_example and not name and tool_example["tool_name"]:
- name = tool_example["tool_name"]
-
- if not name:
- raise ValueError(
- f"Tool name is not specified. Either specify it in the decorator parameter or add a tool description with an example to the docstring."
- )
-
- if tool_example and name != tool_example["tool_name"]:
- raise ValueError(
- f'Specified tool name "{name}" differs from the example tool name "{tool_example["tool_name"]}" in the tool description'
- )
-
- description = f"{arun.__doc__.strip()}"
- tool_ = Tool(
- name=name,
- func=func,
- description=description,
- return_direct=False,
- )
- tool_.coroutine = arun
- return tool_
-
- return _make_tool
diff --git a/api-service/agent/tools/base.py b/api-service/agent/tools/base.py
deleted file mode 100644
index 79e6113ab..000000000
--- a/api-service/agent/tools/base.py
+++ /dev/null
@@ -1,33 +0,0 @@
-from typing import Generator, Any
-from langchain.tools import BaseTool
-
-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(
- playground: NodeJSPlayground,
-) -> Generator[BaseTool, None, None]:
- # Ensure that the function is a generator even if no tools are yielded
- yield from ()
-
- playground_tools: Generator[Any, None, None] = (
- tool
- for tools in (
- tool_factory(playground=playground)
- for tool_factory in [
- create_process_tools,
- create_filesystem_tools,
- create_code_tools,
- ]
- )
- for tool in tools
- )
- yield from playground_tools
-
- human_tools = create_human_tools()
- yield from human_tools
diff --git a/api-service/agent/tools/human/__init__.py b/api-service/agent/tools/human/__init__.py
deleted file mode 100644
index e69de29bb..000000000
diff --git a/api-service/agent/tools/human/tools.py b/api-service/agent/tools/human/tools.py
deleted file mode 100644
index 926585647..000000000
--- a/api-service/agent/tools/human/tools.py
+++ /dev/null
@@ -1,38 +0,0 @@
-from collections.abc import Generator
-from typing import Any
-
-from agent.tools.async_tool import async_tool
-from session.playground.base import Playground
-
-
-def create_human_tools() -> Generator[Any, None, None]:
- # Ensure that the function is a generator even if no tools are yielded
- yield from ()
-
- @async_tool("LetHumanChoose")
- async def let_human_choose(options: str):
- """Let a human choose from one of the options. Sometimes there might be multiple viable paths forward. For example, when the human did not specify implementation details like a third party service, library, or an algorithm.
- Instead of you choosing the path forward, use this tool to present up to 5 best options forward for the human to choose from.
- The input should be a question for the human and possible options. Provide a 1-3 sentence long summary for each option. Example usage:
- <action tool="LetHumanChoose">
- <question>A question asking the human for the path forward</question>
- <option>Option A and the reason why it might be a good idea</option>
- <option>Option B and the reason why it might be a good idea</option>
- </action>
- """
- print("+++ OPTIONS")
- print(options)
- print("--- OPTIONS")
-
- # TODO: Handle ask human via the WS/interaction request API
- pass
-
- # yield let_human_choose
-
- @async_tool("AskHuman")
- async def ask_human(question: str):
- """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."""
- # TODO: Handle ask human via the WS/interaction request API
- pass
-
- # yield ask_human
diff --git a/api-service/agent/tools/playground/__init__.py b/api-service/agent/tools/playground/__init__.py
deleted file mode 100644
index e69de29bb..000000000
diff --git a/api-service/agent/tools/playground/tools/code.py b/api-service/agent/tools/playground/tools/code.py
deleted file mode 100644
index 75592d53d..000000000
--- a/api-service/agent/tools/playground/tools/code.py
+++ /dev/null
@@ -1,131 +0,0 @@
-from agent.tools.async_tool import async_tool
-from session.playground import NodeJSPlayground
-from agent.tools.playground.tools.process import encode_command_output
-
-
-def extract_code(code: str):
- return code.strip().strip("`").strip()
-
-
-def create_code_tools(playground: NodeJSPlayground):
- last_javascript_code: str | None = None
-
- # Ensure that the function is a generator even if no tools are yielded
- yield from ()
-
- @async_tool("InstallNPMDependencies")
- async def install_dependencies(dependencies: str) -> str:
- """Install JavaScript packages with NPM. The input should be valid names of NPM packages."""
- output = await playground.install_dependencies(extract_code(dependencies))
- result = encode_command_output(output, only_errors=True)
- return result if len(result) > 0 else "All dependencies installed"
-
- yield install_dependencies
-
- # A tool for executing index.mjs file
- @async_tool("RunSavedCode")
- async def run_saved_code(empty: str) -> str:
- """Run JavaScript code that is inside the index.mjs. The tool takes no input."""
-
- await playground.update_envs()
-
- output = await playground.run_saved_javascript_code()
- return encode_command_output(output)
-
- # yield run_saved_code
-
- # A tool for writing JavaScript code specifically to the index.mjs file
- @async_tool("WriteJavaScriptCode")
- async def write_javascript_code(code: str) -> str:
- """Write JavaScript code to the index.mjs file. The input should be valid JavaScript code."""
- nonlocal last_javascript_code
- last_javascript_code = code
-
- await playground.write_javascript_code(extract_code(code))
- return "Code written to index.mjs"
-
- # yield write_javascript_code
-
- # # This tool is just for executing JavaScript without doing the request to server
- # @async_tool("RunJavaScriptCode")
- # async def run_javascript_code(code: str) -> str:
- # """
- # Run JavaScript code as ECMAScript module and return output.
- # Input should be a valid JavaScript code. Example usage:
- # <action tool="RunJavaScriptCode">
- # console.log('hello world')
- # </action>
- # """
- # await playground.update_envs()
-
- # nonlocal last_javascript_code
- # last_javascript_code = code
-
- # output = await playground.run_javascript_code(code)
- # result = encode_command_output(output)
- # return result if len(result) > 0 else "Code execution finished without error"
-
- # yield run_javascript_code
-
- @async_tool("Curl")
- async def curl(curl_command: str) -> str:
- """Make a curl request. The input should be the `curl` command."""
- await playground.update_envs()
-
- nonlocal last_javascript_code
- if last_javascript_code is None:
- return "Cannot curl, you need to write code first"
-
- port = 3000
- (
- request_output,
- server_output,
- ) = await playground.run_javascript_server_code_with_request(
- code=last_javascript_code,
- request_cmd=curl_command.strip(),
- port=port,
- )
-
- request_result = encode_command_output(request_output)
- server_result = encode_command_output(server_output)
-
- return f"Curl output:\n{request_result}\nServer output:\n{server_result}"
-
- yield curl
-
- # @async_tool("CurlJavaScriptServer")
- # async def curl_javascript_server(curl_command: str) -> str:
- # """
- # Make a curl request. The input should be the `curl` command. Example usage:
- # <action tool="CurlJavaScriptServer">
- # curl --no-progress-meter -X POST -H "Content-Type: application/json" -d '{{"key": "value"}}' http://localhost:3000/
- # </action>
- # """
- # # """
- # # Make a request to check if the previously run JavaScript code is a server that can handle the needed request. This tool has no input. Example usage:
- # # ```
- # # <action tool="CurlJavaScriptServer">
- # # </action>
- # # ```"""
- # await playground.update_envs()
-
- # nonlocal last_javascript_code
- # if last_javascript_code is None:
- # return "Cannot curl, you need to run code first"
-
- # port = 3000
- # (
- # request_output,
- # server_output,
- # ) = await playground.run_javascript_server_code_with_request(
- # code=last_javascript_code,
- # request_cmd=curl_command.strip(),
- # port=port,
- # )
-
- # request_result = encode_command_output(request_output)
- # server_result = encode_command_output(server_output)
-
- # return f"Curl output:\n{request_result}\nServer output:\n{server_result}"
-
- # yield curl_javascript_server
diff --git a/api-service/agent/tools/playground/tools/filesystem.py b/api-service/agent/tools/playground/tools/filesystem.py
deleted file mode 100644
index 2c834e9f9..000000000
--- a/api-service/agent/tools/playground/tools/filesystem.py
+++ /dev/null
@@ -1,70 +0,0 @@
-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:
- return "\n".join(
- [
- f"{entry.name} - {'directory' if entry.is_dir else 'file'}"
- for entry in entries
- ]
- )
-
-
-def create_filesystem_tools(playground: NodeJSPlayground):
- # Ensure that the function is a generator even if no tools are yielded
- yield from ()
-
- @async_tool("ReadFile")
- async def read_file(path: str) -> str:
- """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 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.strip(), content)
- return "File saved"
-
- yield save_file
-
- @async_tool("DeleteFile")
- async def delete_file(path: str) -> str:
- """Delete the file. The input should be an absolute path to a file."""
- await playground.delete_file(path)
- return "File deleted"
-
- yield delete_file
-
- @async_tool("ListDirectory")
- async def list_directory(path: str) -> str:
- """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. 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
deleted file mode 100644
index 3a7cd76ff..000000000
--- a/api-service/agent/tools/playground/tools/process.py
+++ /dev/null
@@ -1,47 +0,0 @@
-from agent.tools.async_tool import async_tool
-from session.playground import NodeJSPlayground
-from playground_client.models.process_response import ProcessResponse
-
-
-def encode_command_output(response: ProcessResponse, only_errors: bool = False) -> str:
- result = ""
-
- err_lines = [err.line for err in response.stderr if "Error:" in err.line]
- # err_lines = [err.line for err in response.stderr]
-
- errors = "\n".join(err_lines)
-
- if len(errors) > 0:
- result += f"Errors:\n{errors}\n"
-
- if only_errors:
- return result
-
- print(errors)
- out_lines = [out.line for out in response.stdout]
- output = "\n".join(out_lines)
-
- if len(output) > 0:
- result += f"Output:\n{output}"
-
- return result
-
-
-def create_process_tools(playground: NodeJSPlayground):
- # Ensure that the function is a generator even if no tools are yielded
- yield from ()
-
- @async_tool("RunTerminalCommand")
- async def run_terminal_command(command: str) -> str:
- """
- Run specified command in the terminal and return output and errors.
- The input should be a a valid terminal command.
- The returned result will be the output and errors returned when running the command.
- """
- await playground.update_envs()
- output = await playground.run_command(command, rootdir="/repo")
- result = encode_command_output(output)
-
- return result if len(result) > 0 else "Process finished without error"
-
- yield run_terminal_command
diff --git a/api-service/session/playground/nodejs.py b/api-service/session/playground/nodejs.py
index 9382704ab..f7c663d3f 100644
--- a/api-service/session/playground/nodejs.py
+++ b/api-service/session/playground/nodejs.py
@@ -17,17 +17,6 @@ class NodeJSPlayground(Playground):
rootdir=NodeJSPlayground.rootdir,
)
- # async def run_javascript_code(self, code: str):
- # # print(f"Running javascript code...")
- # await self.write_file(self.default_javascript_code_file, code)
- # result = await self.run_command(
- # f"node {self.default_javascript_code_file}",
- # rootdir=self.rootdir,
- # timeout=self.run_code_timeout,
- # )
- # # pprint.pprint(f"Result: {result}")
- # return result
-
async def run_saved_javascript_code(self):
result = await self.run_command(
f"node {self.default_javascript_code_file}",
@@ -37,12 +26,10 @@ class NodeJSPlayground(Playground):
return result
async def install_dependencies(self, dependencies: str):
- # print(f"Installing dependencies: {dependencies}")
result = await self.run_command(
f"npm install {dependencies}",
rootdir=self.rootdir,
)
- # pprint.pprint(f"Result: {result}")
return result
async def run_javascript_server_code_with_request(
@@ -51,7 +38,6 @@ class NodeJSPlayground(Playground):
request_cmd: str,
port: float,
):
- # print(f"Running '{request_cmd}' for code:\n{code}")
await self.write_file(self.default_javascript_code_file, code)
result = await self.run_server_with_request(
server_cmd=f"node {self.default_javascript_code_file}",
@@ -59,7 +45,6 @@ class NodeJSPlayground(Playground):
port=port,
rootdir=self.rootdir,
)
- # pprint.pprint(f"Result: {result}")
return result
async def write_javascript_code(self, code: str):
diff --git a/api-service/test/conftest.py b/api-service/test/conftest.py
deleted file mode 100644
index 16c7d6cdf..000000000
--- a/api-service/test/conftest.py
+++ /dev/null
@@ -1,35 +0,0 @@
-import pytest
-from typing import Dict, List, Any, cast
-
-from agent.output.parse_output import ToolLog, parse_output
-
-
-class Helpers:
- @staticmethod
- def test_llm_outputs_parsing(llm_outputs: List[Dict[str, Any]]):
- """Test LLM action parsing."""
-
- for output in llm_outputs:
- actions = [
- cast(ToolLog, action)
- for action in parse_output(output["llm_output"])
- if action["type"] == "tool"
- ]
-
- assert len(actions) == len(output["expected_actions"])
-
- for action, expected_action in zip(
- actions, cast(List[ToolLog], output["expected_actions"])
- ):
- assert action["tool_name"] == expected_action["tool_name"]
- assert (
- action["tool_input"].strip()
- == expected_action["tool_input"].strip()
- )
-
- print("-----------")
-
-
-def helpers():
- return Helpers
diff --git a/api-service/test/test_action_parsing.py b/api-service/test/test_action_parsing.py
deleted file mode 100644
index 859b9cb55..000000000
--- a/api-service/test/test_action_parsing.py
+++ /dev/null
@@ -1,259 +0,0 @@
-"""Test LLM action parsing"""
-
-from typing import Dict, List, Any
-
-from agent.output.parse_output import ToolLog
-
-
-llm_outputs: List[Dict[str, Any]] = [
- {
- "llm_output": """Install JavaScript packages with NPM. The input should be valid names of NPM packages. Example usage:
- <action tool="InstallNPMDependencies">
- package_name_1 package_name_2
- </action>
- """,
- "expected_actions": [
- ToolLog(
- type="tool",
- tool_name="InstallNPMDependencies",
- tool_input="package_name_1 package_name_2",
- ),
- ],
- },
- {
- "llm_output": """Action:
-<action tool="AskHuman">
-What should the post request handler do?
-</action>
-""",
- "expected_actions": [
- ToolLog(
- type="tool",
- tool_name="AskHuman",
- tool_input="What should the post request handler do?",
- ),
- ],
- },
- {
- "llm_output": """Thought: Lorem ipsum
-
-Action:
-<action tool="Name">
-action input
-</action>
-""",
- "expected_actions": [
- ToolLog(
- type="tool",
- tool_name="Name",
- tool_input="action input",
- ),
- ],
- },
- {
- "llm_output": """Thought: Lorem ipsum
-
-Action:
-<action tool="Name">
-action input
-</action>
-<action tool="Name 2">
-action input 2
-</action>
-""",
- "expected_actions": [
- ToolLog(
- type="tool",
- tool_name="Name",
- tool_input="action input",
- ),
- ToolLog(
- type="tool",
- tool_name="Name 2",
- tool_input="action input 2",
- ),
- ],
- },
- {
- "llm_output": """
-Thought: lorem ipsum
-
-Action:
-<action tool="Name1">content</action 1><action tool="Name2">content 2</action><action tool="Name3">content 3</action>'
-
-""",
- "expected_actions": [
- ToolLog(
- type="tool",
- tool_name="Name1",
- tool_input="content",
- ),
- ToolLog(
- type="tool",
- tool_name="Name2",
- tool_input="content 2",
- ),
- ToolLog(
- type="tool",
- tool_name="Name3",
- tool_input="content 3",
- ),
- ],
- },
- {
- "llm_output": """Thought: I need to install the `email-validator` package using `InstallNPMDependencies`. Then, I need to write the post handler function that checks if the email is valid and sends the appropriate response. Finally, I need to add the post handler to the Express app and start the server using `app.listen()`.
-
-Action:
-<action tool="InstallNPMDependencies">
-email-validator
-</action>
-
-<action tool="RunJavaScriptCode">
-import express from 'express';
-import validator from 'email-validator';
-
-const app = express();
-const port = 3000;
-
-app.use(express.json());
-
-app.post('/', (req, res) => {
- const email = req.body.email;
- if (!validator.validate(email)) {
- res.status(400).json({ error: 'Invalid email format' });
- } else {
- res.status(200).json({});
- }
-});
-
-app.listen(port, () => {
- console.log(`Server listening on port ${port}`);
-});
-</action>
-
-
-""",
- "expected_actions": [
- ToolLog(
- type="tool",
- tool_name="InstallNPMDependencies",
- tool_input="email-validator",
- ),
- ToolLog(
- type="tool",
- tool_name="RunJavaScriptCode",
- tool_input="""import express from 'express';
-import validator from 'email-validator';
-
-const app = express();
-const port = 3000;
-
-app.use(express.json());
-
-app.post('/', (req, res) => {
- const email = req.body.email;
- if (!validator.validate(email)) {
- res.status(400).json({ error: 'Invalid email format' });
- } else {
- res.status(200).json({});
- }
-});
-
-app.listen(port, () => {
- console.log(`Server listening on port ${port}`);
-});""",
- ),
- ],
- },
- {
- "llm_output": """
- <action tool="InstallNPMDependencies">
- package_name_1 package_name_2
- </action>
-""",
- "expected_actions": [
- ToolLog(
- type="tool",
- tool_name="InstallNPMDependencies",
- tool_input="package_name_1 package_name_2",
- ),
- ],
- },
- {
- "llm_output": """
-<action tool="AskHuman">
-What should the post request handler do?
-</action>
-This is a thought:
-Action:
-""",
- "expected_actions": [
- ToolLog(
- type="tool",
- tool_name="AskHuman",
- tool_input="What should the post request handler do?",
- ),
- ],
- },
- {
- "llm_output": """
-<action tool="AskHuman">
-What should the post request handler do?
-</action>
-This is a thought:
-
-<?
-<action tool="AskHuman">
-What
-</action>
-
-This is a thought:
-
-<?
-""",
- "expected_actions": [
- ToolLog(
- type="tool",
- tool_name="AskHuman",
- tool_input="What should the post request handler do?",
- ),
- ToolLog(
- type="tool",
- tool_name="AskHuman",
- tool_input="What",
- ),
- ],
- },
- {
- "llm_output": """
-This is a thought
-Greater <?
-And action:
-
-<action tool="AskHuman">
-What should the post request handler do?
-</action>
-<action tool="AskHuman">
-What
-</action>
-thought after?
-""",
- "expected_actions": [
- ToolLog(
- type="tool",
- tool_name="AskHuman",
- tool_input="What should the post request handler do?",
- ),
- ToolLog(
- type="tool",
- tool_name="AskHuman",
- tool_input="What",
- ),
- ],
- },
-]
-
-
-def test_parsing_llm_action_output(helpers):
- """Test LLM action parsing."""
- helpers.test_llm_outputs_parsing(llm_outputs)
diff --git a/api-service/test/test_incomplete_action_parsing.py b/api-service/test/test_incomplete_action_parsing.py
deleted file mode 100644
index 47f6e37c8..000000000
--- a/api-service/test/test_incomplete_action_parsing.py
+++ /dev/null
@@ -1,40 +0,0 @@
-"""Test LLM incomplete action parsing"""
-
-from typing import Dict, List, Any
-
-from agent.output.parse_output import ToolLog
-
-llm_outputs: List[Dict[str, Any]] = [
- {
- "llm_output": """Action:
-<action tool="AskHuman">
-What should the post request handler do?
-</action
-""",
- "expected_actions": [
- ToolLog(
- type="tool",
- tool_name="AskHuman",
- tool_input="What should the post request handler do?",
- )
- ],
- },
- {
- "llm_output": """Action:
-<action tool="AskHuman">
-What should the post request handler do?
-</""",
- "expected_actions": [
- ToolLog(
- type="tool",
- tool_name="AskHuman",
- tool_input="What should the post request handler do?\n</",
- )
- ],
- },
-]
-
-
-def test_parsing_llm_incomplete_action_output(helpers):
- """Test LLM action parsing."""
- helpers.test_llm_outputs_parsing(llm_outputs)