agent architecture Deep Dive
Delectable AI technical architecture

Agentic grocery intelligence, from shopper intent to cart-ready action.

This deeper dive reframes the original Eagle AI overview as a Delectable AI platform view: model routing, function-calling orchestration, commerce tools, graph intelligence, ML personalization, retail media, governance, safety, search, research, orchestration, and the data services needed for enterprise-grade agentic commerce.

40Declared tool interfaces
17Real-time propensity signals
15Recommender models
4Profile and pantry cache tiers
Live Architecture Map
reviewed from code
Surfaces and identity
Shopper conversation

Chat, mobile, PDP, search, cart, checkout, creator content, operator console.

Context adapter

Tenant profile, loyalty card to mParticle resolution, session state, tool enablement.

A2UI payloads

SSE product cards, meal plan data, structured templates, analytics events.

Agent core
GroceryAgent orchestration loop

Gemini chat session, FunctionDeclaration registry, model routing, guardrails, parallel tool calls, ranking context, result slimming.

fast/deep routing tool loop SSE stream guardrails
Ranking pipeline

Dietary annotation, purchase-history boost, graph affinity, session dedupe, relevance filtering.

Deterministic commerce logic

Ingredient parsing, unit conversion, pantry deduction, package sizing, cart-ready SKU matching.

Intelligence foundation
Food and shopper data

BigQuery product enrichment, recipes, purchase events, profile tables, promos, analytics.

HyperGraph layer

Memgraph and BigQuery property graph for households, products, recipes, ingredients, allergens, communities.

Platform support plane

Governance, safety policy, search abstraction, research signals, orchestration, DB, retail media, and social services.

01Resolve identity
02Prefetch context
03Route model
04Call tools
05Rank and annotate
06Render and evaluate
System frame

The agent is a commerce operating system, not a chatbot.

The current implementation combines generative planning with deterministic grocery math and retrieval-backed product truth. The LLM is used for intent interpretation, planning, and response synthesis; tools own product search, profile lookup, graph traversal, cart operations, pricing, promotions, pantry, and analytics.

Conversation orchestration

Gemini chat sessions receive a retailer-specific system prompt and a filtered function registry. The loop repeats until no function calls remain or the iteration guard is reached.

Commerce execution

Ingredient consolidation, shopping-list optimization, cart management, promo checks, and SKU matching sit outside the LLM so the final commerce output is auditable.

Learning layer

Session propensity deltas, recommender selection, graph communities, evaluation scores, and analytics events create a feedback loop for improved ranking and planning.

Support plane

The grocery agent sits on a broader Delectable platform fabric.

The agent-facing code is only the visible execution layer. The system also depends on cross-platform modules that own durable workflows, data abstraction, search routing, safety evidence, governance evaluation, and continuous research signals.

Safety

Policy registry, runtime checks, framework registry, incidents, evaluations, and append-only evidence ledger for guardrail enforcement and compliance dashboards.

Governance

GovernanceOS provides assessment instruments, cohort scoring, NIST gap analysis, audit trail, RACI, decisions, and human review workflows.

Search

Multi-engine search abstraction over OpenSearch, Elasticsearch, and Meilisearch, with keyword, vector, hybrid, autocomplete, taxonomy, and tenant routing.

Orchestration

Shared framework for LangGraph agents, durable Temporal workflows, job lifecycle management, resource optimization, rate limits, MLflow, and registry services.

DB

Unified database abstraction across PostgreSQL, BigQuery, DuckDB, Memgraph, Cosmos DB, vector stores, schemas, retail domain models, and event loaders.

Research

Continuous signals agent for academic feeds, regulatory updates, supplier streams, public APIs, novelty scoring, parsing, and knowledge-graph updates.

Runtime path
orchestration grocery-agent search db safety
Control path
governance evaluation policy registry audit evidence
Learning path
analytics research signals ML recommender registry GraphRAG updates
Reasoning loop

Every turn moves through a controlled sequence.

