About Me Projects Articles Experience Education Contact
Resume PDF Switch to Portuguese 🇧🇷
Back to Articles

Engineering a Governed Multi-Agent RAG System for Consultative Customer Service

An evidence-driven case study on orchestration, local open-source AI, deterministic execution, conversation state, human handoff, and operational idempotency.

Aug 2026 18 min read Multi-Agent AI RAG
Figure 1: Published ViaSul Multi-Agent RAG Proof of Concept

Abstract

This case study documents a published proof of concept for a fictitious travel company, ViaSul Experiências Turísticas. The business problem was to scale a consultative email service model without replacing personalisation with generic automation or allowing a probabilistic model to claim that operational actions had been completed. The implemented solution combines Microsoft Outlook, n8n, local open-source language and embedding models through Ollama, Supabase-based retrieval-augmented generation, Google Drive ingestion, Google Sheets operational persistence, specialised agents, deterministic routing, conversation memory, human handoff, and calendar integration.

The evidence demonstrates successful tests for document-grounded replies, insufficient-evidence escalation, human-notification verification, two-step call scheduling, persisted conversation state, repeated-confirmation blocking, defensive fallbacks, and controlled publication. No ROI, productivity percentage, or financial saving was measured. The demonstrated value is qualitative: improved operational control, traceability, source governance, and safer automation.

Privacy note: ViaSul Experiências Turísticas is fictitious. The company name, customer scenarios, messages, and identifiers were created or controlled for educational demonstration. The implementation considered privacy and data-protection principles, but it does not constitute a formal certification of compliance with Brazilian data-protection law.

1. Introduction

The project began with a business tension rather than a technology preference. A consultative service model had to absorb growing email demand while preserving context, factual accuracy, and escalation to human staff when necessary. Simply adding a conversational model would not address the main operational risks: delayed responses, unsupported commercial claims, mixed customer contexts, duplicated actions, and confirmations sent before an integration had actually completed its work.

The strategic objective was therefore to prove that AI-assisted service could be scaled under explicit controls. The solution had to distinguish interpretation from execution, keep document retrieval separate from agent autonomy, preserve the state of multi-message interactions, and provide a safe termination path for unexpected conditions.

2. Problem Statement

Organisational pain

The service demand could exceed the team's response capacity during peak periods. A generic chatbot would undermine the consultative experience, while simply expanding headcount would increase fixed operating structure and would not by itself solve out-of-hours coverage.

Operational risk

A plausible model response could be mistaken for evidence that a notification, calendar event, or handoff had occurred. Commercial statements could also be produced without validated documentary support.

Data and context risk

Email bodies and signatures are untrusted content. Customer identity could not be inferred from text alone, and memory had to remain isolated by Outlook conversation rather than by a mutable display name.

Delivery requirement

The proof of concept needed to demonstrate end-to-end behaviour: ingestion, retrieval, routing, specialised handling, operations, human escalation, defensive fallbacks, and publication with active triggers.

3. Solution Architecture

The published solution is an event-driven n8n workflow with two operational entry points. Microsoft Outlook receives service emails. Google Drive monitors new commercial documentation for ingestion into the retrieval layer. A shared RAG subworkflow provides validated evidence to specialised agents.

ARCHITECTURE
Microsoft Outlook Trigger
  → Mark message as read
  → Prepare customer identification
  → Find customer by email in Google Sheets
  → Prepare registration result
  → Classify service destination
  → Route with Switch
      ├─ Sarah
      ├─ Fidelizer
      ├─ Concierge
      ├─ Operational continuation
      ├─ General human service
      └─ Orchestrator fallback

Google Drive Trigger
  → Download document
  → Extract text
  → Split document
  → Generate local embeddings
  → Store vectors and metadata in Supabase

The Orchestrator classifies but does not execute. Specialised agents interpret their assigned requests. A structuring chain converts intermediate responses into validated contracts. Deterministic n8n nodes then decide whether to reply, notify a team, write to a sheet, or create a calendar event.

