PTENES
MODULE 5.1

📧 Project: Email Support Agent with RAG

Your first end-to-end project. You'll build an agent that reads the company policies (return, warranty, and deadline PDFs) into a knowledge base, classifies every incoming email and drafts the answer grounded in the documents — refusing to make things up when the topic is out of scope. These are two workflows in n8n, a comprehensive opening prompt, credentials that only you connect, tests with real cases, and the 6 enhancements applied in layers.

8
Topics
~75
Minutes
Practical
Level
Project
Type
Module progress 0% · 0 of 8

🧰 How to use this module

It’s a real build. Each code block below is a prompt to copy and run in your assistant (with n8n connected via MCP) — always with 🎯 goal, the block to copy and ✅ how to verify. The parts between <chaves> you replace these with your values. Prerequisites: a coding assistant with the n8n MCP connected, an email account, and an AI key with embeddings (e.g., OpenAI). Go in layers: run one prompt, verify it, and only then move on.

The project blueprint has two machines that divide the work: one learns the policies once (the indexer), the other responds with every email (the agent). They communicate through a shared place — the vector store, where knowledge is searchable.

Workflow 1 — Indexer (runs manually, once) 📄 Policy PDFs ✂️ text splitter 🔢 embeddings 🗄️ Vector store searchable knowledge the agent checks here Workflow 2 — Agent (Gmail triggers every 15 min) 📥 Gmail trigger 🏷️ classifier 🤖 agent + RAG tool ✉️ Gmail draft "not relevant" → ends (doesn't respond)

Illustrative diagram — the indexer feeds the vector store; the agent reads from it on each run. Separating “learning” from “responding” keeps each part easy to test.

1

🎯 The project scope

What it is

The project is a email support agent. It starts with two documents: one about policies (shipping, returns, warranty, billing, prices, promotions, privacy, gift cards) and one for FAQ. From those, for each incoming email, it decides whether it’s a support question, looks up the answer in the documents, and drafts a replica—one that a human still approves before sending.

What is it?RAG (Retrieval-Augmented Generation) — instead of AI “guessing” from memory, it first search (retrieval) the right passage in your documents and only then generates the answer based on it. Draft — the reply is saved as a draft in the email inbox; it isn't sent automatically.

The scope is deliberately narrow and safe: the agent drafts, doesn’t send (human in the loop), and the golden rule is to not make things up — if the topic isn't covered by the policies, it doesn't improvise an answer. This scope is what makes the project reliable enough for a real business setting.

Why learn

This is the "hello world" of agents that make money: it combines three skills in one useful case—RAG (grounding in documents), classification (filtering for support requests), and text generation (writing the response in the right tone).

  • •Anchored: answers come from the policies, not the AI’s imagination.
  • •Safe: draft + human approval; out of scope = no response.
  • •Reusable: swap out the PDFs, and the same agent can serve another company.

Key concepts

RAG

Search before generating.

Classify

Is it supported or not?

Draft

Human approves the submission.

Don't make things up

Out of scope = no response.

2

🏗️ The architecture: indexer + agent

What it is

Are two workflows separate. The indexer runs on a manual trigger: reads the documents, splits the text into chunks (text splitter), generates embeddings and write to vector store. O agent runs on an email trigger: every 15 minutes, it reads unread messages, classifies them, queries the vector store as a tool, and creates a draft.

What is it?Embeddings — a way to turn text into numbers that capture meaning, so search finds passages by sense, not just exact words. Vector store — the database that stores those numbers and returns the chunks most similar to the question. Text splitter — splits the document into chunks of the right size for search.

Why learn

Separate who learns of who responds is an engineering decision: you index only when the policies change (rarely), but the agent runs all the time (cheap, because it only queries). Mixing the two would make every email more expensive and make testing harder.

✓ Indexer (learns)

  • ✓Manual trigger — you run it when the PDFs change.
  • ✓Document → splitter → embeddings → vector store.
  • ✓Runs once, and the knowledge is saved.

✓ Agent (responds)

  • ✓Gmail trigger — every 15 min, unread emails.
  • ✓Classifier → agent with the vector store tool.
  • ✓Generates the draft; the "not relevant" branch ends.

🎯 Architecture decision: system prompt vs vector store

For a few small documents, you can paste the entire text into the system prompt (simpler and cheaper). But we chose vector store because it scales: it retrieves only the relevant section instead of sending the entire document with every email—better as the knowledge base grows. Let the AI suggest this and confirm the choice.

Key concepts

Two workflows

Learn vs. answer.

Vector store

Bridge between the two.

Scale

Finds only what's relevant.

Cheap

Index rarely, query often.

3

📝 The comprehensive opening prompt

What it is

É a single request, in Plan Mode, which describes the complete outcome: the source documents, the flow logic, and the expected behavior—letting the AI choose how store and search. Put the PDFs in the project folder and reference them by tag. Instead of asking for a vector store right away, describe the outcome and let the AI propose the architecture.

What is it?Plan Mode — a mode in which the AI researches, asks questions, and proposes a plan before to build, without changing anything. You review and approve; only then does it run.

🎯 Goal: describe the entire agent in a single prompt and let the AI propose the plan (in Plan Mode).

prompt (copy and run in Plan Mode)
Entre em plan mode. Quero um agente de suporte por e-mail no n8n.

Anexei dois documentos na pasta do projeto:
- @ (envio, devoluções, garantia, cobrança, preços, promoções, privacidade)
- @

Resultado desejado:
1. Use esses documentos como base de conhecimento da empresa.
2. A cada e-mail novo, classifique se é uma dúvida de suporte técnico.
3. Se for, rascunhe uma resposta APOIADA nos documentos (não invente nada).
4. Se NÃO for suporte, ignore (não responda).
5. A resposta deve ficar como RASCUNHO no Gmail, nunca enviada automaticamente.

Você decide como armazenar e buscar os documentos. Antes de construir,
me faça as perguntas que precisar e me mostre o plano dos workflows.

✅ How to verify: the AI should ask questions (AI provider, how to store it, what counts as support, tone) and return a plan with two workflows before creating any node. If it starts building right away, ask "stay in plan mode and show me the plan first".

Why learn

A good opening prompt saves hours: the AI anticipates the decisions (provider, storage, tone, what’s "out of scope") and asks what’s missing instead of guessing and building the wrong thing. You answer, approve the plan, and only then let it build — the Plan → Build cycle in action.

✓ Include in the prompt

  • ✓The source documents (by tag/attachment).
  • ✓The complete result (classify, anchor, draft).
  • ✓The safety rules (don't invent, don't send).

✗ Avoid

  • ✗Specify “use an in-memory vector store node with…”.
  • ✗Let the AI build without showing the plan first.
  • ✗Skip her clarifying questions.

Key concepts

Plan Mode

Plan before building.

Result

The "what," not the "how."

Attach docs

PDFs in the folder + tag.

Clarify

Answer the questions.

4

🔧 Building the two workflows

What it is

With the plan approved, the AI builds the nodes. The Workflow 1 (indexer) looks like this: manual trigger → code node with the document text → insertion into the vector store (with a data loader and character text splitter). The Workflow 2 (agent) looks like this: Gmail trigger (every 15 min, unread only) → classifier (support vs. not relevant) → AI agent with the vector store tool → Gmail draft node; the “not relevant” branch ends without replying.

🎯 Goal: populate the database and activate the agent in the right order.

steps (in order)
1. Construa os dois workflows conforme o plano.
2. Rode o Workflow 1 (indexador) manualmente UMA vez,
   para popular o vector store com as políticas.
3. Só depois, ATIVE o Workflow 2 (agente do e-mail).
4. Se algum nó der erro, me copie a mensagem e diga em qual nó —
   eu te devolvo a correção.

✅ How to verify: the indexer should finish without errors, and the vector store should be populated. Activate the agent only then — otherwise, it queries an empty knowledge base.

🐛 Layered debugging (real errors that show up)

In the build, two typical classifier errors: (1) the model property needed the structured format {mode, id/value} instead of plain text; (2) a parsing failure disappears when disable the default JSON response option of the classifier model node. The fix is always the same: copy the node's message and send it back to the AI with the location.

To read a node: on the left the inputs remain (previous nodes), in the middle the node, to the right the output in JSON.

Why learn

Watching the build and returning errors is the core vibe coding cycle: you don't fix nodes by hand; you describe the symptom. Seeing each node's I/O also teaches you the anatomy of a RAG pipeline — and how to confirm that the draft matches the source (e.g., the warranty terms in the draft match the policies PDF).

Key concepts

Order

Index before activating.

Return an error

Message + node.

Read I/O

Left side goes in, right side comes out.

Anchor

Draft matches the PDF.

5

🔑 Credentials (what AI DOESN'T do)

What it is

There's a clear boundary: AI builds the workflows, but you connects the credentials manually. There are two: the email account via Gmail OAuth (authorizes n8n to read and draft) and the AI API key (OpenAI, used by both chat models and embeddings). Never put secrets in chat.

What is it?OAuth — a way to authorize an app to act on your behalf without hand over your password; you click "allow" and the app gets revocable access. API key — a machine password that identifies and bills AI usage; stored in the tool’s credentials, not in the code or chat.

🤖 AI does puts together the workflow nodes and logic writes the system prompt and filters 🙋 You do (hands-on) connects Gmail through OAuth (click "allow") paste the API key into the credential (never in chat)

Illustrative diagram — the AI doesn't have (and shouldn't have) your credentials. Connecting OAuth and pasting the key is your job, in the tool.

Why learn

Knowing what no delegating is half of the security discipline. Credential mapping and authorization are up to you; this protects your data and keeps the secret out of the AI's context—a golden rule that comes up throughout the production track.

Key concepts

Gmail OAuth

Authorize without a password.

AI key

Chat + embeddings.

You connect

AI doesn't have the secret.

Never in chat

The secret stays in the tool.

6

🧪 Tests: refund, warranty, out of scope

What it is

Test with real cases covering the three behaviors: an email from return (should respond with the right policy), one of guarantee (the answer must match the PDF term by term) and a out of scope — a “want to have dinner tomorrow?” — which should be classified as not relevant e not receive a response. Green ≠ correct: only these tests reveal whether the RAG is truly grounding its answers.

🎯 Goal: trigger all three scenarios and check the behavior.

test plan
Envie 3 e-mails de teste para a caixa conectada:

A) "Qual é o prazo para devolver um produto?"      → deve rascunhar a política de devolução
B) "Meu aparelho parou; ainda está na garantia?"   → resposta deve bater com o PDF de garantia
C) "Bora jantar amanhã às 20h?"                     → classificar como "não relevante", NÃO responder

