2023-04-19 04:41:03 +00:00
|
|
|
import json
|
|
|
|
import re
|
|
|
|
from abc import abstractmethod
|
|
|
|
from typing import Dict, NamedTuple
|
|
|
|
|
|
|
|
from langchain.schema import BaseOutputParser
|
|
|
|
|
|
|
|
|
|
|
|
class AutoGPTAction(NamedTuple):
|
2023-07-24 21:21:48 +00:00
|
|
|
"""Action for AutoGPT."""
|
|
|
|
|
2023-04-19 04:41:03 +00:00
|
|
|
name: str
|
2023-07-24 21:21:48 +00:00
|
|
|
"""Name of the action."""
|
2023-04-19 04:41:03 +00:00
|
|
|
args: Dict
|
2023-07-24 21:21:48 +00:00
|
|
|
"""Arguments for the action."""
|
2023-04-19 04:41:03 +00:00
|
|
|
|
|
|
|
|
|
|
|
class BaseAutoGPTOutputParser(BaseOutputParser):
|
2023-07-24 21:21:48 +00:00
|
|
|
"""Base class for AutoGPT output parsers."""
|
|
|
|
|
2023-04-19 04:41:03 +00:00
|
|
|
@abstractmethod
|
|
|
|
def parse(self, text: str) -> AutoGPTAction:
|
2023-07-24 21:21:48 +00:00
|
|
|
"""Parse text and return AutoGPTAction"""
|
2023-04-19 04:41:03 +00:00
|
|
|
|
|
|
|
|
|
|
|
def preprocess_json_input(input_str: str) -> str:
|
2023-06-23 22:49:44 +00:00
|
|
|
"""Preprocesses a string to be parsed as json.
|
|
|
|
|
|
|
|
Replace single backslashes with double backslashes,
|
|
|
|
while leaving already escaped ones intact.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
input_str: String to be preprocessed
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
Preprocessed string
|
|
|
|
"""
|
2023-04-19 04:41:03 +00:00
|
|
|
corrected_str = re.sub(
|
|
|
|
r'(?<!\\)\\(?!["\\/bfnrt]|u[0-9a-fA-F]{4})', r"\\\\", input_str
|
|
|
|
)
|
|
|
|
return corrected_str
|
|
|
|
|
|
|
|
|
|
|
|
class AutoGPTOutputParser(BaseAutoGPTOutputParser):
|
2023-07-24 21:21:48 +00:00
|
|
|
"""Output parser for AutoGPT."""
|
|
|
|
|
2023-04-19 04:41:03 +00:00
|
|
|
def parse(self, text: str) -> AutoGPTAction:
|
|
|
|
try:
|
|
|
|
parsed = json.loads(text, strict=False)
|
|
|
|
except json.JSONDecodeError:
|
|
|
|
preprocessed_text = preprocess_json_input(text)
|
|
|
|
try:
|
|
|
|
parsed = json.loads(preprocessed_text, strict=False)
|
|
|
|
except Exception:
|
|
|
|
return AutoGPTAction(
|
|
|
|
name="ERROR",
|
|
|
|
args={"error": f"Could not parse invalid json: {text}"},
|
|
|
|
)
|
|
|
|
try:
|
|
|
|
return AutoGPTAction(
|
|
|
|
name=parsed["command"]["name"],
|
|
|
|
args=parsed["command"]["args"],
|
|
|
|
)
|
2023-04-21 06:18:46 +00:00
|
|
|
except (KeyError, TypeError):
|
|
|
|
# If the command is null or incomplete, return an erroneous tool
|
2023-04-19 04:41:03 +00:00
|
|
|
return AutoGPTAction(
|
|
|
|
name="ERROR", args={"error": f"Incomplete command args: {parsed}"}
|
|
|
|
)
|