Published workflow areas and nodes

Workflow areaNode typeFunctionReason for use
Email entryMicrosoft Outlook TriggerStarts production execution for incoming email.Preserves the email channel used by the case and exposes message and conversation identifiers.
Document ingestionGoogle Drive TriggerDetects new files in the monitored source.Automates updates to the official documentary base.
Input contractsEdit FieldsNormalises identity, routing, state, RAG, and handoff fields.Supports data minimisation and prevents uncontrolled field propagation.
Customer lookupGoogle SheetsFinds customers by normalised technical sender email.Keeps identity deterministic rather than model-inferred.
OrchestrationBasic LLM Chain and Structured Output ParserClassifies destination and produces a restricted object.Separates routing intent from operational privileges.
RoutingSwitchMaterialises Sarah, Fidelizer, Concierge, continuation, human service, and fallback routes.Makes decision paths visible, testable, and auditable.
Specialist reasoningAI AgentInterprets the message, validated context, and conversation memory.Provides natural-language understanding while remaining outside direct execution.
Agent memorySimple MemoryKeeps recent messages under a conversation-specific session key.Preserves continuity without mixing Outlook conversations.
RAG invocationExecute WorkflowCalls the shared ViaSul recovery subworkflow.Avoids direct Supabase access by agents and reuses one validation pipeline.
Output normalisationBasic LLM Chain and Structured Output ParserTransforms intermediate agent text into restricted action contracts.Resolved instability observed with direct structured output on long prompts.
Branch validationIFChecks operation success, active state, and authorisation conditions.Prevents claims or actions without deterministic evidence.
Customer responseMicrosoft Outlook Message ReplyReplies to the original message.Preserves the same Outlook conversation and conversation ID.
Internal notificationMicrosoft Outlook Message SendSends a separate internal human-service notification.Separates staff communication from the customer thread.
SchedulingMicrosoft Outlook CalendarCreates a 30-minute call event after final confirmation.Only the real connector result proves event creation.
Operational persistenceGoogle Sheets Append / Append or UpdateStores conversation states and human handoffs.Supports continuation, auditability, and idempotency in the proof of concept.
Vector storageSupabase Vector StoreStores document chunks, embeddings, and metadata.Provides the retrieval layer for evidence-grounded responses.

Agent responsibilities

  • Sarah: handles new-customer and new-purchase questions, replies from validated documentation, or requests human review.
  • Fidelizer: supports returning customers, manages the two-step call-scheduling interaction, and uses persisted state for continuation.
  • Concierge: supports customers with contracted travel and escalates unsupported or operational questions.
  • Orchestrator: selects a route but has no operational tools.

4. Technology Stack

n8n
Orchestration, routing, validation, persistence, and publication.
Qwen3 14B
Local open-source language model for orchestration, agents, and structuring.
Ollama
Local model runtime used by the language and embedding models.
nomic-embed-text
Local open-source embeddings for documentary retrieval.
Supabase
Vector and metadata storage for the RAG knowledge base.
Microsoft Outlook
Inbound email, customer replies, and internal notifications.
Outlook Calendar
Operational creation of confirmed 30-minute call events.
Google Drive
Source repository and trigger for documentary ingestion.
Google Sheets
Customer lookup, conversation state, and human-service records.
JavaScript Expressions
Field normalisation, safe fallbacks, date handling, and message composition.
JSON Schema
Restricted output contracts for deterministic downstream routing.
Simple Memory
Local session memory keyed by Outlook conversation ID.

5. Implementation Journey

Discovery and planning

The work retained a stable version while a separate multi-agent workflow was developed. The core responsibilities were identified first: deterministic customer identification, route classification, documentary recovery, controlled agent output, operations, state, and fallbacks.

Architecture and implementation

