Spaces:
Sleeping
Sleeping
Update app.py
Browse files30 unmodified lines31323334353637383940414243444514 unmodified lines60616263646566676869707172737475767778798081828384858687888990919293946 unmodified lines1011021031041051061071081091101116 unmodified lines11811912012112212312412512612712812913013113213313413513613713813914014114214330 unmodified lines]# Load model globally (CPU-safe to avoid startup CUDA errors)pipe = pipeline("text-generation", model="xingyaoww/CodeActAgent-Mistral-7b-v0.1", device_map=None, torch_dtype=torch.float16) # float16 fallback for init; no 'auto'# Generator function with GPU decorator@spaces.GPU(duration=180) # 180s for safety with multi-turn/model movedef run_agent(user_content):yield "Allocating GPU... (may queue if busy)\n\n"yield "Moving model to GPU and initializing...\n\n"# Move to GPU here (unrestricted power move)device = torch.device('cuda')pipe.model.to(device)pipe.device = device14 unmodified linesmax_turns = 10turn = 0yield f"### Starting simulation for prompt: '{user_content}'\n\n"while turn < max_turns:# Generate responseresult = pipe(messages, max_new_tokens=512)assistant_content = result[0]['generated_text'][-1]['content']yield f"**Assistant (Turn {turn+1}):** {assistant_content}\n\n"# Stop checksif re.search(r'(task complete|done|final answer)', assistant_content.lower()):yield "Detected completion keyword. Stopping.\n"break# Extract <execute>execute_match = re.search(r'<execute>(.*?)</execute>', assistant_content, re.DOTALL)if not execute_match:yield "No code to execute. Task likely complete.\n"breakcode = execute_match.group(1).strip()# Loop detectionif code in prev_codes:yield "Repeated code detected. Possible infinite loop—stopping.\n"breakprev_codes.add(code)yield f"**Executing code:**\n```\n{code}\n```\n\n"# Exec with captureold_stdout = sys.stdout6 unmodified linesfinally:sys.stdout = old_stdoutyield f"**Execution Output:** {exec_output}\n\n"# Success stop: If output is pure digit (index), assume doneif re.match(r'^\d+$', exec_output.strip()):yield "Pure index output detected. Task successful—stopping.\n"break# Append feedback6 unmodified linesif 'exec_output' in locals():final_index = re.search(r'(\d+)$', exec_output)if final_index:yield f"**Extracted Result:** Index {final_index.group(1)}\n"else:yield "No clear index found—check errors.\n"else:yield "No execution output.\n"yield f"### End of simulation for prompt: '{user_content}'\n"# Gradio interfacewith gr.Blocks(title="Code Agent Simulator") as demo:gr.Markdown("# Code Agent Simulator on Hugging Face Spaces\nEnter a coding task prompt, and watch the agent simulate execution in real-time.")input_prompt = gr.Textbox(label="Enter your prompt", placeholder="e.g., Implement binary search...")output_log = gr.Textbox(value="", lines=30, autoscroll=True, show_label=True, label="Simulation Log")run_button = gr.Button("Run Simulation")examples = gr.Examples(examples=prompt_list, inputs=[input_prompt])# On click, run the generator and stream to outputrun_button.click(fn=run_agent, inputs=input_prompt, outputs=output_log)# Launch (disable SSR for stability, enable debug for logs)if __name__ == "__main__":30 unmodified lines31323334353637383940414243444546474849505152535414 unmodified lines697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091106 unmodified lines1171181191201211221231241251261271281291306 unmodified lines13713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117230 unmodified lines]# Load model globally (CPU-safe to avoid startup CUDA errors)pipe = pipeline("text-generation", model="xingyaoww/CodeActAgent-Mistral-7b-v0.1", device_map=None, torch_dtype=torch.float16) # float16 for init; no 'auto'# Generator function with GPU decorator@spaces.GPU(duration=180) # 180s for safetydef run_agent(user_content):full_log = ""current_code = ""current_exec_output = ""yield [current_code, current_exec_output, full_log] # Initial emptyfull_log += "Allocating GPU... (may queue if busy)\n\n"yield [current_code, current_exec_output, full_log]full_log += "Moving model to GPU and initializing...\n\n"yield [current_code, current_exec_output, full_log]# Move to GPU heredevice = torch.device('cuda')pipe.model.to(device)pipe.device = device14 unmodified linesmax_turns = 10turn = 0full_log += f"### Starting simulation for prompt: '{user_content}'\n\n"yield [current_code, current_exec_output, full_log]while turn < max_turns:# Generate responseresult = pipe(messages, max_new_tokens=512)assistant_content = result[0]['generated_text'][-1]['content']full_log += f"**Assistant (Turn {turn+1}):** {assistant_content}\n\n"yield [current_code, current_exec_output, full_log]# Stop checksif re.search(r'(task complete|done|final answer)', assistant_content.lower()):full_log += "Detected completion keyword. Stopping.\n"yield [current_code, current_exec_output, full_log]break# Extract <execute>execute_match = re.search(r'<execute>(.*?)</execute>', assistant_content, re.DOTALL)if not execute_match:full_log += "No code to execute. Task likely complete.\n"yield [current_code, current_exec_output, full_log]breakcode = execute_match.group(1).strip()current_code = code# Loop detectionif code in prev_codes:full_log += "Repeated code detected. Possible infinite loop—stopping.\n"yield [current_code, current_exec_output, full_log]breakprev_codes.add(code)full_log += f"**Executing code:**\n```\n{code}\n```\n\n"yield [current_code, current_exec_output, full_log]# Exec with captureold_stdout = sys.stdout6 unmodified linesfinally:sys.stdout = old_stdoutcurrent_exec_output = exec_outputfull_log += f"**Execution Output:** {exec_output}\n\n"yield [current_code, current_exec_output, full_log]# Success stop: If output is pure digit (index), assume doneif re.match(r'^\d+$', exec_output.strip()):full_log += "Pure index output detected. Task successful—stopping.\n"yield [current_code, current_exec_output, full_log]break# Append feedback6 unmodified linesif 'exec_output' in locals():final_index = re.search(r'(\d+)$', exec_output)if final_index:full_log += f"**Extracted Result:** Index {final_index.group(1)}\n"yield [current_code, current_exec_output, full_log]else:full_log += "No clear index found—check errors.\n"yield [current_code, current_exec_output, full_log]else:full_log += "No execution output.\n"yield [current_code, current_exec_output, full_log]full_log += f"### End of simulation for prompt: '{user_content}'\n"yield [current_code, current_exec_output, full_log]# Gradio interfacewith gr.Blocks(title="Code Agent Simulator") as demo:gr.Markdown("# Code Agent Simulator on Hugging Face Spaces\nEnter a coding task prompt, and watch the agent simulate execution in real-time.")input_prompt = gr.Textbox(label="Enter your prompt", placeholder="e.g., Implement binary search...")with gr.Row():generated_code = gr.Code(label="Generated Code", language="python", lines=15, show_label=True)exec_output = gr.Textbox(label="Execution Output", lines=15, show_label=True)full_log = gr.Textbox(label="Full Simulation Log", lines=20, autoscroll=True, show_label=True)run_button = gr.Button("Run Simulation")examples = gr.Examples(examples=prompt_list, inputs=[input_prompt])# On click, run the generator and stream to multiple outputsrun_button.click(fn=run_agent, inputs=input_prompt, outputs=[generated_code, exec_output, full_log])# Launch (disable SSR for stability, enable debug for logs)if __name__ == "__main__":
app.py+49-20