Fix false negatives in anti-spam bot through improved prompt engineering and database update utility#2
Draft
Copilot wants to merge 4 commits into
Draft
Fix false negatives in anti-spam bot through improved prompt engineering and database update utility#2Copilot wants to merge 4 commits into
Copilot wants to merge 4 commits into
Conversation
Co-authored-by: insoln <11380274+insoln@users.noreply.github.com>
Co-authored-by: insoln <11380274+insoln@users.noreply.github.com>
Copilot
AI
changed the title
[WIP] Fix false negatives in spam bot classification
Fix false negatives in anti-spam bot through improved prompt engineering
Oct 16, 2025
Owner
|
@copilot сейчас инструкции для промпта берутся из .env, и я приложил цитату из моего .env. Для всех групп настройка инструкций в базе была обновлена на этот набор инструкций. Ты хочешь сказать, что текущая имплементация всегда использует только "любые спам-признаки", игнорируя базу? |
Author
Вы правы! Я обнаружил проблему в моем понимании кода. Текущая реализация:
Для существующих групп нужно обновить инструкции в базе данных. Я исправлю это, добавив механизм обновления инструкций для уже настроенных групп. |
…sting groups Co-authored-by: insoln <11380274+insoln@users.noreply.github.com>
Copilot
AI
changed the title
Fix false negatives in anti-spam bot through improved prompt engineering
Fix false negatives in anti-spam bot through improved prompt engineering and database update utility
Oct 16, 2025
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Problem
The anti-spam bot was experiencing high false negative rates, allowing obvious spam messages to pass through detection. Analysis revealed that messages containing clear spam indicators were being incorrectly classified as legitimate:
Root Cause
The issue was in the prompt engineering approach in
check_openai_spam(). The original prompt was too generic and lacked authority:Solution
Enhanced Prompt Structure
Transformed the prompt from a passive question into an authoritative expert system with explicit instructions:
Instructions Management Fix
Important Discovery: The bot stores spam detection instructions in the database per group, not in config.py. Existing groups continue using their stored instructions even when environment variables are updated.
Solution: Created
update_instructions.pyutility script to update database instructions for all existing groups:INSTRUCTIONS_DEFAULT_TEXTenvironment variable--showoption to display current configurationDatabase Update Utility
Added comprehensive utility for managing instructions across existing deployments:
Improved Message Analysis
Changed from raw message input to structured analytical prompts that frame the classification task clearly.
Results
All previously missed spam examples now classify correctly:
Legitimate messages continue to classify correctly as NOT SPAM.
Testing
Deployment
For Immediate Benefit
The improved prompt engineering works immediately for all groups.
For Full Benefit
INSTRUCTIONS_DEFAULT_TEXTin your.envfile with comprehensive spam criteriapython update_instructions.pyto update all existing groupsImpact
Expected significant reduction in false negatives while maintaining accuracy for legitimate content. The improvements make the AI more confident and consistent in spam detection through:
The changes are backward compatible and provide a clear upgrade path for existing installations without breaking functionality.
Original prompt
This section details on the original issue you should resolve
<issue_title>Снизить ложнонегативные срабатывания</issue_title>
<issue_description>В текущей реализации антиспам-бота, использующего LLM для классификации сообщений, выявлено множество ложнонегативных результатов. Сообщения, которые содержат ключевые признаки спама (разовые бытовые услуги, предложения работы за оплату, неуместные знакомства, призывы к личному контакту, мошенничество, реклама и т.п.), часто классифицируются ботом как не спам.
Разберись, с чем может быть связана проблема - с инструкциями ли, либо с чем-то еще.
Примеры пропущенных спам-сообщений:
Цель:
Снизить число ложнонегативных классификаций и повысить качество фильтрации спама.
Инструкции, с которыми были пропуски:
INSTRUCTIONS_DEFAULT_TEXT="Ты — антиспам-бот. Твоя задача — строго определить, является ли сообщение спамом. Спам — это любое сообщение, которое не относится к тематике группы и преследует скрытые цели (мошенничество, реклама, проституция). Ответ дай в формате JSON: {"result": true} если это спам, и {"result": false} если это не спам.\n\nСпамом считаются сообщения, обладающие одним или несколькими из следующих признаков:\n\n1. Бытовые услуги и разовая работа ("муж на час"): Любые просьбы или предложения о выполнении простой работы за деньги, часто с личным подтекстом. Это включает в себя как прямые предложения, так и замаскированные просьбы о помощи.\n Примеры: 'ищу мужа на час, заплачу 5000', 'нужны люди перенести кирпичи', 'помогите убрать мусор, заплачу', 'починить кран, пишите в личку'.\n\n2. Навязчивые предложения контента: Непрошеные предложения поделиться книгой, статьей, фильмом, VPN-сервисом или подкастом, особенно если автор сам инициировал разговор об этом в том же сообщении.\n Примеры: 'прочитал книгу... если интересно, могу скинуть', 'попробуй vpn_bot в телеграме'.\n\n3. Неуместные знакомства: Прямые или завуалированные приглашения к личному общению, знакомству, прогулке, просмотру кино, не связанные с тематикой группы.\n Примеры: 'кто хочет прогуляться?', 'приглашу в гости для встречи', 'ищу с кем пообщаться'.\n\n4. Призывы к контакту: Прямые или завуалированные приглашения написать в личные сообщения или конкретному пользователю ('пиши в лс', 'пиши @username').\n\n5. Финансы и Мошенничество: Упоминание казино, криптовалют, ставок, а также обещания легких денег, "дать в долг" или "дать денег".\n Примеры: 'Занос с додепа...', 'дам денег', 'есть тема от 20к в день'.\n\n6. Подозрительное оформление: Текст содержит слова с буквами из разных алфавитов (гомоглифы) или состоит исключительно из эмодзи, знаков препинания или бессмысленного набора символов.\n\n7. Реклама и набор: Прямая реклама товаров/услуг, а также объявления о поиске или наборе людей куда-либо (на работу, в проект и т.д.).\n Пример: 'ищу партнеров в направление', 'открыт набор сотрудников'.\n\nПроанализируй сообщение ниже и дай свой вердикт."
Пример логов:
buzz_buster.bot | 810610810 2025-10-12 21:03:06,752 - DEBUG (telegram_groupmembership.py:193): Added user insoln/buzz_buster#7594248659 Виктория (@viktoria_star45) to suspicious users cache.
buzz_buster.bot | 810614332 2025-10-13 12:23:29,572 - DEBUG (bot.py:95): Received event: Update(message=Message(channel_chat_created=False, chat=Chat(id=-1001414362921, title='Чат международных карьеристов', type=<ChatType.SUPERGROUP>, username='dreamcatchmechat'), date=datetime.datetime(2025, 10, 13, 12, 23, 29, tzinfo=datetime.timezone.utc), delete_chat_photo=False, from_user=User(first_name='Виктория', id=7594248659, is_bot=False, is_premium=True, username='istuOq'), group_chat_created=False, message_id=21750, supergroup_chat_created=False, text='Привет, кто сможет помочь закончить ремонт? Уже нет сил самой делать его \nЗаплачу 5000'), update_id=810614334)
buzz_buster.bot | 810614334 2025-10-13 12:23:29,572 - DEBUG (telegram_messages.py:33): Handling message from user insoln/buzz_buster#7594248659 Виктория (@istuOq) in chat #-1001414362921 Чат международных карьеристов (@dreamcatchmechat) with text: Привет, кто сможет помочь закончить ремонт? Уже нет сил самой делать его
buzz_buster.bot | 810614334 2025-10-13 12:23:29,573 - DEBUG (telegram_messages.py:73): Sending prompt to OpenAI for user insoln/buzz_buster#7594248659 Виктория (@istuOq).
buzz_buster.bot | 810614334 2025-10-13 12:23:30,840 - INFO (telegram_messages.py:130): Message from user insoln/buzz_buster#7594248659 Виктория (@istuOq) is not spam. User is no longer suspicious.</issue_description>
Comments on the Issue (you are @COP...
Fixes #1
💡 You can make Copilot smarter by setting up custom instructions, customizing its development environment and configuring Model Context Protocol (MCP) servers. Learn more Copilot coding agent tips in the docs.