from dotenv import load_dotenv from openai import OpenAI import json import os import gradio as gr import requests from urllib.parse import urlparse from fastapi import FastAPI, Request, Response, status import time load_dotenv(override=True) GEMINI_BASE_URL = "https://generativelanguage.googleapis.com/v1beta/openai/" API_KEY = os.getenv("GEMINI_API_KEY") or os.getenv("GOOGLE_API_KEY") MODEL = "gemini-2.5-flash-preview-05-20" openai = OpenAI(base_url=GEMINI_BASE_URL, api_key=API_KEY) PUSHOVER_USER = os.getenv("PUSHOVER_USER") PUSHOVER_TOKEN = os.getenv("PUSHOVER_TOKEN") PUSHOVER_URL = "https://api.pushover.net/1/messages.json" def push_pushover(text: str) -> bool: if not (PUSHOVER_USER and PUSHOVER_TOKEN): return False try: requests.post(PUSHOVER_URL, data={"user": PUSHOVER_USER, "token": PUSHOVER_TOKEN, "message": text}, timeout=10) return True except Exception: return False def _load_one(json_path: str): base_dir = os.path.dirname(os.path.abspath(__file__)) full_path = json_path if os.path.isabs(json_path) else os.path.join(base_dir, json_path) if not os.path.exists(full_path): return [] with open(full_path, "r", encoding="utf-8") as f: return json.load(f) # --- Remote API backed sections with 2-minute cache and local fallback --- TM_AUTH_TOKEN = os.getenv("TM_AUTH_TOKEN") API_SECTIONS = { "TmResources": "https://uicrowds.somee.com/TestManagerSinglePageResourceModels/GetSections/TmResources", "whomToContact": "https://uicrowds.somee.com/TestManagerSinglePageResourceModels/GetSections/whomToContact", "environments": "https://uicrowds.somee.com/TestManagerSinglePageResourceModels/GetSections/environments", } _remote_cache: dict[str, dict] = {} _server_list_cache: dict = {"ts": 0, "map": {}} def _fetch_section_remote(section: str) -> list: url = API_SECTIONS.get(section) if not url: return [] headers = {} if TM_AUTH_TOKEN: headers["tmauthtoken"] = TM_AUTH_TOKEN try: resp = requests.get(url, headers=headers, timeout=15) if resp.status_code != 200: return [] # Reject typical unauthorized body text = resp.text or "" if "UnAuthorized" in text or "Unauthorized" in text: return [] try: data = resp.json() except Exception: # try to parse lax JSON data = json.loads(text) # Expect a list of section items; if object has 'items' or similar, try to unwrap if isinstance(data, dict): # find a list value for v in data.values(): if isinstance(v, list): return v return [] if isinstance(data, list): return data return [] except Exception: return [] def _get_section(section: str) -> list: now = time.time() cached = _remote_cache.get(section) if cached and (now - cached.get("ts", 0) < 120): # 2 minutes return cached.get("data", []) data = _fetch_section_remote(section) if data: _remote_cache[section] = {"ts": now, "data": data} return data # fallback to local fallback_map = { "TmResources": "resources.json", "whomToContact": "contacts.json", "environments": "environments.json", } local = _load_one(fallback_map.get(section, "")) _remote_cache[section] = {"ts": now, "data": local} return local def _load_all_items() -> list: items = [] # The API returns items with category already set; keep as-is items.extend(_get_section("TmResources")) items.extend(_get_section("whomToContact")) items.extend(_get_section("environments")) return items def _load_server_map() -> dict[str, str]: """Return a map of normalized region key -> serverinfo URL from server_list.json with 2-minute cache.""" now = time.time() if _server_list_cache["ts"] and (now - _server_list_cache["ts"] < 120): return _server_list_cache["map"] try: base_dir = os.path.dirname(os.path.abspath(__file__)) with open(os.path.join(base_dir, "server_list.json"), "r", encoding="utf-8") as f: data = json.load(f) except Exception: data = [] mapping: dict[str, str] = {} for entry in data or []: region = (entry.get("region") or "").strip().lower() base = (entry.get("primaryBaseUrl") or "").strip() info = (entry.get("serverInfo") or "/api/serverinfo").strip() if region and base: mapping[region] = base.rstrip("/") + info _server_list_cache["ts"] = now _server_list_cache["map"] = mapping return mapping def load_resources_text(paths: list[str] | None = None) -> str: # paths is ignored; we now prefer remote API with cache and fallback to local all_items = _load_all_items() lines = [] for item in all_items: title = item.get("title") or "Untitled" category = item.get("category") or "Uncategorized" lines.append(f"## {title} [{category}]") for res in item.get("resources", []): value = res.get("value") or "" link = res.get("link") or "" if link: lines.append(f"- {value}: {link}") else: lines.append(f"- {value}") lines.append("") return "\n".join(lines).strip() KNOWLEDGE = load_resources_text() def _collect_serverinfo_urls(paths: list[str] | None = None) -> dict[str, str]: urls: dict[str, str] = {} # Preload from explicit server list urls.update(_load_server_map()) items = _load_all_items() for item in items: if (item or {}).get("category", "").lower() != "environments": continue title = (item.get("title") or "").strip() for res in item.get("resources", []): value = (res.get("value") or "").strip() link = (res.get("link") or "").strip() if not link or not value: continue # Heuristic: any resource name that contains 'ServerInfo' is the API endpoint if "serverinfo" in value.lower(): # Use a few keys for lookup: exact environment title and common aliases base_key = title.lower() urls.setdefault(base_key, link) # Also map the value prefix before ' - ServerInfo' if present if "-" in value: alias = value.split("-")[0].strip().lower() if alias: urls.setdefault(alias, link) # Add aliases from title tokens (e.g., "Prod UK" -> "uk") tokens = [t for t in ''.join(ch if ch.isalnum() else ' ' for ch in title).lower().split() if t] recognized = { "alpha","staging","tst","europe","us","canada","japan","australia","singapore","uk","india", "agov","sgov","pgov","gxp" } for t in tokens: if t in recognized: urls.setdefault(t, link) # Host/path heuristics to derive well-known environment aliases try: parsed = urlparse(link) host = parsed.netloc.lower() path = parsed.path.lower() except Exception: host = "" path = "" if "alpha." in host: urls.setdefault("alpha", link) if "staging." in host: urls.setdefault("staging", link) # cloud.uipath.com/testmanager/Tenant/... # Extract region tenant name if present try: parts = [p for p in path.split("/") if p] if "testmanager" in parts: idx = parts.index("testmanager") if idx + 1 < len(parts): tenant = parts[idx + 1] if tenant.endswith("tenant"): region = tenant[:-6] # strip 'Tenant' if region: urls.setdefault(region.lower(), link) except Exception: pass return urls SERVERINFO_URLS = _collect_serverinfo_urls() SYSTEM_PROMPT = ( "You are a helpful assistant that answers questions strictly using the provided knowledge. " "When unsure or if the answer isn't present, say you don't have that information. " "Prefer citing specific items and links where helpful. " "If the user asks for an API version for any environment, call the get_api_version tool with the requested environment name (e.g., alpha, staging, tst, europe, us, canada, japan, australia, singapore, uk, india, agov, sgov, pgov, gxp). " "If the user asks for versions for ALL environments, first call list_environments to enumerate ONLY the canonical regions defined in server_list.json, then call get_api_version for each of those." ) def get_api_version(environment: str) -> dict: global SERVERINFO_URLS env_key = (environment or "").strip().lower() if not env_key: return {"ok": False, "error": "environment not provided"} # Try exact match; else partial contains url = SERVERINFO_URLS.get(env_key) if not url: # attempt refresh in case data updated SERVERINFO_URLS = _collect_serverinfo_urls() url = SERVERINFO_URLS.get(env_key) if not url: for k, v in SERVERINFO_URLS.items(): if env_key in k: url = v break if not url: return {"ok": False, "error": f"No ServerInfo URL found for '{environment}'"} try: resp = requests.get(url, timeout=15) except Exception as e: return {"ok": False, "environment": environment, "url": url, "error": str(e)} try: data = resp.json() except Exception: data = None version = None if isinstance(data, dict): # Common keys for key in [ "version", "apiVersion", "git_version", "buildVersion", "serviceVersion", ]: if key in data and isinstance(data[key], str) and data[key].strip(): version = data[key].strip() break # Sometimes nested under 'data' or similar if not version: for k, v in data.items(): if isinstance(v, dict): for key in ["version", "apiVersion", "git_version", "buildVersion"]: if key in v and isinstance(v[key], str) and v[key].strip(): version = v[key].strip() break if version: break if not version: # Fallback: try to extract a semantic-looking version from text text = None try: text = resp.text except Exception: text = None if text: import re m = re.search(r"\b\d+\.\d+(?:\.\d+)?(?:[-+][A-Za-z0-9.]+)?\b", text) if m: version = m.group(0) return { "ok": True if version else False, "environment": environment, "url": url, "version": version, "status_code": resp.status_code, } def list_environments(include_urls: bool = False) -> dict: """Return ONLY the canonical environment keys (from server_list.json).""" server_map = _load_server_map() if include_urls: return {"environments": server_map} return {"environments": sorted(server_map.keys())} # Define a function tool so the model can call it explicitly tools = [ { "type": "function", "function": { "name": "get_api_version", "description": "Fetch current API version from the ServerInfo endpoint for a given environment", "parameters": { "type": "object", "properties": { "environment": { "type": "string", "description": "Target environment key (e.g., alpha, staging, tst, europe, us, canada, japan, australia, singapore, uk, india, agov, sgov, pgov, gxp)", } }, "required": ["environment"], "additionalProperties": False, }, }, }, { "type": "function", "function": { "name": "list_environments", "description": "List all environment keys available for API version queries (from server list with fallback merges)", "parameters": { "type": "object", "properties": { "include_urls": {"type": "boolean", "description": "If true, include ServerInfo URLs", "default": False} }, "required": [], "additionalProperties": False } } } ] def handle_tool_calls(tool_calls): results = [] for tool_call in tool_calls: tool_name = tool_call.function.name arguments = json.loads(tool_call.function.arguments) tool = globals().get(tool_name) result = tool(**arguments) if tool else {"ok": False, "error": "unknown tool"} results.append({"role": "tool", "content": json.dumps(result), "tool_call_id": tool_call.id}) return results def chat(message, history): context = f"\n\n## Knowledge Base\n{KNOWLEDGE}\n\n" messages = [ {"role": "system", "content": SYSTEM_PROMPT + context}, *history, {"role": "user", "content": message}, ] done = False response = None while not done: response = openai.chat.completions.create(model=MODEL, messages=messages, tools=tools) finish_reason = response.choices[0].finish_reason if finish_reason == "tool_calls": message_obj = response.choices[0].message tool_calls = message_obj.tool_calls results = handle_tool_calls(tool_calls) messages.append(message_obj) messages.extend(results) else: done = True return response.choices[0].message.content def make_icon(url: str) -> str: u = url.lower() if "github.com" in u: return "🐙" if "azure.com" in u or "portal.azure.com" in u: return "☁️" if "atlassian.net" in u or "jira" in u: return "🧩" if "slack.com" in u: return "💬" if "grafana" in u or "appinsights" in u or "insights" in u: return "📊" if "powerbi" in u: return "📈" if "sharepoint" in u or "docs" in u or "wiki" in u: return "📘" if "cloud.uipath.com" in u or "uipath" in u: return "🤖" if "dataexplorer" in u: return "🔎" return "🔗" def build_resource_cards() -> str: items = _load_all_items() by_category: dict[str, list[str]] = {} for item in items: title = (item.get("title") or "Untitled").strip() category = (item.get("category") or "Uncategorized").strip() links_html = [] for res in item.get("resources", []): value = (res.get("value") or "").strip() link = (res.get("link") or "").strip() if not value: continue if link: icon = make_icon(link) links_html.append( f"
  • {icon} {value}
  • " ) else: links_html.append(f"
  • 🔹 {value}
  • ") section = ( f"
    " f"
    {title}
    " f"" f"
    " ) by_category.setdefault(category, []).append(section) # Build grouped HTML groups = [] default_collapsed = {"tmresources", "environments", "whomtocontact"} for cat, sections in sorted(by_category.items()): open_attr = "" if cat.strip().lower() in default_collapsed else " open" groups.append( f"{cat}{''.join(sections)}" ) return "".join(groups) def extract_links_markdown_to_html(text: str) -> str: import re from html import escape content = text or "" # First: markdown links [label](url) md_link_re = re.compile(r"\[([^\]]+)\]\((https?://[^\s)]+)\)") seen: dict[str, str] = {} for label, url in md_link_re.findall(content): label = label.strip() seen.setdefault(url, label if label else url) # Then: bare URLs not already captured url_re = re.compile(r"(?No links found in the last response." items = [] for url, label in seen.items(): icon = make_icon(url) items.append( f"
  • {icon} {escape(label)}
  • " ) return f"" custom_css = """ .container {max-width: 1200px; margin: 0 auto;} .group {margin-bottom: 8px;} .group > summary {font-weight: 600; font-size: 16px; margin: 6px 0; cursor: pointer;} .card {border: 1px solid #e5e7eb; border-radius: 8px; padding: 8px 10px; margin: 8px 0; background: #fff;} .card-title {font-weight: 600; margin-bottom: 6px;} .card-list {margin: 0 0 0 14px;} .card-list li {margin: 4px 0;} """ if __name__ == "__main__": # Write a human-readable text file for inspection or downstream usage try: with open("resources.txt", "w", encoding="utf-8") as f: f.write(KNOWLEDGE) except Exception: pass resource_html = build_resource_cards() with gr.Blocks(css=custom_css) as demo: gr.Markdown(""" ### UiCrowds Assistant Ask questions about the knowledge base. Links open in a new tab. Use the API Version tool for environments. """) with gr.Row(): with gr.Column(scale=1): gr.Markdown("**Resources**") resources_panel = gr.HTML(resource_html) gr.Markdown("**API version lookup**") env_in = gr.Textbox(label="Environment (e.g., alpha, staging, europe, us)") env_btn = gr.Button("Get API Version") env_out = gr.JSON(label="Version result") with gr.Column(scale=2): chatbot = gr.Chatbot(height=500) with gr.Row(): user_in = gr.Textbox(placeholder="Type your message...", scale=4) send_btn = gr.Button("Send", scale=1) gr.Markdown("**Links from last response**") links_panel = gr.HTML("Send a message to see extracted links here.") chat_state = gr.State([]) # list of (user, assistant) def on_send(user_message, state): try: push_pushover(f"UiCrowds query: {user_message}") except Exception: pass history_messages = [] for u, a in state: history_messages.append({"role": "user", "content": u}) history_messages.append({"role": "assistant", "content": a}) assistant_message = chat(user_message, history_messages) new_state = state + [(user_message, assistant_message)] links_html = extract_links_markdown_to_html(assistant_message) return new_state, new_state, "", links_html send_btn.click( on_send, inputs=[user_in, chat_state], outputs=[chat_state, chatbot, user_in, links_panel], ) user_in.submit( on_send, inputs=[user_in, chat_state], outputs=[chat_state, chatbot, user_in, links_panel], ) def on_env(env_name): try: push_pushover(f"API version lookup: {env_name}") except Exception: pass return get_api_version(env_name or "") env_btn.click(on_env, inputs=[env_in], outputs=[env_out]) # Local dev launch (no header gating). For Spaces, FastAPI app is defined below as `app`. demo.launch() # --- Hugging Face Spaces: header-gated FastAPI with Gradio mounted --- SECRET_HEADER_NAME = "tmauthtoken" SECRET_HEADER_VALUE = "1xl&e7VykhpG%g7n5V@L**Y@@ito&f" def _no_access_page() -> str: return ( "No Access" "" "
    No Access
    " "
    Missing or invalid access header. Please access this app via the approved proxy.
    " "
    " ) def _build_mounted_app() -> FastAPI: resource_html_local = build_resource_cards() with gr.Blocks(css=custom_css) as mounted_demo: gr.Markdown(""" ### UiCrowds Assistant Ask questions about the knowledge base. Links open in a new tab. Use the API Version tool for environments like alpha, staging, europe, etc. """) with gr.Row(): with gr.Column(scale=1): gr.Markdown("**Resources**") resources_panel = gr.HTML(resource_html_local) gr.Markdown("**API version lookup**") env_in = gr.Textbox(label="Environment (e.g., alpha, staging, europe, us)") env_btn = gr.Button("Get API Version") env_out = gr.JSON(label="Version result") with gr.Column(scale=2): chatbot = gr.Chatbot(height=500) with gr.Row(): user_in = gr.Textbox(placeholder="Type your message...", scale=4) send_btn = gr.Button("Send", scale=1) gr.Markdown("**Links from last response**") links_panel = gr.HTML("Send a message to see extracted links here.") chat_state = gr.State([]) def on_send(user_message, state): try: push_pushover(f"UiCrowds query: {user_message}") except Exception: pass history_messages = [] for u, a in state: history_messages.append({"role": "user", "content": u}) history_messages.append({"role": "assistant", "content": a}) assistant_message = chat(user_message, history_messages) new_state = state + [(user_message, assistant_message)] links_html = extract_links_markdown_to_html(assistant_message) return new_state, new_state, "", links_html send_btn.click(on_send, inputs=[user_in, chat_state], outputs=[chat_state, chatbot, user_in, links_panel]) user_in.submit(on_send, inputs=[user_in, chat_state], outputs=[chat_state, chatbot, user_in, links_panel]) def on_env(env_name): try: push_pushover(f"API version lookup: {env_name}") except Exception: pass return get_api_version(env_name or "") env_btn.click(on_env, inputs=[env_in], outputs=[env_out]) fastapi_app = FastAPI() @fastapi_app.middleware("http") async def _gatekeeper(request: Request, call_next): token = request.headers.get(SECRET_HEADER_NAME, "") if token != SECRET_HEADER_VALUE: return Response(content=_no_access_page(), media_type="text/html", status_code=status.HTTP_403_FORBIDDEN) return await call_next(request) mounted = gr.mount_gradio_app(fastapi_app, mounted_demo, path="/") return mounted # Expose `app` for Spaces runtime app = _build_mounted_app()