forked from TransformerOptimus/SuperAGI
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoutput_parser.py
70 lines (58 loc) · 2.49 KB
/
output_parser.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import json
from abc import ABC, abstractmethod
from typing import Dict, NamedTuple, List
import re
import ast
import json
from superagi.helper.json_cleaner import JsonCleaner
from superagi.lib.logger import logger
class AgentGPTAction(NamedTuple):
name: str
args: Dict
class AgentTasks(NamedTuple):
tasks: List[str] = []
error: str = ""
class BaseOutputParser(ABC):
@abstractmethod
def parse(self, text: str) -> AgentGPTAction:
"""Return AgentGPTAction"""
class AgentSchemaOutputParser(BaseOutputParser):
"""Parses the output from the agent schema"""
def parse(self, response: str) -> AgentGPTAction:
if response.startswith("```") and response.endswith("```"):
response = "```".join(response.split("```")[1:-1])
response = JsonCleaner.extract_json_section(response)
# ast throws error if true/false params passed in json
response = JsonCleaner.clean_boolean(response)
# OpenAI returns `str(content_dict)`, literal_eval reverses this
try:
logger.debug("AgentSchemaOutputParser: ", response)
response_obj = ast.literal_eval(response)
args = response_obj['tool']['args'] if 'args' in response_obj['tool'] else {}
return AgentGPTAction(
name=response_obj['tool']['name'],
args=args,
)
except BaseException as e:
logger.info(f"AgentSchemaOutputParser: Error parsing JSON response {e}")
raise e
class AgentSchemaToolOutputParser(BaseOutputParser):
"""Parses the output from the agent schema for the tool"""
def parse(self, response: str) -> AgentGPTAction:
if response.startswith("```") and response.endswith("```"):
response = "```".join(response.split("```")[1:-1])
response = JsonCleaner.extract_json_section(response)
# ast throws error if true/false params passed in json
response = JsonCleaner.clean_boolean(response)
# OpenAI returns `str(content_dict)`, literal_eval reverses this
try:
logger.debug("AgentSchemaOutputParser: ", response)
response_obj = ast.literal_eval(response)
args = response_obj['args'] if 'args' in response_obj else {}
return AgentGPTAction(
name=response_obj['name'],
args=args,
)
except BaseException as e:
logger.info(f"AgentSchemaToolOutputParser: Error parsing JSON response {e}")
raise e