Fix history limit handling.

This commit is contained in:
OK
2023-04-13 18:36:06 +02:00
parent 79e95ab06c
commit 2508a12b44
4 changed files with 24 additions and 19 deletions
+9 -5
View File
@@ -18,7 +18,7 @@ def pp(*args, **kw):
return pformat(*args, **kw)
def parse_response(content: str) -> Dict:
def parse_json(content: str) -> Dict:
content = content.strip()
try:
return json.loads(content)
@@ -36,7 +36,7 @@ def parse_maybe_json(json_string):
return ' '.join(map(str, (json_string.values() if isinstance(json_string, dict) else json_string)))
json_string = str(json_string).strip()
try:
parsed_json = parse_response(json_string)
parsed_json = parse_json(json_string)
except Exception:
for b, e in [('{', '}'), ('[', ']')]:
if json_string.startswith(b) and json_string.endswith(e):
@@ -215,7 +215,11 @@ class AIResponder(object):
del self.history[0]
else:
current = self.history[index]
count = sum(1 for item in self.history if item.get('channel') == current.get('channel'))
def same_channel(item: Dict[str, Any]) -> bool:
return parse_json(item['content']).get('channel') == parse_json(current['content']).get('channel')
count = sum(1 for item in self.history if same_channel(item))
if count > self.config.get('history-per-channel', 3):
del self.history[index]
else:
@@ -254,14 +258,14 @@ class AIResponder(object):
# Attempt to parse the AI's response
try:
response = parse_response(answer['content'])
response = parse_json(answer['content'])
except Exception as err:
logging.warning(f"failed to parse the answer: {pp(err)}\n{repr(answer['content'])}")
answer['content'] = await self.fix(answer['content'])
# Retry parsing the fixed content
try:
response = parse_response(answer['content'])
response = parse_json(answer['content'])
except Exception as err:
logging.error(f"failed to parse the fixed answer: {pp(err)}\n{repr(answer['content'])}")
retries -= 1