Spaces:
Sleeping
Sleeping
File size: 12,295 Bytes
4548db6 c6c1078 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 | import os
import logging
import time
import requests # Added missing import
import gradio as gr
from dotenv import load_dotenv
from gpt4all import GPT4All
from groq import Groq
# ---------------- SETUP ----------------
load_dotenv()
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
# LLM Configuration
GROQ_MODEL = "openai/gpt-oss-20b"
# MODEL_PATH = "orca-mini-3b-gguf2-q4_0.gguf"
CIRCLECI_API_BASE = "https://circleci.com/api/v2/project"
CIRCLECI_TOKEN = os.getenv("CIRCLECI_TOKEN")
CIRCLECI_ORG = os.getenv("CIRCLECI_ORG")
AUTH_SECRET_KEY = "AUTH_CREDENTIALS" # Name of the Secret containing auth credentials
auth_string = os.getenv(AUTH_SECRET_KEY)
auth_credentials = None
if auth_string:
try:
# Convert "user1:pass1,user2:pass2" into [('user1', 'pass1'), ('user2', 'pass2')]
auth_credentials = [tuple(c.strip().split(':')) for c in auth_string.split(',')]
if not all(len(c) == 2 for c in auth_credentials):
raise ValueError("Credentials must be in the format 'username:password'.")
logging.info(f"Authentication enabled for {len(auth_credentials)} user(s).")
except Exception as e:
auth_credentials = None
logging.error(f"FATAL: Failed to parse {AUTH_SECRET_KEY}. Authentication disabled. Error: {e}")
else:
logging.warning("Authentication disabled: AUTH_CREDENTIALS secret not found.")
# --- 1. CONFIGURATION MAPPING ---
# Structure: { "User Project Name": { "User Component": "REAL_CIRCLECI_PROJECT_SLUG" } }
PROJECT_MAPPING = {
"eNVD": {
"web": {
"slug": "envd-web-playwright-tests",
"environments": ["QA", "UAT","PROD"]
},
"api": {
"slug": "envd-api-tests",
"environments": ["DEV", "QA", "UAT", "PROD"]
},
"mobile": {
"slug": "envd-mobile-appium-tests",
"environments": ["QA", "UAT", "PROD"]
}
},
"NLIS": {
"web": {
"slug": "nlis-playwright-tests",
"environments": ["dev", "qa","uat"]
}
}
}
# Load Model
# try:
# llm = GPT4All(MODEL_PATH, n_threads=4)
# except Exception:
# llm = None
try:
# Groq automatically looks for GROQ_API_KEY environment variable
llm = Groq()
if not llm.api_key:
raise ValueError("GROQ_API_KEY environment variable is not set.")
logger.info(f"Groq client initialized using model: {GROQ_MODEL}")
except Exception as e:
llm = None
logger.error(f"Error initializing Groq client. Ensure 'GROQ_API_KEY' is set in your .env file. Error: {e}")
# ---------------- LOGIC ----------------
def trigger_circleci_pipeline(real_project_slug, branch, environment, send_teams_notification=False):
# NOTE: We use the real_project_slug here, not the user friendly name
url = f"{CIRCLECI_API_BASE}/{CIRCLECI_ORG}/{real_project_slug}/pipeline"
headers = {
"Circle-Token": CIRCLECI_TOKEN,
"Content-Type": "application/json"
}
payload = {
"branch": branch,
"parameters": {"APP_ENV": environment, "MSTEAMS_REPORTING": send_teams_notification}
}
try:
response = requests.post(url, headers=headers, json=payload)
if response.status_code == 201:
return f"β
Pipeline triggered for **{real_project_slug}** ({branch} -> {environment})."
else:
return f"β Failed (Status {response.status_code}): {response.text}"
except Exception as e:
return f"β Connection Error: {str(e)}"
def core_logic(user_input, state):
# Initialize State
if not state:
state = {
"step": "idle",
"project_name": None,
"component": None,
"real_slug": None,
"branch": None,
"environment": None,
"valid_environments": None,
"send_teams_notification": None
}
user_input_clean = user_input.strip()
user_input_lower = user_input_clean.lower()
# Global Cancel
if user_input_lower in ["cancel", "reset", "stop"]:
state = {"step": "idle", "project_name": None, "component": None, "real_slug": None, "branch": None, "environment": None, "valid_environments": None}
return "π Reset. Ready for new command.", state
# --- Step 1: Detect Intent ---
if state["step"] == "idle":
if any(w in user_input_lower for w in ["deploy", "pipeline", "trigger"]):
state["step"] = "get_project"
options = ", ".join(PROJECT_MAPPING.keys())
return f"π **DevOps Mode**: Which project? ({options})", state
else:
# prompt = f"User: {user_input}\nAssistant:"
# response = llm.generate(prompt, max_tokens=100) if llm else "β οΈ Model not loaded."
# return response, state
# Groq LLM API Call
response = "β οΈ LLM (Groq) client not loaded. Check your setup."
if llm:
try:
chat_completion = llm.chat.completions.create(
messages=[
{"role": "system", "content": "You are a helpful, brief, and technical DevOps assistant."},
{"role": "user", "content": user_input_clean},
],
model=GROQ_MODEL,
max_tokens=250
)
response = chat_completion.choices[0].message.content
except Exception as e:
logger.error(f"Groq API call failed: {e}")
response = "β οΈ Groq API call failed. Check your GROQ_API_KEY or connection."
return response, state
# --- Step 2: Select Project ---
elif state["step"] == "get_project":
matched_project = next((p for p in PROJECT_MAPPING.keys() if p.lower() == user_input_lower), None)
if matched_project:
state["project_name"] = matched_project
state["step"] = "get_component"
available_components = PROJECT_MAPPING[matched_project].keys()
opts = ", ".join(available_components)
return f"π Project **{matched_project}** selected.\nWhich component? ({opts})", state
else:
options = ", ".join(PROJECT_MAPPING.keys())
return f"β οΈ Invalid Project. Options: {options}", state
# --- Step 3: Select Component ---
elif state["step"] == "get_component":
current_project = state["project_name"]
components_map = PROJECT_MAPPING[current_project]
matched_component = next((c for c in components_map.keys() if c.lower() == user_input_lower), None)
if matched_component:
component_config = components_map[matched_component] # <-- Get the config dictionary
state["component"] = matched_component
state["real_slug"] = component_config["slug"]
state["valid_environments"] = component_config["environments"] # <-- Store specific environments
state["step"] = "get_branch"
return f"π§ Component **{matched_component}** selected.\nWhich branch?", state
else:
opts = ", ".join(components_map.keys())
return f"β οΈ Invalid Component for {current_project}. Options: {opts}", state
# --- Step 4: Select Branch ---
elif state["step"] == "get_branch":
if user_input_clean:
state["branch"] = user_input_clean
state["step"] = "get_env"
# Use the component-specific environment list for the prompt
env_opts = ", ".join(state["valid_environments"])
return f"πΏ Branch **{user_input_clean}**. Which environment? ({env_opts})", state
# --- Step 5: Select Environment (UPDATED) ---
elif state["step"] == "get_env":
# Get the component-specific environment list from state
valid_envs = state["valid_environments"]
matched = next((e for e in valid_envs if e.lower() == user_input_lower), None)
if matched:
state["environment"] = matched
# state["step"] = "confirm"
state["step"] = "ask_teams_notification"
# Summary
# summary = (
# f"**Project**: {state['project_name']} ({state['component']})\n"
# f"**Slug**: `{state['real_slug']}`\n"
# f"**Branch**: {state['branch']}\n"
# f"**Env**: {matched}"
# )
# return f"π Confirm deploy?\n\n{summary}\n\n(yes/no)", state
return f"Environment **{user_input_clean}** selected.\n π’ Do you want to send Microsoft Teams Notification? (yes/no)", state
else:
# Show the specific options for the current component
opts = ", ".join(valid_envs)
return f"β οΈ Invalid Environment. Options for **{state['component']}**: {opts}", state
# --- Step 6: Ask for Teams Notification ---
elif state["step"] == "ask_teams_notification":
if user_input_lower in ["yes", "y"]:
state["send_teams_notification"] = True
else:
state["send_teams_notification"] = False
state["step"] = "confirm"
summary = (
f"**Project**: {state['project_name']} ({state['component']})\n"
f"**Slug**: `{state['real_slug']}`\n"
f"**Branch**: {state['branch']}\n"
f"**Env**: {state['environment']}\n"
f"**Teams Notification**: {'Yes' if state['send_teams_notification'] else 'No'}"
)
return f"π Confirm deploy?\n\n{summary}\n\n(yes/no)", state
# --- Step 7: Confirm ---
elif state["step"] == "confirm":
if user_input_lower in ["yes", "y", "confirm"]:
res = trigger_circleci_pipeline(state["real_slug"], state["branch"], state["environment"], state["send_teams_notification"])
# Reset State
state = {"step": "idle", "project_name": None, "component": None, "real_slug": None, "branch": None, "environment": None, "valid_environments": None, "send_teams_notification": None}
return res, state
else:
state = {"step": "idle", "project_name": None, "component": None, "real_slug": None, "branch": None, "environment": None, "valid_environments": None, "send_teams_notification": None}
return "β Canceled.", state
return "Error", state
# ---------------- UI (GRADIO 5 COMPATIBLE) ----------------
with gr.Blocks(title="DevOps Bot", theme=gr.themes.Monochrome(), fill_height=True) as demo:
session_state = gr.State()
gr.Markdown("## π€ ISC - Test Automation")
chatbot_component = gr.Chatbot(
scale=1,
bubble_full_width=False,
avatar_images=(None, "https://cdn-icons-png.flaticon.com/512/4712/4712009.png"),
render_markdown=True,
type="tuples"
)
with gr.Row(variant="panel"):
msg_input = gr.Textbox(
scale=4,
show_label=False,
placeholder="Type 'deploy' to start...",
container=False,
autofocus=True
)
send_btn = gr.Button("β€", scale=1, variant="primary", min_width=50)
def user_turn(user_message, history):
return "", history + [[user_message, None]]
def bot_turn(history, state):
user_message = history[-1][0]
bot_response, new_state = core_logic(user_message, state)
history[-1][1] = bot_response
return history, new_state
msg_input.submit(user_turn, [msg_input, chatbot_component], [msg_input, chatbot_component], queue=False).then(
bot_turn, [chatbot_component, session_state], [chatbot_component, session_state]
)
send_btn.click(user_turn, [msg_input, chatbot_component], [msg_input, chatbot_component], queue=False).then(
bot_turn, [chatbot_component, session_state], [chatbot_component, session_state]
)
if __name__ == "__main__":
demo.launch(auth=auth_credentials, server_name="0.0.0.0", server_port=7860, ssr_mode=False) |