-
Notifications
You must be signed in to change notification settings - Fork 280
Expand file tree
/
Copy pathmain.py
More file actions
1639 lines (1342 loc) · 54.1 KB
/
main.py
File metadata and controls
1639 lines (1342 loc) · 54.1 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
import json
from datetime import datetime, timedelta
from typing import ClassVar, Dict, List, Optional
import requests
from src.agent.capability import MatchingCapability
from src.agent.capability_worker import CapabilityWorker
from src.main import AgentWorker
class HubspotAbility1Capability(MatchingCapability):
# {{register capability}}
worker: AgentWorker = None
capability_worker: CapabilityWorker = None
PREFS_FILENAME: ClassVar[str] = "hubspot_crm_prefs.json"
PERSIST: ClassVar[bool] = False
BASE_URL: ClassVar[str] = "https://api.hubapi.com"
# Your HubSpot API token
API_TOKEN: ClassVar[str] = "xxxxx"
# Association Type IDs (HUBSPOT_DEFINED)
ASSOCIATION_TYPES: ClassVar[Dict[str, int]] = {
"note_to_contact": 202,
"note_to_company": 190,
"note_to_deal": 214,
"task_to_contact": 204,
"task_to_company": 192,
"task_to_deal": 216,
}
def call(self, worker: AgentWorker):
self.worker = worker
self.capability_worker = CapabilityWorker(self.worker)
self.worker.session_tasks.create(self.run_main())
# --- MAIN ENTRY POINT ---
async def run_main(self):
try:
# Step 1: Say "HubSpot Ready"
await self.capability_worker.speak("HubSpot Ready.")
await self.worker.session_tasks.sleep(0.5)
# Step 2: Loop for multiple commands
while True:
# Wait for user command
command = await self.capability_worker.run_io_loop(
"What would you like to do?"
)
if not command:
await self.capability_worker.speak("No command received.")
continue
# Check for exit
if self.is_exit(command):
await self.capability_worker.speak("Goodbye.")
break
# Step 3: Detect mode and route
mode = await self.detect_mode(command)
if mode == "search_contact":
await self.search_contacts(command)
elif mode == "search_deal":
await self.search_deals(command)
elif mode == "log_note":
await self.log_note(command)
elif mode == "create_task":
await self.create_task(command)
elif mode == "pipeline_summary":
await self.pipeline_summary()
elif mode == "move_deal":
await self.move_deal_stage(command)
else:
await self.capability_worker.speak(
"I'm not sure what you want me to do. "
"Try 'look up a contact', 'check a deal', "
"'log a note', 'create a task', or 'show my pipeline'."
)
except Exception as e:
self.worker.editor_logging_handler.error(f"HubSpot CRM error: {e}")
await self.capability_worker.speak("Something went wrong.")
finally:
self.capability_worker.resume_normal_flow()
def is_exit(self, text: str) -> bool:
"""Check if user wants to exit."""
exit_words = ["exit", "quit", "done", "goodbye", "bye", "stop"]
return any(word in text.lower() for word in exit_words)
# --- MODE DETECTION ---
async def detect_mode(self, command: str) -> str:
"""Detect which mode based on user command."""
cmd_lower = command.lower()
# Log Note - check FIRST (most specific)
if any(word in cmd_lower for word in [
"log note", "add note", "note on", "note for"
]):
return "log_note"
# Create Task - check for various task patterns
if any(word in cmd_lower for word in [
"create task", "create a task", "add task", "add a task",
"remind me", "task for", "new task"
]):
return "create_task"
# Pipeline Summary
if any(word in cmd_lower for word in [
"pipeline", "my pipeline", "open deals"
]):
return "pipeline_summary"
# Move Deal - check BEFORE search deal (more specific)
if any(word in cmd_lower for word in [
"move", "update deal", "change stage", "mark", "closed won",
"closed lost", "mark as", "change to", "update to"
]):
return "move_deal"
# Search Deal - check for deal-specific keywords
if any(word in cmd_lower for word in [
"deal", "how's the", "how is the", "what's the status",
"check the", "find deal", "deal status"
]):
return "search_deal"
# Search Contact - broad match (check LAST as fallback)
if any(word in cmd_lower for word in [
"look up", "find contact", "who is", "search contact", "find", "search"
]):
return "search_contact"
return "unknown"
# --- MODE 1: SEARCH CONTACTS (FULLY IMPLEMENTED) ---
async def search_contacts(self, query: str):
"""Search for contacts by name or email."""
await self.capability_worker.speak("Searching for contacts...")
# Extract search term from query using LLM
search_term = await self.extract_search_term(query)
if not search_term:
await self.capability_worker.speak(
"I didn't catch who you're looking for. Try again?"
)
return
self.worker.editor_logging_handler.info(
f"Searching for contact: {search_term}"
)
# Build search filters
filters = self.build_contact_filters(search_term)
# Make API call
search_data = {
"filterGroups": filters,
"properties": [
"firstname", "lastname", "email", "phone",
"company", "lifecyclestage", "hubspot_owner_id"
],
"limit": 5
}
result = self._make_request(
"POST",
"/crm/v3/objects/contacts/search",
self.API_TOKEN,
search_data
)
if not result:
await self.capability_worker.speak(
"I had trouble connecting to HubSpot. Please try again."
)
return
# Process results
contacts = result.get("results", [])
self.worker.editor_logging_handler.info(
f"Found {len(contacts)} contacts"
)
if len(contacts) == 0:
await self.capability_worker.speak(
f"I couldn't find any contacts matching {search_term}. "
"Want me to search for something else?"
)
return
if len(contacts) == 1:
# Single result - speak full details
await self.speak_contact_details(contacts[0])
else:
# Multiple results - list them and ask which one
await self.speak_multiple_contacts(contacts)
async def extract_search_term(self, query: str) -> str:
"""Extract the name or email from the query using LLM."""
prompt = (
f"Extract the person's name or email from this query: '{query}'\n"
"Return ONLY the name or email, nothing else.\n"
"Examples:\n"
"Query: 'look up Sarah Chen' → Sarah Chen\n"
"Query: 'find john@acme.com' → john@acme.com\n"
"Query: 'who is the contact at Acme' → Acme\n"
)
response = self.capability_worker.text_to_text_response(prompt).strip()
# Clean up response (remove quotes, extra spaces)
response = response.replace('"', '').replace("'", '').strip()
return response
def build_contact_filters(self, search_term: str) -> List[dict]:
"""Build HubSpot search filters based on search term."""
# Check if it's an email (contains @)
if "@" in search_term:
return [{
"filters": [{
"propertyName": "email",
"operator": "EQ",
"value": search_term
}]
}]
# Check if it's two words (first name + last name)
words = search_term.split()
if len(words) == 2:
# Search for first AND last name
return [{
"filters": [
{
"propertyName": "firstname",
"operator": "CONTAINS_TOKEN",
"value": words[0]
},
{
"propertyName": "lastname",
"operator": "CONTAINS_TOKEN",
"value": words[1]
}
]
}]
if len(words) == 1:
# Search for first name OR last name
return [
{
"filters": [{
"propertyName": "firstname",
"operator": "CONTAINS_TOKEN",
"value": search_term
}]
},
{
"filters": [{
"propertyName": "lastname",
"operator": "CONTAINS_TOKEN",
"value": search_term
}]
}
]
# Default: search in firstname
return [{
"filters": [{
"propertyName": "firstname",
"operator": "CONTAINS_TOKEN",
"value": search_term
}]
}]
async def speak_contact_details(self, contact: dict):
"""Speak full details of a single contact."""
props = contact.get("properties", {})
# Extract fields
first_name = props.get("firstname", "")
last_name = props.get("lastname", "")
full_name = f"{first_name} {last_name}".strip()
email = props.get("email", "no email on file")
phone = props.get("phone", "no phone on file")
company = props.get("company", "no company listed")
lifecycle = props.get("lifecyclestage", "")
# Format lifecycle stage for speaking
lifecycle_text = self.format_lifecycle_stage(lifecycle)
# Build response
response = f"I found {full_name}."
if company != "no company listed":
response += f" They're at {company}."
response += f" Email: {email}."
if phone != "no phone on file":
response += f" Phone: {phone}."
if lifecycle_text:
response += f" They're currently {lifecycle_text}."
await self.capability_worker.speak(response)
# Cache this result for follow-up
await self.cache_recent_result("contact", [contact])
async def speak_multiple_contacts(self, contacts: List[dict]):
"""Speak a list of contacts and ask which one."""
count = len(contacts)
response = f"I found {count} contacts. "
# List first 3
for i, contact in enumerate(contacts[:3]):
props = contact.get("properties", {})
first_name = props.get("firstname", "")
last_name = props.get("lastname", "")
full_name = f"{first_name} {last_name}".strip()
company = props.get("company", "")
if company:
response += f"{full_name} at {company}. "
else:
response += f"{full_name}. "
if count > 3:
response += f"And {count - 3} more. "
response += "Which one?"
await self.capability_worker.speak(response)
# Cache all results for follow-up
await self.cache_recent_result("contact", contacts)
def format_lifecycle_stage(self, stage: str) -> str:
"""Convert lifecycle stage ID to human-readable text."""
stage_map = {
"subscriber": "a subscriber",
"lead": "a lead",
"marketingqualifiedlead": "a marketing qualified lead",
"salesqualifiedlead": "a sales qualified lead",
"opportunity": "an opportunity",
"customer": "a customer",
"evangelist": "an evangelist",
"other": "in other stage"
}
return stage_map.get(stage, "")
# --- CACHING FOR FOLLOW-UP ---
async def cache_recent_result(self, result_type: str, items: List[dict]):
"""Cache search results for follow-up references."""
prefs = await self.get_preferences()
prefs["recent_results"] = {
"type": result_type,
"items": items,
"cached_at": datetime.utcnow().isoformat()
}
await self.save_preferences(prefs)
# --- MODE 2: SEARCH DEALS (FULLY IMPLEMENTED) ---
async def search_deals(self, query: str):
"""Search for deals by name."""
await self.capability_worker.speak("Searching for deals...")
# Extract deal name from query using LLM
deal_name = await self.extract_deal_name(query)
if not deal_name:
await self.capability_worker.speak(
"I didn't catch which deal you're looking for. Try again?"
)
return
self.worker.editor_logging_handler.info(
f"Searching for deal: {deal_name}"
)
# Fetch pipeline stages (cached or fresh)
stage_map = await self.get_stage_map()
# Build search filters
search_data = {
"filterGroups": [{
"filters": [{
"propertyName": "dealname",
"operator": "CONTAINS_TOKEN",
"value": deal_name
}]
}],
"properties": [
"dealname", "dealstage", "pipeline", "amount",
"closedate", "hubspot_owner_id"
],
"limit": 5
}
# Make API call
result = self._make_request(
"POST",
"/crm/v3/objects/deals/search",
self.API_TOKEN,
search_data
)
if not result:
await self.capability_worker.speak(
"I had trouble connecting to HubSpot. Please try again."
)
return
# Process results
deals = result.get("results", [])
self.worker.editor_logging_handler.info(
f"Found {len(deals)} deals"
)
if len(deals) == 0:
await self.capability_worker.speak(
f"I couldn't find any deals matching {deal_name}. "
"Want me to search for something else?"
)
return
if len(deals) == 1:
# Single result - speak full details
await self.speak_deal_details(deals[0], stage_map)
else:
# Multiple results - list them and ask which one
await self.speak_multiple_deals(deals, stage_map)
async def extract_deal_name(self, query: str) -> str:
"""Extract the deal name from the query using LLM."""
prompt = (
f"Extract the deal name from this query: '{query}'\n"
"Return ONLY the deal name, nothing else.\n"
"Examples:\n"
"Query: 'how's the Acme deal' → Acme\n"
"Query: 'what's the status of Project Phoenix' → Project Phoenix\n"
"Query: 'check the Widget Co deal' → Widget Co\n"
)
response = self.capability_worker.text_to_text_response(prompt).strip()
# Clean up response
response = response.replace('"', '').replace("'", '').strip()
return response
async def get_stage_map(self) -> Dict[str, str]:
"""Get pipeline stage mapping (stage_id → stage_label)."""
# Check cache first
prefs = await self.get_preferences()
# Check if cache is fresh (within 30 minutes)
cache_updated = prefs.get("pipeline_cache_updated")
if cache_updated:
cache_time = datetime.fromisoformat(cache_updated)
age_minutes = (datetime.utcnow() - cache_time).total_seconds() / 60
if age_minutes < 30 and prefs.get("pipelines"):
# Use cached pipelines
return self.build_stage_map_from_cache(prefs["pipelines"])
# Fetch fresh pipelines
result = self._make_request(
"GET",
"/crm/v3/pipelines/deals",
self.API_TOKEN
)
if not result or "results" not in result:
# Fallback to empty map
return {}
pipelines = result["results"]
# Cache the pipelines
prefs["pipelines"] = pipelines
prefs["pipeline_cache_updated"] = datetime.utcnow().isoformat()
await self.save_preferences(prefs)
return self.build_stage_map_from_cache(pipelines)
def build_stage_map_from_cache(self, pipelines: List[dict]) -> Dict[str, str]:
"""Build stage_id → stage_label mapping from cached pipelines."""
stage_map = {}
for pipeline in pipelines:
for stage in pipeline.get("stages", []):
stage_id = stage.get("id")
stage_label = stage.get("label")
if stage_id and stage_label:
stage_map[stage_id] = stage_label
return stage_map
async def speak_deal_details(self, deal: dict, stage_map: Dict[str, str]):
"""Speak full details of a single deal."""
props = deal.get("properties", {})
# Extract fields
deal_name = props.get("dealname", "Unknown deal")
stage_id = props.get("dealstage", "")
stage_label = stage_map.get(stage_id, stage_id)
amount = props.get("amount")
close_date = props.get("closedate", "")
owner_id = props.get("hubspot_owner_id", "")
# Format amount
amount_text = self.format_currency(amount)
# Format close date
close_date_text = self.format_close_date(close_date)
# Get owner name
owner_name = await self.get_owner_name(owner_id)
# Build response
response = f"The {deal_name} deal is in {stage_label}."
if amount_text:
response += f" It's worth {amount_text}."
if close_date_text:
response += f" Close date: {close_date_text}."
if owner_name:
response += f" It's owned by {owner_name}."
await self.capability_worker.speak(response)
# Cache this result for follow-up
await self.cache_recent_result("deal", [deal])
async def speak_multiple_deals(
self,
deals: List[dict],
stage_map: Dict[str, str]
):
"""Speak a list of deals and ask which one."""
count = len(deals)
response = f"I found {count} deals. "
# List first 3
for i, deal in enumerate(deals[:3]):
props = deal.get("properties", {})
deal_name = props.get("dealname", "Unknown")
stage_id = props.get("dealstage", "")
stage_label = stage_map.get(stage_id, "unknown stage")
response += f"{deal_name} in {stage_label}. "
if count > 3:
response += f"And {count - 3} more. "
response += "Which one?"
await self.capability_worker.speak(response)
# Cache all results for follow-up
await self.cache_recent_result("deal", deals)
def format_currency(self, amount: Optional[str]) -> str:
"""Format amount as currency for speaking."""
if not amount:
return ""
try:
amount_float = float(amount)
# Round to nearest dollar
amount_int = int(amount_float)
# Format with commas
if amount_int >= 1000000:
# Millions
millions = amount_int / 1000000
return f"{millions:.1f} million dollars"
elif amount_int >= 1000:
# Thousands
thousands = amount_int / 1000
if thousands == int(thousands):
return f"{int(thousands)} thousand dollars"
else:
return f"{thousands:.1f} thousand dollars"
else:
return f"{amount_int} dollars"
except Exception:
return ""
def format_close_date(self, close_date: str) -> str:
"""Format close date for speaking."""
if not close_date:
return ""
try:
# Parse date (format: 2026-03-15)
date_obj = datetime.fromisoformat(close_date.split("T")[0])
# Format as "March 15th"
month = date_obj.strftime("%B")
day = date_obj.day
# Add ordinal suffix
if 10 <= day % 100 <= 20:
suffix = "th"
else:
suffix = {1: "st", 2: "nd", 3: "rd"}.get(day % 10, "th")
return f"{month} {day}{suffix}"
except Exception:
return close_date
async def get_owner_name(self, owner_id: str) -> str:
"""Get owner name from cached owners list."""
if not owner_id:
return ""
# Check cache first
prefs = await self.get_preferences()
# Check if cache is fresh
cache_updated = prefs.get("owners_cache_updated")
owners = prefs.get("owners", [])
if cache_updated:
cache_time = datetime.fromisoformat(cache_updated)
age_minutes = (datetime.utcnow() - cache_time).total_seconds() / 60
if age_minutes >= 30 or not owners:
# Refresh cache
owners = await self.fetch_owners()
prefs["owners"] = owners
prefs["owners_cache_updated"] = datetime.utcnow().isoformat()
await self.save_preferences(prefs)
else:
# No cache, fetch fresh
owners = await self.fetch_owners()
prefs["owners"] = owners
prefs["owners_cache_updated"] = datetime.utcnow().isoformat()
await self.save_preferences(prefs)
# Find owner by ID
for owner in owners:
if str(owner.get("id")) == str(owner_id):
# Return first name only
name = owner.get("name", "")
return name.split()[0] if name else ""
return ""
async def fetch_owners(self) -> List[dict]:
"""Fetch owners from HubSpot API."""
result = self._make_request(
"GET",
"/crm/v3/owners",
self.API_TOKEN
)
if not result or "results" not in result:
return []
return [
{
"id": owner["id"],
"name": f"{owner.get('firstName', '')} {owner.get('lastName', '')}".strip(),
"email": owner.get("email", "")
}
for owner in result["results"]
]
# --- MODE 3: LOG NOTE (FULLY IMPLEMENTED) ---
async def log_note(self, command: str):
"""Log a note on a contact, company, or deal."""
await self.capability_worker.speak("Logging a note...")
# Parse the command to extract target and note content
parsed = await self.parse_note_command(command)
if not parsed:
await self.capability_worker.speak(
"I didn't catch what you want to log. Try again?"
)
return
target_name = parsed.get("target")
note_content = parsed.get("content")
if not target_name or not note_content:
await self.capability_worker.speak(
"I need both who to log the note on and what the note says."
)
return
self.worker.editor_logging_handler.info(
f"Logging note on '{target_name}': {note_content}"
)
# Find the target record (try contact first, then company)
target_record = await self.find_note_target(target_name)
if not target_record:
await self.capability_worker.speak(
f"I couldn't find {target_name}. "
"Make sure they exist in your HubSpot."
)
return
# Create the note
success = await self.create_note(
note_content,
target_record["type"],
target_record["id"]
)
if success:
await self.capability_worker.speak(
f"Done. I've logged a note on {target_record['name']}: {note_content}"
)
else:
await self.capability_worker.speak(
"I had trouble creating the note. Please try again."
)
async def parse_note_command(self, command: str) -> Optional[dict]:
"""Parse note command to extract target and content using LLM."""
prompt = (
f"Parse this note command: '{command}'\n"
"Extract the target (person/company name) and the note content.\n"
"Return ONLY valid JSON with 'target' and 'content' fields.\n\n"
"Examples:\n"
"Input: 'log a note on Acme: they want to move forward'\n"
"Output: {\"target\": \"Acme\", \"content\": \"they want to move forward\"}\n\n"
"Input: 'add a note to Sarah Chen: she's interested in the enterprise plan'\n"
"Output: {\"target\": \"Sarah Chen\", \"content\": \"she's interested in the enterprise plan\"}\n\n"
"Input: 'note for TechCorp: follow up about pricing'\n"
"Output: {\"target\": \"TechCorp\", \"content\": \"follow up about pricing\"}\n"
)
response = self.capability_worker.text_to_text_response(prompt).strip()
# Clean markdown fences if present
response = response.replace("```json", "").replace("```", "").strip()
try:
parsed = json.loads(response)
return parsed
except Exception as e:
self.worker.editor_logging_handler.error(
f"Failed to parse note command: {e}"
)
return None
async def find_note_target(self, target_name: str) -> Optional[dict]:
"""Find target record (contact or company) for the note."""
# Try contact first
contact = await self.search_contact_by_name(target_name)
if contact:
props = contact.get("properties", {})
first_name = props.get("firstname", "")
last_name = props.get("lastname", "")
full_name = f"{first_name} {last_name}".strip()
return {
"type": "contact",
"id": contact["id"],
"name": full_name
}
# Try company
company = await self.search_company_by_name(target_name)
if company:
props = company.get("properties", {})
company_name = props.get("name", "")
return {
"type": "company",
"id": company["id"],
"name": company_name
}
return None
async def search_contact_by_name(self, name: str) -> Optional[dict]:
"""Search for a contact by name (returns first match)."""
self.worker.editor_logging_handler.info(
f"Searching contacts for: {name}"
)
filters = self.build_contact_filters(name)
search_data = {
"filterGroups": filters,
"properties": ["firstname", "lastname", "email"],
"limit": 1
}
result = self._make_request(
"POST",
"/crm/v3/objects/contacts/search",
self.API_TOKEN,
search_data
)
if result and result.get("results"):
self.worker.editor_logging_handler.info(
f"Found contact: {result['results'][0].get('id')}"
)
return result["results"][0]
self.worker.editor_logging_handler.info("No contact found")
return None
async def search_company_by_name(self, name: str) -> Optional[dict]:
"""Search for a company by name (returns first match)."""
self.worker.editor_logging_handler.info(
f"Searching companies for: {name}"
)
search_data = {
"filterGroups": [{
"filters": [{
"propertyName": "name",
"operator": "CONTAINS_TOKEN",
"value": name
}]
}],
"properties": ["name", "domain"],
"limit": 1
}
result = self._make_request(
"POST",
"/crm/v3/objects/companies/search",
self.API_TOKEN,
search_data
)
if result and result.get("results"):
self.worker.editor_logging_handler.info(
f"Found company: {result['results'][0].get('id')}"
)
return result["results"][0]
self.worker.editor_logging_handler.info("No company found")
return None
async def create_note(
self,
note_body: str,
target_type: str,
target_id: str
) -> bool:
"""Create a note associated with a contact or company."""
# Get current timestamp in UTC
timestamp = datetime.utcnow().isoformat() + "Z"
# Determine association type ID
if target_type == "contact":
association_type_id = self.ASSOCIATION_TYPES["note_to_contact"]
elif target_type == "company":
association_type_id = self.ASSOCIATION_TYPES["note_to_company"]
elif target_type == "deal":
association_type_id = self.ASSOCIATION_TYPES["note_to_deal"]
else:
return False
# Build note data
note_data = {
"properties": {
"hs_note_body": note_body,
"hs_timestamp": timestamp
},
"associations": [{
"to": {"id": target_id},
"types": [{
"associationCategory": "HUBSPOT_DEFINED",
"associationTypeId": association_type_id
}]
}]
}
# Make API call
result = self._make_request(
"POST",
"/crm/v3/objects/notes",
self.API_TOKEN,
note_data
)
if result:
self.worker.editor_logging_handler.info(
f"Note created successfully: {result.get('id')}"
)
return True
return False
# --- MODE 4: CREATE TASK (FULLY IMPLEMENTED) ---
async def create_task(self, command: str):
"""Create a task associated with a contact, company, or deal."""
await self.capability_worker.speak("Creating a task...")
# Parse the command to extract task details
parsed = await self.parse_task_command(command)
if not parsed:
await self.capability_worker.speak(
"I didn't catch the task details. Try again?"
)
return
subject = parsed.get("subject")
due_date_text = parsed.get("due_date")
priority = parsed.get("priority", "MEDIUM")
target_name = parsed.get("target")
if not subject:
await self.capability_worker.speak(
"I need at least a task subject."
)
return
self.worker.editor_logging_handler.info(
f"Creating task: {subject} (due: {due_date_text}, priority: {priority})"
)
# Parse due date
due_timestamp = await self.parse_due_date(due_date_text)
# Find target if specified
target_record = None
if target_name:
target_record = await self.find_note_target(target_name)
# Create the task
success = await self.create_task_record(
subject,
due_timestamp,
priority,
target_record
)
if success:
# Build response
response = f"Done. I've created a task: {subject}"
if due_date_text:
response += f", due {due_date_text}"
if priority != "MEDIUM":
response += f", {priority.lower()} priority"
if target_record:
response += f", associated with {target_record['name']}"
response += "."
await self.capability_worker.speak(response)
else:
await self.capability_worker.speak(
"I had trouble creating the task. Please try again."
)
async def parse_task_command(self, command: str) -> Optional[dict]:
"""Parse task command using LLM."""
prompt = (
f"Parse this task command: '{command}'\n"
"Extract: subject, due_date (text), priority (NONE/LOW/MEDIUM/HIGH), and target (person/company).\n"
"Return ONLY valid JSON.\n\n"
"Examples:\n"
"Input: 'create a task: send proposal to Acme by Friday'\n"
"Output: {{\"subject\": \"send proposal to Acme\", \"due_date\": \"Friday\", \"priority\": \"MEDIUM\", \"target\": \"Acme\"}}\n\n"
"Input: 'remind me to follow up with Sarah next Monday'\n"
"Output: {{\"subject\": \"follow up with Sarah\", \"due_date\": \"next Monday\", \"priority\": \"MEDIUM\", \"target\": \"Sarah\"}}\n\n"
"Input: 'task for Widget Co: schedule a demo, high priority'\n"
"Output: {{\"subject\": \"schedule a demo\", \"due_date\": null, \"priority\": \"HIGH\", \"target\": \"Widget Co\"}}\n\n"
"Input: 'create task: call the client tomorrow'\n"