-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.py
More file actions
270 lines (216 loc) · 7.44 KB
/
client.py
File metadata and controls
270 lines (216 loc) · 7.44 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
"""
Code Reviewer Environment - OpenEnv Client
HTTP/WebSocket client for connecting to the environment.
"""
import os
import json
from typing import Optional, Dict, Any, List, Union
from dataclasses import dataclass, asdict
import asyncio
import websockets
import httpx
@dataclass
class CodeReviewerAction:
action_type: str
issue: Optional[Dict] = None
confidence: float = 1.0
reasoning: Optional[str] = None
@dataclass
class CodeReviewerObservation:
code_snippet: Dict
task_description: str
task_difficulty: str
step_number: int
max_steps: int
previous_issues: List
hint_available: bool
hint_text: Optional[str]
done: bool
info: Dict
@dataclass
class CodeReviewerReward:
total_reward: float
step_reward: float
issue_detection_reward: float
false_positive_penalty: float
completeness_reward: float
efficiency_reward: float
task_completion_score: float
@dataclass
class ReviewResult:
task_name: str
identified_issues: List
missed_issues: List
false_positives: List
total_reward: float
completion_score: float
steps_taken: int
success: bool
class CodeReviewerEnv:
"""
OpenEnv Client for Code Reviewer Environment.
Supports both sync (HTTP) and async (WebSocket) modes.
"""
def __init__(
self,
base_url: str = "http://localhost:7860",
task_name: str = "syntax_check",
session_id: Optional[str] = None,
):
"""
Initialize the environment client.
Args:
base_url: Base URL of the environment server
task_name: Default task to run
session_id: Session ID for stateful connections
"""
self.base_url = base_url.rstrip("/")
self.task_name = task_name
self.session_id = session_id or f"session_{id(self)}"
self._ws = None
self._http = httpx.Client(timeout=30.0)
def reset(self, task: Optional[str] = None) -> Dict[str, Any]:
"""
Reset the environment (HTTP mode).
Args:
task: Task name override
Returns:
Reset response with observation
"""
task = task or self.task_name
response = self._http.post(
f"{self.base_url}/reset",
json={"task": task, "session_id": self.session_id}
)
response.raise_for_status()
return response.json()
def step(self, action: Union[Dict, CodeReviewerAction]) -> Dict[str, Any]:
"""
Execute a step (HTTP mode).
Args:
action: Action dict or CodeReviewerAction
Returns:
Step response with observation, reward, done
"""
if isinstance(action, CodeReviewerAction):
action = asdict(action)
response = self._http.post(
f"{self.base_url}/step",
json={"session_id": self.session_id, "action": action}
)
response.raise_for_status()
return response.json()
def state(self) -> Dict[str, Any]:
"""Get current state (HTTP mode)."""
response = self._http.get(f"{self.base_url}/state")
response.raise_for_status()
return response.json()
async def async_reset(self, task: Optional[str] = None) -> Dict[str, Any]:
"""Reset the environment (async/WebSocket mode)."""
await self._ensure_connected()
task = task or self.task_name
await self._ws.send(json.dumps({
"action": "reset",
"task": task
}))
response = await self._ws.recv()
data = json.loads(response)
if data.get("type") == "reset_response":
return data
elif data.get("type") == "error":
raise RuntimeError(data.get("message", "Unknown error"))
else:
raise RuntimeError(f"Unexpected response type: {data.get('type')}")
async def async_step(self, action: Union[Dict, CodeReviewerAction]) -> Dict[str, Any]:
"""Execute a step (async/WebSocket mode)."""
await self._ensure_connected()
if isinstance(action, CodeReviewerAction):
action = asdict(action)
await self._ws.send(json.dumps({
"action": "step",
"data": action
}))
response = await self._ws.recv()
data = json.loads(response)
if data.get("type") == "step_response":
return data
elif data.get("type") == "error":
raise RuntimeError(data.get("message", "Unknown error"))
else:
raise RuntimeError(f"Unexpected response type: {data.get('type')}")
async def async_get_result(self) -> Dict[str, Any]:
"""Get review result (async/WebSocket mode)."""
await self._ensure_connected()
await self._ws.send(json.dumps({
"action": "get_result"
}))
response = await self._ws.recv()
data = json.loads(response)
if data.get("type") == "result_response":
return data.get("result")
elif data.get("type") == "error":
raise RuntimeError(data.get("message", "Unknown error"))
else:
raise RuntimeError(f"Unexpected response type: {data.get('type')}")
async def _ensure_connected(self):
"""Ensure WebSocket is connected."""
if self._ws is None or self._ws.closed:
ws_url = self.base_url.replace("http://", "ws://").replace("https://", "wss://")
self._ws = await websockets.connect(f"{ws_url}/ws")
async def close(self):
"""Close the WebSocket connection."""
if self._ws and not self._ws.closed:
await self._ws.close()
self._ws = None
def sync(self):
"""
Get a synchronous wrapper.
Usage:
with env.sync() as sync_env:
sync_env.reset()
"""
return SyncEnvWrapper(self)
def __del__(self):
"""Cleanup on deletion."""
if hasattr(self, '_http'):
self._http.close()
class SyncEnvWrapper:
"""Synchronous wrapper for async CodeReviewerEnv."""
def __init__(self, async_env: CodeReviewerEnv):
self._env = async_env
self._loop = None
self._task = None
def __enter__(self):
return self
def __exit__(self, *args):
pass
def reset(self, task: Optional[str] = None):
return self._env.reset(task)
def step(self, action: Union[Dict, CodeReviewerAction]):
return self._env.step(action)
def state(self):
return self._env.state()
def create_identify_issue_action(
line_number: int,
issue_type: str,
severity: str,
description: str,
confidence: float = 0.9,
) -> Dict:
"""Helper to create an identify_issue action."""
return {
"action_type": "identify_issue",
"issue": {
"line_number": line_number,
"issue_type": issue_type,
"severity": severity,
"description": description,
},
"confidence": confidence,
}
def create_submit_review_action() -> Dict:
"""Helper to create a submit_review action."""
return {"action_type": "submit_review"}
def create_hint_action() -> Dict:
"""Helper to create a request_hint action."""
return {"action_type": "request_hint"}