{"id":23933034,"url":"https://github.com/parteeksingh24/kubernetes-query-agent","last_synced_at":"2025-09-11T15:33:28.576Z","repository":{"id":259977238,"uuid":"879966155","full_name":"parteeksingh24/kubernetes-query-agent","owner":"parteeksingh24","description":"A demonstration of an AI agent that answers simple queries about apps deployed on a Kubernetes cluster.","archived":false,"fork":false,"pushed_at":"2024-11-05T23:01:59.000Z","size":29,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-01-06T00:34:11.987Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/parteeksingh24.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2024-10-28T21:45:11.000Z","updated_at":"2024-11-05T23:02:02.000Z","dependencies_parsed_at":null,"dependency_job_id":"e7e962d2-a890-4522-9614-12b5c84ad30e","html_url":"https://github.com/parteeksingh24/kubernetes-query-agent","commit_stats":null,"previous_names":["parteeksingh24/kubernetes-query-agent"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/parteeksingh24/kubernetes-query-agent","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/parteeksingh24%2Fkubernetes-query-agent","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/parteeksingh24%2Fkubernetes-query-agent/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/parteeksingh24%2Fkubernetes-query-agent/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/parteeksingh24%2Fkubernetes-query-agent/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/parteeksingh24","download_url":"https://codeload.github.com/parteeksingh24/kubernetes-query-agent/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/parteeksingh24%2Fkubernetes-query-agent/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":274660284,"owners_count":25326175,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-09-11T02:00:13.660Z","response_time":74,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2025-01-06T00:29:29.815Z","updated_at":"2025-09-11T15:33:28.301Z","avatar_url":"https://github.com/parteeksingh24.png","language":"Python","funding_links":[],"categories":["Building"],"sub_categories":["Deployment"],"readme":"# Kubernetes Query Agent\n\nA FastAPI-based AI agent that answers queries about applications deployed on a Kubernetes cluster.\n\n## Table of Contents\n\n1. [Introduction](#introduction)\n2. [Features](#features)\n3. [Architecture](#architecture)\n4. [Installation](#installation)\n5. [Usage](#usage)\n6. [Troubleshooting Tips](#troubleshooting-tips)\n7. [License](#license)\n\n## Introduction\n\nThe Kubernetes Query Agent is a basic tool designed to make understanding Kubernetes cluster resources simple and efficient. By leveraging natural language processing (NLP) with GPT-4o-mini, this application **classifies and processes user queries**, automatically retrieving the relevant information from your Kubernetes environment.\n\nDeveloped as part of the *Cleric Query Agent Assignment*, this Python-based application provides a RESTful API, built with FastAPI and Pydantic, that interprets and responds to user requests.\n\n### How It Works\n\nThe Query Agent follows a three-step process, done in succession to process user queries:\n1. GPT-4o-mini performs **query classification** by determining the *query type* (one of 14 accepted queries) and **extracts parameters** related to that query.\n    - For example, if a user asks about the status of `example-pod`, the main extracted parameter would be `pod_name=example-pod`.\n2. Using the query type and corresponding parameters, the application calls the corresponding Kubernetes API function to retrieve the desired information.\n3. Finally, the application returns a *simplified* version of the API output.\n    - For example, this step would simplify `my-deployment-56c598c8fc` to `my-deployment`, with hash suffixes removed.\n\nAs a result, the *Kubernetes Query Agent* performs **read-only** actions on the Kubernetes cluster.\n\n## Features\n\n- *Query Classification*: The agent uses NLP to classify user queries into predefined types, such as \"count_pods\", \"pod_status\", \"count_nodes\", etc.\n- *Kubernetes Integration*: The agent interacts with the Kubernetes API to fetch information about deployed resources, including pods, deployments, services, and nodes.\n- *Error Handling*: The agent provides clear error messages for various types of errors, including validation errors, Kubernetes API errors, and unexpected exceptions.\n- *Logging*: The agent logs important events, including incoming queries, classification results, and API responses, to the `agent.log` file for debugging and monitoring purposes.\n\n## Architecture\n\n### Key Components\n\n1. FastAPI Application (`main.py`): The main entry point of the application, handling incoming HTTP requests and responses.\n2. Query Classifier (`utils.py`): Responsible for analyzing user queries and classifying them into predefined types using natural language processing.\n3. Kubernetes Client (`clients.py`): Provides a wrapper around the Kubernetes Python client, allowing the agent to interact with the Kubernetes API.\n4. Query Handlers (`handlers.py`): Implement the logic to fetch and process information from the Kubernetes cluster for each query type.\n5. Utilities (`utils.py`): Helper functions for tasks such as Kubernetes resource name simplification and returning Kubernetes cluster information.\n\n### Scope of Queries\n\nThe agent is capable of handling the following types of queries:\n1. `count_pods`: Count pods in a namespace\n2. `pod_status`: Get status of a specific pod\n3. `count_nodes`: Count cluster nodes\n4. `deployment_pods`: Get pods from a deployment\n5. `service_port`: Get port of a service\n6. `deployment_replicas`: Get replica count of deployment\n7. `pod_containers`: List containers in a pod\n8. `service_type`: Get service type\n9. `pod_namespace`: Get namespace of a pod\n10. `list_namespaces`: List all namespaces\n11. `node_status`: Get status of a specific node\n12. `list_services`: List services in a namespace\n13. `pod_logs`: Get recent logs from a pod\n14. `resource_usage`: Get resource usage/requests for a pod\n\n### Technical Implementation\n\nTo *handle* the 14 accepted queries in a modular way, each query is related to its own handler class. These *handlers* call their respective Kubernetes API function.\n\nThe `QUERY_HANDLERS` dictionary links these query types with their associated handler class, as shown below:\n\n```\n# Handler Protocol\nclass QueryHandler(Protocol):\n    def handle(self, parameters: Dict[str, Any]) -\u003e str:\n        pass\n\n# Handler Registry\nQUERY_HANDLERS = {\n    \"count_pods\": CountPodsHandler(),\n    \"pod_status\": PodStatusHandler(),\n    \"count_nodes\": CountNodesHandler(),\n    \"deployment_pods\": DeploymentPodsHandler(),\n    # ... additional handlers\n}\n```\n\nFrom here, the `get_kubernetes_info` function uses the given `query_type` to look up the appropriate handler. It executes this handler with the necessary parameters, and returns a formatted response. This structure effectively *delegates the query processing* to each specific type of question asked:\n\n```\ndef get_kubernetes_info(query_type: str, parameters: dict) -\u003e str:\n    # Get the appropriate handler for this query type from the registry\n    handler = QUERY_HANDLERS.get(query_type)\n    if not handler:\n        raise ValueError(f\"Unsupported query type: {query_type}\")\n        \n    # Delegate the actual query processing to the specific handler\n    return handler.handle(parameters)\n```\n\nPutting all of this together, the `process_query` function will classify the incoming query, then call the `get_kubernetes_info` function to invoke the correct Kubernetes API function for that query:\n\n```\ndef process_query(request: QueryRequest):\n    # Classify query using GPT-4o-mini\n    classification = classify_query(request.query)\n\n    # Get info. from Kubernetes\n    answer = get_kubernetes_info(\n        classification['type'],\n        classification.get('parameters', {})\n    )\n\n    # Return using the specified response model/format\n    return QueryResponse(query=request.query, answer=answer)\n```\n\n## Installation\n\n### Prerequisites\n\nBefore you begin, ensure you have the following installed:\n- **Python 3.10+**: Make sure Python is installed and accessible from your command line.\n- **[Minikube](https://minikube.sigs.k8s.io/docs/start/)**: A tool that runs a single-node Kubernetes cluster locally, perfect for testing the Query Agent.\n- **[kubectl](https://kubernetes.io/docs/tasks/tools/)**: The official Kubernetes CLI tool for interacting with and managing Kubernetes clusters.\n- **[Docker](https://docs.docker.com/get-docker/)**: A platform for developing, shipping, and running containerized applications. Required by Minikube.\n- **Virtual Environment**: A suggested approach to isolate project dependencies from other Python projects and system packages.\n\nYou'll also need:\n- An **[OpenAI API](https://platform.openai.com/) key** with sufficient credits for query classification.\n\n### Setup\n\n1. Clone the repository:\n```\ngit clone https://github.com/parteeksingh24/kubernetes-query-agent.git\ncd kubernetes-query-agent\n```\n\n2. Create and activate a virtual environment:\n```\npython3.10 -m venv venv\nsource venv/bin/activate  # On Windows, use `venv\\Scripts\\activate`\n```\n\n3. Install dependencies:\n```\npip install -r requirements.txt\n```\n\n4. Configure environment variables:\nCreate an `.env` file in the root directory and add your OpenAI API key:\n```\nOPENAI_API_KEY=your-openai-api-key\n```\n\n## Usage\n\n### Running the Agent\n\n1. Start Minikube:\n```\nminikube start\n```\n\n2. Deploy sample applications:\nUse `kubectl` (e.g., create deployments, run pods) to test queries. For example:\n```\nkubectl create deployment example-pod --image=nginx\n```\nThis creates a simple Nginx pod in the default namespace.\n\n3. Start the FastAPI server:\nThere are various ways to run the Query Agent, but the simplest is:\n```\npython main.py\n```\nThe server will start running on http://localhost:8000.\n\n### Interacting with the Agent\n\nYou can interact with the agent using a tool like curl or a web browser. The following shows how to use `curl` on the command line.\n\n1. Submit a query\nTo interact with the Kubernetes Query Agent, send a POST request to the `/query` endpoint. For example:\n```\ncurl -X POST \"http://localhost:8000/query\" \\\n-H \"Content-Type: application/json\" \\\n-d '{\"query\": \"How many pods are in the default namespace?\"}'\n```\n\n2. The agent will respond with the answer:\n```\n{\n    \"query\": \"How many pods are in the default namespace?\",\n    \"answer\": \"1\"\n}\n```\n\n### Logging\n\nLogs are written to `agent.log` for debugging and monitoring query processing.\n\n## Troubleshooting Tips\n\n1. *Connection Issues*: Ensure Minikube is running and your kubeconfig is correctly set up:\n```\nminikube start\nminikube status  # Should show \"Running\"\nkubectl cluster-info  # Should show cluster information\n```\nBe sure to check that the Kubernetes configuration file is located at `~/.kube/config`.\n\n2. Ensure the *FastAPI service* is running (via the command line):\n```\ncurl -X POST \"http://localhost:8000/health\"\n```\n\n3. *API Key errors*: Verify your OpenAI API key is correctly configured in the `.env` file.\n4. *Check logs*: Review the `agent.log` file to help diagnose issues if they persist. \n\n## License\n\nThis project is licensed under the MIT License.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fparteeksingh24%2Fkubernetes-query-agent","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fparteeksingh24%2Fkubernetes-query-agent","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fparteeksingh24%2Fkubernetes-query-agent/lists"}