{"repo": "alli-ekundayo/ego", "files": {"alibaba_cloud_proof.py": {"3b567d429cf53d1afa52e57aff5e4f4036b23fdc": {"t": 1785674245.905973, "n": 11963, "h": "bd858d77c6770575", "c": "\"\"\"alibaba_cloud_proof.py\n========================\nProof of Alibaba Cloud deployment — required by the Global AI Hackathon\nwith Qwen Cloud (Track 1: MemoryAgent).\n\nThis file demonstrates use of Alibaba Cloud services and APIs:\n\n 1. Qwen Cloud (DashScope) — LLM inference via the OpenAI-compatible endpoint\n Used by: agents/memory_agent.py → consolidate_node()\n\n 2. Alibaba Cloud Container Service for Kubernetes (ACK) or ECS\n The Docker image is pushed to Alibaba Cloud Container Registry (ACR)\n and deployed on ACK/ECI.\n\n 3. Alibaba Cloud Object Storage Service (OSS) — optional dataset mirror\n\nRun this script to verify live connectivity to Alibaba Cloud / DashScope:\n\n python alibaba_cloud_proof.py\n\nExpected output:\n ✓ DashScope API reachable\n ✓ Qwen model: qwen-plus\n ✓ Response: \n\"\"\"\n\nimport os\nimport sys\nfrom pathlib import Path\n\n# Load .env from the project root so DASHSCOPE_API_KEY is available\n_env_path = Path(__file__).parent / \".env\"\nif _env_path.exists():\n for _line in _env_path.read_text().splitlines():\n _line = _line.strip()\n if _line and not _line.startswith(\"#\") and \"=\" in _line:\n _k, _, _v = _line.partition(\"=\")\n os.environ.setdefault(_k.strip(), _v.strip())\n\n\n\ndef verify_dashscope_connection() -> None:\n \"\"\"\n Verify that the DashScope (Alibaba Cloud AI) endpoint is reachable and\n the configured Qwen model responds correctly.\n\n This uses the OpenAI-compatible DashScope international endpoint:\n https://dashscope-intl.aliyuncs.com/compatible-mode/v1\n\n Environment variables:\n DASHSCOPE_API_KEY : your Alibaba Cloud DashScope API key\n QWEN_MODEL : model name (default: qwen-plus)\n \"\"\"\n api_key = os.environ.get(\"DASHSCOPE_API_KEY\", \"\")\n if not api_key:\n print(\"✗ DASHSCOPE_API_KEY not set — skipping live check.\")\n print(\" Set it with: export DASHSCOPE_API_KEY=sk-...\")\n sys.exit(1)\n\n model = os.environ.get(\"QWEN_MODEL\", \"qwen-plus\")\n base_url = \"https://dashscope-intl.aliyuncs.com/compatible-mode/v1\"\n\n print(f\" Connecting to DashScope: {base_url}\")\n print(f\" Model: {model}\")\n\n try:\n from openai import OpenAI # openai >= 1.0 (DashScope-compatible)\n\n client = OpenAI(api_key=api_key, base_url=base_url)\n completion = client.chat.completions.create(\n model=model,\n messages=[\n {\n \"role\": \"user\",\n \"content\": (\n \"You are a helpful assistant. \"\n \"Reply with exactly one sentence confirming you are Qwen running on Alibaba Cloud.\"\n ),\n }\n ],\n max_tokens=60,\n temperature=0.0,\n )\n reply = completion.choices[0].message.content or \"\"\n print(\"✓ DashScope API reachable\")\n print(f\"✓ Qwen model: {model}\")\n print(f\"✓ Response: {reply.strip()}\")\n\n except Exception as exc:\n print(f\"✗ DashScope connection failed: {exc}\")\n sys.exit(1)\n\n\ndef show_deployment_info() -> None:\n \"\"\"\n Actively verify each Alibaba Cloud deployment claim instead of printing\n hardcoded strings.\n\n Checks performed:\n 1. ACR image — HTTP manifest query to Alibaba Cloud Container Registry\n 2. Codebase patterns — scan source files for Qwen/DashScope usage\n 3. requirements.txt — confirm dashscope, openai, langchain-openai are listed\n 4. Installed packages — verify they are importable in the current venv\n \"\"\"\n import importlib.util\n import urllib.request\n import urllib.error\n import urllib.parse\n import base64\n from pathlib import Path\n\n root = Path(__file__).parent\n passed = 0\n failed = 0\n\n def ok(label: str, detail: str = \"\") -> None:\n nonlocal passed\n passed += 1\n suffix = f\" ({detail})\" if detail else \"\"\n print(f\" ✓ {label}{suffix}\")\n\n def fail(label: str, detail: str = \"\") -> None:\n nonlocal failed\n failed += 1\n suffix = f\" ({detail})\" if detail else \"\"\n print(f\" ✗ {label}{suffix}\")\n\n print()\n print(\"=== Alibaba Cloud Deployment Verification ===\")\n\n # ------------------------------------------------------------------\n # 1. ACR image — query the registry manifest endpoint\n # ------------------------------------------------------------------\n print()\n print(\"[ 1 / 4 ] Alibaba Cloud Container Registry (ACR)\")\n registry = os.environ.get(\"ACR_REGISTRY\", \"\")\n namespace = os.environ.get(\"ACR_NAMESPACE\", \"\")\n acr_user = os.environ.get(\"ACR_USER\", \"\")\n acr_pass = os.environ.get(\"ACR_PASSWORD\", \"\") # fixed password set in ACR console (not a GitHub PAT)\n image_tag = \"latest\"\n image_repo = \"ego-api\"\n\n if not registry:\n fail(\"ACR_REGISTRY not set in .env — cannot verify image\")\n elif not acr_pass:\n fail(\"ACR_PASSWORD not set in .env — add your ACR fixed password\")\n else:\n full_image = f\"{registry}/{namespace}/{image_repo}:{image_tag}\"\n print(f\" Registry : {registry}\")\n print(f\" Image : {namespace}/{image_repo}:{image_tag}\")\n\n import json as _json\n import re as _re\n import subprocess as _sp\n\n # ── Helper: get a Bearer token via the ACR OAuth dance ────────────\n def _get_token(scope: str) -> str:\n probe = urllib.request.Request(f\"https://{registry}/v2/\")\n www_auth = \"\"\n try:\n urllib.request.urlopen(probe, timeout=10)\n except urllib.error.HTTPError as _e:\n if _e.code == 401:\n www_auth = _e.headers.get(\"Www-Authenticate\", \"\")\n realm = _re.search(r'realm=\"([^\"]+)\"', www_auth).group(1)\n service = _re.search(r'service=\"([^\"]+)\"', www_auth).group(1)\n turl = (\n f\"{realm}\"\n f\"?service={urllib.parse.quote(service)}\"\n f\"&scope={urllib.parse.quote(scope)}\"\n )\n treq = urllib.request.Request(turl)\n creds = base64.b64encode(f\"{acr_user}:{acr_pass}\".encode()).decode()\n treq.add_header(\"Authorization\", f\"Basic {creds}\")\n with urllib.request.urlopen(treq, timeout=10) as tr:\n d = _json.loads(tr.read())\n return d.get(\"token\") or d.get(\"access_token\", \"\")\n\n # ── Part A: tags/list — confirms the tag exists in the registry ───\n try:\n token = _get_token(f\"repository:{namespace}/{image_repo}:pull\")\n tags_url = f\"https://{registry}/v2/{namespace}/{image_repo}/tags/list\"\n treq = urllib.request.Request(tags_url)\n treq.add_header(\"Authorization\", f\"Bearer {token}\")\n with urllib.request.urlopen(treq, timeout=10) as tr:\n tags_data = _json.loads(tr.read())\n tags = tags_data.get(\"tags\") or []\n if image_tag in tags:\n ok(f\"Tag '{image_tag}' confirmed in ACR tags/list\", f\"all tags: {tags}\")\n else:\n fail(f\"Tag '{image_tag}' not found in ACR\", f\"available: {tags}\")\n except urllib.error.HTTPError as exc:\n fail(\"ACR tags/list HTTP error\", f\"{exc.code} {exc.reason}\")\n except Exception as exc:\n fail(\"ACR tags/list failed\", str(exc))\n\n # ── Part B: docker manifest inspect — fetches the full manifest ───\n try:\n # Login first so docker has valid credentials in its store\n login_result = _sp.run(\n [\"docker\", \"login\", \"--username\", acr_user,\n \"--password-stdin\", registry],\n input=acr_pass, capture_output=True, text=True, timeout=30,\n )\n if login_result.returncode != 0:\n raise RuntimeError(f\"docker login failed: {login_result.stderr.strip()}\")\n\n inspect_result = _sp.run(\n [\"docker\", \"manifest\", \"inspect\", full_image],\n capture_output=True, text=True, timeout=30,\n )\n if inspect_result.returncode == 0:\n # Parse the manifest to extract digest + platform info\n try:\n mf = _json.loads(inspect_result.stdout)\n schema = mf.get(\"schemaVersion\", \"?\")\n media = mf.get(\"mediaType\", mf.get(\"config\", {}).get(\"mediaType\", \"\"))\n ok(\n \"docker manifest inspect succeeded\",\n f\"schemaVersion={schema} mediaType={media.split('.')[-1]}\",\n )\n except _json.JSONDecodeError:\n ok(\"docker manifest inspect succeeded\", inspect_result.stdout[:80].strip())\n else:\n fail(\"docker manifest inspect failed\", inspect_result.stderr.strip()[:120])\n except FileNotFoundError:\n fail(\"docker not found — install Docker to enable manifest check\")\n except Exception as exc:\n fail(\"docker manifest inspect error\", str(exc)[:120])\n\n # ------------------------------------------------------------------\n # 2. Codebase patterns — scan for Qwen/DashScope references\n # ------------------------------------------------------------------\n print()\n print(\"[ 2 / 4 ] Qwen API usage in codebase\")\n patterns = [\n (\"agents/memory_agent.py\", \"_get_qwen_llm\"),\n (\"agents/memory_agent.py\", \"consolidate_node\"),\n (\"core/config.py\", \"DASHSCOPE_API_KEY\"),\n (\"core/config.py\", \"QWEN_MODEL\"),\n ]\n for rel_path, token in patterns:\n fpath = root / rel_path\n if not fpath.exists():\n fail(f\"{rel_path} · {token}\", \"file not found\")\n elif token in fpath.read_text(encoding=\"utf-8\", errors=\"replace\"):\n ok(f\"{rel_path} · {token}\")\n else:\n fail(f\"{rel_path} · {token}\", \"token not found in file\")\n\n # ------------------------------------------------------------------\n # 3. requirements.txt — confirm packages are declared\n # ------------------------------------------------------------------\n print()\n print(\"[ 3 / 4 ] requirements.txt declarations\")\n req_file = root / \"requirements.txt\"\n required_pkgs = [\"openai\", \"langchain-openai\", \"dashscope\"]\n if not req_file.exists():\n for pkg in required_pkgs:\n fail(f\"{pkg} in requirements.txt\", \"file not found\")\n else:\n req_text = req_file.read_text(encoding=\"utf-8\").lower()\n for pkg in required_pkgs:\n if pkg.lower() in req_text:\n ok(f\"{pkg} listed in requirements.txt\")\n else:\n fail(f\"{pkg} listed in requirements.txt\", \"missing\")\n\n # ------------------------------------------------------------------\n # 4. Installed packages — importable in current environment\n # ------------------------------------------------------------------\n print()\n print(\"[ 4 / 4 ] Packages installed in current Python environment\")\n import_map = {\n \"openai\": \"openai\",\n \"langchain-openai\": \"langchain_openai\",\n \"dashscope\": \"dashscope\",\n }\n for display_name, import_name in import_map.items():\n if importlib.util.find_spec(import_name) is not None:\n ok(f\"{display_name} importable ({import_name})\")\n else:\n fail(f\"{display_name} not importable ({import_name})\", \"run: pip install \" + display_name)\n\n # ------------------------------------------------------------------\n # Summary\n # ------------------------------------------------------------------\n print()\n total = passed + failed\n print(f\"=== Result: {passed}/{total} checks passed {'✓' if failed == 0 else '✗'} ===\")\n\n\nif __name__ == \"__main__\":\n print(\"=== Ego — Alibaba Cloud / Qwen Proof of Deployment ===\")\n print()\n verify_dashscope_connection()\n show_deployment_info()\n"}}}}