ai-assistant-eduflow
Health Uyari
- No license — Repository has no license file
- Description — Repository has a description
- Active repo — Last push 0 days ago
- Low visibility — Only 5 GitHub stars
Code Gecti
- Code scan — Scanned 12 files during light audit, no dangerous patterns found
Permissions Gecti
- Permissions — No dangerous permissions requested
This multi-agent AI assistant is designed for the EduFlow online learning platform. It automatically processes student queries via Telegram and MAX Messenger, handling tasks like FAQ answering, course information retrieval, CRM integration, and payment processing.
Security Assessment
Overall Risk: Low. The automated code scan of 12 files found no dangerous execution patterns and noted that no dangerous permissions are requested. However, because this tool is designed for production use and integrates directly with external services, it inherently makes external network requests. It communicates with third-party APIs including OpenAI, YandexGPT, Bitrix24 CRM, and messaging platforms. This means it actively processes and transmits potentially sensitive data, such as student contact details, payment statuses, and CRM records. The documentation notes built-in protections against prompt injection and XSS, and claims to use structured logging with PII (Personally Identifiable Information) masking, which are excellent security practices. As with any tool connecting to external APIs, you must ensure you manage your own API keys securely via environment variables rather than hardcoding them.
Quality Assessment
The project demonstrates strong engineering hygiene and is actively maintained, with its last push occurring today. It features an impressive testing setup (170 tests with 84% coverage) and utilizes CI/CD pipelines for testing, security, and Docker builds. The primary concerns are regarding community adoption and licensing. It currently has low visibility with only 5 GitHub stars, meaning it has not been broadly vetted by the open-source community. Additionally, the rule-based scan detected a missing license file, though the README badge claims it is MIT licensed. Until a formal LICENSE file is added to the repository, the legal terms of use remain technically ambiguous.
Verdict
Use with caution — the code appears safe and well-built, but you should verify the licensing and be mindful of external data transmissions before integrating it into a production environment.
Production-ready multi-agent AI assistant with RAG, MCP server, and CRM integration. Reference implementation. Telegram/MAX Messenger, Bitrix24, ChromaDB, OpenAI/YandexGPT. 170 tests, 84% coverage.
EduFlow AI Assistant
AI-ассистент для платформы онлайн-обучения EduFlow. Автоматически отвечает на вопросы студентов, предоставляет информацию о курсах, обрабатывает платежи, эскалирует сложные запросы к живым преподавателям.
170 тестов | 84% coverage | Production-Ready
Возможности
- Многоагентная система с классификацией запросов
- Поддержка OpenAI и YandexGPT (Protocol abstraction)
- RAG с ChromaDB для базы знаний (200+ статей)
- Интеграция с Bitrix24 CRM (статусы сделок, контакты, история)
- Мультиканальность: Telegram + MAX Messenger (через Wappi, различение по profile_id)
- Структурированное логирование JSON (маскирование PII)
- Защита от prompt injection, XSS, SQL injection
- Асинхронная архитектура (FastAPI + asyncpg + asyncio)
- Docker + nginx + PostgreSQL 15
- GitHub Actions CI/CD (тесты, security, Docker build)
Архитектура
flowchart TD
A["Входящее сообщение\n(Telegram / MAX Messenger)"] --> B["Wappi Webhook\nchannel detection, validation,\ndeduplication, user mapping"]
B --> C["Orchestrator\nFAQ short-answer check"]
C --> D["ClassifierAgent\nrule-based + LLM classification"]
D -->|"~15%"| E["TypicalAgent\ngreeting / thanks / confirmations"]
D -->|"~50%"| F["CourseAgent\ncourse info + deal status\nfrom Bitrix24"]
D -->|"~5%"| G["PlatformAgent\ntechnical support\nRAG knowledge base"]
D -->|"~30%"| H["ESCALATE\ncomplex queries\nlive instructor"]
E --> I["Response via Wappi API"]
F --> I
G --> I
H --> I
Компоненты
| Компонент | Назначение |
|---|---|
| Orchestrator | Main message routing engine |
| ClassifierAgent | Message type detection (rule-based + LLM fallback) |
| TypicalAgent | FAQ templates, greetings, confirmations |
| CourseAgent | Course enrollment, payment status (Bitrix24) |
| PlatformAgent | Platform FAQ, technical help (RAG) |
| LLMClient | Protocol abstraction for OpenAI/YandexGPT |
| VectorDB | ChromaDB with OpenAI embeddings |
| BitrixClient | CRM integration (deals, contacts, stages) |
| WappiIncomingHandler | Webhook parsing + deduplication |
| WappiOutgoingHandler | Message sending via Wappi API |
Требования
- Python 3.11+
- PostgreSQL 15+
- Docker & Docker Compose (для продакшена)
- API ключи: OpenAI, YandexGPT (опционально), Wappi, Bitrix24
Быстрый старт
1. Клонирование и подготовка
git clone https://github.com/your-org/ai_assistant_eduflow.git
cd ai_assistant_eduflow
python -m venv .venv
source .venv/bin/activate # или .venv\Scripts\activate на Windows
pip install -r requirements.txt
2. Конфигурация
cp deployment/.env.example .env
# Отредактировать .env:
# - OPENAI_API_KEY или YANDEX_API_KEY (обязательно)
# - POSTGRES_DSN (по умолчанию: postgresql+asyncpg://postgres:postgres@localhost:5432/ai_assistant_eduflow)
# - WAPPI_API_TOKEN (для Telegram/WhatsApp)
# - BITRIX24_WEBHOOK_URL (для CRM интеграции)
3. База данных
createdb ai_assistant_eduflow
alembic upgrade head
4. Запуск
python -m uvicorn app:app --reload
# http://localhost:8000
# http://localhost:8000/docs (Swagger UI)
# http://localhost:8000/health
5. Тесты
pytest tests/ -v
pytest tests/ --cov=. --cov-report=html
Deployment (Docker)
docker-compose -f docker-compose.prod.yml up -d
curl http://localhost/health
Сервисы
| Сервис | Порт | Назначение |
|---|---|---|
| webhook | 8000 | FastAPI приложение |
| db | 5432 | PostgreSQL (внутренний) |
| nginx | 80, 443 | Reverse proxy + SSL |
MCP Server
EduFlow предоставляет MCP-сервер (Model Context Protocol), который даёт AI-ассистентам доступ к базе знаний и CRM через стандартный протокол.
Quick Start
# Локальный запуск (stdio — для Claude Code / Cursor)
python -m mcp_server.server
# Docker (SSE — для сетевого доступа)
docker compose -f docker-compose.prod.yml up mcp-server
Подключение к Claude Code
Файл .mcp.json в корне проекта автоматически подхватывается Claude Code:
{
"mcpServers": {
"eduflow": {
"command": "python",
"args": ["-m", "mcp_server.server"]
}
}
}
Доступные инструменты
| Tool | Описание |
|---|---|
search_knowledge_base |
Поиск по базе знаний EduFlow (RAG) |
get_deal |
Получить информацию о сделке из Bitrix24 CRM |
find_deals_by_phone |
Найти сделки по номеру телефона |
Пример использования
> search_knowledge_base("Как сбросить пароль?")
1. Если вы забыли пароль, нажмите на кнопку 'Забыли пароль?'
на странице входа. Вам будет отправлено письмо со ссылкой...
2. Для восстановления пароля потребуется доступ к электронной
почте, с которой вы регистрировались...
LangChain Pipeline
Проект содержит две параллельные реализации обработки сообщений:
| Пайплайн | Описание | Переключение |
|---|---|---|
| Original (по умолчанию) | Собственная оркестрация, прямые вызовы OpenAI API | PIPELINE_MODE=original |
| LangChain | LangChain Retriever + Chains, тот же RAG и промпты | PIPELINE_MODE=langchain |
Обе реализации возвращают одинаковый AgentResponse — переключение прозрачно для клиентов.
Langfuse Observability
Трейсинг LLM-вызовов через Langfuse:
- Original pipeline:
@observeдекораторы на Orchestrator, Classifier, CourseAgent, PlatformAgent - LangChain pipeline: автоматический CallbackHandler для всех chains и retrievers
- Dashboard: промпты, ответы, токены, латентность, стоимость — фильтрация по
pipelineиuser_id
LANGFUSE_ENABLED=true
LANGFUSE_PUBLIC_KEY=pk-...
LANGFUSE_SECRET_KEY=sk-...
API Endpoints
POST /webhook/wappi — Telegram/WhatsApp
{
"message_type": "text",
"from": "+79991234567",
"body": "Как начать изучать курс?",
"message_id": "msg_abc123xyz",
"timestamp": 1700000000,
"chat_id": "1234567890"
}
POST /webhook/bitrix — Bitrix24 CRM
События: ONCRMDEALUPDATE, ONCRMDEALSTAGECHANGE, ONCRMLEADUPDATE
GET /health
{"status": "ok", "database": "connected"}
GET /stats
{"total_messages": 1542, "total_escalations": 187}
Безопасность
- HMAC webhook validation — timing-safe token comparison
- Rate limiting — 100 req/min per IP (slowapi)
- Input sanitization — XSS, SQL injection, null bytes
- No stack trace leaks — global exception handler
- PII masking — логирование без телефонов и user_id
- Prompt injection protection — security gates в system prompts
- Strict typing — pyright strict mode, zero
any - Supply chain — pip-audit + gitleaks в CI
Переменные окружения
OPENAI_API_KEY=sk-...
YANDEX_API_KEY=...
BITRIX24_WEBHOOK_URL=https://...
WAPPI_API_TOKEN=...
POSTGRES_DSN=postgresql+asyncpg://...
Тестирование
170 тестов, 84% coverage, TDD подход.
pytest tests/ # все
pytest tests/unit/ -v # unit
pytest tests/integration/ -v # integration
pytest tests/e2e/ -v # e2e (full pipeline)
pytest --cov=. --cov-report=term-missing # coverage
CI/CD
| Workflow | Триггер | Что делает |
|---|---|---|
| test.yml | Push/PR | pytest, coverage, pyright |
| security.yml | Push/PR | bandit, gitleaks, pip-audit |
| docker-build.yml | Push main | docker build + smoke test |
Структура проекта
ai_assistant_eduflow/
├── agents/ # Multi-agent system
│ ├── orchestrator.py
│ ├── classifier.py
│ ├── typical_agent.py
│ ├── course_agent.py
│ └── platform_agent.py
├── integrations/ # External services
│ ├── llm_client.py
│ ├── bitrix_client.py
│ ├── vector_db.py
│ ├── database.py
│ ├── logging.py
│ └── wappi/
│ ├── incoming.py
│ ├── outgoing.py
│ └── templates.py
├── repositories/ # Database layer
│ ├── user_mapping.py
│ ├── dialog_log.py
│ └── analytics.py
├── routers/ # FastAPI routes
│ ├── wappi.py
│ ├── bitrix.py
│ └── admin.py
├── prompts/ # LLM prompts
├── utils/ # Sanitization, validation
├── tests/ # 170 tests (unit + integration + e2e)
├── alembic/ # Database migrations
├── deployment/ # Docker, nginx, .env
├── app.py
├── config.py
├── Dockerfile
└── docker-compose.prod.yml
Contributing
Commit Convention
feat(agents): add TypicalAgent for greetings
fix(db): handle concurrent user mapping updates
refactor(orchestrator): simplify message routing
test(classifier): add edge case tests
chore(docker): update base image
Workflow
git checkout -b feature/my-feature- Тесты первыми (TDD), код проходит все проверки
pytest tests/ --cov=. && ruff check . && pyright .git push origin feature/my-feature+ PR
License
MIT
Yorumlar (0)
Yorum birakmak icin giris yap.
Yorum birakSonuc bulunamadi