Blank white background with no objects or features visible.

TrueFoundry anuncia la adquisición de Seldon AI, ampliando su plataforma de control para IA empresarial. Lea el informe completo →

Deterministic vs Agentic Workflows: Lessons from Building a Shopping Assistant

Por Sourav Gupta

Published: July 1, 2026

Lessons in Deterministic Workflows, Agentic Reasoning, and State Management

⚡ TL;DR

Building a shopping assistant, TrueFoundry learned two things: don't force every interaction through agentic reasoning (deterministic execution for known intents like specs/coupons/reviews; ReAct agents only for open-ended, multi-step tasks like inventory or fulfillment), and design state around workflows, not data types (separating user vs. product state, tracking current_product_id explicitly, and scoping memory per agent thread to avoid token bloat as the assistant scaled to a full catalog).

Building AI assistants often starts with a deceptively simple problem. A user asks a question, the system retrieves information, and an LLM generates a response. The first version usually works surprisingly well.

The real challenge emerges as capabilities expand. As new tools and workflows are introduced, users begin asking questions that span multiple domains. Conversations become longer and more contextual, transitioning the assistant from a simple QA bot into a tool that helps users complete complex tasks.

At TrueFoundry, we encountered this exact challenge while building a conversational shopping assistant. The assistant began as a Product Detail Page (PDP) companion capable of answering questions about a single product. Over time, it evolved into a catalog-wide shopping assistant capable of handling product discovery, retrieval, review summarization, coupon processing, store discovery, inventory checks, fulfillment selection, and cart operations.

While the external capabilities expanded significantly, the most critical engineering challenges emerged in two areas:

  1. Deciding when to use deterministic workflows versus agentic reasoning.
  2. Evolving state management from a single-product conversation model into a multi-product shopping experience.

1. System Architecture Overview

The shopping assistant is built on four major architectural layers designed to balance performance, cost, and reliability.

A. Data Layer

The system maintains strict separation between structured and unstructured storage systems:

  • Product Catalog: Stored in PostgreSQL (Cloud SQL), containing product metadata, pricing, variants, category information, and fulfillment metadata.
  • Reviews: Customer reviews are stored in Qdrant. This allows semantic retrieval of review content rather than relying solely on keyword matching. When users ask semantic questions like "What do customers say about battery life?", the system retrieves relevant reviews and generates an evidence-based summary.

B. Data Ingestion Pipeline

Catalog and review data arrive continuously through Google Cloud Storage (GCS) and are processed via Google Dataflow pipelines:

  • Catalog Pipeline: GCS → Dataflow → Cloud SQL (Processed daily).
  • Review Pipeline: GCS → Dataflow → Embedding Generation → Qdrant (Processed on both daily and hourly schedules for fresh customer feedback).

C. Model Layer

All model interactions are routed through the TrueFoundry AI Gateway. This provides centralized model access, observability, governance, cost tracking, rate limiting, and model abstraction. The assistant utilizes Gemini 2.5 Flash and Qwen models to balance latency, quality, and operational cost.

D. Orchestration Layer

The conversational workflow is orchestrated using LangGraph, which enables explicit state transitions and workflow management while supporting both deterministic execution paths and agentic reasoning.

2. Challenge #1: Deterministic vs. Agentic Workflows

A common trend in AI systems is to make everything completely agentic under the assumption that if an LLM can reason, it should handle everything. In production, a pure-agent approach quickly becomes expensive, slow, and difficult to control.

We split shopping interactions into two distinct execution paradigms based on clear trade-offs in performance and intent:

Workflow Type When It Is Used Execution Pattern Example Capabilities
Deterministic Clear intent, known tools, predictable patterns, single-step answers. Direct Execution Route Specs lookup, review summarization, coupon retrieval.
Agentic (ReAct) Workflow-oriented requests, broad goals, multiple paths, missing context. Dynamic Reasoning & Selection Loop Location resolution, inventory validation, open-ended search.

Under the Hood: The Mechanics of Execution

