From d66aed35d6c49ee0b4b1042b4f2d33f9791cfd2a Mon Sep 17 00:00:00 2001 From: gleb Date: Sat, 13 Dec 2025 14:50:46 +0300 Subject: [PATCH] init --- .env | 6 + .env.example | Bin 0 -> 586 bytes .idea/.gitignore | 8 ++ .../inspectionProfiles/profiles_settings.xml | 6 + .idea/misc.xml | 7 ++ .idea/modules.xml | 8 ++ .idea/new-planet-ai-agents.iml | 10 ++ CLAUDE.md | 67 +++++++++++ README.md | 107 ++++++++++++++++++ pyproject.toml | 62 ++++++++++ requirements.txt | 22 ++++ 11 files changed, 303 insertions(+) create mode 100644 .env create mode 100644 .env.example create mode 100644 .idea/.gitignore create mode 100644 .idea/inspectionProfiles/profiles_settings.xml create mode 100644 .idea/misc.xml create mode 100644 .idea/modules.xml create mode 100644 .idea/new-planet-ai-agents.iml create mode 100644 CLAUDE.md create mode 100644 README.md create mode 100644 pyproject.toml create mode 100644 requirements.txt diff --git a/.env b/.env new file mode 100644 index 0000000..98d6023 --- /dev/null +++ b/.env @@ -0,0 +1,6 @@ +GIGACHAT_CLIENT_ID=your-client-id +GIGACHAT_CLIENT_SECRET=your-client-secret +GIGACHAT_AUTH_URL=https://ngw.devices.sberbank.ru:9443/api/v2/oauth +GIGACHAT_BASE_URL=https://gigachat.devices.sberbank.ru/api/v1 + +REDIS_URL=redis://localhost:6379/0 diff --git a/.env.example b/.env.example new file mode 100644 index 0000000000000000000000000000000000000000..da187732b6d4f04ee8c7a92bc405e242dff11881 GIT binary patch literal 586 zcma))TWi8V5QWckp#P!ZvrTVUD)b>$tASvPm%d86h9oo?$wo{6y!Km_;)5-+?Cj3Y z&Y3f3ce`omQhnu06|18RTXPcVO`$v@Au}K{z)mz{7jf3paOZ{U>Pg=!wNj;~j0&(4 zEkJ3qo1cL(2CbtJcJdFF1=Ua^0r?cKKvVJuFr0!Ffs}Ex)>2k&`HTfUe(4HMiPms4 ztQOzugI$GYi~&W(-Qsy4EeW#9x7&o#gS1POhWBd8A-Dwar28a~U1; zxS_VE1}`;&`y51z?= + + + \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml new file mode 100644 index 0000000..f4a3d9c --- /dev/null +++ b/.idea/misc.xml @@ -0,0 +1,7 @@ + + + + + + \ No newline at end of file diff --git a/.idea/modules.xml b/.idea/modules.xml new file mode 100644 index 0000000..c5a5a5d --- /dev/null +++ b/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/.idea/new-planet-ai-agents.iml b/.idea/new-planet-ai-agents.iml new file mode 100644 index 0000000..836f2f3 --- /dev/null +++ b/.idea/new-planet-ai-agents.iml @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..0dfa2ed --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,67 @@ +# Инструкции для Claude AI + +## Контекст проекта + +Это репозиторий **AI-агентов** для проекта "Новая Планета" — визуальное расписание для детей с расстройством аутистического спектра (РАС). + +## Архитектура + +Проект разделен на три репозитория: +1. **new-planet-backend** — FastAPI backend +2. **new-planet-android** — Android приложение +3. **new-planet-ai-agents** (текущий) — Python агенты и скрипты + +## Структура + +- `agents/` — ИИ-агенты (GigaChat клиент, генератор расписаний, чат-агент) +- `prompts/` — промпты для LLM (персона "Земля", генерация расписаний) +- `services/` — сервисы (управление токенами, Redis кэш, обработка изображений) +- `models/` — Pydantic модели данных +- `scripts/` — утилиты (генерация данных, анализ использования) + +## Основные компоненты + +### GigaChatClient +Асинхронный клиент для работы с GigaChat API. Использует TokenManager для получения токенов. + +### ScheduleGenerator +Генерирует расписания для детей с РАС на основе возраста, предпочтений и даты. + +### ChatAgent +ИИ-агент "Планета Земля" для общения с детьми и родителями. Использует Redis для хранения контекста. + +### RecommendationEngine +Простая рекомендательная система на основе TF-IDF (MVP-1). + +## Интеграция с Backend + +Backend использует эти агенты через импорты: +```python +from agents.schedule_generator import ScheduleGenerator +from agents.chat_agent import ChatAgent +``` + +## Переменные окружения + +- `GIGACHAT_CLIENT_ID` — ID клиента GigaChat +- `GIGACHAT_CLIENT_SECRET` — секрет клиента +- `REDIS_URL` — URL Redis для кэширования + +## Стиль кода + +- Python 3.11+ +- Async/await для всех I/O операций +- Pydantic для валидации +- Type hints везде +- Docstrings для всех публичных методов + +## Тестирование + +Используется pytest с asyncio. Моки для внешних API (GigaChat, Redis). + +## Важные замечания + +- GigaChat токены обновляются автоматически +- Контекст разговоров хранится в Redis с TTL 24 часа +- Промпты оптимизированы для детей с РАС (простой язык, короткие предложения) + diff --git a/README.md b/README.md new file mode 100644 index 0000000..298dcbb --- /dev/null +++ b/README.md @@ -0,0 +1,107 @@ +# Новая Планета - AI Agents (Python) + +ИИ-агенты и скрипты для проекта "Новая Планета" - визуальное расписание для детей с РАС. + +## Возможности + +- 🤖 **GigaChat интеграция** — работа с API для генерации расписаний +- 📊 **Обработка данных** — анализ прогресса детей +- 🧠 **ML модели** — рекомендательная система +- 🔧 **Скрипты автоматизации** — генерация контента, обработка изображений + +## Tech Stack + +- Python 3.11+ +- LangChain, OpenAI SDK (адаптер для GigaChat) +- Pydantic для валидации +- sentence-transformers, scikit-learn для ML +- aiohttp, redis-py для инфраструктуры + +## Установка + +```bash +pip install -r requirements.txt +# или +poetry install +``` + +## Настройка + +```bash +cp .env.example .env +# Заполните GIGACHAT_CLIENT_ID и GIGACHAT_CLIENT_SECRET +``` + +## Использование + +### Генерация расписания + +```python +from agents.gigachat_client import GigaChatClient +from agents.schedule_generator import ScheduleGenerator +from services.token_manager import TokenManager + +token_manager = TokenManager() +gigachat = GigaChatClient(token_manager) +generator = ScheduleGenerator(gigachat) + +schedule = await generator.generate( + child_age=7, + preferences=["рисование", "прогулка"], + date="2025-12-16" +) +``` + +### Чат с агентом + +```python +from agents.chat_agent import ChatAgent +from services.cache_service import CacheService + +cache = CacheService() +agent = ChatAgent(gigachat, cache) + +response, tokens = await agent.chat( + user_id=user_id, + message="Помоги составить расписание", + conversation_id="conv_123" +) +``` + +## Скрипты + +```bash +# Генерация тестовых данных +python scripts/generate_test_data.py --users 100 --schedules 500 + +# Анализ использования токенов +python scripts/analyze_usage.py --month 2025-12 + +# Экспорт промптов +python scripts/migrate_prompts.py export --file prompts.json +``` + +## Тестирование + +```bash +pytest tests/ -v +pytest --cov=agents --cov-report=html +``` + +## Структура + +- `agents/` — ИИ-агенты (GigaChat, генератор расписаний, чат) +- `prompts/` — промпты для LLM +- `services/` — сервисы (токены, кэш, обработка изображений) +- `models/` — Pydantic модели +- `scripts/` — скрипты автоматизации + +## Связанные репозитории + +- [Backend (Python/FastAPI)](https://github.com/your-org/new-planet-backend) +- [Frontend (Android)](https://github.com/your-org/new-planet-android) + +## Лицензия + +MIT License + diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..0e79d8d --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,62 @@ +[build-system] +requires = ["setuptools>=61.0", "wheel"] +build-backend = "setuptools.build_meta" + +[project] +name = "new-planet-ai-agents" +version = "0.1.0" +description = "ИИ-агенты и скрипты для проекта Новая Планета" +readme = "README.md" +requires-python = ">=3.11" +license = {text = "MIT"} +authors = [ + {name = "Новая Планета", email = "team@novayaplaneta.ru"} +] + +dependencies = [ + "langchain>=0.1.0", + "openai>=1.0.0", + "pydantic>=2.0.0", + "python-dotenv>=1.0.0", + "sentence-transformers>=2.2.0", + "scikit-learn>=1.3.0", + "pandas>=2.0.0", + "numpy>=1.24.0", + "aiohttp>=3.9.0", + "redis>=5.0.0", + "Pillow>=10.0.0", +] + +[project.optional-dependencies] +dev = [ + "pytest>=7.4.0", + "pytest-cov>=4.1.0", + "pytest-asyncio>=0.21.0", + "jupyter>=1.0.0", + "black>=23.0.0", + "isort>=5.12.0", + "flake8>=6.0.0", + "mypy>=1.5.0", +] + +[tool.black] +line-length = 100 +target-version = ['py311'] + +[tool.isort] +profile = "black" +line_length = 100 + +[tool.mypy] +python_version = "3.11" +warn_return_any = true +warn_unused_configs = true +disallow_untyped_defs = false + +[tool.pytest.ini_options] +testpaths = ["tests"] +python_files = ["test_*.py"] +python_classes = ["Test*"] +python_functions = ["test_*"] +asyncio_mode = "auto" + diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..5723a2f --- /dev/null +++ b/requirements.txt @@ -0,0 +1,22 @@ +# Core +langchain +openai +pydantic>=2.0 +python-dotenv + +# AI/ML +sentence-transformers +scikit-learn +pandas +numpy + +# Utils +aiohttp +redis +Pillow + +# Dev +pytest +pytest-cov +pytest-asyncio +jupyter