-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconsole_app.py
More file actions
281 lines (232 loc) · 9.76 KB
/
Copy pathconsole_app.py
File metadata and controls
281 lines (232 loc) · 9.76 KB
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
# console_app.py
from datetime import datetime
from cleaning_agent import CleaningAgent
from extraction_agent import ExtractionAgent
from indexing_agent import IndexingAgent
from session_state import SessionState
from memory_store import save_incident_to_memory, save_feedback_to_memory, load_all_incidents
from context_utils import build_compact_summary
import os
def generate_report_id() -> str:
"""Create an ID like IR_20251129_173055."""
ts = datetime.now().strftime("%Y%m%d_%H%M%S")
return f"IR_{ts}", ts
def format_report(report_id: str,
created_at: str,
description: str,
case) -> str:
"""
Build a nicely formatted incident report as a text block.
`case` is an ExtractedCase from ExtractionAgent.
"""
perpetrators = ", ".join(case.entities.get("perpetrators") or []) or "None"
locations = ", ".join(case.entities.get("locations") or []) or "None"
violations = ", ".join(case.entities.get("violations") or []) or "None"
lines = []
lines.append("=" * 60)
lines.append(f"Incident Report ID: {report_id}")
lines.append(f"Created At: {created_at}")
lines.append("")
lines.append("Original Description")
lines.append("--------------------")
lines.append(description.strip())
lines.append("")
lines.append("Cleaned Summary")
lines.append("----------------")
lines.append(case.summary.strip())
lines.append("")
lines.append("Entities")
lines.append("--------")
lines.append(f"Perpetrators : {perpetrators}")
lines.append(f"Locations : {locations}")
lines.append(f"Violations : {violations}")
lines.append("=" * 60)
return "\n".join(lines)
def save_report_to_file(report_id: str, report_text: str, folder: str = "generated_reports"):
"""
Optional: save each report as a text file.
Creates folder `generated_reports/` if it does not exist.
"""
if not os.path.exists(folder):
os.makedirs(folder)
filename = os.path.join(folder, f"{report_id}.txt")
with open(filename, "w", encoding="utf-8") as f:
f.write(report_text)
print(f"[Saved] {filename}")
def log_feedback(report_id: str,
description: str,
case,
category: str,
user_note: str,
feedback_file: str = "customer_feedback.txt"):
"""
Append a feedback record to customer_feedback.txt.
Includes timestamp, report_id, category, user note, and current entities.
"""
ts = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
perpetrators = ", ".join(case.entities.get("perpetrators") or []) or "None"
locations = ", ".join(case.entities.get("locations") or []) or "None"
violations = ", ".join(case.entities.get("violations") or []) or "None"
with open(feedback_file, "a", encoding="utf-8") as f:
f.write("\n" + "#" * 70 + "\n")
f.write(f"Feedback Timestamp : {ts}\n")
f.write(f"Report ID : {report_id}\n")
f.write(f"Category : {category}\n")
f.write(f"User Feedback : {user_note.strip()}\n")
f.write("\n")
f.write("Original Description:\n")
f.write(description.strip() + "\n\n")
f.write("Current Extracted Entities:\n")
f.write(f" Perpetrators : {perpetrators}\n")
f.write(f" Locations : {locations}\n")
f.write(f" Violations : {violations}\n")
f.write("#" * 70 + "\n")
print(f"[Feedback logged] ({category}) → {feedback_file}")
def run_console():
cleaner = CleaningAgent()
extractor = ExtractionAgent()
indexer = IndexingAgent()
session_id = datetime.now().strftime("SESSION_%Y%m%d_%H%M%S")
session = SessionState(
session_id=session_id,
started_at=datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
)
print("=== Incident Helper Console ===")
print("Available commands: history, last, today, exit\n")
print(f"(Session: {session_id})")
print("Type an incident description and press Enter.")
print("Type 'exit' to quit.\n")
while True:
print("\n Commands: history = show all the incidents,last = show previous incident, today = list today's incidents, exit = quit \n")
description = input("Describe incident or enter a command: ").strip()
#Context Engineering
if description.lower() == "context":
print("\n=== COMPACT CONTEXT BLOCK (last 5 incidents) ===")
from context_utils import build_compact_context
ctx = build_compact_context(session, limit=5)
print(ctx)
print()
continue
# Memory Bank
if description.lower() == "history":
all_incidents = load_all_incidents()
if not all_incidents:
print("No incidents in long-term memory yet.\n")
else:
print("\n=== ALL INCIDENTS (LONG-TERM) ===")
for inc in all_incidents[-20:]: #for demo purpose , we will show only 20 incidents
print(f"- {inc.created_at} | {inc.report_id} | {inc.description}")
print()
continue
# Exit command
if description.lower() == "exit":
print("Goodbye!")
break
# Session Show all incidents for today
if description.lower() == "today":
today_list = session.incidents_today()
if not today_list:
print("\nNo incidents created today.\n")
continue
print("\n=== INCIDENTS CREATED TODAY ===")
for inc in today_list:
print(f"- {inc.report_id} | {inc.created_at} | Desc: {inc.description[:40]}...")
print()
continue
# Last incident in this session
if description.lower() == "last":
last = session.last_incident()
if not last:
print("\nNo incidents in this session yet.\n")
continue
print("\n=== LAST INCIDENT THIS SESSION ===")
print(f"Report ID : {last.report_id}")
print(f"Created : {last.created_at}")
print(f"Desc : {last.description}")
print(f"Perp : {', '.join(last.case.entities.get('perpetrators') or []) or 'None'}")
print()
continue
if not description:
print("Please enter some text.\n")
continue
word_count = len(description.split())
if word_count < 3:
print("Description too short. Please enter at least 3 meaningful words.\n")
continue
# 1) Generate report ID with timestamp
report_id, ts_str = generate_report_id()
# 2) Cleaning
clean_result = cleaner.clean(description)
compact = build_compact_summary(description, clean_result.tokens)
# 3) Extraction (LLM)
case = extractor.extract(report_id, description, clean_result.tokens)
# 4) Add to index
indexer.add_case(case)
# 5) Store in session state
session.add_incident(report_id, description, case,compact)
session_incident = session.last_incident()
save_incident_to_memory(session_incident)
with open("long_term_memory.txt", "a", encoding="utf-8") as f:
inc = session.last_incident()
f.write(f"{inc.created_at} | {inc.report_id} | {inc.compact}\n")
# 6) Build formatted report text
created_at_human = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
report_text = format_report(
report_id=report_id,
created_at=created_at_human,
description=description,
case=case,
)
# 7) Print to console
print()
print(report_text)
print()
# 8) Save to file?
save_choice = input("Save this report to file? (y/n): ").strip().lower()
if save_choice == "y":
save_report_to_file(report_id, report_text)
# 9) Feedback
fb_choice = input("Was anything wrong in the extracted info? (y/n): ").strip().lower()
if fb_choice == "y":
print("What was wrong?")
print("1) Perpetrators")
print("2) Locations")
print("3) Violations")
print("4) Other")
raw_choices = input("Enter choice(s), e.g. 1,3 or 2,4: ").strip()
choice_list = [c.strip() for c in raw_choices.split(",") if c.strip()]
category_map = {
"1": "perpetrators",
"2": "locations",
"3": "violations",
"4": "other",
}
# Collect selected categories
selected_categories = [category_map[c] for c in choice_list if c in category_map]
if not selected_categories:
print("No valid categories selected.\n")
else:
category_str = ", ".join(selected_categories)
print(f"\nYou selected: {category_str}")
user_note = input(
"Please describe what was wrong and (optionally) what it should be:\n> "
)
# Log one combined feedback record
log_feedback(
report_id=report_id,
description=description,
case=case,
category=category_str,
user_note=user_note,
)
# Also store a lightweight note in session state
session.add_feedback(
report_id=report_id,
categories=selected_categories,
user_note="(See feedback file for details)",
)
last_fb = session.feedback[-1]
save_feedback_to_memory(last_fb)
print()
if __name__ == "__main__":
run_console()