DocUA commited on
Commit
ac50cc2
·
1 Parent(s): cb898e1

Оновлено модуль логування MAI-DX: повернуто вивід в консоль, вдосконалено обробку захопленого тексту та покращено документацію. Виправлено помилки в парсері для надійнішого захоплення розмов агентів.

Browse files
Files changed (1) hide show
  1. enhanced_mai_dx_logger.py +8 -16
enhanced_mai_dx_logger.py CHANGED
@@ -1,7 +1,7 @@
1
  #!/usr/bin/env python3
2
  """
3
  Покращений модуль для повного логування діагностичних сесій MAI-DX
4
- з детальним захопленням розмов між агентами. (ВЕРСІЯ З ВИПРАВЛЕНИМ ПАРСЕРОМ)
5
  """
6
  import os
7
  import io
@@ -63,9 +63,13 @@ class EnhancedOutputCapture:
63
  sys.stdout = self.original_stdout
64
 
65
  def write(self, text):
 
 
 
 
 
66
  self.captured_output.write(text)
67
- # Уникаємо подвійного виводу в консоль, якщо Gradio робить це сам
68
- # self.original_stdout.write(text)
69
 
70
  def flush(self):
71
  self.original_stdout.flush()
@@ -96,7 +100,6 @@ class MAIDxConversationLogger:
96
 
97
  def finalize_and_save_session(self, session: DiagnosisSession, result: Any, raw_output: str, duration: float) -> DiagnosisSession:
98
  session.raw_output = raw_output
99
- # Головний виклик, що парсить лог
100
  self._parse_captured_output(session, raw_output)
101
 
102
  session.diagnosis = getattr(result, 'final_diagnosis', 'N/A')
@@ -112,10 +115,6 @@ class MAIDxConversationLogger:
112
  return session
113
 
114
  def _parse_captured_output(self, session: DiagnosisSession, captured_text: str):
115
- """
116
- FIXED: Повністю перероблений, більш надійний парсер, який не залежить
117
- від рядка "Starting Diagnostic Loop".
118
- """
119
  lines = captured_text.split('\n')
120
  current_round: Optional[AgentConversation] = None
121
  current_agent: Optional[str] = None
@@ -126,10 +125,8 @@ class MAIDxConversationLogger:
126
  for line in lines:
127
  stripped_line = line.strip()
128
 
129
- # Визначаємо початок блоку агента
130
  if "Agent Name" in line and ("╭" in line or "┌" in line):
131
- # Якщо це перший агент у раунді, створюємо новий раунд
132
- if not current_round or in_agent_output: # in_agent_output check for nested blocks
133
  round_number += 1
134
  if current_round:
135
  current_round.end_time = datetime.now().isoformat()
@@ -143,16 +140,13 @@ class MAIDxConversationLogger:
143
  buffer = []
144
  continue
145
 
146
- # Визначаємо кінець блоку агента
147
  if in_agent_output and ("╰" in line or "└" in line):
148
  if buffer and current_agent and current_round:
149
  self._add_agent_message(current_round, current_agent, '\n'.join(buffer))
150
  in_agent_output, current_agent, buffer = False, None, []
151
  continue
152
 
153
- # Збираємо вміст блоку
154
  if in_agent_output:
155
- # Очищуємо рядки від символів рамок
156
  clean_line = re.sub(r'^[│|]\s*|\s*[│|]\s*$', '', line)
157
  buffer.append(clean_line)
158
  continue
@@ -162,10 +156,8 @@ class MAIDxConversationLogger:
162
 
163
  def _add_agent_message(self, conversation: AgentConversation, agent_name: str, content: str):
164
  message_type = "output"
165
- # Видаляємо зайві порожні рядки на початку та в кінці
166
  formatted_content = content.strip()
167
 
168
- # Покращуємо визначення типу повідомлення
169
  if "Structured Output - Attempting Function Call Execution" in formatted_content:
170
  message_type = "function_call"
171
  elif "Score:" in formatted_content and "Justification:" in formatted_content:
 
1
  #!/usr/bin/env python3
2
  """
3
  Покращений модуль для повного логування діагностичних сесій MAI-DX
4
+ з детальним захопленням розмов між агентами. (ВЕРСІЯ З ВИПРАВЛЕНИМ ПАРСЕРОМ І ПОВЕРНЕНИМ ВИВОДОМ)
5
  """
6
  import os
7
  import io
 
63
  sys.stdout = self.original_stdout
64
 
65
  def write(self, text):
66
+ """
67
+ FIX: Повертаємо вивід в консоль.
68
+ Цей метод тепер і записує вивід у буфер для парсингу,
69
+ і дублює його в оригінальну консоль.
70
+ """
71
  self.captured_output.write(text)
72
+ self.original_stdout.write(text)
 
73
 
74
  def flush(self):
75
  self.original_stdout.flush()
 
100
 
101
  def finalize_and_save_session(self, session: DiagnosisSession, result: Any, raw_output: str, duration: float) -> DiagnosisSession:
102
  session.raw_output = raw_output
 
103
  self._parse_captured_output(session, raw_output)
104
 
105
  session.diagnosis = getattr(result, 'final_diagnosis', 'N/A')
 
115
  return session
116
 
117
  def _parse_captured_output(self, session: DiagnosisSession, captured_text: str):
 
 
 
 
118
  lines = captured_text.split('\n')
119
  current_round: Optional[AgentConversation] = None
120
  current_agent: Optional[str] = None
 
125
  for line in lines:
126
  stripped_line = line.strip()
127
 
 
128
  if "Agent Name" in line and ("╭" in line or "┌" in line):
129
+ if not current_round or in_agent_output:
 
130
  round_number += 1
131
  if current_round:
132
  current_round.end_time = datetime.now().isoformat()
 
140
  buffer = []
141
  continue
142
 
 
143
  if in_agent_output and ("╰" in line or "└" in line):
144
  if buffer and current_agent and current_round:
145
  self._add_agent_message(current_round, current_agent, '\n'.join(buffer))
146
  in_agent_output, current_agent, buffer = False, None, []
147
  continue
148
 
 
149
  if in_agent_output:
 
150
  clean_line = re.sub(r'^[│|]\s*|\s*[│|]\s*$', '', line)
151
  buffer.append(clean_line)
152
  continue
 
156
 
157
  def _add_agent_message(self, conversation: AgentConversation, agent_name: str, content: str):
158
  message_type = "output"
 
159
  formatted_content = content.strip()
160
 
 
161
  if "Structured Output - Attempting Function Call Execution" in formatted_content:
162
  message_type = "function_call"
163
  elif "Score:" in formatted_content and "Justification:" in formatted_content: