Spaces:
Runtime error
Runtime error
File size: 6,982 Bytes
90a59c9 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 |
"""
RunPod Client - Low-level GraphQL API client for RunPod
Provides direct access to RunPod's GraphQL API for pod management.
"""
import os
import requests
from typing import Optional, List, Dict
from dataclasses import dataclass
@dataclass
class PodInfo:
"""Information about a RunPod pod"""
id: str
name: str
status: str
gpu_type: str
gpu_count: int
cost_per_hour: float
runtime: Optional[Dict] = None
class RunPodClient:
"""Low-level client for RunPod GraphQL API"""
def __init__(self, api_key: Optional[str] = None):
self.api_key = api_key or os.getenv("RUNPOD_API_KEY")
if not self.api_key:
raise ValueError("RunPod API key required. Set RUNPOD_API_KEY environment variable.")
self.endpoint = "https://api.runpod.io/graphql"
self.headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {self.api_key}"
}
def _query(self, query: str, variables: Optional[Dict] = None) -> Dict:
"""Execute a GraphQL query"""
payload = {
"query": query,
"variables": variables or {}
}
response = requests.post(
self.endpoint,
json=payload,
headers=self.headers,
timeout=30
)
if response.status_code != 200:
raise Exception(f"GraphQL request failed: {response.status_code} {response.text}")
return response.json()
def list_pods(self) -> List[PodInfo]:
"""List all pods"""
query = """
query {
myself {
pods {
id
name
desiredStatus
runtime {
gpus {
id
}
}
machine {
podHostId
}
costPerHr
gpuCount
}
}
}
"""
result = self._query(query)
if "errors" in result:
print(f"Error listing pods: {result['errors']}")
return []
pods_data = result.get("data", {}).get("myself", {}).get("pods", [])
pods = []
for pod_data in pods_data:
gpu_type = "GPU" # Generic GPU type since API doesn't provide type details
if pod_data.get("runtime") and pod_data["runtime"].get("gpus"):
gpu_id = pod_data["runtime"]["gpus"][0].get("id", "")
if gpu_id:
gpu_type = f"GPU-{gpu_id[:8]}" # Use shortened GPU ID
pods.append(PodInfo(
id=pod_data["id"],
name=pod_data["name"],
status=pod_data.get("desiredStatus", "unknown"),
gpu_type=gpu_type,
gpu_count=pod_data.get("gpuCount", 0),
cost_per_hour=pod_data.get("costPerHr", 0.0),
runtime=pod_data.get("runtime")
))
return pods
def create_pod(
self,
name: str,
image_name: str,
gpu_type_id: str,
gpu_count: int = 1,
volume_in_gb: int = 100,
container_disk_in_gb: int = 50,
ports: str = "8888/http"
) -> Optional[str]:
"""Create a new pod"""
query = """
mutation($input: PodFindAndDeployOnDemandInput!) {
podFindAndDeployOnDemand(input: $input) {
id
name
desiredStatus
}
}
"""
variables = {
"input": {
"name": name,
"imageName": image_name,
"gpuTypeId": gpu_type_id,
"gpuCount": gpu_count,
"volumeInGb": volume_in_gb,
"containerDiskInGb": container_disk_in_gb,
"ports": ports,
"cloudType": "ALL"
}
}
result = self._query(query, variables)
if "errors" in result:
print(f"Error creating pod: {result['errors']}")
return None
pod_data = result.get("data", {}).get("podFindAndDeployOnDemand")
if pod_data:
return pod_data["id"]
return None
def stop_pod(self, pod_id: str) -> bool:
"""Stop a running pod"""
query = """
mutation($input: PodStopInput!) {
podStop(input: $input) {
id
desiredStatus
}
}
"""
variables = {
"input": {
"podId": pod_id
}
}
result = self._query(query, variables)
if "errors" in result:
print(f"Error stopping pod: {result['errors']}")
return False
return True
def terminate_pod(self, pod_id: str) -> bool:
"""Terminate a pod"""
query = """
mutation($input: PodTerminateInput!) {
podTerminate(input: $input)
}
"""
variables = {
"input": {
"podId": pod_id
}
}
result = self._query(query, variables)
if "errors" in result:
print(f"Error terminating pod: {result['errors']}")
return False
return True
def get_gpu_types(self) -> List[Dict]:
"""Get available GPU types"""
query = """
query {
gpuTypes {
id
displayName
memoryInGb
secureCloud
communityCloud
}
}
"""
result = self._query(query)
if "errors" in result:
print(f"Error getting GPU types: {result['errors']}")
return []
gpu_types = result.get("data", {}).get("gpuTypes", [])
return gpu_types
def get_pod_details(self, pod_id: str) -> Optional[Dict]:
"""Get detailed information about a specific pod"""
query = """
query($podId: String!) {
pod(input: {podId: $podId}) {
id
name
desiredStatus
runtime {
gpus {
id
}
ports {
ip
isIpPublic
privatePort
publicPort
type
}
}
machine {
podHostId
}
gpuCount
costPerHr
}
}
"""
variables = {"podId": pod_id}
result = self._query(query, variables)
if "errors" in result:
print(f"Error getting pod details: {result['errors']}")
return None
return result.get("data", {}).get("pod")
|