Severian commited on
Commit
8127272
·
verified ·
1 Parent(s): 896eafc

Update response_formatter.py

Browse files
Files changed (1) hide show
  1. response_formatter.py +49 -40
response_formatter.py CHANGED
@@ -20,52 +20,48 @@ class ToolType:
20
  class ResponseFormatter:
21
  @staticmethod
22
  def format_thought(
23
- thought: str,
24
- observation: Optional[str] = None,
25
  citations: List[Dict] = None,
26
- metadata: Dict = None
 
27
  ) -> Tuple[str, str]:
28
- """Format agent thought and observation for both terminal and XML output"""
29
  # Terminal format
30
- terminal_output = thought.strip()
31
- if observation:
32
- cleaned_obs = ResponseFormatter._clean_markdown(observation)
33
- if cleaned_obs:
34
- terminal_output += f"\n\nObservation:\n{cleaned_obs}"
35
-
 
 
 
36
  # XML format
37
  root = ET.Element("agent_response")
38
  thought_elem = ET.SubElement(root, "thought")
39
- thought_elem.text = thought.strip()
40
 
41
  if observation:
42
  obs_elem = ET.SubElement(root, "observation")
43
-
44
- # Extract and format tool outputs
45
- tool_outputs = ResponseFormatter._extract_tool_outputs(observation)
46
- if tool_outputs:
47
- tools_elem = ET.SubElement(obs_elem, "tools")
48
- for tool_name, tool_data in tool_outputs.items():
49
- tool_elem = ResponseFormatter._create_tool_element(tools_elem, tool_name, tool_data)
50
-
51
- # Add citations if available
52
  if citations:
53
- citations_elem = ET.SubElement(root, "citations")
54
  for citation in citations:
55
- cite_elem = ET.SubElement(citations_elem, "citation")
56
  for key, value in citation.items():
57
- cite_detail = ET.SubElement(cite_elem, key)
58
- cite_detail.text = str(value)
59
-
60
- # Add metadata if available
61
- if metadata:
62
- metadata_elem = ET.SubElement(root, "metadata")
63
- for key, value in metadata.items():
64
- meta_detail = ET.SubElement(metadata_elem, key)
65
- meta_detail.text = str(value)
66
-
67
  xml_output = ET.tostring(root, encoding='unicode')
68
- return terminal_output, xml_output
69
 
70
  @staticmethod
71
  def _create_tool_element(parent: ET.Element, tool_name: str, tool_data: Dict) -> ET.Element:
@@ -113,16 +109,29 @@ class ResponseFormatter:
113
 
114
  @staticmethod
115
  def _format_mermaid_data(tool_elem: ET.Element, data: Dict) -> None:
116
- """Format mermaid diagram data"""
117
  try:
118
  diagram_elem = ET.SubElement(tool_elem, "diagram")
119
- if "mermaid_diagram" in data:
120
- # Clean the mermaid code
121
- mermaid_code = re.sub(r'```mermaid\s*|\s*```', '', data["mermaid_diagram"])
122
- diagram_elem.text = mermaid_code.strip()
123
- except:
 
 
 
 
 
 
 
 
 
 
 
 
 
124
  content_elem = ET.SubElement(tool_elem, "content")
125
- content_elem.text = ResponseFormatter._clean_markdown(str(data))
126
 
127
  @staticmethod
128
  def _format_health_data(tool_elem: ET.Element, data: Dict) -> None:
 
20
  class ResponseFormatter:
21
  @staticmethod
22
  def format_thought(
23
+ thought: str,
24
+ observation: str,
25
  citations: List[Dict] = None,
26
+ metadata: Dict = None,
27
+ tool_outputs: List[Dict] = None
28
  ) -> Tuple[str, str]:
29
+ """Format agent thought for both terminal and XML output"""
30
  # Terminal format
31
+ terminal_output = {
32
+ "type": "agent_thought",
33
+ "content": thought,
34
+ "metadata": metadata or {}
35
+ }
36
+
37
+ if tool_outputs:
38
+ terminal_output["tool_outputs"] = tool_outputs
39
+
40
  # XML format
41
  root = ET.Element("agent_response")
42
  thought_elem = ET.SubElement(root, "thought")
43
+ thought_elem.text = thought
44
 
45
  if observation:
46
  obs_elem = ET.SubElement(root, "observation")
47
+ obs_elem.text = observation
48
+
49
+ if tool_outputs:
50
+ tools_elem = ET.SubElement(root, "tool_outputs")
51
+ for tool_output in tool_outputs:
52
+ tool_elem = ET.SubElement(tools_elem, "tool_output")
53
+ tool_elem.attrib["type"] = tool_output.get("type", "")
54
+ tool_elem.text = tool_output.get("content", "")
55
+
56
  if citations:
57
+ cites_elem = ET.SubElement(root, "citations")
58
  for citation in citations:
59
+ cite_elem = ET.SubElement(cites_elem, "citation")
60
  for key, value in citation.items():
61
+ cite_elem.attrib[key] = str(value)
62
+
 
 
 
 
 
 
 
 
63
  xml_output = ET.tostring(root, encoding='unicode')
64
+ return json.dumps(terminal_output), xml_output
65
 
66
  @staticmethod
67
  def _create_tool_element(parent: ET.Element, tool_name: str, tool_data: Dict) -> ET.Element:
 
109
 
110
  @staticmethod
111
  def _format_mermaid_data(tool_elem: ET.Element, data: Dict) -> None:
112
+ """Format mermaid diagram data with improved error handling"""
113
  try:
114
  diagram_elem = ET.SubElement(tool_elem, "diagram")
115
+
116
+ # Extract content from data
117
+ content = ""
118
+ if isinstance(data, dict):
119
+ content = data.get("content", data.get("mermaid_diagram", ""))
120
+ elif isinstance(data, str):
121
+ content = data
122
+
123
+ # Clean any remaining markdown/JSON formatting
124
+ content = re.sub(r'```mermaid\s*|\s*```', '', content)
125
+ content = re.sub(r'tool response:.*?{', '{', content)
126
+ content = re.sub(r'}\s*\.$', '}', content)
127
+
128
+ # Set cleaned content
129
+ diagram_elem.text = content.strip()
130
+
131
+ except Exception as e:
132
+ logger.error(f"Error formatting mermaid data: {e}")
133
  content_elem = ET.SubElement(tool_elem, "content")
134
+ content_elem.text = "Error formatting diagram"
135
 
136
  @staticmethod
137
  def _format_health_data(tool_elem: ET.Element, data: Dict) -> None: