-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
1959 lines (1867 loc) · 87.5 KB
/
main.py
File metadata and controls
1959 lines (1867 loc) · 87.5 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
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""CPA-Agent FastAPI backend with optimizations."""
import asyncio
import json
import os
import re
import time
import uuid
from datetime import date, timedelta
from functools import lru_cache
from pathlib import Path
from typing import Any
from fastapi import FastAPI, HTTPException, Request, Response
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from pydantic import BaseModel, Field
from slowapi import Limiter, _rate_limit_exceeded_handler
from slowapi.util import get_remote_address
from slowapi.middleware import SlowAPIMiddleware
import requests
import speech_recognition as sr
from dotenv import load_dotenv
load_dotenv()
from core.model_client import get_model_client
from memory_manager import MemoryManager
from skills import (
GoogleDocsManager, GoogleSheetsManager, KnowledgeManager,
CategorizationEngine, RecurringEngine, FinancialStatements,
BudgetEngine, ReconciliationEngine, ARAPEngine, TaxEngine
)
ROOT_DIR = Path(__file__).resolve().parent
PERSONA_DIR = ROOT_DIR / "persona"
SYSTEM_PROMPT_PATH = PERSONA_DIR / "system_prompt.md"
CUSTOM_RULES_PATH = PERSONA_DIR / "custom_rules.json"
# Action constants
ACTION_SWITCH_BUSINESS = "switch_business"
ACTION_CREATE_BUSINESS = "create_business"
ACTION_RECORD_TRANSACTION = "record_transaction"
ACTION_READ_SHEET = "read_sheet"
ACTION_CREATE_BUSINESS_DOC = "create_business_doc"
ACTION_APPEND_DOC_NOTE = "append_doc_note"
ACTION_CALCULATE_PAYROLL = "calculate_payroll"
ACTION_RESEARCH_TAX = "research_tax"
ACTION_RESPOND = "respond"
class CPAAgent:
"""Optimized CPAAgent class with caching."""
LEDGER_HEADERS = [
"Date", "Description", "Category", "Amount", "Type",
"Reference", "Notes"
]
# Cache configuration
_STATUS_CACHE_TTL = 2.0 # seconds
_LEDGER_CACHE_TTL = 30.0 # seconds for ledger queries
_PREDICTION_CACHE_TTL = 60.0 # seconds for AI predictions
def __init__(self) -> None:
self.memory = MemoryManager(ROOT_DIR / "memory")
self.reasoning_mode = self._normalize_reasoning_mode(
os.getenv("CPA_AGENT_REASONING_MODE", "fast")
)
self._refresh_model_clients()
self.sheets = GoogleSheetsManager()
self.docs = GoogleDocsManager()
self.knowledge = KnowledgeManager()
self.categorization = CategorizationEngine(
rules_data=self.memory.load_category_rules()
)
self.recurring = RecurringEngine(
recurring_data=self.memory.load_recurring()
)
self.financial_statements = FinancialStatements()
self.budget_engine = BudgetEngine()
self.reconciliation_engine = ReconciliationEngine()
self.ar_ap_engine = ARAPEngine(self.memory)
self.tax_engine = TaxEngine(self.memory)
if not self.categorization._rules:
try:
profile = self.memory.get_current_business()
if profile.get("google_sheet_id"):
rows = self.sheets.read_range(
spreadsheet_id=profile["google_sheet_id"],
range_name="Ledger!A2:G200",
)
count = self.categorization.backfill_rules_from_ledger(rows)
if count:
self._save_category_rules()
except Exception: # noqa: BLE001
pass
self.recognizer = sr.Recognizer()
self.recognizer.pause_threshold = 0.8
self.wake_words = ("hey cpa-agent", "hey cpa agent", "cpa-agent", "cpa agent")
self.input_mode = self._determine_input_mode()
self.workspace_boot_error: str | None = None
self._workbook_ready: set[str] = set()
self._load_persona_assets()
try:
self.ensure_business_workspace_assets()
except Exception as exc: # noqa: BLE001
self.workspace_boot_error = str(exc)
@staticmethod
def _normalize_reasoning_mode(value: str) -> str:
normalized = (value or "fast").strip().lower()
return normalized if normalized in {"fast", "quality"} else "fast"
def _refresh_model_clients(self) -> None:
self.model_client = get_model_client(purpose="reasoning", reasoning_mode=self.reasoning_mode)
self.reflection_client = get_model_client(purpose="reflection", reasoning_mode=self.reasoning_mode)
def set_reasoning_mode(self, mode: str) -> dict[str, str]:
self.reasoning_mode = self._normalize_reasoning_mode(mode)
os.environ["CPA_AGENT_REASONING_MODE"] = self.reasoning_mode
self._refresh_model_clients()
return self.get_model_status()
def _determine_input_mode(self) -> str:
forced_mode = os.getenv("CPA_AGENT_INPUT_MODE", "").strip().lower()
if forced_mode in {"text", "voice"}:
return forced_mode
try:
with sr.Microphone():
return "voice"
except OSError:
return "text"
def _load_persona_assets(self) -> None:
self.system_prompt = SYSTEM_PROMPT_PATH.read_text(encoding="utf-8")
with CUSTOM_RULES_PATH.open("r", encoding="utf-8") as handle:
self.custom_rules = json.load(handle)
def _save_category_rules(self) -> None:
self.memory.save_category_rules(self.categorization.get_rules_data())
def _save_recurring(self) -> None:
self.memory.save_recurring(self.recurring.get_recurring_data())
def refresh_rules(self) -> None:
mtime = CUSTOM_RULES_PATH.stat().st_mtime
if mtime == getattr(self, "_rules_mtime", None):
return
with CUSTOM_RULES_PATH.open("r", encoding="utf-8") as handle:
self.custom_rules = json.load(handle)
self._rules_mtime = mtime
def speak(self, message: str) -> None:
safe_message = os.fsencode(message)
subprocess = __import__("subprocess")
subprocess.run(f"say {safe_message.decode()}", shell=True, check=False)
def listen_for_command(self) -> str | None:
if self.input_mode == "text":
try:
typed = input("CPA-Agent command> ").strip()
except EOFError:
return "exit"
return typed or None
with sr.Microphone() as source:
print("Listening for wake word...")
self.recognizer.adjust_for_ambient_noise(source, duration=1)
audio = self.recognizer.listen(source)
try:
transcript = self.recognizer.recognize_google(audio).lower().strip()
except (sr.UnknownValueError, sr.RequestError):
return None
if any(wake_word in transcript for wake_word in self.wake_words):
cleaned = transcript
for wake_word in self.wake_words:
cleaned = cleaned.replace(wake_word, "")
return cleaned.strip(" ,.")
return None
def _build_financial_context(self) -> str:
parts = []
try:
overdue = self.ar_ap_engine.get_overdue_items()
upcoming = self.ar_ap_engine.get_upcoming_due(days_ahead=7)
overdue_r = len(overdue.get("receivables", []))
overdue_p = len(overdue.get("payables", []))
upcoming_p = len(upcoming.get("payables", []))
if overdue_r or overdue_p or upcoming_p:
parts.append(
f"AR/AP snapshot: {overdue_r} overdue receivable(s), "
f"{overdue_p} overdue payable(s), {upcoming_p} payable(s) due within 7 days."
)
except Exception: # noqa: BLE001
pass
try:
budget_data = self.memory.load_budgets()
budgets = budget_data.get("budgets", [])
if budgets:
parts.append(f"Active budgets: {len(budgets)} monthly budget(s) set.")
except Exception: # noqa: BLE001
pass
return "\n".join(parts)
def _enrich_with_category(self, user_input: str) -> str:
lower = user_input.lower()
is_transaction_intent = any(
kw in lower for kw in ("record", "add", "log", "post", "expense", "income", "spent", "received", "paid")
)
if not is_transaction_intent:
return user_input
try:
suggestion = self.categorization.suggest_category(user_input)
if suggestion and suggestion.get("confidence", 0) >= 0.6:
return (
f"[Suggested category from local rules: {suggestion['category']} "
f"(confidence {suggestion['confidence']:.0%})]\n{user_input}"
)
except Exception: # noqa: BLE001
pass
return user_input
def build_messages(self, user_input: str) -> list[dict[str, str]]:
self.refresh_rules()
business = self.memory.get_current_business()
short_term = self.memory.load_short_term_context()
learned_context = self._build_learned_context()
financial_context = self._build_financial_context()
custom_rules = json.dumps(self.custom_rules, indent=2)
business_context = json.dumps(business, indent=2)
short_term_context = json.dumps(short_term, indent=2)
system_content = (
f"{self.system_prompt}\n\n"
"Custom correction rules that must be applied before every action:\n"
f"{custom_rules}\n\n"
"Current active business silo:\n"
f"{business_context}\n\n"
"Current short-term context:\n"
f"{short_term_context}\n\n"
)
if financial_context:
system_content += f"Current financial alerts:\n{financial_context}\n\n"
system_content += f"Learned operating knowledge:\n{learned_context}"
return [
{"role": "system", "content": system_content},
{"role": "user", "content": user_input},
]
@lru_cache(maxsize=128) # Cache AI predictions
def run_reasoning_cached(self, user_input: str) -> dict[str, Any]:
response_text = self.model_client.chat(self.build_messages(user_input))
return self.extract_action_plan(response_text)
def run_reasoning(self, user_input: str) -> dict[str, Any]:
return self.run_reasoning_cached(user_input)
def extract_action_plan(self, response_text: str) -> dict[str, Any]:
text = re.sub(r"```(?:json)?\s*", "", response_text).strip().strip("`").strip()
try:
start = text.index("{")
end = text.rindex("}") + 1
return json.loads(text[start:end])
except (ValueError, json.JSONDecodeError):
return {
"thought": "Model returned plain text; no tool action extracted.",
"action": "respond",
"parameters": {},
"response": response_text.strip(),
}
def _parse_json_response(self, text: str) -> dict[str, Any] | None:
try:
start = text.index("{")
end = text.rindex("}") + 1
return json.loads(text[start:end])
except (ValueError, json.JSONDecodeError):
return None
def execute_action(self, plan: dict[str, Any], user_input: str) -> dict[str, Any]:
action = plan.get("action", ACTION_RESPOND)
parameters = plan.get("parameters", {})
if action == ACTION_SWITCH_BUSINESS:
business_name = parameters.get("business_name") or self.detect_business_switch(user_input)
if not business_name:
raise ValueError("Business switch requested without a business name.")
new_profile = self.memory.switch_business(business_name)
return {
"status": "success",
"message": f"Switched to {new_profile['business_name']}.",
"details": new_profile,
}
if action == ACTION_CREATE_BUSINESS:
business_name = parameters.get("business_name") or self.detect_business_creation(user_input)
if not business_name:
raise ValueError("Business creation requested without a business name.")
state = parameters.get("state", "")
currency = parameters.get("default_books_currency", "USD")
business_key, profile, created = self.memory.create_business(
business_name, state=state, default_currency=currency
)
sheet_url = None
self.workspace_boot_error = None
try:
profile = self.ensure_business_workspace_assets()
sheet_url = self._sheet_url(profile["google_sheet_id"])
except Exception as exc: # noqa: BLE001
self.workspace_boot_error = str(exc)
status = "success" if created else "noop"
prefix = "Created" if created else "Switched to existing"
message = f"{prefix} business {profile['business_name']}."
if sheet_url:
message = f"{message} Sheet: {sheet_url}"
elif self.workspace_boot_error:
message = f"{message} Local silo is ready, but Google workspace setup still needs attention."
return {
"status": status,
"message": message,
"details": {
"business_key": business_key,
"created": created,
"profile": profile,
"sheet_url": sheet_url,
"workspace_boot_error": self.workspace_boot_error,
},
}
if action == ACTION_RECORD_TRANSACTION:
profile = self.ensure_business_workspace_assets()
values = self._normalize_bulk_values(parameters.get("values"))
if not values:
inferred_values = self._infer_bulk_values_from_user_input(user_input, parameters)
if inferred_values:
values = inferred_values
row_values = self._build_row_values_from_plan(parameters)
worksheet_name = parameters.get("worksheet_name", "Ledger")
sheet_url = self._sheet_url(profile["google_sheet_id"])
if values:
start_row = self._next_ledger_row_number(profile["google_sheet_id"], worksheet_name)
end_row = start_row + len(values) - 1
range_name = parameters.get("range") or f"{worksheet_name}!A{start_row}:G{end_row}"
result = self.sheets.update_range(
spreadsheet_id=profile["google_sheet_id"],
range_name=range_name,
values=values,
)
verification = self._verify_sheet_write(
spreadsheet_id=profile["google_sheet_id"],
range_name=range_name,
)
self._record_transaction_audit(
mode="bulk_update",
requested_payload=values,
result=result,
verification=verification,
)
if not verification["verified"]:
return {
"status": "needs_review",
"message": "I could not verify that the transaction rows were written to the sheet.",
"details": {
"result": result,
"verification": verification,
"sheet_url": sheet_url,
},
}
return {
"status": "success",
"message": f"Transactions recorded. Sheet: {sheet_url}",
"details": {
"result": result,
"verification": verification,
"sheet_url": sheet_url,
},
}
if not row_values:
return {
"status": "needs_review",
"message": "I could not record that transaction because the ledger row was incomplete.",
"details": {
"plan_parameters": parameters,
"sheet_url": sheet_url,
},
}
result = self.sheets.append_ledger_row(
spreadsheet_id=profile["google_sheet_id"],
worksheet_name=worksheet_name,
row_values=row_values,
)
updated_range = result.get("updates", {}).get("updatedRange")
verification = self._verify_sheet_write(
spreadsheet_id=profile["google_sheet_id"],
range_name=updated_range or f"{worksheet_name}!A:Z",
)
self._record_transaction_audit(
mode="append",
requested_payload=row_values,
result=result,
verification=verification,
)
if not verification["verified"]:
return {
"status": "needs_review",
"message": "I could not verify that the transaction was written to the sheet.",
"details": {
"result": result,
"verification": verification,
"sheet_url": sheet_url,
},
}
return {
"status": "success",
"message": f"Transaction recorded. Sheet: {sheet_url}",
"details": {
"result": result,
"verification": verification,
"sheet_url": sheet_url,
},
}
if action == ACTION_READ_SHEET:
profile = self.ensure_business_workspace_assets()
range_name = parameters.get("range_name", "Ledger!A1:Z20")
# Add pagination for large ranges
if "2000" in range_name:
range_name = range_name.replace("2000", "200")
values = self.sheets.read_range(
spreadsheet_id=profile["google_sheet_id"],
range_name=range_name,
)
return {"status": "success", "message": "Sheet data retrieved.", "details": values}
if action == ACTION_CREATE_BUSINESS_DOC:
profile = self.ensure_business_workspace_assets()
return {
"status": "success",
"message": "Business document is ready.",
"details": {"document_id": profile["google_doc_id"]},
}
if action == ACTION_APPEND_DOC_NOTE:
profile = self.ensure_business_workspace_assets()
result = self.docs.append_text(
document_id=profile["google_doc_id"],
text=parameters.get("text", ""),
)
return {"status": "success", "message": "Document note saved.", "details": result}
if action == ACTION_CALCULATE_PAYROLL:
from skills.payroll_engine import calculate_simple_payroll
gross_pay = self._safe_float(parameters.get("gross_pay", 0))
federal_rate = float(parameters.get("federal_rate", 0.12))
if gross_pay <= 0:
return {"status": "needs_review", "message": "Gross pay must be a positive number.", "details": {"parameters": parameters}}
calc = calculate_simple_payroll(gross_pay=gross_pay, federal_rate=federal_rate)
return {
"status": "success",
"message": f"Payroll: Gross ${calc.gross_pay:.2f} | Federal ${calc.federal_withholding:.2f} | SS ${calc.social_security:.2f} | Medicare ${calc.medicare:.2f} | Net ${calc.net_pay:.2f}.",
"details": {"gross_pay": calc.gross_pay, "federal_withholding": calc.federal_withholding, "social_security": calc.social_security, "medicare": calc.medicare, "net_pay": calc.net_pay},
}
if action == ACTION_RESEARCH_TAX:
from skills.tax_researcher import fetch_tax_update
url = parameters.get("url", "").strip()
if not url:
return {"status": "needs_review", "message": "A URL is required for tax research.", "details": {}}
result = fetch_tax_update(url)
self.memory.record_learned_source({"url": result.url, "title": result.title, "summary": result.summary, "topic": "tax"})
return {"status": "success", "message": f"Tax research complete. Stored: {result.title}", "details": {"url": result.url, "title": result.title, "summary": result.summary}}
return {
"status": "success",
"message": plan.get("response", "No tool call was needed."),
"details": {"action": action, "parameters": parameters},
}
def record_structured_transaction(
self,
*,
date: str,
description: str,
category: str,
amount: float,
entry_type: str,
reference: str = "",
notes: str = "",
) -> dict[str, Any]:
profile = self.ensure_business_workspace_assets()
sheet_url = self._sheet_url(profile["google_sheet_id"])
normalized_type = entry_type.strip().title()
amount_value = round(float(amount), 2)
row_values = [
date.strip(),
description.strip(),
category.strip(),
amount_value,
normalized_type,
reference.strip(),
notes.strip(),
]
duplicate = self.sheets.find_duplicate_row(
spreadsheet_id=profile["google_sheet_id"],
date=date.strip(),
amount=str(amount_value),
entry_type=normalized_type,
)
if duplicate and "confirm duplicate" not in notes.lower():
return {
"ok": False,
"message": (
f"Duplicate detected: a {duplicate['type']} of {duplicate['amount']} "
f"on {duplicate['date']} ({duplicate['description']}) already exists. "
"If this is intentional, add 'confirm duplicate' to the Notes field."
),
}
draft_result = {
"status": "success",
"message": (
f"Prepared a {normalized_type.lower()} transaction for {description.strip()} "
f"for ${amount_value:.2f}."
),
"details": {
"business": profile["business_name"],
"row_values": row_values,
},
}
reflection = self.self_reflect(
user_input=(
f"Record {normalized_type.lower()} transaction: {description.strip()} "
f"({category.strip()}) for ${amount_value:.2f} on {date.strip()}."
),
draft_result=draft_result,
)
if not reflection.get("approved"):
return {
"ok": False,
"message": reflection.get(
"corrected_message",
"I found a possible issue during verification and paused the transaction.",
),
"reflection": reflection,
}
result = self.sheets.append_ledger_row(
spreadsheet_id=profile["google_sheet_id"],
worksheet_name="Ledger",
row_values=row_values,
)
updated_range = result.get("updates", {}).get("updatedRange")
verification = self._verify_sheet_write(
spreadsheet_id=profile["google_sheet_id"],
range_name=updated_range or "Ledger!A:Z",
)
self._record_transaction_audit(
mode="structured_append",
requested_payload=row_values,
result=result,
verification=verification,
)
if not verification["verified"]:
return {
"ok": False,
"message": "I could not verify that the structured transaction was written to the sheet.",
"details": {
"result": result,
"verification": verification,
"sheet_url": sheet_url,
},
}
outcome = {
"status": "success",
"message": (
reflection.get("corrected_message")
or f"Recorded {normalized_type.lower()} transaction for {description.strip()}."
)
+ f" Sheet: {sheet_url}",
"details": {
"result": result,
"verification": verification,
"sheet_url": sheet_url,
},
}
user_input = (
f"Structured transaction: {normalized_type.lower()} {description.strip()} "
f"for ${amount_value:.2f} in {category.strip()}."
)
self.memory.record_skill_outcome(
action_name="record_transaction",
success=True,
details={
"user_input": user_input,
"draft_result": draft_result,
"reflection": reflection,
"row_values": row_values,
},
)
self.update_short_term_memory(user_input, outcome)
return {
"ok": True,
"message": outcome["message"],
"details": {
"append_result": result,
"verification": verification,
"row_values": row_values,
"sheet_url": sheet_url,
},
}
def record_bulk_transactions(
self,
rows: list[list[Any]],
*,
source_name: str = "",
source_note: str = "",
) -> dict[str, Any]:
profile = self.ensure_business_workspace_assets()
sheet_url = self._sheet_url(profile["google_sheet_id"])
normalized_rows = []
for row in rows:
normalized = self._normalize_row(row)
if source_name and not normalized[5]:
normalized[5] = source_name
if source_note and not normalized[6]:
normalized[6] = source_note
normalized_rows.append(normalized)
if not normalized_rows:
return {
"ok": False,
"message": "There were no draft transactions to record.",
"details": {"sheet_url": sheet_url},
}
draft_result = {
"status": "success",
"message": f"Prepared {len(normalized_rows)} transaction rows for approval.",
"details": {
"business": profile["business_name"],
"rows": normalized_rows,
},
}
reflection = self.self_reflect(
user_input=f"Record {len(normalized_rows)} approved document-based transactions.",
draft_result=draft_result,
)
if not reflection.get("approved"):
return {
"ok": False,
"message": reflection.get(
"corrected_message",
"I found a possible issue during verification and paused these transactions.",
),
"reflection": reflection,
}
start_row = self._next_ledger_row_number(profile["google_sheet_id"], "Ledger")
end_row = start_row + len(normalized_rows) - 1
range_name = f"Ledger!A{start_row}:G{end_row}"
result = self.sheets.update_range(
spreadsheet_id=profile["google_sheet_id"],
range_name=range_name,
values=normalized_rows,
)
verification = self._verify_sheet_write(
spreadsheet_id=profile["google_sheet_id"],
range_name=range_name,
)
self._record_transaction_audit(
mode="approved_document_bulk_update",
requested_payload=normalized_rows,
result=result,
verification=verification,
)
if not verification["verified"]:
return {
"ok": False,
"message": "I could not verify that the approved document transactions were written to the sheet.",
"details": {
"result": result,
"verification": verification,
"sheet_url": sheet_url,
},
}
return {
"ok": True,
"message": f"Approved document transactions recorded. Sheet: {sheet_url}",
"details": {
"result": result,
"verification": verification,
"sheet_url": sheet_url,
"rows": normalized_rows,
},
}
def draft_document_transactions(
self,
*,
file_name: str,
document_text: str,
instruction: str = "",
) -> dict[str, Any]:
prompt = [
{
"role": "system",
"content": (
"You are CPA-Agent drafting accounting entries from a source document. "
"Read the extracted document text and return only JSON with keys summary, rows, concerns. "
"Each row must contain date, description, category, amount, type, reference, notes. "
"Use multiple rows if the document has multiple purchases. "
"Be conservative and do not guess missing values."
),
},
{
"role": "user",
"content": json.dumps(
{
"active_business": self.memory.get_current_business(),
"instruction": instruction,
"file_name": file_name,
"document_text": document_text[:12000],
},
indent=2,
),
},
]
response_text = self.model_client.chat(prompt)
payload = self._parse_json_response(response_text)
if payload is None:
return {
"ok": False,
"message": "I could not convert that document into a clean draft table yet.",
"details": {"raw_response": response_text},
}
raw_rows = payload.get("rows", [])
rows = []
for item in raw_rows:
if not isinstance(item, dict):
continue
if item.get("amount") in (None, "") or not item.get("description"):
continue
rows.append(
self._normalize_row(
[
item.get("date", ""),
item.get("description", ""),
item.get("category", "Uncategorized"),
item.get("amount", ""),
item.get("type", "Expense"),
item.get("reference", file_name),
item.get("notes", ""),
]
)
)
if not rows:
return {
"ok": False,
"message": "I read the document, but I could not draft a reliable expense table from it.",
"details": {
"summary": payload.get("summary", ""),
"concerns": payload.get("concerns", []),
},
}
total_amount = sum(self._safe_float(row[3]) for row in rows)
return {
"ok": True,
"message": (
f"I prepared a draft with {len(rows)} row(s) totaling ${total_amount:.2f}. "
"Review it and approve when you're ready."
),
"details": {
"summary": payload.get("summary", ""),
"concerns": payload.get("concerns", []),
"rows": rows,
"total_amount": round(total_amount, 2),
"file_name": file_name,
},
}
def list_businesses(self) -> list[dict[str, str]]:
businesses = []
for key in self.memory.list_business_keys():
profile = self.memory.load_business_profile(key)
businesses.append(
{
"key": key,
"business_name": profile["business_name"],
}
)
return businesses
def get_dashboard_snapshot(self) -> dict[str, Any]:
current = self.memory.get_current_business()
skill_memory = self.memory.load_skill_memory()
transaction_audit = self.memory.load_transaction_audit().get("entries", [])
conversation = self.memory.load_short_term_context().get("conversation", [])
totals = {
"income_total": 0.0,
"expense_total": 0.0,
"transaction_count": 0,
"recent_transactions": [],
}
if current.get("google_sheet_id"):
try:
# Paginate for large datasets
rows = self.sheets.read_range(
spreadsheet_id=current["google_sheet_id"],
range_name="Ledger!A1:G100",
)
totals = self._summarize_ledger_rows(rows)
except Exception as exc: # noqa: BLE001
totals["ledger_error"] = str(exc)
success_history = [item for item in skill_memory.get("history", []) if item.get("success")]
failure_history = [item for item in skill_memory.get("history", []) if not item.get("success")]
recent_audits = [entry for entry in transaction_audit if entry.get("business") == self.memory.current_business_key][-5:]
return {
"active_business_name": current["business_name"],
"transaction_count": totals["transaction_count"],
"income_total": round(totals["income_total"], 2),
"expense_total": round(totals["expense_total"], 2),
"recent_transactions": totals["recent_transactions"],
"recent_audits": recent_audits,
"conversation_count": len(conversation),
"successful_actions": len(success_history),
"flagged_actions": len(failure_history),
"ledger_error": totals.get("ledger_error"),
}
def get_status(self) -> dict[str, Any]:
now = time.monotonic()
if hasattr(self, "_status_cache"):
ts, cached = self._status_cache
if now - ts < self._STATUS_CACHE_TTL:
return cached
result = self._build_status()
self._status_cache = (now, result)
return result
def _build_status(self) -> dict[str, Any]:
today_str = date.today().isoformat()
due: list = []
if today_str != getattr(self, "_last_schedule_check", None):
due = self.recurring.run_due_schedules()
self._last_schedule_check = today_str
if due:
self._save_recurring()
for entry in due:
try:
self.record_structured_transaction(
date=entry.get("last_posted_date", ""),
description=entry["description"],
category=entry["category"],
amount=entry["amount"],
entry_type=entry["entry_type"],
notes="Auto-posted by recurring schedule",
)
except Exception as exc: # noqa: BLE001
self.memory.record_skill_outcome(
action_name="recurring_auto_post",
success=False,
details={"error": str(exc), "entry": entry},
)
short_term = self.memory.load_short_term_context()
current = self.memory.get_current_business()
raw_conv = short_term.get("conversation", [])
conversation = []
for entry in raw_conv:
if entry.get("user_input"):
conversation.append({"role": "user", "content": entry["user_input"]})
if entry.get("outcome", {}).get("message"):
conversation.append({"role": "agent", "content": entry["outcome"]["message"]})
# Proactive AR/AP alerts
overdue_ar_ap: dict = {"receivables": [], "payables": []}
upcoming_ar_ap: dict = {"receivables": [], "payables": []}
try:
overdue_ar_ap = self.ar_ap_engine.get_overdue_items()
upcoming_ar_ap = self.ar_ap_engine.get_upcoming_due(days_ahead=7)
except Exception: # noqa: BLE001
pass
return {
"active_business_key": self.memory.current_business_key,
"active_business": current,
"businesses": self.list_businesses(),
"conversation": conversation,
"workspace_boot_error": self.workspace_boot_error,
"input_mode": self.input_mode,
"model_config": self.get_model_status(),
"dashboard": self.get_dashboard_snapshot(),
"learned_source_count": len(self.memory.load_learned_sources().get("entries", [])),
"tax_alerts": self.tax_engine.get_upcoming_alerts(days_ahead=60),
"overdue_ar_ap": overdue_ar_ap,
"upcoming_ar_ap": upcoming_ar_ap,
}
def get_model_status(self) -> dict[str, str]:
provider = os.getenv("MODEL_PROVIDER", "ollama").strip().lower() or "ollama"
if provider == "ollama":
reasoning_model = (
os.getenv("OLLAMA_QUALITY_MODEL")
if self.reasoning_mode == "quality" and os.getenv("OLLAMA_QUALITY_MODEL")
else os.getenv("OLLAMA_MODEL", "gpt-oss:20b")
)
reflection_model = (
os.getenv("OLLAMA_REFLECTION_MODEL")
or os.getenv("OLLAMA_AUDIT_MODEL")
or reasoning_model
)
elif provider == "openai":
reasoning_model = os.getenv("OPENAI_MODEL", "gpt-4o-mini")
reflection_model = reasoning_model
elif provider == "openrouter":
reasoning_model = os.getenv("OPENROUTER_MODEL", "nvidia/nemotron-3-super-120b-a12b:free")
reflection_model = reasoning_model
else:
reasoning_model = os.getenv("GEMINI_MODEL", "gemini-2.5-flash")
reflection_model = reasoning_model
return {
"provider": provider,
"reasoning_mode": self.reasoning_mode,
"reasoning_model": reasoning_model,
"reflection_model": reflection_model,
}
def _summarize_ledger_rows(self, rows: list[list[Any]]) -> dict[str, Any]:
if not rows:
return {
"income_total": 0.0,
"expense_total": 0.0,
"transaction_count": 0,
"recent_transactions": [],
}
data_rows = rows[1:] if rows[0][: len(self.LEDGER_HEADERS)] == self.LEDGER_HEADERS else rows
income_total = 0.0
expense_total = 0.0
parsed_rows: list[dict[str, Any]] = []
for row in data_rows:
if len(row) < 5:
continue
amount = self._safe_float(row[3] if len(row) > 3 else 0)
entry_type = str(row[4]).strip().lower()
record = {
"date": str(row[0]) if len(row) > 0 else "",
"description": str(row[1]) if len(row) > 1 else "",
"category": str(row[2]) if len(row) > 2 else "",
"amount": round(amount, 2),
"type": str(row[4]) if len(row) > 4 else "",
"reference": str(row[5]) if len(row) > 5 else "",
"notes": str(row[6]) if len(row) > 6 else "",
}
parsed_rows.append(record)
if entry_type == "income":
income_total += amount
else:
expense_total += amount
return {
"income_total": income_total,
"expense_total": expense_total,
"transaction_count": len(parsed_rows),
"recent_transactions": list(reversed(parsed_rows[-5:])),
}
def _build_row_values_from_plan(self, parameters: dict[str, Any]) -> list[Any]:
row_values = parameters.get("row_values")
if row_values:
return self._normalize_row(row_values)
if parameters.get("date") and parameters.get("description") and parameters.get("amount") is not None:
category = parameters.get("category") or parameters.get("account") or "Uncategorized"
transaction_type = parameters.get("type") or parameters.get("entry_type") or "Expense"
return self._normalize_row([
parameters.get("date", ""),
parameters.get("description", ""),
category,
parameters.get("amount", ""),
transaction_type,
parameters.get("reference", ""),
parameters.get("notes", ""),
])
return []
def _normalize_bulk_values(self, values: Any) -> list[list[Any]]:
if not values or not isinstance(values, list):
return []
normalized = []
for row in values:
if isinstance(row, list):
normalized_row = self._normalize_row(row)
if normalized_row:
normalized.append(normalized_row)
return normalized
def _normalize_row(self, row: list[Any]) -> list[Any]:
normalized = list(row[:7])
while len(normalized) < 7:
normalized.append("")
if len(normalized) >= 5 and not normalized[4]:
normalized[4] = "Expense"
if len(normalized) >= 3 and not normalized[2]:
normalized[2] = "Uncategorized"
return normalized