Разработка AI-системы автогенерации CI/CD пайплайнов
AI-генерация CI/CD конфигураций — автоматическое создание GitHub Actions, GitLab CI, Jenkins Pipeline файлов на основе анализа кодовой базы. Система определяет технологический стек, зависимости, тест-фреймворки и генерирует оптимальную конфигурацию.
Анализ кодовой базы
class ProjectAnalyzer:
def analyze(self, repo_path: str) -> ProjectProfile:
profile = ProjectProfile()
# Определение языков
file_counts = Counter()
for f in glob.glob(f"{repo_path}/**/*", recursive=True):
ext = Path(f).suffix
file_counts[ext] += 1
profile.languages = self._infer_languages(file_counts)
# Детектирование фреймворков
profile.frameworks = self._detect_frameworks(repo_path, profile.languages)
# Тест-фреймворки
profile.test_frameworks = self._detect_test_frameworks(repo_path)
# Контейнеризация
profile.has_dockerfile = Path(f"{repo_path}/Dockerfile").exists()
profile.has_docker_compose = Path(f"{repo_path}/docker-compose.yml").exists()
# CI/CD провайдер (если уже настроен)
if Path(f"{repo_path}/.github/workflows").exists():
profile.current_ci = "github_actions"
elif Path(f"{repo_path}/.gitlab-ci.yml").exists():
profile.current_ci = "gitlab_ci"
return profile
def _detect_frameworks(self, path: str, languages: list[str]) -> list[str]:
frameworks = []
if "python" in languages:
if Path(f"{path}/requirements.txt").exists():
reqs = Path(f"{path}/requirements.txt").read_text()
if "django" in reqs.lower(): frameworks.append("django")
if "fastapi" in reqs.lower(): frameworks.append("fastapi")
if "flask" in reqs.lower(): frameworks.append("flask")
if "javascript" in languages or "typescript" in languages:
if Path(f"{path}/package.json").exists():
pkg = json.loads(Path(f"{path}/package.json").read_text())
deps = {**pkg.get("dependencies", {}), **pkg.get("devDependencies", {})}
if "react" in deps: frameworks.append("react")
if "next" in deps: frameworks.append("nextjs")
return frameworks
Генерация CI/CD конфигурации
def generate_cicd_config(profile: ProjectProfile, target_ci: str) -> str:
context = f"""Проект: {profile.languages}
Фреймворки: {profile.frameworks}
Тесты: {profile.test_frameworks}
Dockerfile: {profile.has_dockerfile}
Среды: dev/staging/prod"""
prompt = f"""Сгенерируй {target_ci} конфигурацию для проекта:
{context}
Требования:
- Тесты при каждом push
- Lint/type check
- Build Docker image при merge в main
- Deploy на staging автоматически, на prod — вручную
- Кэширование зависимостей
- Секреты через environment variables"""
return llm.generate(prompt, max_tokens=2000)
Пример сгенерированного GitHub Actions
# Типичный результат для FastAPI + pytest + Docker
name: CI/CD Pipeline
on:
push:
branches: [main, develop]
pull_request:
branches: [main]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with: {python-version: "3.11"}
- uses: actions/cache@v4
with:
path: ~/.cache/pip
key: ${{ runner.os }}-pip-${{ hashFiles('requirements*.txt') }}
- run: pip install -r requirements.txt -r requirements-dev.txt
- run: ruff check . && mypy .
- run: pytest --cov=app --cov-report=xml
- uses: codecov/codecov-action@v4
build-and-push:
needs: test
if: github.ref == 'refs/heads/main'
steps:
- uses: docker/build-push-action@v5
with:
push: true
tags: ghcr.io/${{ github.repository }}:${{ github.sha }}
deploy-staging:
needs: build-and-push
environment: staging
steps:
- run: kubectl set image deployment/app app=ghcr.io/${{ github.repository }}:${{ github.sha }}
Итеративное улучшение
После первой генерации система запрашивает обратную связь: что работает, что нужно изменить. LLM уточняет конфигурацию на основе комментариев. История изменений хранится — можно откатиться к предыдущей версии.
Валидация сгенерированных конфигураций
Перед применением: синтаксическая проверка (yamllint, actionlint для GitHub Actions), сухой запуск (act для локальной симуляции GitHub Actions), статический анализ безопасности (checkov для обнаружения небезопасных паттернов).







