-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUnityAPIClient.py
More file actions
executable file
·283 lines (229 loc) · 9.78 KB
/
UnityAPIClient.py
File metadata and controls
executable file
·283 lines (229 loc) · 9.78 KB
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
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
import logging
import aiohttp
import asyncio
from typing import Dict, Any, List, Optional, Union
import json
import time
logger = logging.getLogger(__name__)
class UnityAPIClient:
"""
Client for interacting with the Unity API endpoints.
Handles request/response and connection management with error handling.
"""
def __init__(self, base_url: str = "http://localhost:8080",
retry_count: int = 3, retry_delay: float = 1.0,
connection_timeout: float = 5.0):
"""
Initialize the Unity API client.
Args:
base_url: Base URL for the Unity API
retry_count: Number of retry attempts for failed requests
retry_delay: Delay between retry attempts in seconds
connection_timeout: Timeout for connection attempts in seconds
"""
self.base_url = base_url
self.retry_count = retry_count
self.retry_delay = retry_delay
self.connection_timeout = aiohttp.ClientTimeout(total=connection_timeout)
# Keep a single session for all requests
self._session = None
self._session_lock = asyncio.Lock()
# Keep track of connection status
self.connected = False
self.last_connection_attempt = 0
self.connection_check_interval = 10 # seconds
async def _ensure_session(self) -> aiohttp.ClientSession:
"""
Ensure a session exists and create one if needed.
Returns:
Active aiohttp ClientSession
"""
async with self._session_lock:
if self._session is None or self._session.closed:
self._session = aiohttp.ClientSession(timeout=self.connection_timeout)
return self._session
async def _close_session(self) -> None:
"""
Close the current session if it exists.
"""
async with self._session_lock:
if self._session and not self._session.closed:
await self._session.close()
self._session = None
async def check_connection(self) -> bool:
"""
Check if the Unity API is reachable.
Returns:
True if connected, False otherwise
"""
current_time = time.time()
# Don't check too frequently
if current_time - self.last_connection_attempt < self.connection_check_interval:
return self.connected
self.last_connection_attempt = current_time
try:
# Try to connect to the health endpoint
session = await self._ensure_session()
async with session.get(f"{self.base_url}/health", timeout=2.0) as response:
self.connected = response.status == 200
return self.connected
except Exception as e:
logger.warning(f"Connection check failed: {str(e)}")
self.connected = False
return False
async def _request(self, method: str, endpoint: str, data: Any = None,
headers: Dict[str, str] = None) -> Dict[str, Any]:
"""
Send a request to the Unity API with retry logic.
Args:
method: HTTP method (GET, POST, etc.)
endpoint: API endpoint path
data: Request payload (will be serialized to JSON)
headers: Request headers
Returns:
Response data as a dictionary
"""
if not await self.check_connection():
raise ConnectionError("Unity API is not reachable")
url = f"{self.base_url}/{endpoint.lstrip('/')}"
session = await self._ensure_session()
# Prepare headers with defaults
request_headers = {
"Content-Type": "application/json",
"Accept": "application/json"
}
if headers:
request_headers.update(headers)
# Convert data to JSON string if provided
json_data = json.dumps(data) if data else None
# Implement retry logic
for attempt in range(self.retry_count + 1):
try:
async with session.request(
method=method,
url=url,
data=json_data,
headers=request_headers
) as response:
response_text = await response.text()
if response.status == 204: # No content
return {"status": "success"}
# Try to parse as JSON
try:
response_data = json.loads(response_text)
except json.JSONDecodeError:
response_data = {"text": response_text}
# Handle error status
if response.status >= 400:
error_message = response_data.get("error", f"HTTP {response.status}: {response_text}")
if attempt < self.retry_count:
logger.warning(f"Request failed: {error_message}. Retrying ({attempt+1}/{self.retry_count})...")
await asyncio.sleep(self.retry_delay)
continue
else:
raise aiohttp.ClientResponseError(
request_info=response.request_info,
history=response.history,
status=response.status,
message=error_message,
headers=response.headers
)
return response_data
except (aiohttp.ClientError, asyncio.TimeoutError) as e:
if attempt < self.retry_count:
logger.warning(f"Request error: {str(e)}. Retrying ({attempt+1}/{self.retry_count})...")
await asyncio.sleep(self.retry_delay)
else:
logger.error(f"Request failed after {self.retry_count} retries: {str(e)}")
# Reset connection status on persistent failure
self.connected = False
raise
# Should never reach here, but just in case
raise RuntimeError("Request failed for unknown reason")
async def move_agent(self, agent_id: str, location: str) -> Dict[str, Any]:
"""
Send a move command to an agent.
Args:
agent_id: Unique identifier for the agent
location: Target location name or coordinates
Returns:
Response data as a dictionary
"""
endpoint = f"agent/{agent_id}/move"
data = {"location": location}
return await self._request("POST", endpoint, data)
async def agent_speak(self, agent_id: str, message: str) -> Dict[str, Any]:
"""
Send a speak command to an agent.
Args:
agent_id: Unique identifier for the agent
message: Message content
Returns:
Response data as a dictionary
"""
endpoint = f"agent/{agent_id}/speak"
data = {"message": message}
return await self._request("POST", endpoint, data)
async def initiate_conversation(self, agent_id: str, target_agent_id: str) -> Dict[str, Any]:
"""
Initiate a conversation between agents.
Args:
agent_id: Unique identifier for the initiating agent
target_agent_id: Unique identifier for the target agent
Returns:
Response data as a dictionary
"""
endpoint = f"agent/{agent_id}/converse"
data = {"targetAgent": target_agent_id}
return await self._request("POST", endpoint, data)
async def get_environment_state(self, agent_id: str) -> Dict[str, Any]:
"""
Get the current environment state from the perspective of an agent.
Args:
agent_id: Unique identifier for the agent
Returns:
Environment state data as a dictionary
"""
endpoint = f"env/{agent_id}"
return await self._request("GET", endpoint)
async def register_agent(self, agent_id: str, agent_data: Dict[str, Any]) -> Dict[str, Any]:
"""
Register a new agent with the Unity environment.
Args:
agent_id: Unique identifier for the agent
agent_data: Agent configuration data
Returns:
Response data as a dictionary
"""
endpoint = "agent/register"
data = {
"agentId": agent_id,
**agent_data
}
return await self._request("POST", endpoint, data)
async def deregister_agent(self, agent_id: str) -> Dict[str, Any]:
"""
Deregister an agent from the Unity environment.
Args:
agent_id: Unique identifier for the agent
Returns:
Response data as a dictionary
"""
endpoint = f"agent/{agent_id}/deregister"
return await self._request("POST", endpoint)
async def close(self) -> None:
"""
Close the client and release resources.
"""
await self._close_session()
async def __aenter__(self):
"""
Context manager entry.
"""
await self._ensure_session()
return self
async def __aexit__(self, exc_type, exc_val, exc_tb):
"""
Context manager exit.
"""
await self.close()