Skip to content

armgit / E2B

Public Imported from GitHub
0

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

Improve action parsing

Tomas Valenta3c7509f0f283
diff --git a/api-service/app.py b/api-service/app.py
index f274a02a7..c43877331 100644
--- a/api-service/app.py
+++ b/api-service/app.py
@@ -3,6 +3,7 @@ import uuid
from dotenv import load_dotenv
from typing import List
+from playground_client.exceptions import NotFoundException
from quart import Quart, request
from quart_cors import cors
@@ -15,6 +16,10 @@ load_dotenv()
url = os.environ.get("SUPABASE_URL")
key = os.environ.get("SUPABASE_SECRET_KEY")
+
+if not url or not key:
+ raise NotFoundException("Suapbase credentials not found")
+
db = Database(url, key)
app = Quart(__name__)
diff --git a/api-service/codegen/agent/base.py b/api-service/codegen/agent/base.py
index d94878415..9d1c04829 100644
--- a/api-service/codegen/agent/base.py
+++ b/api-service/codegen/agent/base.py
@@ -2,151 +2,93 @@ import xml.etree.ElementTree as ET
import re
import traceback
-from typing import Optional, Tuple, List, Dict, Union
-from html import unescape
+from enum import Enum
+from typing_extensions import NotRequired
+from typing import Literal, Optional, Tuple, List, Dict, Union, cast
from lxml import etree
from langchain.agents.tools import InvalidTool
from langchain.agents import AgentExecutor
from langchain.agents.chat.base import ChatAgent
from langchain.schema import AgentAction, AgentFinish
from langchain.tools.base import BaseTool
+from typing import List, TypedDict
FINAL_ANSWER_ACTION = "Final Answer:"
ACTIONS_QUEUE = "action_queue"
MALFORMED_ANSWER = "malformed_answer"
-xml_escape_dict = {
- '"': """,
- "'": "'",
+escape_table = str.maketrans({
"<": "&lt;",
">": "&gt;",
"&": "&amp;",
-}
-
-
-def xml_escape(text: str) -> str:
- for k, v in xml_escape_dict.items():
- text = text.replace(k, v)
- return text
-
-
-def actions_from_xml_string(xml_string: str):
- """The `xml_string` must be escaped"""
+ "'": "&apos;",
+ '"': "&quot;",
+})
+
+def xml_escape(txt: str):
+ return txt.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_dict(t: TypedDict, o: TypedDict):
+ t.update(o)
+
+action_tag_open = "<action(\\s+tool=\".+?\")?\\s*\\/?>?"
+action_tag_close = "</\\s*action>?"
+
+action_tag_check_pattern = re.compile(f"{action_tag_open}|{action_tag_close}")
+action_tag_split_pattern = re.compile(f"({action_tag_open}.*?{action_tag_close})|(.+)")
+
+def parse_text(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
+ )
- # Parse the escaped string as an XML tree.
root = ET.fromstring(
# Wrapping the XML in a fully formed root tag while some inner tags can be incomplete doesn't make sense.
- f"<root>{xml_string}",
+ f"<root>{escaped}",
# Use Parser with C binding for libxml2+libxslt, with recovery mode that allows to parse incomplete XML.
etree.XMLParser(recover=True),
)
- actions = root.findall("action")
-
- # Because we XML-escaped action element's body (= tool input) so we could XML-parse it,
- # we need to unescape it now to get the actual tool input.
- for a in actions:
- if a.text:
- a.text = unescape(a.text)
- else:
- a.text = ""
- return actions
-
-
-def parse_action_string(action_string: str):
- lines = action_string.strip().splitlines()
-
- if len(lines) == 0:
- # TODO: What to do here?
- pass
-
- # === SINGLE-LINE CASE
- # <action tool="name">content</action><action tool="name">content</action>
- #
- if len(lines) == 1:
- # We assume that the XML is in valid format, just on a single line.
- line = lines[0]
- parts = line.split("</action>")
- # We have an array that looks like this:
- # ['<action tool="name">content', '<action tool="name">content', ..., '']
- # We will use regex to match content after the `<action tool="name">` part.
- for idx, part in enumerate(parts):
- if part:
- match = re.search(r"<action tool=\"(.*)\">(.*)$", part)
- if not match:
- return []
-
- action_name, action_content = match.groups()
- escaped_content = (
- xml_escape(action_content) if action_content else action_content
- )
- # Assemble the action with escaped content back together.
- parts[idx] = f'<action tool="{action_name}">{escaped_content}</action>'
-
- escaped_xml_string = "\n".join(parts)
-
- # Parse the escaped string as an XML tree.
- actions = actions_from_xml_string(escaped_xml_string)
- return actions
-
- # === MULTI-LINE CASE
- #
- # The action is in the XML format, we need to try to a XML escape
- # the body of an XML element. We'll use a bit of heuristics here.
- # We assume the action looks like this:
- # <action tool="...">
- # action_text_content
- # </action>
- # In this case, we escape all but the first and the last line.
- # However!
- # What happens sometimes is that the model outputs multiple actions
- # in sequence like this:
- # <action tool="...">
- # action_text_content
- # </action>
- # <action tool="...">
- # action_text_content
- # </action>
- # So we should really escape everyline that DOES NOT start with either
- # <action or with </action.
- # Split the action into a list of lines.
-
- # Escape all but the lines the start or end the XML element.
- for idx, line in enumerate(lines):
- if line.startswith("<action") or line.startswith("</action"):
- continue
- lines[idx] = xml_escape(line)
-
- # Join the lines back into a single string.
- escaped = "\n".join(lines)
- # Parse the escaped string as an XML tree.
- actions = actions_from_xml_string(escaped)
- return actions
+ 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 "")
-def separate_thought_and_action(llm_input: str) -> Tuple[str, str]:
- thought, *actions = llm_input.split("```")
- action_str = "\n".join(actions).strip()
- return thought, action_str
-
+ # 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)
class CodegenAgent(ChatAgent):
def _extract_tool_and_input(self, text: str) -> Optional[Tuple[str, str | None]]:
if FINAL_ANSWER_ACTION in text:
return "Final Answer", text.split(FINAL_ANSWER_ACTION)[-1].strip()
try:
- _, action_string = separate_thought_and_action(text)
-
- # A list of XML elements that represents actions.
- actions = parse_action_string(action_string)
-
- # We handle the case when the LLM starts specifying multiple actions in a single response.
- # Return a special `ACTIONS_QUEUE` identifier and the raw action string.
- if len(actions) > 1:
- return ACTIONS_QUEUE, action_string
- else:
- return actions[0].attrib["tool"], actions[0].text
+ return ACTIONS_QUEUE, text
except Exception as e:
print(traceback.format_exc())
print("Got exception in `_extract_tool_and_input:\n", e)
@@ -266,17 +208,12 @@ class CodegenAgentExecutor(AgentExecutor):
if output.tool == ACTIONS_QUEUE:
observation = ""
- # The `output.tool_input` is a raw action string
- actions = parse_action_string(output.tool_input)
-
# Go through each action and run it.
# Collect outputs from each action.
- for action in actions:
- tool_name = action.attrib["tool"]
- tool_input = action.text
+ for action in (cast(ToolLog, action) for action in parse_text(output.tool_input) if action["type"] == "tool"):
observation = await self._arun_tool(
- tool_name=tool_name,
- tool_input=tool_input,
+ tool_name=action["tool_name"],
+ tool_input=action["tool_input"],
name_to_tool_map=name_to_tool_map,
color_mapping=color_mapping,
)
@@ -300,77 +237,3 @@ class CodegenAgentExecutor(AgentExecutor):
color_mapping=color_mapping,
)
return output, observation
-
- def _take_next_step(
- self,
- name_to_tool_map: Dict[str, BaseTool],
- color_mapping: Dict[str, str],
- inputs: Dict[str, str],
- intermediate_steps: List[Tuple[AgentAction, str]],
- ) -> Union[AgentFinish, Tuple[AgentAction, str]]:
- """Take a single step in the thought-action-observation loop.
-
- Override this to take control of how the agent makes and acts on choices.
- """
- # Call the LLM to see what to do.
- output = self.agent.plan(intermediate_steps, **inputs)
-
- # If the tool chosen is the finishing tool, then we end and return.
- 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": output.tool_input}, output.log)
-
- # 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
-
- self.callback_manager.on_agent_action(
- output, verbose=self.verbose, color="green"
- )
-
- # 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 raw action string
- actions = parse_action_string(output.tool_input)
-
- # Go through each action and run it.
- # Collect outputs from each action.
- for action in actions:
- tool_name = action.attrib["tool"]
- tool_input = action.text
- observation = self._run_tool(
- tool_name=tool_name,
- tool_input=tool_input,
- name_to_tool_map=name_to_tool_map,
- color_mapping=color_mapping,
- )
- # observation = (
- # observation
- # + f"Output of action '{tool_name}':\n"
- # + self._run_tool(
- # tool_name=tool_name,
- # tool_input=tool_input,
- # name_to_tool_map=name_to_tool_map,
- # color_mapping=color_mapping,
- # )
- # + "==="
- # )
-
- else:
- observation = self._run_tool(
- tool_name=output.tool,
- tool_input=output.tool_input,
- name_to_tool_map=name_to_tool_map,
- color_mapping=color_mapping,
- )
- return output, observation
diff --git a/api-service/codegen/callbacks/log_parser.py b/api-service/codegen/callbacks/log_parser.py
index 8324de303..d3c81a4de 100644
--- a/api-service/codegen/callbacks/log_parser.py
+++ b/api-service/codegen/callbacks/log_parser.py
@@ -1,9 +1,17 @@
import datetime
import uuid
-from typing import Dict, List
+from typing import List, TypedDict
-from codegen.agent.base import parse_action_string, separate_thought_and_action
+from codegen.agent.base import ThoughtLog, ToolLog, merge_dict, parse_text
+
+class ToolOutput(TypedDict):
+ finish_at: str
+ tool_output: str
+
+class LogMeta(TypedDict):
+ id: str
+ created_at: str
class LogStreamParser:
"""
@@ -19,10 +27,8 @@ class LogStreamParser:
This is a thought
Action:
- ```
<action type="CurlJavaScriptServer">
</ac
- ```
// End of example
This is parsed as following buffered logs:
@@ -53,79 +59,48 @@ class LogStreamParser:
self._tool_names = tool_names
# All "finished" logs that the parser saved.
- self._logs: List[Dict[str, str]] = []
+ self._logs: List[ToolLog | ThoughtLog] = []
self._token_buffer: str = ""
# 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[Dict[str, str]] = []
+ self._logs_buffer: List[ToolLog | ThoughtLog] = []
+ self._logs_meta_buffer: List[LogMeta] = []
# This is a list of tools' outputs that corresponds to the tool logs in the self._logs.buffer.
- self._tools_output_buffer: List[Dict[str, str]] = []
- # List of ids corresponding to the buffered logs.
- self._id_buffer: List[str] = []
- # List of timestamps corresponding to the buffered logs.
- self._start_timestamp_buffer: List[str] = []
+ self._tools_output_buffer: List[ToolOutput] = []
def _parse(self):
"""This function should be called only after ingesting new token or tool output to update the buffered logs."""
- thought, action_string = separate_thought_and_action(self._token_buffer)
- tools_logs = [
- {
- "type": "tool",
- "tool_name": action.attrib["tool"],
- "tool_input": action.text or "",
- }
- for action in parse_action_string(action_string)
- if action.attrib.get("tool", None) in self._tool_names
- ]
-
- # Update tools' logs with the information from ingested tools' outputs.
- for i in range(len(self._tools_output_buffer)):
- tools_logs[i] = {
- **tools_logs[i],
- **self._tools_output_buffer[i],
- }
-
# 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 = [
- {
- "type": "thought",
- "content": thought.removeprefix("Thought:")
- .replace("Action:", "")
- .strip(),
- },
- *tools_logs,
+ log for log
+ in parse_text(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._id_buffer.extend(
+ self._logs_meta_buffer.extend(
(
- str(uuid.uuid4())
- for _ in range(len(self._logs_buffer) - len(self._id_buffer))
+ 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 to logs
- for log, id in zip(self._logs_buffer, self._id_buffer):
- log["id"] = id
+ # Assign the stable ids and timestamps to logs
+ for log, meta in zip(self._logs_buffer, self._logs_meta_buffer):
+ merge_dict(log, meta)
- # Add a new timestamps to timestamps buffer if we have less timestamps that there are logs in the logs buffer.
- self._start_timestamp_buffer.extend(
- (
- str(datetime.datetime.now())
- for _ in range(
- len(self._logs_buffer) - len(self._start_timestamp_buffer)
- )
- )
- )
-
- # Assign the corresponding timestamps to logs
- for log, timestamp in zip(self._logs_buffer, self._start_timestamp_buffer):
- log["created_at"] = timestamp
+ # 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_dict(tool_log, output)
def ingest_token(self, token: str):
"""Ingest token and update the logs."""
@@ -156,8 +131,5 @@ class LogStreamParser:
return self
- def get_logs(self):
- return [
- *self._logs,
- *self._logs_buffer,
- ]
+ def get_logs(self) -> list[ToolLog | ThoughtLog]:
+ return [*self._logs, *self._logs_buffer]
diff --git a/api-service/codegen/callbacks/logs.py b/api-service/codegen/callbacks/logs.py
index d5a0322f5..c8e9587ab 100644
--- a/api-service/codegen/callbacks/logs.py
+++ b/api-service/codegen/callbacks/logs.py
@@ -1,4 +1,5 @@
from typing import Dict, Any, List, Union
+from codegen.agent.base import ThoughtLog, ToolLog
from codegen.callbacks.log_queue import LogQueue
from langchain.callbacks.base import AsyncCallbackHandler
from langchain.schema import AgentAction, AgentFinish, LLMResult
@@ -31,7 +32,7 @@ class LogsCallbackHandler(AsyncCallbackHandler):
coro = self._database.push_raw_logs(self._run_id, self._raw_logs)
self._raw_log_queue.queue.put_nowait(coro)
- def _push_logs(self, logs: List[Dict[str, str]]) -> None:
+ def _push_logs(self, logs: list[ToolLog | ThoughtLog]) -> None:
coro = self._database.push_logs(self._run_id, logs)
self._log_queue.queue.put_nowait(coro)
diff --git a/api-service/codegen/prompt.py b/api-service/codegen/prompt.py
index d86d88d0f..1aa919293 100644
--- a/api-service/codegen/prompt.py
+++ b/api-service/codegen/prompt.py
@@ -12,22 +12,19 @@ SYSTEM_FORMAT_INSTRUCTIONS = """"The way you use the tools is by specifying a XM
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:
Instructions: the input instructions you must implement
Thought: you should always think about what to do
Action:
-```
<action tool="$TOOL_NAME">
$INPUT
</action>
-```
Observation: the result of the action
... (this Thought/Action/Observation can repeat N times)
Thought: I now know the final server code and can show it.
diff --git a/api-service/codegen/tools/human/tools.py b/api-service/codegen/tools/human/tools.py
index 1b7189b0d..81c0874c6 100644
--- a/api-service/codegen/tools/human/tools.py
+++ b/api-service/codegen/tools/human/tools.py
@@ -16,11 +16,9 @@ def create_human_tools(
@async_tool("AskHuman")
async def ask_human(question: str) -> 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. Example usage:
- ```
<action tool="AskHuman">
I'm not sure what to do, can you specify what should to do next?
- </action>
- ```"""
+ </action>"""
response = playground.api.wait_for_human_response(
run_id=run_id,
)
diff --git a/api-service/codegen/tools/playground/tools/code.py b/api-service/codegen/tools/playground/tools/code.py
index 05daf10b2..df681f616 100644
--- a/api-service/codegen/tools/playground/tools/code.py
+++ b/api-service/codegen/tools/playground/tools/code.py
@@ -15,11 +15,10 @@ def create_code_tools(playground: NodeJSPlayground, mock: MockRequestFactory, **
@async_tool("InstallNPMDependencies")
async def install_dependencies(dependencies: str) -> str:
"""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>
- ```"""
+ """
output = playground.install_dependencies(extract_code(dependencies))
result = encode_command_output(output, only_errors=True)
return result if len(result) > 0 else "All dependencies installed"
@@ -34,11 +33,10 @@ def create_code_tools(playground: NodeJSPlayground, mock: MockRequestFactory, **
"""
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
@@ -54,11 +52,10 @@ def create_code_tools(playground: NodeJSPlayground, mock: MockRequestFactory, **
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:
# ```
diff --git a/api-service/database/database.py b/api-service/database/database.py
index a5e8c6491..8c9223dad 100644
--- a/api-service/database/database.py
+++ b/api-service/database/database.py
@@ -1,8 +1,7 @@
-from typing import List, Dict
+from typing import List
from enum import Enum
-# from supabase.client import create_client
-
+from codegen.agent.base import ThoughtLog, ToolLog
from database.client import Client
from session.env import EnvVar
@@ -17,7 +16,6 @@ class DeploymentState(Enum):
tableDeployments = "deployments"
tableProjects = "projects"
-
class Database:
def __init__(self, supabase_url: str, supabase_key: str) -> None:
self.client = Client(supabase_url=supabase_url, supabase_key=supabase_key)
@@ -34,7 +32,7 @@ class Database:
},
).execute()
- async def push_logs(self, run_id: str, logs: List[Dict[str, str]]) -> None:
+ async def push_logs(self, run_id: str, logs: list[ToolLog | ThoughtLog]) -> None:
if len(logs) > 0:
await self.client.table(tableDeployments).update(
{
diff --git a/components/Editor/RightSidebar/Logs/Tool/Base.tsx b/components/Editor/RightSidebar/Logs/Tool/Base.tsx
index 1cf633a64..679adbd6b 100644
--- a/components/Editor/RightSidebar/Logs/Tool/Base.tsx
+++ b/components/Editor/RightSidebar/Logs/Tool/Base.tsx
@@ -54,6 +54,7 @@ function BaseTool({
py-6
max-w-full
overflow-x-auto
+ scroller
">
{body}
</div>
diff --git a/components/Editor/RightSidebar/Logs/Tool/index.tsx b/components/Editor/RightSidebar/Logs/Tool/index.tsx
index 94f9bf251..d7dcc42ae 100644
--- a/components/Editor/RightSidebar/Logs/Tool/index.tsx
+++ b/components/Editor/RightSidebar/Logs/Tool/index.tsx
@@ -24,7 +24,7 @@ function Tool({
case ToolName.AskHuman:
return <AskHuman log={log} onAnswer={onAnswer} />
default:
- throw new Error(`'${log.tool_name}': Unknown tool log`)
+ return <div>Unknown tool {log.tool_name}</div>
}
}
diff --git a/package.json b/package.json
index 971a7e077..0dc733f46 100644
--- a/package.json
+++ b/package.json
@@ -51,6 +51,7 @@
"autoprefixer": "^10.4.13",
"concurrently": "^7.6.0",
"cssnano": "^5.1.15",
+ "date-fns": "^2.29.3",
"eslint": "^8.35.0",
"eslint-config-next": "^13.2.3",
"eslint-plugin-react": "^7.32.2",
@@ -63,4 +64,4 @@
"tailwindcss": "^3.2.7",
"typescript": "^4.9.5"
}
-}
\ No newline at end of file
+}
diff --git a/yarn.lock b/yarn.lock
index f86a3b525..2180be0de 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -870,7 +870,7 @@ data-uri-to-buffer@^4.0.0:
resolved "https://registry.yarnpkg.com/data-uri-to-buffer/-/data-uri-to-buffer-4.0.1.tgz#d8feb2b2881e6a4f58c2e08acfd0e2834e26222e"
integrity sha512-0R9ikRb668HB7QDxT1vkpuUBtqc53YyAwMwGeUFKRojY/NWKvdZ+9UYtRfGmhqNbRkTSVpMbmyhXipFFv2cb/A==
-date-fns@^2.29.1:
+date-fns@^2.29.1, date-fns@^2.29.3:
version "2.29.3"
resolved "https://registry.yarnpkg.com/date-fns/-/date-fns-2.29.3.tgz#27402d2fc67eb442b511b70bbdf98e6411cd68a8"
integrity sha512-dDCnyH2WnnKusqvZZ6+jA1O51Ibt8ZMRNkDZdyAyK4YfbDwa/cEmuztzG5pk6hqlp9aSBPYcjOlktquahGwGeA==