The Orchestrator and physical Switch routes were introduced, followed by the shared RAG subworkflow, specialist agents, structuring chains, human-service flows, and persisted continuation. Outlook Reply replaced the previous draft-and-send pattern to preserve the same conversation.

Validation

Each route was tested incrementally. Real executions validated replies, calendar creation, team notifications, and Google Sheets writes. Controlled simulation nodes validated inactive states, unknown statuses, notification failures, and fallback actions without sending unintended messages.

Publication

The first publication attempt was blocked because the Google Drive credential required reconnection. After the credential was restored and the ingestion trigger was tested, the workflow was published with production triggers active for a controlled demonstration.

6. Technical Decisions and Architecture Rationale

Decision: Dedicated Orchestrator without tools

Context: routing had to remain separate from operations.

Rationale: the Orchestrator emits a restricted classification object, while Switch nodes execute visible routes.

Benefits: auditability and reduced autonomy.

Trade-offs: more nodes and contracts to maintain.

Engineering impact: improved reliability and maintainability; no measured performance effect.

Decision: Agent text followed by structuring chain

Context: direct structured output on long agent prompts produced truncation and inconsistency.

Rationale: separate natural-language interpretation from deterministic object formation.

Benefits: clearer failure boundaries and restricted schemas.

Trade-offs: an additional model inference for applicable agents.

Engineering impact: higher maintainability and reliability; additional latency was not measured.

Decision: Shared validated RAG subworkflow

Context: agents needed facts from one official documentary layer.

Rationale: retrieval, filtering, and validation occur outside the agent; only validated context is exposed.

Benefits: source governance and reduced unsupported claims.

Trade-offs: more retrieval stages and operational dependencies.

Engineering impact: stronger security and consistency; retrieval latency was not benchmarked.

Decision: Two-step scheduling with persisted state

Context: a date and time mention must not create an event automatically.

Rationale: persist the proposed date and time, wait for confirmation in the same conversation, then create the event.

Benefits: explicit consent and idempotent behaviour.

Trade-offs: state lifecycle and continuation logic increase complexity.

Engineering impact: improved operational reliability; Google Sheets concurrency remains untested.

Decision: Local open-source AI

Context: the project explored local inference for language and embeddings.

Rationale: Qwen3 14B and nomic-embed-text run through Ollama without external token or embedding charges in this implementation.

Benefits: local execution and privacy-oriented experimentation.

Trade-offs: infrastructure capacity, uptime, energy, RAM, VRAM, and maintenance become local responsibilities.

Engineering impact: cost transfer rather than proven cost reduction; total cost was not measured.

Decision: Safe fallback without technical persistence

Context: the proof of concept needed a fast, safe response for unexpected routing.

Alternatives considered: create an occurrences sheet or respond safely and terminate.

Rationale: the second option was selected for the POC.

Benefits: lower implementation complexity.

Trade-offs: no consolidated technical occurrence history.

Engineering impact: faster delivery with reduced observability.

7. Source Code Analysis

The implementation evidence includes n8n JavaScript expressions and JSON Schemas rather than a conventional application repository. The excerpts below are taken from the configured workflow expressions discussed and tested during implementation.

Conversation-scoped memory key

Purpose: bind Sarah's local memory to the normalised Outlook conversation identifier. Problem solved: prevents using an individual message ID or mutable customer attribute as the session key. Architectural role: supports continuity in the AI Agent without mixing distinct conversations.

JAVASCRIPT
{{
  String(
    $('Reunir Contexto da Sarah e RAG')
      .first()
      .json
      .conversation_id ?? ''
  )
}}

Technical analysis: the expression explicitly reads the normalised contract and applies an empty-string fallback. The dependency is the context-unification node. Security depends on ensuring the key is not empty in production execution. The pattern improves maintainability by reducing direct coupling to the trigger's raw field name. Simple Memory remains local to one n8n instance and was not validated for multiple workers.