The main loop resolves identity, prefetches context in parallel, routes to the fast or deep model, executes tools, slims tool results for the LLM, retains full data for UI cards, and logs a trace for evaluation.

01

Normalize context and resolve shopper identity

Tenant, retailer, model override, search backend, dietary enforcement, session ID, loyalty ID, and mParticle ID are collected before the tool loop starts.

loyalty -> mpid
02

Prefetch profile, purchases, pantry, and graph intelligence

ThreadPoolExecutor runs shopper profile, purchase history, virtual pantry, and graph prefetch together so the LLM starts with personalized context.

parallel reads
03

Route to fast or deep reasoning

Product search can use the fast model. Meal planning, multi-day plans, budget constraints, family context, and complex requests route to the deeper model with more iterations.

adaptive model
04

Execute tool calls and ranking stages

Function calls are executed in parallel when possible. Product results pass through post-search ranking, dietary annotation, purchase matching, graph affinity, and dedupe logic.

up to 6 workers
05

Return compact context to the LLM and full payloads to UI

Bulky fields are removed before results re-enter the model. Full product records and meal-plan structures still stream to the UI through SSE and structured templates.

token control
06

Guard, render, log, and evaluate

Retrieval guardrails force catalog search when needed. The response is parsed into canonical render hints, logged to analytics, and available for LLM-as-judge evaluation.

traceable output
Agent operating modes

Different shopper intents should not use the same execution plan.

The current code already uses intent classification and tool gating. This section turns the architecture into explicit commerce playbooks that can become runtime policy.

Product search and substitution

Best for "show me oat milk", "healthy cereal", "gluten-free pasta", and "what can I use instead of butter?" The system uses query cleaning, category anchoring, semantic search, relevance filtering, dietary annotations, and purchase-history boost.

search_productsidentity, nutrition, or usage search
get_product_detailsnutrition, allergens, food scores
get_product_alternativeshealthier or compliant swaps
rerank_productsprofile, graph, and session signals
structured productcards, badges, reasons, SKUs

Recipe and meal planning

Best for multi-day plans, family meals, recipe ideas, dietary constraints, and shopping-list generation. The agent should search recipes before synthesis, then use deterministic consolidation and optional product retrieval only when the shopper wants a shoppable plan.

classify intentdays, meals, household, budget
search_recipesground the plan in known recipes
create_meal_planstructured plan generation
optimize_shopping_listdedupe, units, pantry deduction
meal_plan_dataSSE payload plus brief response

Perfect cart and commerce execution

Best for "build my cart", recipe-to-cart, replenishment, and budget-aware basket assembly. Deterministic cart services match ingredients to retail packages, then ranking and pricing services personalize final SKU choices.

get_virtual_pantrystock, running low, depleted
build_shopping_cartingredient lines to products
get_cart_pairingscomplete-the-kit suggestions
get_promos_and_offerscoupons and weekly specials
manage_cartsession-backed cart CRUD

Retail media and social commerce

Best for sponsored search, contextual social content, CPG-funded swaps, and creator-led discovery. These should be ranked as commerce content, with clear labels, attribution events, and incrementality measurement.

select_recommenderschoose carousels and slots
get_sponsored_productsad decisions and bids
get_social_contentcreator content matched to intent
log_ad_interactionimpression, click, cart, purchase
analyticsattribution and performance lift
Tool plane

The function registry is the platform contract.

The agent exposes core and optional tools with tenant-level enablement. The most important next engineering move is to treat the tool registry as a formal product surface: versioned schemas, SLAs, auth scopes, evaluation cases, and telemetry by tool family.