The architectural decision to separate these flows is driven heavily by the internal loops, total LLM call counts, and token processing overhead.

[ReAct Loop]          
--> (1. Complex Tool-Selection Prompt) 
--> [Tool Call] 
--> (2. Synthesis Prompt) 
[Deterministic Flow]  
--> [Tool Call] 
--> (1. Light Formatting Prompt) 

The ReAct Agent Lifecycle (3-Step Loop)

For complex workflows, a dedicated ReAct agent handles execution dynamically through a three-step cycle:

  1. Step 1: The Planning Prompt (LLM Call): The system passes the user query along with system prompts containing the definitions of all available tools. The LLM must reason about what the user said, identify which tool to use, and extract the exact parameters required for that tool.
  2. Step 2: The Tool Execution: The system executes the actual tool or API call using the extracted parameters.
  3. Step 3: The Observation & Synthesis Prompt (LLM Call): The raw tool response is fed back into the LLM. The model evaluates the tool's response against the user's original question and modifies it into a clean, contextual user response.

The Deterministic Lifecycle (2-Step Shortcut)

Capabilities like product specifications, reviews, and coupons do not need to reason about tool choices or execution ordering. To optimize performance, we bypass the planning phase entirely:

  1. Step 1: Direct Tool Execution: Because intent classification maps directly to a known tool, the first LLM prompt call is completely skipped. The system executes the tool immediately, cutting out a full inference cycle and reducing the time-to-first-byte.
  2. Step 2: Response Synthesis (LLM Call): The system passes the raw tool data and the user query directly to a highly focused prompt to format the final answer.

The Latency and Prompt Complexity Penalty

Beyond counting the number of calls, the complexity of the prompt significantly dictates response speeds:

  • ReAct Prompt Burden: In Step 1 of a ReAct agent, the prompt is highly complex. The LLM must look across multiple tools, evaluate execution logic, and maintain context. This high cognitive load increases token processing time and generation latency.
  • Deterministic Prompt Efficiency: In a deterministic flow, the final prompt is straightforward: "Here is the question, and here is the raw tool response. Give the answer." Because the model doesn't need to evaluate paths or track tools, token generation is fast and lightweight.

Core Lesson: Forcing a ReAct reasoning loop onto basic data queries adds unnecessary latency, cost, and operational complexity without improving answer quality. If an interaction can be handled deterministically, it must be.

Guardrailing the ReAct Agents

Where deterministic paths break down (e.g., "Can I get this today?" involving location resolution, store discovery, and fulfillment checks), ReAct agents are vital. However, fully autonomous agents often produce inconsistent customer experiences. To maintain control, TrueFoundry implemented structured workflow stages inside the dynamic agents:

  • Inventory Agent Stages: Location Resolution → Store Selection → Inventory Check → Result Explanation.
  • Purchase Agent Stages: Product Validation → Inventory Verification → Fulfillment Selection → Cart Operation → Confirmation.

3. Challenge #2: State Management Evolution

Evolving from a single-product page assistant to a catalog-wide shopping companion is fundamentally a state management problem.

  • Phase 1 (Single Product State): Product context was implicitly derived from the active page. The state model was a simple, flat conversation history thread.
  • Phase 2 (Multi-Product Conversations): Catalog search allows users to introduce, compare, and switch between multiple products simultaneously.

To scale without introducing system fragility, the state architecture was completely overhauled across four key design principles:

1. Separation of State Scopes

Mixing user data with transient product data creates fragile systems. State was refactored into distinct boundaries:

  • User-Level State: Persistent across the entire shopping session (e.g., favorite store, location preferences, fulfillment choices).
  • Product-Level State: Tied to specific items (e.g., catalog metadata, active coupons, reviews).

2. Explicit Context Tracking (current_product_id)

We shifted product context from implicit to explicit by introducing current_product_id as a first-class state variable. When a user shifts focus to a new item, updating this single ID automatically flushes and refreshes downstream catalog data, reviews, coupons, and inventory variables.