Rode o agente e me diga: ele ancorou nas políticas?
Algum número (ex.: "30 dias") confere com o documento?
Ele recusou o caso C sem inventar?

✅ How to verify: A and B produce a draft faithful to the PDF (check the numbers — "30 days" ≠ "one year"); C doesn't produce an answer. If C was answered, adjust the classifier.

✓ Signs it’s correct

  • ✓The warranty terms match the PDF word for word.
  • ✓The social email is marked "not relevant" and ends.
  • ✓Numbers (deadlines, amounts) match the source.

✗ Warning signs

  • ✗A “polished” answer with an invented deadline.
  • ✗The agent replies to the dinner invitation.
  • ✗Trusting the “green” status without reading the draft content.

Why learn

The out-of-scope case is the most important: it proves that the agent refuses to make things up. An agent that answers everything is dangerous; one that knows how to say "that’s not in my knowledge base" is trustworthy. Edge cases reveal this better than any "green" run.

Key concepts

3 scenarios

Returns, warranty, social.

Check facts

Numbers vs. PDF.

Refuse

Out of scope = silence.

Green ≠ correct

Read the content.

7

✨ The 6 enhancements applied

What it is

Six incremental improvements, requested in natural language and tested one at a time — iterate in layers in practice. The first three address logic/errors (fallback, time filter, ignore automated messages); the last three address output quality (tone, customer name, confidence indicator).

