### Ollama Setup: Install and Pull Model Source: https://context7.com/eslazarev/ai-wildberries-review-responder/llms.txt Installs Ollama and downloads a specified model (e.g., gemma3:4b) for local LLM inference. ```bash # Установка Ollama и загрузка модели curl -fsSL https://ollama.com/install.sh | sh ollama pull gemma3:4b ``` -------------------------------- ### Install and Initialize Yandex CLI Source: https://github.com/eslazarev/ai-wildberries-review-responder/blob/main/README.md Installs the Yandex Cloud CLI and initializes it for use. Follow the official documentation for detailed setup. ```bash curl https://storage.yandexcloud.net/yandexcloud-yc/install.sh | bash yc init ``` -------------------------------- ### Ollama Setup: Environment Variables Source: https://context7.com/eslazarev/ai-wildberries-review-responder/llms.txt Configures environment variables to point the application to a local Ollama instance, including the base URL, model name, and API key. ```bash # Настройка через переменные окружения export LLM__BASE_URL='http://localhost:11434/v1' export LLM__MODEL='gemma3:4b' export LLM__API_KEY='ollama' export WILDBERRIES__API_TOKEN='your_wb_token' ``` -------------------------------- ### Application Settings (settings.yaml) Source: https://github.com/eslazarev/ai-wildberries-review-responder/blob/main/README.md Example structure for the main application configuration file, settings.yaml. Defines settings for Wildberries API and LLM provider. ```yaml wildberries: base_url: "https://feedbacks-api.wildberries.ru" request_timeout: 10 batch_size: 10 check_every_minutes: 30 llm: model: "gpt://{FOLDER_ID}/aliceai-llm/latest" base_url: "https://rest-assistant.api.cloud.yandex.net/v1" temperature: 0.3 max_tokens: 600 instructions: "..." prompt_template: "..." timeout: 10 ``` -------------------------------- ### Install Dependencies Source: https://github.com/eslazarev/ai-wildberries-review-responder/blob/main/README.md Installs project dependencies using pip within a virtual environment. Ensure you have Python and venv set up. ```bash python -m venv .venv source .venv/bin/activate pip install -r requirements-dev.txt ``` -------------------------------- ### Deploy AI Responder with npm Source: https://github.com/eslazarev/ai-wildberries-review-responder/blob/main/README.md Installs dependencies and deploys the function to Yandex Cloud Functions. Requires WILDBERRIES__API_TOKEN to be set. ```bash npm install WILDBERRIES__API_TOKEN='your_wb_token' serverless deploy ``` -------------------------------- ### Local Ollama Configuration (Environment Variables) Source: https://github.com/eslazarev/ai-wildberries-review-responder/blob/main/README.md Example configuration for using a local Ollama model via environment variables. Sets the base URL, model name, and API key. ```bash export LLM__BASE_URL='http://localhost:11434/v1' export LLM__MODEL='gemma3:4b' export LLM__API_KEY='ollama' ``` -------------------------------- ### Yandex Cloud Deployment: Install Dependencies Source: https://context7.com/eslazarev/ai-wildberries-review-responder/llms.txt Installs the necessary Node.js dependencies for deploying with the Serverless Framework. ```bash # Установка зависимостей npm install ``` -------------------------------- ### Run with Local Cron Source: https://github.com/eslazarev/ai-wildberries-review-responder/blob/main/README.md Starts the review processing with an internal cron scheduler. The interval is determined by `wildberries.check_every_minutes`. Requires API tokens. ```bash export WILDBERRIES__API_TOKEN='your_wb_token' export LLM__API_KEY='your_llm_api_key' python -m src.entrypoints.docker_cron ``` -------------------------------- ### Configure and Use OpenAIClient for LLM Interactions Source: https://context7.com/eslazarev/ai-wildberries-review-responder/llms.txt Configure OpenAIClient with settings for YandexGPT, OpenAI, or Ollama. Instantiate the client with specific parameters like temperature, max tokens, system instructions, and timeout. Use generate_reply to get responses. ```python from src.infra.llm.openai_client import OpenAIClient from src.infra.config.settings import LLMRuntimeSettings # Конфигурация для YandexGPT yandex_config = LLMRuntimeSettings( api_key="your-iam-token-or-api-key", model="gpt://folder-id/aliceai-llm/latest", base_url="https://rest-assistant.api.cloud.yandex.net/v1" ) # Конфигурация для OpenAI openai_config = LLMRuntimeSettings( api_key="sk-your-openai-key", model="gpt-4o-mini", base_url="https://api.openai.com/v1" ) # Конфигурация для локальной Ollama ollama_config = LLMRuntimeSettings( api_key="ollama", # Любое непустое значение model="gemma3:4b", base_url="http://localhost:11434/v1" ) # Создание клиента llm_client = OpenAIClient( config=openai_config, temperature=0.3, max_tokens=600, instructions="Ты — вежливый сотрудник поддержки реселлера на Wildberries.", timeout=10 ) # Генерация ответа на промпт prompt = """Ответь на отзыв Wildberries в дружелюбном тоне. Full review payload: {"text": "Сумка отличная!", "productValuation": 5, "has_photos": true}""" reply = llm_client.generate_reply(prompt) print(reply) # "Благодарим за отзыв и приложенные фотографии! Рады, что сумка вам понравилась." ``` -------------------------------- ### Local Ollama Configuration (YAML) Source: https://github.com/eslazarev/ai-wildberries-review-responder/blob/main/README.md Example configuration for using a local Ollama model via settings.yaml. Sets the base URL, model name, and API key. ```yaml llm: base_url: "http://localhost:11434/v1" model: "gemma3:4b" api_key: "ollama" ``` -------------------------------- ### Docker Entrypoint: Cron Schedule Source: https://context7.com/eslazarev/ai-wildberries-review-responder/llms.txt Starts a blocking process that uses APScheduler to run review processing at a defined interval. Suitable for continuous operation within a container. ```python # Запуск с cron-расписанием (docker_cron) from src.entrypoints.docker_cron import main main() ``` -------------------------------- ### Initialize and Use WildberriesClient Source: https://context7.com/eslazarev/ai-wildberries-review-responder/llms.txt Shows how to initialize the WildberriesClient with settings and use its methods to fetch reviews and publish replies. Requires the settings object to be configured. ```python from src.infra.clients.wildberries import WildberriesClient from src.infra.config.settings import Settings # Инициализация клиента с настройками settings = Settings() wb_client = WildberriesClient(settings) # Получение списка неотвеченных отзывов reviews = wb_client.fetch_reviews() # Возвращает: List[Review] — список доменных объектов Review for review in reviews: print(f"ID: {review.id}") print(f"Текст: {review.text}") # JSON-сериализованный payload отзыва print(f"Сводка: {review.summary}") # Объединение text, pros, cons # Публикация ответа на конкретный отзыв wb_client.publish_reply( review_id="wb-123456", message="Благодарим за отзыв! Рады, что товар вам понравился." ) ``` -------------------------------- ### Initialize Application Components for Review Response Orchestration Source: https://context7.com/eslazarev/ai-wildberries-review-responder/llms.txt Initialize all necessary components for the main application logic, including settings, logger, Wildberries client, LLM client, prompt builder, and reply generator. This sets up the core pipeline for processing reviews. ```python from src.application.respond_on_reviews import respond_on_reviews from src.infra.clients.wildberries import WildberriesClient from src.infra.reply_generator import LLMReplyGenerator from src.infra.prompt import PromptBuilder from src.infra.llm.base import make_llm_client from src.infra.config.settings import Settings from src.infra.logger import init_logger # Инициализация всех компонентов settings = Settings() logger = init_logger() wildberries_client = WildberriesClient(settings) llm_client = make_llm_client(settings) prompt_builder = PromptBuilder(template=settings.llm.prompt_template) reply_generator = LLMReplyGenerator(prompt_builder, llm_client) ``` -------------------------------- ### Docker Entrypoint: Run Once Source: https://context7.com/eslazarev/ai-wildberries-review-responder/llms.txt Executes a single iteration of review processing and then exits. Suitable for one-off tasks. ```python # Разовый запуск (docker_once) from src.entrypoints.docker_once import run_once run_once() ``` -------------------------------- ### Deploy with Optional Parameters Source: https://github.com/eslazarev/ai-wildberries-review-responder/blob/main/README.md Deploys the application with optional environment variables for LLM API key and check interval. This allows customization during deployment. ```bash LLM__API_KEY='your_llm_api_key' WILDBERRIES__API_TOKEN='your_wb_token' serverless deploy WILDBERRIES__CHECK_EVERY_MINUTES='15' WILDBERRIES__API_TOKEN='your_wb_token' serverless deploy ``` -------------------------------- ### Load Application Settings with Settings Class Source: https://context7.com/eslazarev/ai-wildberries-review-responder/llms.txt Demonstrates how to load application settings using the Settings class, which supports environment variables, .env files, file secrets, and settings.yaml. Accesses Wildberries API and LLM provider configurations. ```python from src.infra.config.settings import Settings # Загрузка настроек с автоматическим поиском settings.yaml и .env settings = Settings() # Доступ к настройкам Wildberries API print(settings.wildberries.api_token) # Токен API Wildberries print(settings.wildberries.base_url) # https://feedbacks-api.wildberries.ru print(settings.wildberries.batch_size) # Количество отзывов за итерацию (по умолчанию 10) print(settings.wildberries.request_timeout) # Таймаут HTTP-запросов (по умолчанию 10 сек) print(settings.wildberries.check_every_minutes) # Интервал cron (по умолчанию 30 мин) # Доступ к настройкам LLM-провайдера print(settings.llm.api_key) # API-ключ LLM (опционально для YC Functions) print(settings.llm.model) # Идентификатор модели print(settings.llm.base_url) # URL API LLM-провайдера print(settings.llm.temperature) # Креативность ответа (по умолчанию 0.3) print(settings.llm.max_tokens) # Лимит токенов ответа (по умолчанию 600) print(settings.llm.instructions) # Системные инструкции для модели print(settings.llm.prompt_template) # Шаблон промпта для отзыва ``` -------------------------------- ### Deploy with Custom LLM API Key Source: https://github.com/eslazarev/ai-wildberries-review-responder/blob/main/README.md Deploys the function while specifying a custom LLM API key. Requires WILDBERRIES__API_TOKEN. ```bash LLM__API_KEY='your_llm_api_key' WILDBERRIES__API_TOKEN='your_wb_token' serverless deploy ``` -------------------------------- ### Run Linting, Testing, and CI Checks Source: https://github.com/eslazarev/ai-wildberries-review-responder/blob/main/README.md Executes static analysis, security checks, and unit tests using make commands. These are typically part of the continuous integration pipeline. ```bash make lint make test make ci ``` -------------------------------- ### Yandex Cloud Deployment: Basic Deploy Source: https://context7.com/eslazarev/ai-wildberries-review-responder/llms.txt Deploys the application to Yandex Cloud using Serverless Framework. Requires the Wildberries API token to be set as an environment variable. ```bash # Деплой с обязательным токеном Wildberries WILDBERRIES__API_TOKEN='your_wb_token' serverless deploy ``` -------------------------------- ### Create and Process WildberriesReview Object Source: https://context7.com/eslazarev/ai-wildberries-review-responder/llms.txt Illustrates the creation of a WildberriesReview object from raw data, accessing its computed properties, serializing it to a JSON payload, and converting it to a domain review entity. ```python from src.infra.clients.wildberries_dto import WildberriesReview, ProductDetails # Создание объекта отзыва из данных API review_data = { "id": "fb-001", "productId": "12345", "userName": "Иван", "productValuation": 5, "text": "Отличный товар, рекомендую!", "pros": "Быстрая доставка", "cons": "Нет инструкции", "createdDate": "2024-01-15T10:30:00Z", "language": "ru", "productDetails": { "productName": "Сумка женская", "brandName": "BrandX", "supplierName": "SupplierY" }, "photoLinks": [{"fullSize": "https://example.com/photo.jpg"}], "matchingSize": "Соответствует" } wb_review = WildberriesReview(**review_data) # Вычисляемые свойства print(wb_review.has_photos) # True (есть фотографии) print(wb_review.has_video) # False (нет видео) print(wb_review.summary) # "Отличный товар...\nБыстрая доставка\nНет инструкции" # Сериализация в JSON для промпта LLM json_payload = wb_review.to_source_payload() # {"id": "fb-001", "text": "...", "pros": "...", "has_photos": true, ...} # Преобразование в доменную сущность domain_review = wb_review.to_review() # Review(id="fb-001", text=, summary=) ``` -------------------------------- ### Build Contextualized Prompts with PromptBuilder Source: https://context7.com/eslazarev/ai-wildberries-review-responder/llms.txt Use PromptBuilder to create prompts from review data. It incorporates a custom template and the full review JSON payload for richer context, allowing LLMs to consider all review details. ```python from src.infra.prompt import PromptBuilder from src.domain.entities import Review # Создание билдера с кастомным шаблоном builder = PromptBuilder( template="""Отвечай на отзыв Wildberries на том же языке, что и отзыв. Тон: дружелюбный, лаконичный, полезный. До 600 символов. Не используй эмодзи.""" ) # Создание доменного отзыва review = Review( id="review-123", text='{"text": "Качество хорошее", "productValuation": 4, "pros": "Цена"}', summary="Качество хорошее\nЦена" ) # Построение финального промпта prompt = builder.build(review) print(prompt) # Отвечай на отзыв Wildberries на том же языке, что и отзыв. # Тон: дружелюбный, лаконичный, полезный. До 600 символов. # Не используй эмодзи. # Full review payload: # { # "id": "review-123", # "text": "{\"text\": \"Качество хорошее\"...}", # "summary": "Качество хорошее\nЦена" # } ``` -------------------------------- ### Pull Docker Image Source: https://github.com/eslazarev/ai-wildberries-review-responder/blob/main/README.md Pulls the latest Docker image for the AI Wildberries Review Responder from Docker Hub. ```bash docker pull eslazarev/ai-wildberries-review-responder:latest ``` -------------------------------- ### Deploy with Custom Check Schedule Source: https://github.com/eslazarev/ai-wildberries-review-responder/blob/main/README.md Deploys the function and customizes the schedule for checking reviews. Requires WILDBERRIES__API_TOKEN. ```bash WILDBERRIES__CHECK_EVERY_MINUTES='15' WILDBERRIES__API_TOKEN='your_wb_token' serverless deploy ``` -------------------------------- ### Initiate Review Processing Source: https://context7.com/eslazarev/ai-wildberries-review-responder/llms.txt This function orchestrates the review processing pipeline, fetching reviews, generating replies, and publishing them. ```python respond_on_reviews( review_fetcher=wildberries_client, reply_generator=reply_generator, review_publisher=wildberries_client, logger=logger ) ``` -------------------------------- ### Run Single Processing Iteration Source: https://github.com/eslazarev/ai-wildberries-review-responder/blob/main/README.md Executes a single run of the review processing logic. Requires Wildberries and LLM API tokens to be set as environment variables. ```bash export WILDBERRIES__API_TOKEN='your_wb_token' export LLM__API_KEY='your_llm_api_key' python -m src.entrypoints.docker_once ``` -------------------------------- ### Configuration Settings Source: https://context7.com/eslazarev/ai-wildberries-review-responder/llms.txt Defines default settings for Wildberries API interaction and LLM parameters. Environment variables can override these values. ```yaml # settings.yaml wildberries: base_url: "https://feedbacks-api.wildberries.ru" request_timeout: 10 batch_size: 10 check_every_minutes: 30 llm: model: "gpt://{FOLDER_ID}/aliceai-llm/latest" base_url: "https://rest-assistant.api.cloud.yandex.net/v1" temperature: 0.3 max_tokens: 600 instructions: | Ты — вежливый сотрудник поддержки реселлера, отвечающий на отзывы Wildberries. prompt_template: | Отвечай на отзыв Wildberries на том же языке, что и отзыв. Тон: дружелюбный, лаконичный, полезный. До 600 символов. Ты не работаешь в Wildberries, не упоминай компанию в ответе. Не используй эмодзи. timeout: 10 ``` -------------------------------- ### Configure LLM Provider Source: https://github.com/eslazarev/ai-wildberries-review-responder/blob/main/README.md Sets environment variables to connect to an OpenAI-compatible LLM provider. This allows using different LLM services by changing the base URL, model, and API key. ```bash export LLM__BASE_URL='https://api.openai.com/v1' export LLM__MODEL='gpt-4o-mini' export LLM__API_KEY='your_key' ``` -------------------------------- ### Generate Replies using LLMReplyGenerator Source: https://context7.com/eslazarev/ai-wildberries-review-responder/llms.txt LLMReplyGenerator combines PromptBuilder and LLMClient to generate review replies. It takes a domain Review object and returns the final reply text, integrating prompt construction and LLM interaction. ```python from src.infra.reply_generator import LLMReplyGenerator from src.infra.prompt import PromptBuilder from src.infra.llm.base import make_llm_client from src.infra.config.settings import Settings from src.domain.entities import Review settings = Settings() # Создание компонентов prompt_builder = PromptBuilder(template=settings.llm.prompt_template) llm_client = make_llm_client(settings) # Фабрика создает OpenAIClient # Сборка генератора ответов reply_generator = LLMReplyGenerator( prompt_builder=prompt_builder, llm_client=llm_client ) # Генерация ответа на отзыв review = Review( id="wb-456", text='{"text": "Товар пришел с дефектом", "productValuation": 2}', summary="Товар пришел с дефектом" ) reply = reply_generator.generate(review) print(reply) # "Приносим извинения за неудобства. Пожалуйста, свяжитесь с нами для замены товара." ``` -------------------------------- ### Run Docker Container for Single Iteration Source: https://github.com/eslazarev/ai-wildberries-review-responder/blob/main/README.md Runs the Docker container to perform a single review processing task. Specify `src.entrypoints.docker_once` to override the default scheduled mode. Requires API tokens. ```bash docker run --rm \ -e WILDBERRIES__API_TOKEN='your_wb_token' \ -e LLM__API_KEY='your_llm_api_key' \ eslazarev/ai-wildberries-review-responder:latest src.entrypoints.docker_once ``` -------------------------------- ### Run Docker Container with Internal Schedule Source: https://github.com/eslazarev/ai-wildberries-review-responder/blob/main/README.md Runs the Docker container in its default mode, which includes an internal scheduler. Configure the check interval using environment variables. Requires API tokens. ```bash docker run --rm \ -e WILDBERRIES__API_TOKEN='your_wb_token' \ -e WILDBERRIES__CHECK_EVERY_MINUTES='15' \ -e LLM__API_KEY='your_llm_api_key' \ eslazarev/ai-wildberries-review-responder:latest ``` -------------------------------- ### Ollama Local Run Source: https://context7.com/eslazarev/ai-wildberries-review-responder/llms.txt Executes the review processing using a locally running Ollama model. This command initiates a single run. ```python # Локальный запуск python -m src.entrypoints.docker_once ``` -------------------------------- ### Docker Run Command: One-Time Execution Source: https://context7.com/eslazarev/ai-wildberries-review-responder/llms.txt Command to run a Docker container for a single review processing task. It mounts environment variables for authentication and API keys. ```bash # docker run --rm \ # -e WILDBERRIES__API_TOKEN='your_wb_token' \ # -e LLM__API_KEY='your_llm_api_key' \ # eslazarev/ai-wildberries-review-responder:latest \ # src.entrypoints.docker_once ``` -------------------------------- ### Yandex Cloud Deployment: Custom LLM Key Source: https://context7.com/eslazarev/ai-wildberries-review-responder/llms.txt Deploys the application with a custom LLM API key, such as for OpenAI. This overrides the default YandexGPT configuration. ```bash # Деплой с кастомным LLM-ключом (для OpenAI) LLM__API_KEY='sk-openai-key' \ WILDBERRIES__API_TOKEN='your_wb_token' \ serverless deploy ``` -------------------------------- ### Run Architectural Tests Source: https://github.com/eslazarev/ai-wildberries-review-responder/blob/main/README.md Executes architectural tests using pytest. The `-m architecture` flag filters tests specifically for architectural validation. ```bash pytest -m architecture ``` -------------------------------- ### Yandex Cloud Deployment: Change Check Interval Source: https://context7.com/eslazarev/ai-wildberries-review-responder/llms.txt Deploys the application with a modified interval for checking reviews. The WILDBERRIES__CHECK_EVERY_MINUTES variable controls this setting. ```bash # Изменение интервала проверки на 15 минут WILDBERRIES__CHECK_EVERY_MINUTES='15' \ WILDBERRIES__API_TOKEN='your_wb_token' \ serverless deploy ``` -------------------------------- ### Yandex Cloud Functions Entrypoint Source: https://context7.com/eslazarev/ai-wildberries-review-responder/llms.txt The handler function for Yandex Cloud Functions. It automatically uses FOLDER_ID for YandexGPT and an IAM token from the context if LLM__API_KEY is not set. Returns a JSON status. ```python # src/entrypoints/yandex_cloud_function.py from src.entrypoints.yandex_cloud_function import handler # Вызов из Yandex Cloud Functions (event и context передаются платформой) event = {} context = type('Context', (), { 'function_folder_id': 'b1g123456789', 'token': {'access_token': 'iam-token-from-yc'} })() result = handler(event, context) print(result) ``` -------------------------------- ### Yandex Cloud Deployment: Remove Resources Source: https://context7.com/eslazarev/ai-wildberries-review-responder/llms.txt Removes all deployed resources associated with the Serverless Framework application from Yandex Cloud. ```bash # Удаление всех ресурсов serverless remove ``` -------------------------------- ### Docker Run Command: Cron Schedule Source: https://context7.com/eslazarev/ai-wildberries-review-responder/llms.txt Command to run a Docker container in detached mode with an internal cron schedule. The WILDBERRIES__CHECK_EVERY_MINUTES variable sets the check interval. ```bash # docker run -d \ # -e WILDBERRIES__API_TOKEN='your_wb_token' \ # -e WILDBERRIES__CHECK_EVERY_MINUTES='15' \ # -e LLM__API_KEY='your_llm_api_key' \ # eslazarev/ai-wildberries-review-responder:latest ``` -------------------------------- ### Remove Yandex Cloud Resources Source: https://github.com/eslazarev/ai-wildberries-review-responder/blob/main/README.md Removes all deployed resources associated with the serverless application from Yandex Cloud. ```bash serverless remove ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.