3. Agent-Specific Thread Memory

Maintaining a single, flat conversation_history = [] array introduced massive token noise and degraded model performance. Search conversations require entirely different context windows than final checkout operations. Memory was scoped directly into isolated agent threads (Search, Inventory, Purchase, Product) to minimize cross-context pollution.

4. Product Reference Resolution

Intent classification alone is insufficient when dealing with a global catalog. When a user asks "Is this available near me?", the system relies on a newly introduced Product Reference Resolution layer to mathematically deduce what item "this" refers to, evaluate if the query is ambiguous, and decide if a clarification prompt is required.

Key Architecture Takeaway: State should represent workflows (Search, Inventory, Purchase) rather than data domains (Reviews, Coupons, Products). Designing state around user intent and workflow progression significantly simplifies orchestration and reduces multi-agent tracking complexity.

Try now.

One gateway for all your models, MCP servers, and agents.
No credit card needed.

Inscríbase
Tabla de contenido

Controle, implemente y rastree la IA en su propia infraestructura

Reserva 30 minutos con nuestro Experto en IA

Reserve una demostración

La forma más rápida de crear, gobernar y escalar su IA

Demo del libro
Summarize with
ChatGPT logo by OpenAI
Perplexity AI logo
Blurry red snowflake on white background, symmetrical frosty design with soft edges and abstract shape.

Descubra más

No se ha encontrado ningún artículo.
August 14, 2026
|
5 minutos de lectura

The Human Gate: Designing MCP Tool Approvals at the Gateway Boundary

No se ha encontrado ningún artículo.
August 13, 2026
|
5 minutos de lectura

AI Coding Agent Pricing: How to Choose the Right Plan

No se ha encontrado ningún artículo.
 What is an LLM Gateway
August 12, 2026
|
5 minutos de lectura

¿Qué es un LLM Gateway? Una guía completa

Ingeniería y producto
openrouter vs litellm
August 12, 2026
|
5 minutos de lectura

LitellM vs OpenRouter: ¿Cuál es el adecuado para usted?

comparación
No se ha encontrado ningún artículo.

Blogs recientes

Black left pointing arrow symbol on white background, directional indicator.
Black left pointing arrow symbol on white background, directional indicator.

Preguntas frecuentes

¿Cuándo debo usar un flujo de trabajo determinista en lugar de un agente ReAct?

Utiliza flujos de trabajo deterministas cuando la intención es clara, la herramienta es conocida y el resultado es predecible, por ejemplo, para obtener especificaciones de productos, recuperar cupones o resumir reseñas. Reserva los agentes ReAct para objetivos de varios pasos donde la ruta de ejecución depende de resultados intermedios.

¿Cuántas llamadas al LLM utiliza un agente ReAct en comparación con un flujo determinista?

Un bucle ReAct requiere dos llamadas al LLM por ciclo, una para la planificación y selección de herramientas, otra para la síntesis, más ciclos adicionales si el agente necesita reevaluar. Un flujo determinista omite por completo la llamada de planificación, reduciéndola a una única y ligera instrucción de síntesis.

¿Cómo sabe el sistema a qué producto se refiere un usuario en una conversación con múltiples productos?

Una capa de resolución de referencias de productos evalúa el estado actual, el contexto de la conversación y la variable current_product_id para deducir a qué artículo se refiere el usuario. Si la referencia es ambigua, el sistema activa una solicitud de aclaración en lugar de intentar adivinar.

¿Por qué es importante la memoria de hilo específica del agente para el rendimiento?

Un historial de conversación único y lineal acumula contexto irrelevante en flujos de trabajo no relacionados, lo que aumenta la carga de tokens y degrada el enfoque del modelo. Limitar la memoria a hilos de agente individuales (Búsqueda, Inventario, Compra) mantiene cada ventana de contexto concisa y relevante, mejorando tanto la velocidad como la calidad de las respuestas.

Realice un recorrido rápido por el producto
Comience el recorrido por el producto
Visita guiada por el producto