This repository was archived by the owner on Jun 3, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 56
Expand file tree
/
Copy pathingest.py
More file actions
1449 lines (1245 loc) · 52.3 KB
/
Copy pathingest.py
File metadata and controls
1449 lines (1245 loc) · 52.3 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
"""
Ingest Pipeline — the full LangGraph workflow for storing user memories.
Takes raw user input, processes it through extraction agents, judges each
domain, and executes writes via the Weaver.
Flow::
┌─────────┐ ┌──────────────┐
│ START │────>│ classify │
└─────────┘ └──────┬───────┘
│ fan-out (conditional)
┌────────────┼────────────┐
▼ ▼ ▼
┌──────────┐ ┌──────────┐ ┌──────────┐
│ profile │ │ temporal │ │ summary │
└────┬─────┘ └────┬─────┘ └────┬─────┘
│ │ │
▼ ▼ ▼
┌──────────┐ ┌──────────┐ ┌──────────┐
│ judge_p │ │ judge_t │ │ judge_s │
└────┬─────┘ └────┬─────┘ └────┬─────┘
│ │ │
▼ ▼ ▼
┌──────────┐ ┌──────────┐ ┌──────────┐
│ weave_p │ │ weave_t │ │ weave_s │
└────┬─────┘ └────┬─────┘ └────┬─────┘
│ │ │
└────────────┼────────────┘
▼
┌─────────┐
│ END │
└─────────┘
Each vertical lane (profile / temporal / summary) runs independently via
LangGraph's ``Send`` (fan-out). All three converge at END.
Usage::
from src.pipelines.ingest import IngestPipeline
pipeline = IngestPipeline() # reads config from env / .env
result = await pipeline.run({
"user_query": "I just got a new job at Google!",
"agent_response": "Congratulations!",
"user_id": "user_123",
})
"""
from __future__ import annotations
import functools
import asyncio
import logging
from typing import Any, Callable, Dict, List, Optional
import operator
from langgraph.graph import END, START, StateGraph
from langgraph.types import Send
from typing_extensions import TypedDict, Annotated
from src.agents.classifier import ClassifierAgent
from src.agents.code import CodeAgent
from src.agents.image import ImageAgent
from src.agents.judge import JudgeAgent
from src.agents.profiler import ProfilerAgent
from src.agents.snippet import SnippetAgent
from src.agents.summarizer import SummarizerAgent
from src.agents.temporal import TemporalAgent
from src.config import settings
from src.graph.code_graph_client import CodeGraphClient
from src.graph.neo4j_client import Neo4jClient
from src.graph.schema import setup_constraints
from src.models import get_model, get_vision_model
from src.pipelines.weaver import Weaver
from src.schemas.classification import ClassificationResult
from src.schemas.code import (
CodeAnnotationResult,
SnippetExtractionResult,
annotations_namespace,
snippets_namespace,
)
from src.schemas.events import EventResult
from src.schemas.image import ImageResult
from src.schemas.judge import JudgeDomain, JudgeResult
from src.schemas.profile import ProfileResult
from src.schemas.summary import SummaryResult
from src.schemas.weaver import WeaverResult
from src.storage.base import BaseVectorStore, SearchResult
from src.storage.factory import get_vector_store
from src.config.effort import (
EffortLevel,
EffortConfig,
get_effort_config,
chunk_text,
estimate_tokens,
)
logger = logging.getLogger("xmem.pipelines.ingest")
# ---------------------------------------------------------------------------
# Embedding helper — supports Google GenAI, OpenAI, Amazon Bedrock, Ollama, FastEmbed
# ---------------------------------------------------------------------------
import json as _json
from google import genai
from google.genai import types
_embedding_client: Optional[genai.Client] = None
_openai_embedding_client = None
_bedrock_embedding_client = None
_fastembed_model = None
def _is_bedrock_embedding() -> bool:
"""Check if the configured embedding model is an Amazon Bedrock model."""
return settings.embedding_model.lower().startswith("amazon.")
def _is_openai_embedding() -> bool:
"""Check if the configured embedding model is an OpenAI embedding model."""
return settings.embedding_model.lower().startswith("text-embedding")
def _embedding_provider() -> str:
provider = (settings.embedding_provider or "auto").strip().lower()
if provider == "auto":
if _is_bedrock_embedding():
return "bedrock"
if _is_openai_embedding():
return "openai"
return "gemini"
return provider
def get_embedding_client() -> genai.Client:
global _embedding_client
if _embedding_client is None:
api_key_to_use = settings.gemini_api_key or None
_embedding_client = (
genai.Client(api_key=api_key_to_use) if api_key_to_use else genai.Client()
)
logger.info(
"Loaded Gemini embedding client for model: %s", settings.embedding_model
)
return _embedding_client
def _get_bedrock_embedding_client():
global _bedrock_embedding_client
if _bedrock_embedding_client is None:
import boto3
from botocore.config import Config
kwargs = {
"region_name": settings.bedrock_region,
"config": Config(read_timeout=60),
}
if settings.aws_access_key_id and settings.aws_secret_access_key:
kwargs["aws_access_key_id"] = settings.aws_access_key_id
kwargs["aws_secret_access_key"] = settings.aws_secret_access_key
_bedrock_embedding_client = boto3.client("bedrock-runtime", **kwargs)
logger.info(
"Loaded Bedrock embedding client for model: %s", settings.embedding_model
)
return _bedrock_embedding_client
def _get_openai_embedding_client():
"""Lazily create an OpenAI client for embeddings."""
global _openai_embedding_client
if _openai_embedding_client is None:
try:
from openai import OpenAI
except ImportError as exc:
raise ImportError(
"openai package is not installed. Install with: pip install openai"
) from exc
api_key = settings.openai_api_key
if not api_key:
raise ValueError("OPENAI_API_KEY is not set but EMBEDDING_PROVIDER=openai")
_openai_embedding_client = OpenAI(api_key=api_key)
logger.info(
"Loaded OpenAI embedding client for model: %s", settings.embedding_model
)
return _openai_embedding_client
def _get_fastembed_model():
global _fastembed_model
if _fastembed_model is None:
try:
from fastembed import TextEmbedding
except ImportError as exc:
raise ImportError(
"FastEmbed is not installed. Install local embedding dependencies "
'with: pip install -e ".[local]"'
) from exc
_fastembed_model = TextEmbedding(model_name=settings.fastembed_model)
logger.info("Loaded FastEmbed model: %s", settings.fastembed_model)
return _fastembed_model
def _ensure_embedding_dimension(
values: tuple[float, ...], provider: str
) -> tuple[float, ...]:
expected = int(settings.pinecone_dimension)
if len(values) != expected:
raise ValueError(
f"{provider} embedding dimension is {len(values)}, but PINECONE_DIMENSION "
f"is {expected}. Set PINECONE_DIMENSION to match the selected embedding model "
"before creating vector indexes."
)
return values
@functools.lru_cache(maxsize=4096)
def embed_text(text: str) -> tuple[float, ...]:
"""Embed a single text string → tuple of floats.
Dispatches to the configured embedding provider (auto-detected or explicit).
Supported: gemini, openai, bedrock, ollama, fastembed.
"""
provider = _embedding_provider()
if provider == "gemini":
return _embed_text_gemini(text)
if provider == "openai":
return _embed_text_openai(text)
if provider == "bedrock":
return _embed_text_bedrock(text)
if provider == "ollama":
return _embed_text_ollama(text)
if provider == "fastembed":
return _embed_text_fastembed(text)
raise ValueError(
f"Unsupported EMBEDDING_PROVIDER={provider!r}. "
"Use auto, gemini, openai, bedrock, ollama, or fastembed."
)
def _embed_text_gemini(text: str) -> tuple[float, ...]:
import time as _time
client = get_embedding_client()
start = _time.perf_counter()
result = client.models.embed_content(
model=settings.embedding_model,
contents=text,
config=types.EmbedContentConfig(
output_dimensionality=settings.pinecone_dimension
),
)
elapsed = _time.perf_counter() - start
[embedding_obj] = result.embeddings
# Track embedding call for cost analytics
input_tokens = getattr(result, "input_tokens", 0) or len(text.split())
try:
from src.config.analytics import analytics
analytics.track_llm_call(
provider="gemini",
model=settings.embedding_model,
agent="embedding",
latency_ms=round(elapsed * 1000, 2),
input_tokens=input_tokens,
output_tokens=0,
total_tokens=input_tokens,
)
except Exception:
pass
return tuple(embedding_obj.values)
def _embed_text_openai(text: str) -> tuple[float, ...]:
"""Embed text using the OpenAI Embeddings API.
Supports text-embedding-3-small, text-embedding-3-large, and
text-embedding-ada-002. The v3 models accept a ``dimensions``
parameter for native dimension reduction (e.g. 384 for Pinecone).
"""
import time as _time
client = _get_openai_embedding_client()
model = settings.embedding_model
dimension = int(settings.pinecone_dimension)
start = _time.perf_counter()
# text-embedding-3-* supports the dimensions parameter;
# ada-002 does not (fixed at 1536).
kwargs: dict = {"model": model, "input": text}
if model.startswith("text-embedding-3"):
kwargs["dimensions"] = dimension
response = client.embeddings.create(**kwargs)
elapsed = _time.perf_counter() - start
embedding = response.data[0].embedding
# Track embedding call for cost analytics
input_tokens = getattr(response.usage, "total_tokens", 0) or len(text.split())
try:
from src.config.analytics import analytics
analytics.track_llm_call(
provider="openai",
model=model,
agent="embedding",
latency_ms=round(elapsed * 1000, 2),
input_tokens=input_tokens,
output_tokens=0,
total_tokens=input_tokens,
)
except Exception:
pass
values = tuple(float(v) for v in embedding)
return _ensure_embedding_dimension(values, "OpenAI")
def _embed_text_bedrock(text: str) -> tuple[float, ...]:
client = _get_bedrock_embedding_client()
request_body = {
"taskType": "SINGLE_EMBEDDING",
"singleEmbeddingParams": {
"embeddingPurpose": "GENERIC_INDEX",
"embeddingDimension": settings.pinecone_dimension,
"text": {
"truncationMode": "END",
"value": text,
},
},
}
response = client.invoke_model(
body=_json.dumps(request_body),
modelId=settings.embedding_model,
accept="application/json",
contentType="application/json",
)
response_body = _json.loads(response["body"].read())
return tuple(response_body["embeddings"][0]["embedding"])
def _embed_text_ollama(text: str) -> tuple[float, ...]:
"""Embed text with a local Ollama server.
Supports Ollama's newer /api/embed endpoint and falls back to the older
/api/embeddings shape for compatibility.
"""
import httpx
model = settings.ollama_embedding_model or settings.embedding_model
if model == "gemini-embedding-001":
model = "nomic-embed-text"
base_url = settings.ollama_base_url.rstrip("/")
with httpx.Client(timeout=120.0) as client:
response = client.post(
f"{base_url}/api/embed",
json={"model": model, "input": text},
)
if response.status_code == 404:
response = client.post(
f"{base_url}/api/embeddings",
json={"model": model, "prompt": text},
)
response.raise_for_status()
data = response.json()
if "embeddings" in data:
[embedding] = data["embeddings"]
else:
embedding = data["embedding"]
return _ensure_embedding_dimension(tuple(float(v) for v in embedding), "Ollama")
def _embed_text_fastembed(text: str) -> tuple[float, ...]:
model = _get_fastembed_model()
embedding = next(model.embed([text]))
return _ensure_embedding_dimension(tuple(float(v) for v in embedding), "FastEmbed")
# ---------------------------------------------------------------------------
# LangGraph state (typed dict shared across all nodes)
# ---------------------------------------------------------------------------
class IngestState(TypedDict, total=False):
# ── input ─────────────────────────────────────────────────────────
user_query: str
agent_response: str
user_id: str
image_url: str
session_datetime: str
# ── routing (internal — set by _route_after_classify) ─────────────
profile_queries: List[str] # batched profile sub-queries
temporal_queries: List[str] # batched temporal sub-queries
image_queries: List[str] # batched image sub-queries
code_queries: List[str] # batched code sub-queries
# ── classification ────────────────────────────────────────────────
classification_result: ClassificationResult
# ── extraction outputs ────────────────────────────────────────────
profile_result: ProfileResult
temporal_result: EventResult
summary_result: SummaryResult
image_result: ImageResult
code_result: CodeAnnotationResult
snippet_result: SnippetExtractionResult
# ── judge outputs ─────────────────────────────────────────────────
profile_judge: JudgeResult
temporal_judge: JudgeResult
summary_judge: JudgeResult
image_judge: JudgeResult
code_judge: JudgeResult
snippet_judge: JudgeResult
disabled_domains: List[str]
# ── weaver outputs ────────────────────────────────────────────────
profile_weaver: WeaverResult
temporal_weaver: WeaverResult
summary_weaver: WeaverResult
image_weaver: WeaverResult
code_weaver: WeaverResult
snippet_weaver: WeaverResult
# ── metadata ──────────────────────────────────────────────────────
status: Annotated[str, lambda a, b: b]
errors: Annotated[List[str], operator.add]
# ---------------------------------------------------------------------------
# Pipeline class
# ---------------------------------------------------------------------------
class IngestPipeline:
"""End-to-end ingest pipeline wired with real Pinecone + Neo4j."""
def __init__(
self,
vector_store: Optional[BaseVectorStore] = None,
neo4j_client: Optional[Neo4jClient] = None,
code_graph_client: Optional[CodeGraphClient] = None,
embed_fn: Optional[Callable[[str], List[float]]] = None,
org_id: str = "default",
) -> None:
self.org_id = org_id
# ── Embedding function ────────────────────────────────────────
self.embed_fn = embed_fn or embed_text
# ── Pinecone (vector store) ───────────────────────────────────
if vector_store:
self.vector_store = vector_store
else:
self.vector_store = get_vector_store(
namespace=settings.pinecone_namespace,
)
logger.info(
"Vector store initialised (provider=%s).", settings.vector_store_provider
)
# ── Code annotations Pinecone store (annotations namespace) ──
self.code_vector_store = get_vector_store(
namespace=annotations_namespace(org_id),
create_if_not_exists=False,
)
logger.info(
"Code annotations vector store initialised (ns=%s).",
annotations_namespace(org_id),
)
# ── Neo4j (graph store — temporal) ────────────────────────────
if neo4j_client:
self.neo4j = neo4j_client
else:
self.neo4j = Neo4jClient(
uri=settings.neo4j_uri,
username=settings.neo4j_username,
password=settings.neo4j_password,
embedding_fn=self.embed_fn,
)
self.neo4j.connect()
try:
setup_constraints(self.neo4j.driver)
self.neo4j.initialize_date_nodes()
except Exception as exc:
logger.warning("Neo4j init (constraints/dates) failed: %s", exc)
logger.info("Neo4j client initialised.")
# ── Neo4j (code graph) ────────────────────────────────────────
if code_graph_client:
self.code_graph = code_graph_client
else:
self.code_graph = CodeGraphClient(
uri=settings.neo4j_uri,
username=settings.neo4j_username,
password=settings.neo4j_password,
embedding_fn=self.embed_fn,
)
self.code_graph.connect()
try:
self.code_graph.setup()
except Exception as exc:
logger.warning("Code graph init (constraints) failed: %s", exc)
logger.info("Code graph client initialised.")
# ── LLM ──────────────────────────────────────────────────────
self.model = get_model()
def _agent_model(agent_name: str):
"""Get model for a specific agent, falling back to default."""
override = getattr(settings, f"{agent_name}_model", None)
if override:
return get_model(model_name=override)
return self.model
# ── Agents ────────────────────────────────────────────────────
self.classifier = ClassifierAgent(model=_agent_model("classifier"))
self.profiler = ProfilerAgent(model=_agent_model("profiler"))
self.temporal = TemporalAgent(model=_agent_model("temporal"))
self.summarizer = SummarizerAgent(model=_agent_model("summarizer"))
self.image_agent = ImageAgent(model=get_vision_model())
self.code_agent = CodeAgent(model=_agent_model("code"))
self.snippet_agent = SnippetAgent(model=_agent_model("code"))
self.judge = JudgeAgent(
model=_agent_model("judge"),
vector_store=self.vector_store,
graph_event_search=self._graph_event_search_wrapper,
top_k=3,
)
# Snippet stores are user-scoped — lazily created per user_id
self._snippet_stores: Dict[str, BaseVectorStore] = {}
# ── Weaver ────────────────────────────────────────────────────
self.weaver = Weaver(
vector_store=self.vector_store,
embed_fn=self.embed_fn,
graph_create_event=self._graph_create_event,
graph_update_event=self._graph_update_event,
graph_delete_event=self._graph_delete_event,
code_vector_store=self.code_vector_store,
graph_create_annotation=self._graph_create_annotation,
)
# ── Build graph ───────────────────────────────────────────────
self.graph = self._build_graph()
# ------------------------------------------------------------------
# Neo4j callable wrappers (injected into Judge + Weaver)
# ------------------------------------------------------------------
async def _graph_event_search_wrapper(
self,
event_name: str,
user_id: str,
top_k: int = 1,
) -> List[SearchResult]:
"""Bridge Neo4j search results → SearchResult for the Judge."""
loop = asyncio.get_running_loop()
from functools import partial
raw = await loop.run_in_executor(
None,
partial(
self.neo4j.search_events_by_name,
event_name=event_name,
user_id=user_id,
top_k=top_k,
),
)
results: List[SearchResult] = []
for r in raw:
content = (
f"{r.get('date', '')} | {r.get('event_name', '')} | {r.get('desc', '')}"
)
results.append(
SearchResult(
id=f"{r.get('date', '')}_{r.get('event_name', '')}",
content=content,
score=1.0,
metadata=r,
)
)
return results
async def _graph_create_event(
self,
user_id: str,
date_str: str,
event_data: Dict[str, Any],
) -> None:
loop = asyncio.get_running_loop()
from functools import partial
await loop.run_in_executor(
None,
partial(
self.neo4j.create_event,
user_id=user_id,
date_str=date_str,
event_data=event_data,
),
)
async def _graph_update_event(
self,
user_id: str,
date_str: str,
event_data: Dict[str, Any],
) -> None:
loop = asyncio.get_running_loop()
from functools import partial
await loop.run_in_executor(
None,
partial(
self.neo4j.update_event,
user_id=user_id,
date_str=date_str,
event_data=event_data,
),
)
async def _graph_delete_event(
self,
user_id: str,
embedding_id: str = "",
**kwargs,
) -> None:
# embedding_id for temporal is "date_str_event_name"
parts = embedding_id.split("_", 1)
date_str = parts[0] if parts else ""
event_name = parts[1] if len(parts) > 1 else None
loop = asyncio.get_running_loop()
from functools import partial
await loop.run_in_executor(
None,
partial(
self.neo4j.delete_event,
user_id=user_id,
date_str=date_str,
event_name=event_name,
),
)
async def _graph_create_annotation(
self,
content: str,
annotation_type: str = "explanation",
severity: Optional[str] = None,
author_id: Optional[str] = None,
repo: Optional[str] = None,
target_file: Optional[str] = None,
target_symbol: Optional[str] = None,
) -> str:
"""Bridge for creating code annotations in the code graph."""
loop = asyncio.get_running_loop()
from functools import partial
return await loop.run_in_executor(
None,
partial(
self.code_graph.create_annotation,
org_id=self.org_id,
content=content,
annotation_type=annotation_type,
severity=severity,
author_id=author_id,
repo=repo,
target_file=target_file,
target_symbol=target_symbol,
),
)
# ------------------------------------------------------------------
# User-scoped snippet store
# ------------------------------------------------------------------
def _get_snippet_store(self, user_id: str) -> BaseVectorStore:
"""Get or create a vector store for a user's snippets namespace."""
if user_id not in self._snippet_stores:
ns = snippets_namespace(user_id)
self._snippet_stores[user_id] = get_vector_store(
namespace=ns,
create_if_not_exists=False,
)
logger.info("Snippet store initialised (ns=%s).", ns)
return self._snippet_stores[user_id]
# ------------------------------------------------------------------
# LangGraph node functions
# ------------------------------------------------------------------
async def _node_classify(self, state: IngestState) -> Dict[str, Any]:
"""Run the classifier on the user query."""
user_query = state.get("user_query", "")
# Hint the classifier if an image is attached
if state.get("image_url"):
user_query += " [User has attached an image]"
result = await self.classifier.arun(
{
"user_query": user_query,
}
)
return {"classification_result": result}
def _route_after_classify(self, state: IngestState) -> List[Send]:
"""Fan out to extraction agents based on classification."""
routes: List[Send] = []
user_id = state.get("user_id", "default")
user_query = state.get("user_query", "").strip()
agent_response = state.get("agent_response", "").strip()
disabled_domains = set(state.get("disabled_domains") or [])
# Collect queries per domain — merge duplicates so each agent runs once
profile_queries: List[str] = []
temporal_queries: List[str] = []
image_queries: List[str] = []
code_queries: List[str] = []
classification_result = state.get("classification_result")
if classification_result and classification_result.classifications:
for c in classification_result.classifications:
if c["source"] == "profile":
profile_queries.append(c["query"])
elif c["source"] == "event":
temporal_queries.append(c["query"])
elif c["source"] == "image":
image_queries.append(c["query"])
elif c["source"] == "code":
code_queries.append(c["query"])
# Determine if we should run the summary extraction
# Heuristic: Don't summarize tiny acknowledgments or greetings (unless they had classified facts)
words = f"{user_query} {agent_response}".split()
is_trivial = len(words) < 4 and not any(
[profile_queries, temporal_queries, code_queries, image_queries]
)
if not is_trivial:
routes.append(
Send(
"extract_summary",
{
**state,
"user_id": user_id,
},
)
)
else:
logger.info("Skipping summary extraction for trivial query.")
if profile_queries:
routes.append(
Send(
"extract_profile",
{
**state,
"profile_queries": profile_queries,
"user_id": user_id,
},
)
)
if temporal_queries:
routes.append(
Send(
"extract_temporal",
{
**state,
"temporal_queries": temporal_queries,
"user_id": user_id,
},
)
)
if code_queries and not {"code", "snippet"}.issubset(disabled_domains):
# Enterprise users → team annotation extraction (Code Agent)
# Single users → personal snippet extraction (Snippet Agent)
# Tier determined by org_id: "default" means single user
is_enterprise = self.org_id != "default"
if is_enterprise and "code" not in disabled_domains:
routes.append(
Send(
"extract_code",
{
**state,
"code_queries": code_queries,
"user_id": user_id,
},
)
)
elif not is_enterprise and "snippet" not in disabled_domains:
routes.append(
Send(
"extract_snippet",
{
**state,
"code_queries": code_queries,
"user_id": user_id,
},
)
)
# Image route
if state.get("image_url"):
if not image_queries:
image_queries.append("Analyze this image for memory-relevant details.")
combined_query = " ".join(image_queries)
routes.append(
Send(
"extract_image",
{
**state,
"classifier_output": combined_query,
"user_id": user_id,
},
)
)
return routes
# ── Extraction nodes ──────────────────────────────────────────────
async def _node_extract_profile(self, state: IngestState) -> Dict[str, Any]:
"""Extract profile facts from the classifier query."""
queries = state.get("profile_queries", [])
user_id = state.get("user_id", "default")
# Merge into a single query (safety net if classifier outputs duplicate lines)
combined_query = " ".join(queries)
result = await self.profiler.arun({"classifier_output": combined_query})
if result.is_empty:
return {"status": "no_profile_facts"}
# Profile facts are already structured; exact metadata lookup avoids
# an extra judge LLM call on the hot path.
items = [f.model_dump() for f in result.facts]
judge_result = await self.judge.arun_deterministic(
{
"domain": "profile",
"new_items": items,
"user_id": user_id,
}
)
# Weave
weaver_result = await self.weaver.execute(
judge_result=judge_result,
domain=JudgeDomain.PROFILE,
user_id=user_id,
extra_metadata=state.get("lifecycle_metadata"),
)
return {
"profile_result": result,
"profile_judge": judge_result,
"profile_weaver": weaver_result,
}
async def _node_extract_temporal(self, state: IngestState) -> Dict[str, Any]:
"""Extract temporal events from the classifier query."""
queries = state.get("temporal_queries", [])
user_id = state.get("user_id", "default")
session_dt = state.get("session_datetime", "")
# Merge into a single query
combined_query = " ".join(queries)
result = await self.temporal.arun(
{
"classifier_output": combined_query,
"session_datetime": session_dt,
}
)
if result.is_empty:
return {"status": "no_temporal_event"}
all_items: List[Dict[str, str]] = []
for event in result.events:
all_items.append(
{
"date": event.date,
"event_name": event.event_name or "",
"desc": event.desc or "",
"year": event.year or "",
"time": event.time or "",
"date_expression": event.date_expression or "",
}
)
judge_result = await self.judge.arun_deterministic(
{
"domain": "temporal",
"new_items": all_items,
"user_id": user_id,
}
)
weaver_result = await self.weaver.execute(
judge_result=judge_result,
domain=JudgeDomain.TEMPORAL,
user_id=user_id,
)
return {
"temporal_result": result,
"temporal_judge": judge_result,
"temporal_weaver": weaver_result,
}
async def _node_extract_image(self, state: IngestState) -> Dict[str, Any]:
"""Extract visual observations from the image and store them as summary."""
user_id = state.get("user_id", "default")
# ImageAgent reads classifier_output and image_url from state
result = await self.image_agent.arun(state)
if result.is_empty:
return {"status": "no_image_observations"}
# Convert observations to list of dicts for Judge
# items = [obs.model_dump() for obs in result.observations]
# converted observation of images to summary and stored as summary
items = []
if result.description:
items.append(f"[Image] {result.description}")
for obs in result.observations:
conf = f" ({obs.confidence})" if obs.confidence else ""
items.append(f"[Image/{obs.category}] {obs.description}{conf}")
if not items:
return {"status": "no_image_observations"}
judge_result = await self.judge.arun(
{
"domain": JudgeDomain.SUMMARY,
"new_items": items,
"user_id": user_id,
}
)
weaver_result = await self.weaver.execute(
judge_result=judge_result,
domain=JudgeDomain.SUMMARY,
user_id=user_id,
extra_metadata=state.get("lifecycle_metadata"),
)
return {
"image_result": result,
"image_judge": judge_result,
"image_weaver": weaver_result,
}
async def _node_extract_code(self, state: IngestState) -> Dict[str, Any]:
"""Extract code annotations from the classifier query."""
queries = state.get("code_queries", [])
user_id = state.get("user_id", "default")
# Merge into a single query
combined_query = " ".join(queries)
result = await self.code_agent.arun({"classifier_output": combined_query})
if result.is_empty:
return {"status": "no_code_annotations"}
all_items: List[str] = []
for ann in result.annotations:
parts = [
ann.annotation_type.value,
ann.target_symbol or "",
ann.target_file or "",
ann.repo or "",
ann.severity.value if ann.severity else "",
ann.content,
]
all_items.append(" | ".join(parts))
judge_result = await self.judge.arun(