|
| 1 | +import asyncio |
| 2 | +import json |
| 3 | +import logging |
| 4 | +import re |
| 5 | +import subprocess |
| 6 | +from pathlib import Path |
| 7 | +from typing import Optional, Any |
| 8 | + |
| 9 | +from agno.agent import Agent |
| 10 | +from agno.models.openai import OpenAIChat |
| 11 | +from agno.tools.mcp import MultiMCPTools |
| 12 | +from agno.tools.thinking import ThinkingTools |
| 13 | +from dotenv import load_dotenv |
| 14 | +from xpander_utils.sdk.adapters import AgnoAdapter |
| 15 | + |
| 16 | +# set up logging |
| 17 | +t_logger = logging.getLogger(__name__) |
| 18 | + |
| 19 | +# look for any kubectl command and strip code fences |
| 20 | +KUBECTL = re.compile(r"kubectl\s+(.+)", re.IGNORECASE) |
| 21 | +FENCE = re.compile(r"```[\s\S]*?```", re.MULTILINE) |
| 22 | + |
| 23 | +class LocalKubectlTool(MultiMCPTools): |
| 24 | + name = "kubectl" |
| 25 | + |
| 26 | + def __init__(self) -> None: |
| 27 | + super().__init__([self.name], env={}) |
| 28 | + # capture context once |
| 29 | + self.ctx = subprocess.run( |
| 30 | + ["kubectl","config","current-context"], |
| 31 | + capture_output=True, text=True, check=False |
| 32 | + ).stdout.strip() |
| 33 | + |
| 34 | + def kubectl(self, flags: str) -> str: |
| 35 | + # run kubectl with saved context |
| 36 | + cmd = ["kubectl"] + (["--context", self.ctx] if self.ctx else []) + flags.split() |
| 37 | + p = subprocess.run(cmd, capture_output=True, text=True) |
| 38 | + return p.stdout if p.returncode == 0 else p.stderr |
| 39 | + |
| 40 | +class SREAgent: |
| 41 | + def __init__(self, adapter: AgnoAdapter) -> None: |
| 42 | + self.adapter = adapter |
| 43 | + self.agent: Optional[Agent] = None |
| 44 | + self.ktool = LocalKubectlTool() |
| 45 | + |
| 46 | + async def run( |
| 47 | + self, |
| 48 | + message: str, |
| 49 | + *, |
| 50 | + user_id: str, |
| 51 | + session_id: str, |
| 52 | + cli: bool = False |
| 53 | + ) -> Any: |
| 54 | + # initialize LLM agent if needed |
| 55 | + if not self.agent: |
| 56 | + self.agent = self.build_agent() |
| 57 | + |
| 58 | + # get AI response |
| 59 | + resp = await ( |
| 60 | + self.agent.aprint_response(message, user_id, session_id) |
| 61 | + if cli |
| 62 | + else self.agent.arun(message, user_id=user_id, session_id=session_id) |
| 63 | + ) |
| 64 | + |
| 65 | + # remove code fences |
| 66 | + clean = FENCE.sub( |
| 67 | + lambda m: "\n".join(m.group(0).splitlines()[1:-1]), resp.content |
| 68 | + ) |
| 69 | + # search anywhere for kubectl |
| 70 | + m = KUBECTL.search(clean) |
| 71 | + if m: |
| 72 | + flags = m.group(1).splitlines()[0].strip() |
| 73 | + resp.content = self.ktool.kubectl(flags) |
| 74 | + t_logger.info("ran kubectl %s", flags) |
| 75 | + return resp |
| 76 | + |
| 77 | + def build_agent(self) -> Agent: |
| 78 | + # set up the Agno agent with kubectl tool |
| 79 | + prompt = self.adapter.get_system_prompt() |
| 80 | + instr = ([prompt] if isinstance(prompt, str) else list(prompt)) + [ |
| 81 | + "When user asks about Kubernetes, reply with a kubectl command.", |
| 82 | + "Always run commands to fetch live data." |
| 83 | + ] |
| 84 | + return Agent( |
| 85 | + model=OpenAIChat(id="gpt-4o"), |
| 86 | + tools=[ThinkingTools(add_instructions=True), self.ktool], |
| 87 | + instructions=instr, |
| 88 | + storage=self.adapter.storage, |
| 89 | + markdown=True, |
| 90 | + add_history_to_messages=True |
| 91 | + ) |
| 92 | + |
| 93 | +async def _cli() -> None: |
| 94 | + load_dotenv() |
| 95 | + cfg = json.loads(Path("xpander_config.json").read_text()) |
| 96 | + backend = await asyncio.to_thread( |
| 97 | + AgnoAdapter, |
| 98 | + agent_id=cfg["agent_id"], api_key=cfg["api_key"], base_url=cfg.get("base_url") |
| 99 | + ) |
| 100 | + agent = SREAgent(backend) |
| 101 | + while True: |
| 102 | + text = input("➜ ").strip() |
| 103 | + if text.lower() in {"exit","quit"}: |
| 104 | + break |
| 105 | + print((await agent.run(text, user_id="cli", session_id="dev", cli=True)).content) |
| 106 | + |
| 107 | +if __name__ == "__main__": |
| 108 | + asyncio.run(_cli()) |
0 commit comments