File size: 5,037 Bytes
ef51d88 | 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 | """
Client implementation for DevOps Incident Response Environment.
This module provides an EnvClient class that can connect to a
remote OpenEnv server via HTTP requests.
"""
from __future__ import annotations
from typing import Any, Optional
import requests
from pydantic import BaseModel
from models import Action, Observation, EnvironmentState
class EnvClientConfig(BaseModel):
"""Configuration for the environment client."""
base_url: str = "http://localhost:7860"
timeout: int = 30
class EnvClient:
"""
Client for interacting with a remote DevOps Incident Response Environment.
This client connects to the FastAPI server and provides a Python interface
for the OpenEnv API endpoints.
Example:
```python
from client import EnvClient
client = EnvClient("http://localhost:7860")
session_id, observation = client.reset("task_easy_oom")
while True:
action = get_action(observation) # Your agent logic
observation, reward, done, info = client.step(session_id, action)
if done:
break
score = client.grade(session_id)
print(f"Final score: {score}")
```
"""
def __init__(self, base_url: str = "http://localhost:7860", timeout: int = 30):
"""
Initialize the client.
Args:
base_url: URL of the OpenEnv server
timeout: Request timeout in seconds
"""
self.base_url = base_url.rstrip("/")
self.timeout = timeout
self._session = requests.Session()
def reset(self, task_id: str = "task_easy_oom") -> tuple[str, Observation]:
"""
Reset the environment and start a new episode.
Args:
task_id: The task to run
Returns:
Tuple of (session_id, initial_observation)
"""
response = self._session.post(
f"{self.base_url}/reset",
json={"task_id": task_id},
timeout=self.timeout,
)
response.raise_for_status()
data = response.json()
return data["session_id"], Observation(**data["observation"])
def step(
self,
session_id: str,
action: Action | str,
) -> tuple[Observation, float, bool, dict[str, Any]]:
"""
Take a step in the environment.
Args:
session_id: The session ID from reset()
action: The action to take (Action object or action string)
Returns:
Tuple of (observation, reward, done, info)
"""
if isinstance(action, str):
payload = {"session_id": session_id, "action_str": action}
else:
payload = {"session_id": session_id, "action": action.model_dump()}
response = self._session.post(
f"{self.base_url}/step",
json=payload,
timeout=self.timeout,
)
response.raise_for_status()
data = response.json()
return (
Observation(**data["observation"]),
data["reward"],
data["done"],
data.get("info", {}),
)
def state(self, session_id: str) -> EnvironmentState:
"""
Get the current environment state.
Args:
session_id: The session ID
Returns:
Full environment state
"""
response = self._session.get(
f"{self.base_url}/state/{session_id}",
timeout=self.timeout,
)
response.raise_for_status()
data = response.json()
return EnvironmentState(**data["state"])
def grade(self, session_id: str) -> dict[str, Any]:
"""
Grade the completed episode.
Args:
session_id: The session ID
Returns:
Grading result with score and breakdown
"""
response = self._session.post(
f"{self.base_url}/grade",
json={"session_id": session_id},
timeout=self.timeout,
)
response.raise_for_status()
return response.json()
def list_tasks(self) -> list[dict[str, Any]]:
"""
List all available tasks.
Returns:
List of task information dictionaries
"""
response = self._session.get(
f"{self.base_url}/tasks",
timeout=self.timeout,
)
response.raise_for_status()
return response.json()["tasks"]
def health(self) -> dict[str, Any]:
"""
Check server health.
Returns:
Health status
"""
response = self._session.get(
f"{self.base_url}/health",
timeout=self.timeout,
)
response.raise_for_status()
return response.json()
def close(self):
"""Close the client session."""
self._session.close()
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.close()
|