Two-step state cleanup

Purpose: clear pending proposal attributes after successful event creation. Problem solved: avoids reusing a previously confirmed date and time. Architectural role: prepares the deterministic contract used to update the existing conversation-state row.

JAVASCRIPT
{{ '' }}

Technical analysis: an explicit empty string was used for ultima_acao_pendente, data_proposta, and horario_proposto. The pattern is intentionally simple because the Google Sheets update must clear previous cell values. The dependency is the successful Outlook Calendar path. This supports idempotency but does not itself address concurrent writes.

Fallback-safe message composition

Purpose: build a safe customer reply for an unknown Sarah action. Problem solved: avoids guessing the correct route while preserving a professional response. Architectural role: terminates the defensive branch before any operational action.

JAVASCRIPT
{{
  (() => {
    const nome = String(
      $json.nome ??
      $json.output?.cliente ??
      $('Reunir Contexto da Sarah e RAG').first().json.nome ??
      'cliente'
    );

    return [
      `Olá, ${nome}!`,
      '',
      'Não consegui processar a sua solicitação com segurança.',
      '',
      'Por favor, descreva novamente o que deseja solicitar para que o atendimento seja direcionado corretamente.',
      '',
      'Sarah',
      'ViaSul Experiências Turísticas'
    ].join('\n');
  })()
}}

Technical analysis: the expression prioritises current-item data, then the structured output, then the unified context. This made the node work both in the real path and in isolated controlled simulations. The nested fallback increases resilience but also couples the expression to named n8n nodes. The message intentionally avoids exposing technical details or claiming a completed action.

Restricted Sarah action schema

Purpose: constrain Sarah's structured decisions to a minimal contract. Problem solved: prevents obsolete or unsupported operations such as direct call scheduling. Architectural role: supplies deterministic input to the action Switch.

JSON SCHEMA
{
  "type": "object",
  "properties": {
    "acao": {
      "type": "string",
      "enum": [
        "responder",
        "encaminhar_atendimento_humano"
      ]
    },
    "cliente": { "type": "string" },
    "resposta_cliente": { "type": "string" },
    "necessita_atendimento_humano": { "type": "boolean" },
    "motivo": { "type": "string" }
  },
  "required": [
    "acao",
    "cliente",
    "resposta_cliente",
    "necessita_atendimento_humano",
    "motivo"
  ],
  "additionalProperties": false
}

Technical analysis: the enum limits the route space and additionalProperties: false rejects unplanned fields. The schema depends on the structuring chain and is not attached directly to Sarah's AI Agent. This improves reliability and security by reducing operational ambiguity. It also means any new action requires coordinated schema, routing, and downstream changes.

8. Challenges and Resolutions

Structured output instability

Cause: direct parser use with extensive agent prompts produced truncation and inconsistency. Resolution: intermediate text plus a dedicated structuring chain and parser.

False operational confirmation risk

Cause: model intent could be confused with actual integration success. Resolution: Outlook and Calendar outcomes are checked before final customer confirmation.

Repeated scheduling confirmation

Cause: a repeated short confirmation could reuse the same proposal. Resolution: the state is closed after successful event creation; a later confirmation is routed to a completed-state reply.

Testing isolated defensive paths

Cause: n8n expressions referenced earlier nodes that were absent in isolated executions. Resolution: self-contained temporary simulators and expressions that prioritise the current item before named-node fallbacks.

Publication blocked by disconnected credential

Cause: the Google Drive Trigger credential required reconnection. Resolution: reconnect the credential, test ingestion, and publish the workflow again.

