Skip to content

Commit

Permalink
More json cleaning (All-Hands-AI#924)
Browse files Browse the repository at this point in the history
* More json cleaning

* remove redundant check
  • Loading branch information
enyst authored Apr 10, 2024
1 parent b2de79a commit 973a42f
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 13 deletions.
12 changes: 7 additions & 5 deletions agenthub/monologue_agent/utils/json.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import json
from json_repair import repair_json


def my_encoder(obj):
"""
Encodes objects as dictionaries
Expand All @@ -11,25 +12,26 @@ def my_encoder(obj):
Returns:
- dict: If the object can be converted it is returned in dict format
"""
if hasattr(obj, "to_dict"):
if hasattr(obj, 'to_dict'):
return obj.to_dict()


def dumps(obj, **kwargs):
"""
Serialize an object to str format
"""

return json.dumps(obj, default=my_encoder, **kwargs)


def loads(s, **kwargs):
"""
Create a JSON object from str
"""
json_start = s.find("{")
json_end = s.rfind("}") + 1
json_start = s.find('{')
json_end = s.rfind('}') + 1
if json_start == -1 or json_end == -1:
raise ValueError("Invalid response: no JSON found")
raise ValueError('Invalid response: no JSON found')
s = s[json_start:json_end]
s = repair_json(s)
return json.loads(s, **kwargs)

13 changes: 5 additions & 8 deletions agenthub/monologue_agent/utils/monologue.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import agenthub.monologue_agent.utils.json as json
import agenthub.monologue_agent.utils.prompts as prompts


class Monologue:
"""
The monologue is a representation for the agent's internal monologue where it can think.
Expand All @@ -26,7 +27,7 @@ def add_event(self, t: dict):
- ValueError: If t is not a dict
"""
if not isinstance(t, dict):
raise ValueError("Event must be a dictionary")
raise ValueError('Event must be a dictionary')
self.thoughts.append(t)

def get_thoughts(self):
Expand Down Expand Up @@ -63,17 +64,13 @@ def condense(self, llm: LLM):
Raises:
- RunTimeError: When the condensing process fails for any reason
"""

try:
prompt = prompts.get_summarize_monologue_prompt(self.thoughts)
messages = [{"content": prompt,"role": "user"}]
messages = [{'content': prompt, 'role': 'user'}]
resp = llm.completion(messages=messages)
summary_resp = resp['choices'][0]['message']['content']
self.thoughts = prompts.parse_summary_response(strip_markdown(summary_resp))
self.thoughts = prompts.parse_summary_response(summary_resp)
except Exception as e:
traceback.print_exc()
raise RuntimeError(f"Error condensing thoughts: {e}")

def strip_markdown(markdown_json):
# remove markdown code block
return markdown_json.replace('```json\n', '').replace('```', '').strip()

0 comments on commit 973a42f

Please sign in to comment.