1fallback 2time filter 3ignores automations 4brand voice 5customer name 6trust logic / error output quality

Illustrative diagram — one layer at a time, testing each one. If something breaks, you know exactly which change caused it.

🎯 Enhancement 1 — Not-found fallback: if the knowledge base doesn't have the answer, don't make one up.

prompt (copy and run)
Quando a base de conhecimento NÃO tiver a resposta, o agente não deve inventar.
Faça o agente emitir um marcador ("política encontrada" / "política não encontrada");
um nó de código lê esse marcador, um nó IF ramifica, e no caso "não encontrada"
crie um rascunho educado de "vamos pesquisar e retornamos em breve".
Antes de mudar, me pergunte o limiar de match e o texto do fallback.

✅ How to verify: ask a question outside the knowledge base (e.g., "Do you ship internationally?"). It should go to the research draft—not an invented answer.

🎯 Enhancements 2 and 3 — Filters: only recent emails; ignore automated ones.

prompts (one at a time)
[2] Processe apenas e-mails recebidos há menos de <10> minutos.
    (a IA descobre a sintaxe de busca do Gmail e adiciona um filtro
     "newer than" no próprio gatilho, sem nó extra.)

[3] Ignore e-mails automáticos: fora-do-escritório, notificações de entrega,
    newsletters e remetentes no-reply / postmaster / bounce / marketing.
    Adicione um nó de código que marque isAutomated + motivo e ramifique
    para PULAR esses casos.

