This automation is a full-fledged AI customer service agent for Gmail. The system automatically tracks incoming emails, determines whether they are customer support, responds to customer requests using the company's knowledge base, creates professional draft responses and notifies the team via Telegram about all requests.
API keys and services: Gmail OAuth2 - for monitoring and sending emails OpenAI API Key - for AI analysis and response generation (gpt-4o-mini)Pinecone API - for a vector knowledge base Telegram Bot API - for team notifications System architecture by blocks SECTION 1: MONITORING INCOMING EMAILS 1.1 Gmail Trigger — Track new emails Purpose: Automatically receives all new emails sent to corporate emails
Gmail Trigger settings:
Poll Times: EveryMinute (check every minute)Simple: false (advanced settings)Filters: {} (no filters - processes all emails)Credentials: your Gmail account What we get:
{
“id”: “1234567890abcdef”,
“threadID”: “thread_abc123",
“text”: “Good afternoon! I'm having a problem with order #12345... “,
“subject”: “Order problem”,
“from”: {
“value”: [{"address”: "client@example.com “, “name”: “Ivan Petrov"}]
},
“to”: {
“value”: [{"address”: "support@startduck.com “}]
},
“date”: “2024-01-15T 10:30:00 Z”
}
1.2 Set Content - Data preparation Purpose: Extracts key information from an email for further processing
Extracted fields:
{
“assignments”: [
{
“name”: “EmailBody”,
“value”: “= {{$json.text}}”,
“type”: “string”
},
{
“name”: “ThreadID”,
“value”: “= {{$json.threadID}}”,
“type”: “string”
},
{
“name”: “from”,
“value”: “= {{$json.to.value [0] .address}}”,
“type”: “string”
}
]
}
SECTION 2: CLASSIFICATION OF EMAILS 2.1 Custom support test - AI classification Purpose: Determines if the email relates to customer service
OpenAI settings:
Model: gpt-4o-miniJSON Output: true (structured response)Credentials: OpenAI account 6System prompt:
Analyze the content of the following email to determine whether it is relevant to customer service.
Customer support topics include:
- Questions about order status, tracking, or changes
- Problems with damaged or defective products
- Refund or exchange requests
- Cancelling or changing a subscription
- Technical issues with products, website, or app
- Payment or billing inquiries
- Requests to speak to a customer service representative
The result is in JSON format: {"CustomerSupport”: true/false}
Classification examples:
Customer Support (true):
“My order didn't arrive, where is it?” “Your app doesn't work” “I want to return an item” “Payment issues” Not Customer Support (false):
“Cooperation offer” “Vacancy resume” “Marketing offer” “Spam or ads” 2.2 Verification — Result Routing Purpose: Sends emails to the appropriate processing flow
Switch conditions:
Output 0 “Customer Support”: $JSON.message.content.CustomerSupport === trueOutput 1 “Not Customer Support”: $JSON.message.content.CustomerSupport === falseSTEP 3: NON-SUPPORT TREATMENT 3.1 If not custom support - Telegram notification Purpose: Notifies the team about non-support emails
Telegram settings:
Chat ID: (your chat id)Credentials: Telegram accountNotification format:
You received a new Email at 2:30pm with this content:
[Email text]
Why do you need this:
Control all incoming emails Redirecting commercial offers Handling HR requests Spam and spam detection SECTION 4: AI CUSTOMER SUPPORT AGENT 4.1 Custom Support Agent - Main AI Agent Purpose: Chief AI agent that processes customer requests and creates professional answers
Connected components:
OpenAI Chat Model (main language model)Vector Store Tool (access to the knowledge base)CreateDraft (creating drafts in Gmail)System prompt (short version):
# Role in the system
You are a highly trained StartDuck customer service employee.
# Task description
1. Analyze the customer's incoming email
2. Use the CustomerSupportDocs tool to find relevant information
3. Create a draft response using the CreateDraft tool
4. Provide a short summary of the answer
# Response requirements
- Responds directly to the customer's request
- A polite and professional tone
- Signature: “Artem, StartDuck IT company”
# Required tools
- CustomerSupportDocs - for finding information in the knowledge base
- CreateDraft - for creating a draft in Gmail
Examples of request processing:
Request for order status:
Customer: “Ordered the product a week ago, when will it arrive?”
AI Agent:
1. Knowledgebase searches: “delivery times”
2. Finds: “7-10 business days, delays may occur”
3. Creates a draft: “Standard delivery is 7-10 days, your order is being prepared...”
4. Summary: “I informed you about delivery times and order status”
4.2 Vector Store Tool - Knowledge Base Access Purpose: Provides AI agents with access to the corporate knowledge base
Settings:
Name: CustomerSupportDocsDescription: “I have enough information about the company's policies and custom support protocols”Vector Store: Pinecone Vector StoreKnowledge base content:
Return and exchange policies Delivery times and conditions Product Technical Support Payment and invoice terms FAQ on popular questions Departmental contact information 4.3 Pinecone Vector Store - Vector Knowledge Base Purpose: Stores and indexes documents for semantic search
Settings:
Pinecone Index: the name of your Pinecone indexNamespace: CustomerSupport (support data isolation)Credentials: your PineconeAPI account4.4 CreateDraft — Creating Gmail Drafts Purpose: Automatically creates draft responses in Gmail for review and submission
Gmail Tool settings:
Resource: draftSubject: {{$fromAI (“subject”)}} (AI-generated theme)Message: {{$fromAI (“EmailBody”)}} (AI-generated text)Thread ID: {{$ ('Set Content') .item.Json.ThreadID}} (link to the original email)Send To: {{$ ('Set Content') .item.json.from}} (customer address)The advantages of drafts:
A person can check the answer before sending it The ability to make changes if necessary Preserving the context of the conversation Контроль качества ответов РАЗДЕЛ 5: УВЕДОМЛЕНИЯ И МОНИТОРИНГ 5.1 Ответ - Уведомление о созданном черновике Назначение: Уведомляет команду в Telegram о созданном черновике ответа
Настройки:
Chat ID: ваш чат айдиText: {{ $json.output }} (резюме от AI агента)Формат уведомления:
Создан черновик ответа клиенту:
Проблема: Вопрос о статусе заказа
Решение: Проинформировал о сроках доставки (7-10 дней) и статусе заказа
Черновик готов к отправке в Gmail
РАЗДЕЛ 6: УПРАВЛЕНИЕ БАЗОЙ ЗНАНИЙ 6.1 On form submission - Загрузка документов Назначение: Веб-форма для загрузки новых документов в базу знаний
Настройки формы:
Form Title: "База знаний"Form Description: "Загрузите документ"Field Type: fileStatus: disabled (отключена в текущей конфигурации, включите её только когда нужно загрузить документ)6.2 Default Data Loader → Character Text Splitter → Pinecone Vector Store1 Назначение: Обрабатывает загруженные документы и добавляет в векторную базу
Процесс обработки:
Default Data Loader - читает загруженные файлыCharacter Text Splitter - разбивает на управляемые фрагментыEmbeddings OpenAI1 - создает векторные представленияPinecone Vector Store1 - сохраняет в базу знанийСхема подключений нод Основной поток обработки: Gmail Trigger → Set Content → Проверка на кастомер саппорт → Проверка Поток службы поддержки: Проверка (Customer Support) → Агент кастомер саппорт → Ответ Поток не-поддержки: Проверка (Not Customer Support) → Если не кастомер саппорт AI подключения агента: OpenAI Chat Model → Агент кастомер саппорт Vector Store Tool → Агент кастомер саппорт createDraft → Агент кастомер саппорт База знаний: Pinecone Vector Store + Embeddings OpenAI → Vector Store Tool Управление контентом: On form submission → Default Data Loader → Character Text Splitter → Pinecone Vector Store1 Необходимые сервисы и их настройки Настройка Gmail: Создайте корпоративный Gmail аккаунт для поддержки Настройте OAuth2 доступ для чтения и создания писем Убедитесь в активации Gmail API Настройка Pinecone: Создайте индекс Используйте namespace "customerSupport" для изоляции Настройте векторные размерности (1536 для OpenAI embeddings) Настройка Telegram: Создайте бота через @BotFather Создайте группу/канал для команды поддержки Получите ваш Chat ID Подготовка базы знаний: Соберите все документы политик компании FAQ по продуктам и услугам Returns and Exchanges Instructions Departmental contact information System capabilities Automatic processing: 24/7 monitoring - tracking all incoming emailsSmart classification - separating support requests from othersContextual responses - use of the corporate knowledge baseProfessional drafts - ready to send answersAI capabilities: Semantic search - finding relevant information in the databaseUnderstanding the context - analysis of the nature of the client's problemGenerating answers - creating personalized solutionsMaintaining the tone - courteous and professional styleQuality control: Drafts instead of auto-sending - person checks before shippingTeam notifications - full transparency of the processLink to original emails - maintaining the context of the correspondenceMonitoring all types of emails - nothing goes unnoticedSystem application For customer support: Save time - AI prepares draft answers automaticallyConsistency of answers - use of the corporate knowledge baseQuick response - instant notifications about new requestsScalability - processing an unlimited number of emailsFor small businesses: Professional level - high-quality answers even without a large teamReducing the load - AI takes care of routine workQuality control - an opportunity to check every answerTraining new employees - knowledge base as a source of standardsFor large companies: Standardization of processes - common approaches to all requestsShorter response times - from hours to minutesInquiries analytics - data on the types and frequency of requestsScaling support - one agent = several employeesThe result of the system What happens is: Automated support with quality controlProfessional answers to customers based on corporate standardsFull transparency of the process via Telegram notificationsSave team time by 70-80% while maintaining qualityScalable solution for business growthPerformance metrics: Classification time: instantly (AI analysis)Response creation time: 30-60 secondsClassification accuracy: 95% + correct definition of the type of letterQuality of answers: compliance with corporate standardsAdvantages over manual processing: Speed - seconds instead of minutes to analyze a letterConsistency - same quality for all customersAccessibility - works around the clock without breaksScalability - handles any volume of emailsAccuracy - uses relevant information from the knowledge baseROI and business indicators: Savings on wages - reducing the workload on the support teamSpeeding up responses - increasing customer satisfactionReducing errors - standardized answers from the knowledge baseService improvement - professional level even outside of office hoursThis system turns Gmail into an intelligent help desk platform with an AI agent who works like an experienced specialist!