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)