✅ How to verify: there are three gates in sequence — automatic? → is it support? → does it have a policy? Watch out for a classic bug: the filter may let a no-reply@ if the code reads the wrong sender field.

🎯 Enhancements 4, 5, and 6 — Quality: tone, name, and confidence.

prompts (one at a time)
[4] Ajuste o tom para <amigável, prestativo, descontraído> — "experto, mas
    nunca condescendente". Atualize TANTO o system prompt do agente QUANTO o
    rascunho de "vamos pesquisar". Varie as despedidas.

[5] Personalize com o nome do cliente: um nó de código extrai o nome da
    assinatura ("Abraço, João" / "Obrigada, Sara") e usa na saudação,
    com fallback "Olá" quando não houver assinatura.

[6] Adicione um indicador de confiança (uso interno): o agente marca
    alto/médio/baixo conforme o match (alto > 0.8, médio 0.6–0.8, baixo < 0.6);
    um nó de código monta um selo HTML (verde/amarelo/vermelho) anexado ao
    rascunho, só para revisão interna.

✅ How to verify: the tone changes in both drafts (reply and fallback); an email signed "Best, João" gets a reply starting with "Hi João"; the confidence badge appears in the draft. Test each one before before asking for the next one.

Why learn

The enhancements show the stair-step real: each improvement is a request in Portuguese, tested in isolation. Notice how the AI sometimes does more than you asked (reorganizes nodes, rewrites the false branch) — that’s why you review each step. Anchor each request in terms of the desired behavior, not the implementation.

Key concepts

Layers

One improvement at a time.

3 gates

Automatic? Support? Policy?

Confidence

High/medium/low badge.

Review

AI does extra work; check it.

8

✅ Final verification & checklist

What it is

Before declaring “done,” go through the objective checklist. Defining what “done” means prevents the endless loop of “just one more improvement” — and gives you a clear criterion for safely closing the project.

🎯 Goal: confirm that the project is ready and save a backup.

checklist + backup
[ ] O indexador popula o vector store sem erro.
[ ] E-mails de suporte são classificados como suporte.
[ ] As respostas ancoram nas políticas (números conferem com o PDF).
[ ] Fora de escopo NÃO é respondido (recusa inventar).
[ ] Automáticos e antigos são ignorados (3 portões funcionando).
[ ] Tom, nome e selo de confiança aparecem no rascunho.
[ ] Tudo fica como RASCUNHO; humano aprova o envio.

Backup: "Exporte os dois workflows como JSON para eu guardar."

✅ How to verify: all items checked + the exported JSON saved. If an item fails, go back to the corresponding topic and iterate only on that layer.

Why learn

"Done" is a decision, not a feeling. The checklist makes verification repeatable, and the export JSON is your backup — if a future change breaks something, you restore the version that worked. It’s the same “back up before changing things” habit that applies to every project in this track.

A customer asks something that isn’t there in the policies. What is the behavior correct of the agent?

📌 Module Summary

✓
Scope — read policies → classify → draft; draft + human approval; don’t make things up.
✓
Architecture — two workflows: indexer (learns once) + agent (answers every time), connected through the vector store.
✓
Opening prompt — a broad request in Plan Mode; the AI asks questions and proposes a plan.
✓
Build & credentials — index before activating; connect Gmail OAuth and the AI key (never in chat).
✓
Tests — returns, warranty, and out of scope; green ≠ correct; numbers match the PDF.
✓
6 enhancements — fallback, time filter, ignore automated messages, tone, name, confidence — in layers.
✓
Ready — a clear checklist + backup (JSON export) wrap up the project.

Next Module:

5.2 — Hosted Agents (Scheduled + Webhook): move the agent off your machine and into the cloud.