9. Results and Outcomes

  • Sarah produced a real document-grounded reply for a new-purchase request and preserved the Outlook conversation.
  • An unsupported package question was escalated through Sarah without inventing the requested commercial fact.
  • The human-service team notification was sent, success was verified, the customer was then informed, and the handoff was recorded in Google Sheets.
  • The Fidelizer created one 30-minute Outlook event only after final confirmation in the same conversation.
  • A repeated confirmation was blocked by the completed conversation state and did not create a duplicate event.
  • Cancelled, inactive, unknown-state, notification-failure, unknown-agent, and unknown-action paths were validated through controlled simulations.
  • The workflow was published after Google Drive credential recovery, with email and document-ingestion triggers active for controlled demonstration.

Measurement boundary: no financial ROI, productivity gain, latency benchmark, load result, or percentage improvement was produced. Claims are limited to validated functional and qualitative outcomes.

10. Engineering Highlights

RELIABILITY

Idempotent scheduling

Technologies: n8n, Google Sheets, Outlook Calendar.

Technical impact: prevents reuse of a completed proposal.

Business impact: reduces the risk of duplicated customer commitments.

Evidence: a repeated confirmation was routed to the completed-state response and no second event was created.

GOVERNANCE

Validated evidence before commercial replies

Technologies: Supabase, nomic-embed-text, Ollama, n8n.

Technical impact: agents receive only validated documentary context.

Business impact: supports more controlled commercial communication.

Evidence: insufficient documentation triggered human review rather than a fabricated answer.

SAFETY

Verified human handoff

Technologies: Outlook Send, IF, Outlook Reply, Google Sheets.

Technical impact: customer confirmation depends on real notification success.

Business impact: avoids communicating a handoff that did not occur.

Evidence: success and failure branches were tested, including a controlled failure simulation.

MAINTAINABILITY

Separated reasoning, contracts, and operations

Technologies: AI Agent, Basic LLM Chain, Structured Output Parser, Switch.

Technical impact: clearer responsibility boundaries and restricted actions.

Business impact: supports controlled evolution of the service model.

Evidence: the final architecture replaced direct parser usage on long agents after observed instability.

11. Lessons Learned

  1. Model intent is not operational proof. The workflow must verify the connector that performs the action.
  2. RAG quality depends on evidence governance. Retrieving semantically similar text is not enough; validation and entity filtering matter.
  3. State can be more reliable than memory for operational continuation. Persisted date, time, status, and pending action protected the scheduling process.
  4. Fallbacks are part of the product, not an afterthought. Unknown values must terminate safely rather than silently or by guesswork.
  5. Controlled simulations are valuable. They validated defensive routes without sending messages or creating events.
  6. Publication readiness includes credentials. A correct workflow still cannot activate if a trigger credential is disconnected.

12. Future Improvements

  • Implement persisted continuation for Sarah and Concierge.
  • Replace local Simple Memory with a shared memory architecture if multiple workers or queue mode are adopted.
  • Test concurrent Google Sheets updates and duplicate conversation rows.
  • Define retention, deletion, and expiration rules for states, messages, and handoff records.
  • Replace provisional internal email addresses with official corporate mailboxes.
  • Implement monitoring, retry policies, incident response, and dependency-outage tests.
  • Evaluate a technical-occurrence store, which was intentionally left outside the POC scope.
  • Complete formal privacy governance, legal-basis mapping, data-subject processes, access controls, and legal review before real-customer production use.
  • Confirm rotation or revocation of the previously exposed elevated Supabase key.

13. Conclusion

The ViaSul proof of concept demonstrates that a multi-agent RAG service can be implemented with local open-source AI while preserving explicit operational boundaries. Its most important contribution is not the number of agents. It is the architecture around them: deterministic identity, validated evidence, restricted contracts, visible routing, persisted state, real-operation verification, and defensive termination.

The project was published for controlled demonstration, not declared production-ready for real customers. That distinction is part of the engineering maturity demonstrated by the case. The evidence supports technical feasibility and qualitative improvements in control, traceability, and operational safety. It does not support unmeasured financial or performance claims.

Found this case study useful?

Share the engineering insights with your network.

Have a question or want to discuss the architecture?

Get in Touch