Repository navigation
Expand file tree
/
Copy pathcoding_agent.py
More file actions
433 lines (345 loc) · 14.1 KB
/
Copy pathcoding_agent.py
File metadata and controls
433 lines (345 loc) · 14.1 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
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
# Copyright 2026 The Kubernetes Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import asyncio
import os
import sys
import tempfile
from typing import TypedDict, Literal, Optional
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM
class AgentState(TypedDict):
user_request: str
generated_code: str
execution_result: str
error_message: Optional[str]
iteration_count: int
max_iterations: int
status: Literal["planning", "coding", "executing", "fixing", "completed", "failed"]
class LocalCodeExecutor:
@staticmethod
async def execute(code: str) -> tuple[str, bool]:
temp_filename = None
try:
# Use a unique temporary file to prevent race conditions during concurrent executions
with tempfile.NamedTemporaryFile(mode='w', suffix='.py', delete=False) as f:
temp_filename = f.name
f.write(code)
# Use sys.executable as the interpreter path, and provide a minimal sanitized environment
# containing only safe and necessary variables (like PATH). This prevents exposure of
# sensitive orchestrator credentials (like HF_TOKEN) to untrusted code execution.
passthrough_keys = ["PATH", "LANG", "LC_ALL"]
extra_keys = os.getenv("SUBPROCESS_ENV_PASSTHROUGH", "")
if extra_keys:
passthrough_keys.extend([k.strip() for k in extra_keys.split(",") if k.strip()])
env = {}
for key in passthrough_keys:
if key in os.environ:
env[key] = os.environ[key]
proc = await asyncio.create_subprocess_exec(
sys.executable, temp_filename,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
env=env
)
try:
stdout, stderr = await asyncio.wait_for(proc.communicate(), timeout=60.0)
if proc.returncode == 0:
return stdout.decode(), True
else:
return stderr.decode(), False
except asyncio.TimeoutError:
try:
proc.kill()
await proc.wait() # Reap the process to prevent zombie process accumulation
except ProcessLookupError:
pass
return "Execution timeout (60s)", False
except Exception as e:
return f"Execution error: {str(e)}", False
finally:
if temp_filename and os.path.exists(temp_filename):
try:
os.remove(temp_filename)
except OSError:
pass
class CodeGenerationLLM:
def __init__(self, model_id: str = "Salesforce/codegen-350M-mono", hf_token: str = None):
if not hf_token:
hf_token = os.getenv("HF_TOKEN")
if hf_token == "<HF_TOKEN>":
hf_token = None
cache_dir = os.getenv("HF_HOME", "/models")
print(f"Loading model {model_id} from local cache ({cache_dir})...")
try:
self.tokenizer = AutoTokenizer.from_pretrained(
model_id,
token=hf_token,
trust_remote_code=True,
local_files_only=True,
cache_dir=cache_dir
)
self.model = AutoModelForCausalLM.from_pretrained(
model_id,
token=hf_token,
trust_remote_code=True,
torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
device_map="auto",
low_cpu_mem_usage=True,
local_files_only=True,
cache_dir=cache_dir
)
except OSError as e:
error_msg = (
f"Failed to load model '{model_id}' from local cache at '{cache_dir}'.\n"
f"Details: {e}\n\n"
"This usually indicates that the model files have not been downloaded or cached yet.\n"
"Please ensure that the 'model-downloader' initContainer ran successfully,\n"
"or download the model manually by running:\n"
" python download_model.py\n"
"================================================================================"
)
raise RuntimeError(error_msg) from e
if self.tokenizer.pad_token is None:
self.tokenizer.pad_token = self.tokenizer.eos_token
print(f"Model loaded successfully on device: {self.model.device}")
print(f"Model memory footprint: ~{self.model.get_memory_footprint() / 1e9:.2f} GB")
def generate_code_sync(self, task: str) -> str:
prompt = f"""You are an expert programmer. Generate clean, executable code for the following task.
Your code must be completely self-contained with no external dependencies.
Include proper error handling and print informative output.
Output ONLY executable code, no markdown, no explanations, no backticks.
Task: {task}
Python code:"""
inputs = self.tokenizer(prompt, return_tensors="pt", padding=True)
inputs = {k: v.to(self.model.device) for k, v in inputs.items()}
with torch.no_grad():
outputs = self.model.generate(
**inputs,
max_new_tokens=256,
temperature=0.1,
do_sample=True,
top_p=0.9,
pad_token_id=self.tokenizer.pad_token_id,
eos_token_id=self.tokenizer.eos_token_id,
repetition_penalty=1.2
)
generated_text = self.tokenizer.decode(outputs[0], skip_special_tokens=True)
code = generated_text[len(prompt):].strip()
return self._clean_code(code)
def fix_code_sync(self, task: str, code: str, error: str) -> str:
prompt = f"""You are debugging code. The code failed with an error. Fix the code to resolve the error.
Output ONLY the corrected code, no markdown, no explanations, no backticks.
Original Task: {task}
Failed code:
{code}
Error:
{error}
Fixed Python code:"""
inputs = self.tokenizer(prompt, return_tensors="pt", padding=True)
inputs = {k: v.to(self.model.device) for k, v in inputs.items()}
with torch.no_grad():
outputs = self.model.generate(
**inputs,
max_new_tokens=256,
temperature=0.1,
do_sample=True,
top_p=0.9,
pad_token_id=self.tokenizer.pad_token_id,
eos_token_id=self.tokenizer.eos_token_id,
repetition_penalty=1.2
)
generated_text = self.tokenizer.decode(outputs[0], skip_special_tokens=True)
code = generated_text[len(prompt):].strip()
return self._clean_code(code)
@staticmethod
def _clean_code(code: str) -> str:
code = code.strip()
if code.startswith("```python"):
code = code[9:].strip()
elif code.startswith("```"):
code = code[3:].strip()
if code.endswith("```"):
code = code[:-3].strip()
lines = code.split('\n')
cleaned_lines = []
prev_line = None
repeat_count = 0
for line in lines:
stripped = line.strip()
if stripped.startswith(('Note:', 'Explanation:', 'This code', 'The code', 'Output:')):
break
if prev_line == stripped and len(stripped) < 3:
repeat_count += 1
if repeat_count > 2:
break
else:
repeat_count = 0
cleaned_lines.append(line)
prev_line = stripped
return '\n'.join(cleaned_lines).strip()
class CodingAgent:
def __init__(self, llm: CodeGenerationLLM, executor: LocalCodeExecutor):
self.llm = llm
self.executor = executor
async def generate_code_node(self, state: AgentState) -> AgentState:
print("\nGenerating code...")
loop = asyncio.get_event_loop()
code = await loop.run_in_executor(None, self.llm.generate_code_sync, state["user_request"])
print(f"Code generated ({len(code)} chars)")
return {
**state,
"generated_code": code,
"status": "executing"
}
async def execute_code_node(self, state: AgentState) -> AgentState:
print("Executing code...")
output, success = await self.executor.execute(state["generated_code"])
if success:
print("Execution successful")
return {
**state,
"execution_result": output,
"status": "completed",
"error_message": None
}
else:
print("Execution failed")
return {
**state,
"execution_result": output,
"error_message": output,
"status": "fixing",
"iteration_count": state["iteration_count"] + 1
}
async def fix_code_node(self, state: AgentState) -> AgentState:
if state["iteration_count"] >= state["max_iterations"]:
return {
**state,
"status": "failed",
"execution_result": f"Max iterations reached ({state['max_iterations']})"
}
print(f"Fixing code (attempt {state['iteration_count']}/{state['max_iterations']})...")
loop = asyncio.get_event_loop()
fixed_code = await loop.run_in_executor(
None,
self.llm.fix_code_sync,
state["user_request"],
state["generated_code"],
state["error_message"]
)
print(f"Code fixed ({len(fixed_code)} chars)")
return {
**state,
"generated_code": fixed_code,
"status": "executing"
}
def should_continue(self, state: AgentState) -> Literal["execute", "fix", "end"]:
if state["status"] == "executing":
return "execute"
elif state["status"] == "fixing":
return "fix"
else:
return "end"
def create_graph(llm: CodeGenerationLLM, executor: LocalCodeExecutor):
from langgraph.graph import StateGraph, END
agent = CodingAgent(llm, executor)
workflow = StateGraph(AgentState)
workflow.add_node("generate", agent.generate_code_node)
workflow.add_node("execute", agent.execute_code_node)
workflow.add_node("fix", agent.fix_code_node)
workflow.set_entry_point("generate")
workflow.add_conditional_edges(
"generate",
agent.should_continue,
{"execute": "execute", "end": END}
)
workflow.add_conditional_edges(
"execute",
agent.should_continue,
{"fix": "fix", "end": END}
)
workflow.add_conditional_edges(
"fix",
agent.should_continue,
{"execute": "execute", "end": END}
)
return workflow.compile()
async def run_agent(task: str, graph) -> dict:
initial_state: AgentState = {
"user_request": task,
"generated_code": "",
"execution_result": "",
"error_message": None,
"iteration_count": 0,
"max_iterations": 3,
"status": "planning"
}
final_state = await graph.ainvoke(initial_state)
return final_state
async def interactive_chat():
print("=" * 80)
print("LangGraph Coding Agent (Local Transformers)")
print("=" * 80)
print("I can help you write and execute Python code.")
print("Commands: 'exit', 'quit', or Ctrl+C to quit")
print("=" * 80)
print("\nInitializing LLM (this takes 2-5 minutes)...")
try:
llm = CodeGenerationLLM()
except RuntimeError as e:
print(f"\nERROR: {e}", file=sys.stderr)
sys.exit(1)
executor = LocalCodeExecutor()
graph = create_graph(llm, executor)
print("Ready!\n")
while True:
try:
print("\n" + "=" * 80)
user_input = input("You: ").strip()
if not user_input:
continue
if user_input.lower() in ['exit', 'quit']:
print("\nGoodbye!")
break
print("")
result = await run_agent(user_input, graph)
print("\n" + "=" * 80)
print("Generated Code:")
print("-" * 80)
print(result["generated_code"])
print("\n" + "=" * 80)
print("Execution Result:")
print("-" * 80)
print(result["execution_result"])
print("=" * 80)
if result["status"] == "failed":
print(f"\nStatus: FAILED (tried {result['iteration_count']} times)")
else:
print(f"\nStatus: {result['status'].upper()}")
if result["iteration_count"] > 0:
print(f" (Fixed after {result['iteration_count']} attempts)")
except KeyboardInterrupt:
print("\n\nGoodbye!")
break
except Exception as e:
print(f"\nError: {e}")
import traceback
traceback.print_exc()
def main():
try:
asyncio.run(interactive_chat())
except KeyboardInterrupt:
print("\n\nGoodbye!")
if __name__ == "__main__":
main()