Phoenix21 commited on
Commit
272d10a
·
verified ·
1 Parent(s): 81b1da9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +131 -4
app.py CHANGED
@@ -1,7 +1,134 @@
 
 
 
 
 
 
1
  import gradio as gr
 
2
 
3
- def greet(name):
4
- return "Hello " + name + "!!"
5
 
6
- demo = gr.Interface(fn=greet, inputs="text", outputs="text")
7
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ import logging
3
+ import torch
4
+ import builtins
5
+ import io
6
+ import sys
7
  import gradio as gr
8
+ from transformers import pipeline
9
 
10
+ # Suppress warnings
11
+ logging.getLogger("transformers").setLevel(logging.ERROR)
12
 
13
+ # Load model (do this once at startup)
14
+ pipe = pipeline("text-generation", model="xingyaoww/CodeActAgent-Mistral-7b-v0.1", device_map='auto', torch_dtype=torch.bfloat16)
15
+
16
+ # System prompt (same as original)
17
+ system_prompt = """
18
+ A chat between a curious user and an artificial intelligence assistant. The assistant gives helpful, detailed, and polite answers to the user’s questions. The assistant can interact with an interactive Python (Jupyter Notebook) environment and receive the corresponding output when needed. The code should be enclosed using "<execute>" tag, for example: <execute> print("Hello World!") </execute>. The assistant should attempt fewer things at a time instead of putting too much code in one <execute> block. The assistant can install packages through PIP by <execute> !pip install [package needed] </execute> and should always import packages and define variables before starting to use them. For algorithms that return values (like search functions), ALWAYS define them as proper functions with def function_name(...): ... return value ... and then call the function to print or use the result. Do NOT use return outside a function. The assistant should stop <execute> and provide an answer when they have already obtained the answer from the execution result. Whenever possible, execute the code for the user using <execute> instead of providing it. The assistant’s response should be concise, but do express their thoughts. Once the task is complete and tested successfully (e.g., correct index printed), stop generating more code and say 'Task complete' without <execute> tags.
19
+ """
20
+
21
+ # List of example prompts (from previous)
22
+ prompt_list = [
23
+ "Print 'Hello, World!' using code. Once done, stop.",
24
+ "Compute and print the sum of numbers from 1 to 10 using a loop. Use code to do it.",
25
+ "Define a function def add(a, b) that returns a + b. Test it by calling add(3, 4) and printing the result.",
26
+ "Print the length of numbers from 0 to 9 using len and range.",
27
+ "Create a list [1,2,3] and print its length. Use code.",
28
+ "Implement a function def factorial(n) to compute factorial recursively. Test on 5 and print result.",
29
+ "Try to import math and print math.sqrt(16). If needed, install packages.",
30
+ "Find if 10 is even or odd using a function def is_even(n), return True/False, test and print.",
31
+ "Implement linear search to find index of 7 in [3,5,7,9], return -1 if not found. Test and print.",
32
+ "Cause a deliberate error like divide by zero, then fix it in next step and print 10 / 2."
33
+ ]
34
+
35
+ # Generator function to run the simulation and yield logs in real-time
36
+ def run_agent(user_content):
37
+ # Initial messages
38
+ messages = [
39
+ {"role": "system", "content": system_prompt},
40
+ {"role": "user", "content": user_content},
41
+ ]
42
+
43
+ # REPL state (restricted builtins)
44
+ repl_globals = {'__builtins__': {k: v for k, v in builtins.__dict__.items() if k in ['print', 'len', 'range', 'int']}}
45
+
46
+ # History for loop detection
47
+ prev_codes = set()
48
+
49
+ # Max turns
50
+ max_turns = 10
51
+ turn = 0
52
+
53
+ yield f"### Starting simulation for prompt: '{user_content}'\n\n"
54
+
55
+ while turn < max_turns:
56
+ # Generate response
57
+ result = pipe(messages, max_new_tokens=512)
58
+ assistant_content = result[0]['generated_text'][-1]['content']
59
+
60
+ yield f"**Assistant (Turn {turn+1}):** {assistant_content}\n\n"
61
+
62
+ # Stop checks
63
+ if re.search(r'(task complete|done|final answer)', assistant_content.lower()):
64
+ yield "Detected completion keyword. Stopping.\n"
65
+ break
66
+
67
+ # Extract <execute>
68
+ execute_match = re.search(r'<execute>(.*?)</execute>', assistant_content, re.DOTALL)
69
+ if not execute_match:
70
+ yield "No code to execute. Task likely complete.\n"
71
+ break
72
+
73
+ code = execute_match.group(1).strip()
74
+
75
+ # Loop detection
76
+ if code in prev_codes:
77
+ yield "Repeated code detected. Possible infinite loop—stopping.\n"
78
+ break
79
+ prev_codes.add(code)
80
+
81
+ yield f"**Executing code:**\n```\n{code}\n```\n\n"
82
+
83
+ # Exec with capture
84
+ old_stdout = sys.stdout
85
+ sys.stdout = io.StringIO()
86
+ try:
87
+ exec(code, repl_globals)
88
+ exec_output = sys.stdout.getvalue().strip() or "No output."
89
+ except Exception as e:
90
+ exec_output = f"Error: {str(e)}"
91
+ finally:
92
+ sys.stdout = old_stdout
93
+
94
+ yield f"**Execution Output:** {exec_output}\n\n"
95
+
96
+ # Success stop: If output is pure digit (index), assume done
97
+ if re.match(r'^\d+$', exec_output.strip()):
98
+ yield "Pure index output detected. Task successful—stopping.\n"
99
+ break
100
+
101
+ # Append feedback
102
+ messages.append({"role": "assistant", "content": assistant_content})
103
+ messages.append({"role": "user", "content": f"Observation: {exec_output}"})
104
+
105
+ turn += 1
106
+
107
+ # Final parse (grab last number as index if applicable)
108
+ if 'exec_output' in locals():
109
+ final_index = re.search(r'(\d+)$', exec_output)
110
+ if final_index:
111
+ yield f"**Extracted Result:** Index {final_index.group(1)}\n"
112
+ else:
113
+ yield "No clear index found—check errors.\n"
114
+ else:
115
+ yield "No execution output.\n"
116
+
117
+ yield f"### End of simulation for prompt: '{user_content}'\n"
118
+
119
+ # Gradio interface
120
+ with gr.Blocks(title="Code Agent Simulator") as demo:
121
+ gr.Markdown("# Code Agent Simulator on Hugging Face Spaces\nEnter a coding task prompt, and watch the agent simulate execution in real-time.")
122
+
123
+ input_prompt = gr.Textbox(label="Enter your prompt", placeholder="e.g., Implement binary search...")
124
+ output_log = gr.Markdown(label="Simulation Log")
125
+ run_button = gr.Button("Run Simulation")
126
+
127
+ examples = gr.Examples(examples=prompt_list, inputs=[input_prompt])
128
+
129
+ # On click, run the generator and stream to output
130
+ run_button.click(fn=run_agent, inputs=input_prompt, outputs=output_log)
131
+
132
+ # Launch (for local) or for HF Spaces, this is app.py
133
+ if __name__ == "__main__":
134
+ demo.queue().launch()