Tool family Representative tools Architecture role
Shopper context get_user_profile get_recent_purchases save_user_preference Fetch and persist the declared plus inferred profile. Preference fusion follows a declared-wins rule, with inferred propensities filling gaps.
Catalog discovery search_products get_product_details get_product_alternatives Ground answers in real products, SKUs, nutrition, allergens, and substitutions instead of model memory.
Recipes and plans search_recipes create_recipe create_meal_plan modify_meal_plan Separate recipe retrieval from generative planning, then emit structured plan payloads for the UI.
Cart and lists optimize_shopping_list build_shopping_cart manage_cart manage_shopping_list Perform deterministic grocery math, SKU mapping, package rounding, and session-backed commerce actions.
Graph reasoning query_household_personas query_allergy_exclusions get_graph_recommendations get_ingredient_substitutes Use graph structure for households, communities, recipe-to-cart paths, product authority, cross-category bridges, and substitutions.
Monetization get_promos_and_offers select_recommenders get_sponsored_products get_social_content Unify discovery, promotions, sponsored placements, and social proof without letting ads bypass relevance or safety policy.
Data and ML foundation

Personalization is assembled from profile, session, graph, and commerce signals.

The platform already contains the core building blocks: batch propensity profiles, real-time session deltas, recommender orchestration, virtual pantry logic, food-science enrichment, analytics backends, and LLM-based evaluation.

Profile memory
Declared preferences Inferred propensities Dietary resolutions Brand affinity Mission cluster
Real-time signals
Query intent Product click Recipe saved Add to cart Coupon clipped Dwell time
Model-of-models
Similar products Healthier swap Budget swap Complete the kit Replenishment Sponsored products
Food intelligence
Nutri-Score NOVA Food Compass Allergen detection Flavor DNA Ingredient bridge

Session propensity

Current session interactions are decayed, capped, and merged with batch propensities so search ranking can react immediately without overwriting long-term shopper truth.

Recommender orchestrator

A model registry selects the right carousel mix for each surface by filtering requirements, scoring relevance, and applying operator or sponsor overrides.

HyperGraph intelligence

The graph layer is where the agent earns its grocery-specific edge.

Product search answers "what matches this text?" Graph intelligence answers "what does this mean inside a household, recipe, basket, category, community, promotion, and safety context?"

Household personas

Multi-hop traversal finds patterns such as parent, athlete, health-conscious, entertainer, and time-constrained personas inside one shared loyalty account.

Allergy exclusions

User to allergen to product and ingredient paths can precompute exclusions for meal plans and explain why a recipe or SKU is unsafe.

Recipe to cart path

Recipe to ingredient to product edges produce cart-ready SKUs and let propensities rerank each ingredient's product candidates.

Tribe recommendations

MAGE-powered PageRank and community detection can identify shoppers with similar behavior and products with authority in a category.

Cross-category bridges

Graph paths reveal products that connect categories, enabling "complete the meal", "add the missing staple", and bundle recommendations.

Ingredient substitutes

Vector and co-occurrence graph search support context-aware substitutions for recipe edits, dietary needs, and out-of-stock recovery.

Governance and reliability

Trust comes from policy, traces, and deterministic exits.

The existing implementation already contains several reliability patterns. The next step is to make them first-class, measurable controls across tenants and surfaces.

Annotate, do not blindly filter

Dietary propensity is not always a hard purchase constraint because shoppers often buy for household members, guests, parties, or gifts. The right default is rank compliant products first, annotate conflicts clearly, and only hard-filter when the user explicitly requests it or a declared allergy policy requires it.

Retrieval guardrails

When the model answers a catalog-grounded request without calling product or recipe search, the agent can force retrieval and ask the model to rewrite using only the returned products and recipes.

Tool result slimming

Large product and meal-plan outputs are slimmed before re-entering the LLM context. The UI still receives complete structured payloads, keeping token cost down without losing render quality.

Observability and LLM-as-judge evaluation

Debug traces capture model, prompts, tool calls, durations, backends, products, and outcomes. Separate evaluator modules score per-turn and per-session quality across response quality, relevance, helpfulness, safety, and journey completion.

Policy shape to formalize:

intent + user_request + declared_constraints + inferred_profile + household_context
  -> tool allowlist
  -> retrieval requirement
  -> ranking policy
  -> annotation policy
  -> evaluation rubric
  -> audit event
Expert recommendations

Additional ML and AI capabilities worth adding next.

