update 2
This commit is contained in:
52
main.py
52
main.py
@@ -1,48 +1,52 @@
|
|||||||
from fastapi import FastAPI, HTTPException
|
from fastapi import FastAPI, HTTPException
|
||||||
|
from pydantic import BaseModel
|
||||||
import requests
|
import requests
|
||||||
import yaml
|
import yaml
|
||||||
from pydantic import BaseModel
|
|
||||||
|
|
||||||
app = FastAPI()
|
app = FastAPI(title="AI CI/CD Assistant")
|
||||||
|
|
||||||
OLLAMA_URL = "http://10.10.10.136:11434/api/generate"
|
# ЗАМЕНИТЕ на IP вашего контейнера с Ollama
|
||||||
|
OLLAMA_API_URL = "http://10.10.10.136:11434/api/generate"
|
||||||
|
|
||||||
class Prompt(BaseModel):
|
class GenerationRequest(BaseModel):
|
||||||
task_description: str
|
description: str
|
||||||
|
platform: str = "GitHub Actions" # или GitLab CI
|
||||||
model: str = "codellama"
|
model: str = "codellama"
|
||||||
|
|
||||||
def validate_yaml(content: str):
|
def validate_config(config_text: str):
|
||||||
|
"""Простая валидация YAML синтаксиса"""
|
||||||
try:
|
try:
|
||||||
yaml.safe_load(content)
|
yaml.safe_load(config_text)
|
||||||
return True, "Valid YAML"
|
return True, "Success"
|
||||||
except yaml.YAMLError as exc:
|
except Exception as e:
|
||||||
return False, str(exc)
|
return False, str(e)
|
||||||
|
|
||||||
|
@app.post("/generate")
|
||||||
|
async def generate_pipeline(req: GenerationRequest):
|
||||||
|
prompt = f"Write only a valid {req.platform} YAML configuration for: {req.description}. No explanations, just code."
|
||||||
|
|
||||||
@app.post("/generate_config")
|
|
||||||
async def generate_config(data: Prompt):
|
|
||||||
payload = {
|
payload = {
|
||||||
"model": data.model,
|
"model": req.model,
|
||||||
"prompt": f"Generate only a valid CI/CD YAML configuration for the following task: {data.task_description}. Return ONLY the code block.",
|
"prompt": prompt,
|
||||||
"stream": False
|
"stream": False
|
||||||
}
|
}
|
||||||
|
|
||||||
try:
|
try:
|
||||||
response = requests.post(OLLAMA_URL, json=payload)
|
response = requests.post(OLLAMA_API_URL, json=payload, timeout=60)
|
||||||
response_data = response.json()
|
raw_text = response.json().get("response", "")
|
||||||
generated_text = response_data.get("response", "")
|
|
||||||
|
|
||||||
# Очистка от markdown-тегов, если модель их добавила
|
# Очистка от Markdown-оберток (```yaml ... ```)
|
||||||
config_content = generated_text.replace("```yaml", "").replace("```", "").strip()
|
clean_code = raw_text.replace("```yaml", "").replace("```", "").strip()
|
||||||
|
|
||||||
is_valid, message = validate_yaml(config_content)
|
is_valid, error_msg = validate_config(clean_code)
|
||||||
|
|
||||||
return {
|
return {
|
||||||
"config": config_content,
|
"status": "ok" if is_valid else "error",
|
||||||
"is_valid": is_valid,
|
"config": clean_code,
|
||||||
"validation_message": message
|
"validation_error": error_msg if not is_valid else None
|
||||||
}
|
}
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
raise HTTPException(status_code=500, detail=str(e))
|
raise HTTPException(status_code=500, detail=f"Ollama error: {str(e)}")
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
import uvicorn
|
import uvicorn
|
||||||
|
|||||||
16
run.sh
Normal file
16
run.sh
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
# Активируем виртуальное окружение (если есть)
|
||||||
|
source venv/bin/activate
|
||||||
|
|
||||||
|
# Запускаем Бэкенд в фоне
|
||||||
|
echo "Starting Backend..."
|
||||||
|
python3 app.py > backend.log 2>&1 &
|
||||||
|
|
||||||
|
# Запускаем Фронтенд в фоне
|
||||||
|
echo "Starting Frontend..."
|
||||||
|
streamlit run ui.py --server.port 8501 > frontend.log 2>&1 &
|
||||||
|
|
||||||
|
echo "Services are running in background!"
|
||||||
|
echo "Backend: http://localhost:8000"
|
||||||
|
echo "Frontend: http://localhost:8501"
|
||||||
51
ui.py
51
ui.py
@@ -1,39 +1,38 @@
|
|||||||
import streamlit as st
|
import streamlit as st
|
||||||
import requests
|
import requests
|
||||||
|
|
||||||
st.set_page_config(page_title="AI DevOps Assistant", layout="wide")
|
st.set_page_config(page_title="DevOps AI Assistant", page_icon="🚀")
|
||||||
|
|
||||||
st.title("🚀 CI/CD AI Generator & Validator")
|
st.title("🤖 AI CI/CD Pipeline Generator")
|
||||||
st.subheader("Генерация и проверка конфигураций пайплайнов")
|
st.markdown("Прототип сервиса для генерации и валидации конфигураций")
|
||||||
|
|
||||||
backend_url = "http://localhost:8000/generate_config"
|
|
||||||
|
|
||||||
with st.sidebar:
|
with st.sidebar:
|
||||||
st.info("Настройки")
|
st.header("Настройки")
|
||||||
model_name = st.selectbox("Выберите модель Ollama", ["codellama", "llama3", "mistral"])
|
api_url = st.text_input("Backend URL", "http://localhost:8000/generate")
|
||||||
|
model = st.selectbox("LLM Модель", ["deepseek-r1:1.5b", "qwen2.5-coder:1.5b", "llama3.1:8b", "Arena Model"])
|
||||||
|
platform = st.radio("Платформа", ["GitHub Actions", "GitLab CI"])
|
||||||
|
|
||||||
task = st.text_area("Опишите задачу (напр. 'Pipeline for Dockerized Node.js app with Jest tests'):")
|
user_input = st.text_area("Опишите пайплайн (например: 'Python app with pytest and docker build')", height=150)
|
||||||
|
|
||||||
if st.button("Сгенерировать и проверить"):
|
if st.button("Сгенерировать конфигурацию", type="primary"):
|
||||||
if task:
|
if user_input:
|
||||||
with st.spinner("ИИ формирует конфигурацию..."):
|
with st.spinner("LLM думает..."):
|
||||||
res = requests.post(backend_url, json={"task_description": task, "model": model_name})
|
try:
|
||||||
if res.status_code == 200:
|
res = requests.post(api_url, json={
|
||||||
|
"description": user_input,
|
||||||
|
"platform": platform,
|
||||||
|
"model": model
|
||||||
|
})
|
||||||
data = res.json()
|
data = res.json()
|
||||||
|
|
||||||
col1, col2 = st.columns(2)
|
if data["status"] == "ok":
|
||||||
|
st.success("✅ Конфигурация валидна!")
|
||||||
with col1:
|
|
||||||
st.markdown("### Сгенерированный YAML")
|
|
||||||
st.code(data["config"], language="yaml")
|
st.code(data["config"], language="yaml")
|
||||||
|
st.download_button("Скачать .yml", data["config"], file_name="pipeline.yml")
|
||||||
with col2:
|
|
||||||
st.markdown("### Статус валидации")
|
|
||||||
if data["is_valid"]:
|
|
||||||
st.success("✅ Конфигурация синтаксически верна")
|
|
||||||
else:
|
else:
|
||||||
st.error(f"❌ Ошибка в YAML: {data['validation_message']}")
|
st.error(f"❌ Ошибка валидации: {data['validation_error']}")
|
||||||
|
st.code(data["config"], language="yaml")
|
||||||
|
except Exception as e:
|
||||||
|
st.error(f"Ошибка подключения к бекенду: {e}")
|
||||||
else:
|
else:
|
||||||
st.error("Ошибка связи с бекендом")
|
st.warning("Пожалуйста, введите описание.")
|
||||||
else:
|
|
||||||
st.warning("Введите описание задачи")
|
|
||||||
Reference in New Issue
Block a user