Gmail CS Agent - Automated AI support agent
.jpeg)
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-mini
- JSON Output: true (structured response)
- Credentials: OpenAI account 6
System 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 === true
- Output 1 “Not Customer Support”: $JSON.message.content.CustomerSupport === false
STEP 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 account
Notification 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: CustomerSupportDocs
- Description: “I have enough information about the company's policies and custom support protocols”
- Vector Store: Pinecone Vector Store
Knowledge 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 index
- Namespace: CustomerSupport (support data isolation)
- Credentials: your PineconeAPI account
4.4 CreateDraft — Creating Gmail Drafts
Purpose: Automatically creates draft responses in Gmail for review and submission
Gmail Tool settings:
- Resource: draft
- Subject: {{$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: file
- Status: 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 emails
- Smart classification - separating support requests from others
- Contextual responses - use of the corporate knowledge base
- Professional drafts - ready to send answers
AI capabilities:
- Semantic search - finding relevant information in the database
- Understanding the context - analysis of the nature of the client's problem
- Generating answers - creating personalized solutions
- Maintaining the tone - courteous and professional style
Quality control:
- Drafts instead of auto-sending - person checks before shipping
- Team notifications - full transparency of the process
- Link to original emails - maintaining the context of the correspondence
- Monitoring all types of emails - nothing goes unnoticed
System application
For customer support:
- Save time - AI prepares draft answers automatically
- Consistency of answers - use of the corporate knowledge base
- Quick response - instant notifications about new requests
- Scalability - processing an unlimited number of emails
For small businesses:
- Professional level - high-quality answers even without a large team
- Reducing the load - AI takes care of routine work
- Quality control - an opportunity to check every answer
- Training new employees - knowledge base as a source of standards
For large companies:
- Standardization of processes - common approaches to all requests
- Shorter response times - from hours to minutes
- Inquiries analytics - data on the types and frequency of requests
- Scaling support - one agent = several employees
The result of the system
What happens is:
- Automated support with quality control
- Professional answers to customers based on corporate standards
- Full transparency of the process via Telegram notifications
- Save team time by 70-80% while maintaining quality
- Scalable solution for business growth
Performance metrics:
- Classification time: instantly (AI analysis)
- Response creation time: 30-60 seconds
- Classification accuracy: 95% + correct definition of the type of letter
- Quality of answers: compliance with corporate standards
Advantages over manual processing:
- Speed - seconds instead of minutes to analyze a letter
- Consistency - same quality for all customers
- Accessibility - works around the clock without breaks
- Scalability - handles any volume of emails
- Accuracy - uses relevant information from the knowledge base
ROI and business indicators:
- Savings on wages - reducing the workload on the support team
- Speeding up responses - increasing customer satisfaction
- Reducing errors - standardized answers from the knowledge base
- Service improvement - professional level even outside of office hours
This system turns Gmail into an intelligent help desk platform with an AI agent who works like an experienced specialist!