These recommendations build on the current codebase. I would prioritize capabilities that make the agent more reliable, measurable, and commercially useful before adding more generative surface area.

Now

Versioned tool contracts and eval packs

Give every grocery-agent, search, db, safety, governance, research, and orchestration contract a version, schema owner, SLA, policy class, and golden test set.

Why it matters: it prevents silent regressions when a tool response shape, search backend, workflow policy, or evidence requirement changes.
Now

Extend the ILP cart optimizer

Build on the existing OR-Tools ILP / cart-optimizer path with richer MILP or CP-SAT constraint families for budgets, macros, prep time, leftovers, package sizes, pantry state, promos, inventory, and household rules.

Why it matters: the current ILP layer certifies package math and cost tradeoffs; the next step is broader meal-plan and household feasibility across the full cart.
Now

Unified real-time feature stream

Move session propensity, social velocity, cart events, ad events, and search interactions onto a single event stream with a feature-store contract.

Why it matters: ranking, ads, analytics, and evaluation should learn from the same canonical event spine.
Now

Allergy and medical-adjacent red-team suite

Create adversarial scenarios for allergies, pregnancy, baby food, medications, alcohol, substitutions, and "shopping for someone else" ambiguity.

Why it matters: grocery safety failures are high-trust failures, and generic LLM evals will not catch domain-specific hazards.
Next

Fulfillment-aware ranking

Inject store inventory, pick confidence, substitution likelihood, cold-chain constraints, and delivery window fit into product and cart ranking.

Why it matters: a product recommendation is only valuable if it can be fulfilled reliably at the shopper's store.
Next

Causal retail media incrementality

Go beyond last-click attribution with holdouts, uplift models, bid relevance penalties, and incrementality by mission, household, category, and creator content.

Why it matters: CPG budgets grow when Delectable can prove lift instead of only reporting impressions and clicks.
Next

GraphRAG proof traces

Expose compact graph paths and supporting evidence to the model and UI: household persona, allergy edge, recipe-product path, authority score, and substitute rationale.

Why it matters: explainability becomes a user-facing feature and an operator debugging tool.
Next

Pantry state estimator with package depletion

Upgrade virtual pantry from purchase recency to household-size, product-size, consumption velocity, meal-plan usage, repeat purchase, and confidence bands.

Why it matters: proactive replenishment is one of the highest-value agentic grocery behaviors.
Later

Multimodal ingestion for products and social content

Use OCR, image embeddings, video transcripts, and shelf-label parsing to enrich products, recipes, creator videos, and in-store discovery.

Why it matters: it turns unstructured retail and creator media into shoppable, searchable, attributable intelligence.
Later

Autonomous policy simulator

Run synthetic shoppers through thousands of policy combinations before rollout, scoring utility, safety, margin, ad load, and shopper trust.

Why it matters: it lets operators tune the agent like a marketplace, not a static prompt.
Implementation evidence

Source files reviewed for this deep dive.

The page content is grounded in the current grocery-agent, ML, knowledge graph, analytics, and legacy VIA ML modules. These are the highest-signal files used to shape the architecture narrative.

grocery-agent/grocery/agent.py
grocery-agent/grocery/tools/declarations.py
grocery-agent/grocery/tools/shopping_optimizer.py
grocery-agent/commerce_pkg/protocols/mcp.py
grocery-agent/commerce_pkg/protocols/a2a.py
grocery-agent/commerce_pkg/profile/fusion.py
delectable/ml/README.md
delectable/ml/propensity/session_propensity.py
delectable/ml/recommenders/orchestrator.py
delectable/knowledge-graph/src/knowledge_graph
analytics/src/analytics/evaluation/evaluator.py
via/ml/llm and via/ml/domains/grocery
governance/README.md and governance/docs/TECHNICAL.md
safety/README.md and safety/src/safety/app.py
search/docs/TECHNICAL.md and search/src/search/unified_search.py
research/docs/TECHNICAL.md and research/docs/USER-GUIDE.md
orchestration/README.md and orchestration/src/orchestration
db/README.md and db/src/db/app.py