doodle-med commited on
Commit
b859c11
·
verified ·
1 Parent(s): b5ba55e

Update App.py

Browse files
Files changed (1) hide show
  1. App.py +114 -189
App.py CHANGED
@@ -1,8 +1,7 @@
1
- # app.py
2
  # A production-quality, local, and uncensored text-editing agent
3
- # that can read, reason over, and rewrite large documents.
4
 
5
- import asyncio
6
  import gradio as gr
7
  import pathlib
8
  import re
@@ -10,241 +9,167 @@ import textwrap
10
  from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
11
  from transformers.agents import Agent, Tool
12
  from fastmcp import FastMCP
 
 
 
 
 
13
 
14
  # --- Configuration ---
15
- # Use a more descriptive model name for clarity
16
  MODEL_ID = "NousResearch/Meta-Llama-3-8B-Instruct-GPTQ"
17
- # Sandbox all file operations to this directory for security
18
  ROOT = pathlib.Path("workspace")
19
- ROOT.mkdir(exist_ok=True) # Ensure the workspace directory exists
20
 
21
  # --- 1. MCP Text-Editing Server (The "Tools" Backend) ---
22
- # This server runs locally and provides the agent with tools to interact with files.
23
  server = FastMCP("DocTools")
24
 
 
 
25
  @server.tool()
26
  def list_files(relative_path: str = ".") -> list[str]:
27
- """
28
- Lists all files and directories within a given subdirectory of the workspace.
29
- Args:
30
- relative_path (str): The subdirectory path relative to the workspace root.
31
- Defaults to the current directory ('.').
32
- """
33
  try:
34
- # Security: Prevent directory traversal attacks
35
  safe_path = (ROOT / relative_path).resolve()
36
- if not safe_path.is_relative_to(ROOT.resolve()):
37
- return ["Error: Access denied. Path is outside the workspace."]
38
-
39
- if not safe_path.exists():
40
- return [f"Error: Directory '{relative_path}' not found."]
41
-
42
  return [p.name for p in safe_path.iterdir()]
43
- except Exception as e:
44
- return [f"An error occurred: {str(e)}"]
45
 
46
  @server.tool()
47
  def search_in_file(file_path: str, pattern: str, max_hits: int = 40) -> list[str]:
48
- """
49
- Searches for a regex pattern within a specified file in the workspace.
50
- Args:
51
- file_path (str): The path to the file relative to the workspace root.
52
- pattern (str): The regular expression pattern to search for (case-insensitive).
53
- max_hits (int): The maximum number of matching lines to return.
54
- """
55
  try:
56
- # Security: Resolve and check the file path
57
  safe_path = (ROOT / file_path).resolve()
58
- if not safe_path.is_relative_to(ROOT.resolve()):
59
- return ["Error: Access denied. Path is outside the workspace."]
60
-
61
- if not safe_path.is_file():
62
- return [f"Error: File '{file_path}' not found."]
63
-
64
- output = []
65
- regex = re.compile(pattern, re.IGNORECASE)
66
  with open(safe_path, 'r', encoding='utf-8') as f:
67
  for i, line in enumerate(f):
68
  if regex.search(line):
69
  output.append(f"{i+1}: {line.rstrip()}")
70
- if len(output) >= max_hits:
71
- break
72
  return output if output else ["No matches found."]
73
- except Exception as e:
74
- return [f"An error occurred while reading the file: {str(e)}"]
75
 
76
  @server.tool()
77
  def read_lines(file_path: str, start_line: int, end_line: int) -> str:
78
- """
79
- Reads and returns a specific range of lines from a file.
80
- Args:
81
- file_path (str): The path to the file relative to the workspace root.
82
- start_line (int): The starting line number (1-indexed).
83
- end_line (int): The ending line number (inclusive).
84
- """
85
  try:
86
- # Security: Resolve and check the file path
87
  safe_path = (ROOT / file_path).resolve()
88
- if not safe_path.is_relative_to(ROOT.resolve()):
89
- return "Error: Access denied. Path is outside the workspace."
90
-
91
- if not safe_path.is_file():
92
- return f"Error: File '{file_path}' not found."
93
-
94
- with open(safe_path, 'r', encoding='utf-8') as f:
95
- lines = f.readlines()
96
-
97
- # Adjust for 0-based indexing and ensure bounds are valid
98
- start_index = max(0, start_line - 1)
99
- end_index = min(len(lines), end_line)
100
-
101
- return "".join(lines[start_index:end_index])
102
- except Exception as e:
103
- return f"An error occurred: {str(e)}"
104
 
105
  @server.tool()
106
  def patch_file(file_path: str, start_line: int, end_line: int, new_content: str) -> str:
107
- """
108
- Replaces a range of lines in a file with new content.
109
- Args:
110
- file_path (str): The path to the file relative to the workspace root.
111
- start_line (int): The starting line number for replacement (1-indexed).
112
- end_line (int): The ending line number for replacement (inclusive).
113
- new_content (str): The new text to insert.
114
- """
115
  try:
116
- # Security: Resolve and check the file path
117
  safe_path = (ROOT / file_path).resolve()
118
- if not safe_path.is_relative_to(ROOT.resolve()):
119
- return "Error: Access denied. Path is outside the workspace."
 
 
 
 
 
 
 
120
 
121
- if not safe_path.is_file():
122
- return f"Error: File '{file_path}' not found."
123
-
124
- with open(safe_path, 'r', encoding='utf-8') as f:
125
- lines = f.readlines()
126
 
127
- start_index = max(0, start_line - 1)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
128
 
129
- # Create the new file content in memory
130
- new_lines = (
131
- lines[:start_index] +
132
- [line + '\n' for line in new_content.splitlines()] +
133
- lines[end_line:]
 
 
 
134
  )
135
 
136
- with open(safe_path, 'w', encoding='utf-8') as f:
137
- f.writelines(new_lines)
138
-
139
- return f"Success: Patched lines {start_line}-{end_line} in '{file_path}'."
140
- except Exception as e:
141
- return f"An error occurred during patching: {str(e)}"
142
-
143
-
144
- # --- 2. Local Function-Calling LLM ---
145
- # Initialize the model and tokenizer for the agent.
146
- # Using a GPTQ quantized model for efficient inference on GPUs.
147
- tokenizer = AutoTokenizer.from_pretrained(MODEL_ID, trust_remote_code=True)
148
- model = AutoModelForCausalLM.from_pretrained(
149
- MODEL_ID,
150
- device_map="auto",
151
- # 8-bit quantization for a balance of speed and performance.
152
- quantization_config={"bits": 8, "load_in_8bit": True}
153
- )
154
-
155
- # Create the pipeline for text generation with streaming capabilities.
156
- llm_pipeline = pipeline(
157
- "text-generation",
158
- model=model,
159
- tokenizer=tokenizer,
160
- return_full_text=False, # Essential for streaming and agent control
161
- max_new_tokens=1024,
162
- )
163
-
164
- # --- 3. Transformers Agent Orchestrator ---
165
- # This agent coordinates the LLM and the tools to accomplish user goals.
166
-
167
- def build_hf_tool(mcp_tool_name: str) -> Tool:
168
- """Dynamically creates a Hugging Face Tool from a FastMCP tool's schema."""
169
- schema = server.get_schema(mcp_tool_name)
170
-
171
- # The actual function that the agent will call
172
- def tool_function(**kwargs):
173
- # The FastMCP server handles the invocation internally
174
- return server.invoke(mcp_tool_name, **kwargs)
175
-
176
- return Tool(
177
- name=mcp_tool_name,
178
- description=schema["description"],
179
- inputs=schema["parameters"],
180
- function=tool_function
181
- )
182
 
183
- # Automatically build HF tools from all registered MCP server tools
184
- tools = [build_hf_tool(tool_name) for tool_name in server.list_tools()]
185
-
186
- # System prompt to define the agent's role and constraints
187
- SYSTEM_PROMPT = textwrap.dedent("""
188
- You are an expert technical editor and programmer.
189
- Your task is to assist the user by performing file operations.
190
- You have access to a set of tools for listing, searching, reading, and modifying files.
191
- - All file paths are relative to the '/workspace' directory.
192
- - Always verify file contents with `read_lines` or `search_in_file` before attempting to modify a file with `patch_file`.
193
- - When you are done, provide a summary of the actions you have taken.
194
- """)
195
-
196
- # Initialize the agent with the LLM, tools, and a system prompt.
197
- # memory=True enables conversational history.
198
- agent = Agent(
199
- llm_pipeline=llm_pipeline,
200
- tools=tools,
201
- system_prompt=SYSTEM_PROMPT,
202
- max_steps=10, # Increased max steps for more complex tasks
203
- memory=True
204
- )
205
-
206
- # --- 4. Interactive Gradio Chat Application ---
207
-
208
- async def chat_fn(history: list, user_message: str):
209
- """
210
- Handles the chat interaction, streaming the agent's response back to the UI.
211
- """
212
- history.append((user_message, None))
213
-
214
- # Use astream for real-time streaming of thoughts and actions
215
- async for step_output in agent.astream(user_message):
216
- # The final output is a string, intermediate steps are tool calls/thoughts
217
- if isinstance(step_output, str):
218
- history[-1] = (user_message, step_output)
219
- yield history
220
 
221
- return history
 
 
 
 
222
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
223
  with gr.Blocks(theme=gr.themes.Soft(), css="footer {display: none !important}") as demo:
224
- gr.Markdown("# Local Text-Editing Agent 📝")
225
  gr.Markdown(
226
  """
227
  Chat with this AI agent to perform complex edits on text documents in the workspace.
228
- **Example:** "List the files. Then, open `sample.txt`, summarize the second paragraph, and correct any passive-voice sentences you find."
229
  """
230
  )
231
 
232
- chatbot = gr.Chatbot(height=600)
233
- msg_textbox = gr.Textbox(label="Your Prompt", placeholder="Type your request here...")
234
 
235
- msg_textbox.submit(chat_fn, [chatbot, msg_textbox], chatbot)
236
- gr.ClearButton([msg_textbox, chatbot])
 
237
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
238
  # Add a sample file to the workspace for easy testing
239
  with open(ROOT / "sample.txt", "w") as f:
240
- f.write(textwrap.dedent("""
241
- This is the first paragraph. It contains some basic information.
242
-
243
- The second paragraph is where the interesting details are located. A decision was made by the team to proceed. This text will be reviewed by the agent for clarity and conciseness.
244
-
245
- The final paragraph concludes the document.
246
- """))
247
-
248
- # .queue() is essential for handling multiple users and streaming
249
- # share=True creates a public link for easy sharing from Colab or locally.
250
- demo.queue().launch(share=True)
 
1
+ # app.py (ZeroGPU Version)
2
  # A production-quality, local, and uncensored text-editing agent
3
+ # designed specifically for the Hugging Face ZeroGPU platform.
4
 
 
5
  import gradio as gr
6
  import pathlib
7
  import re
 
9
  from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
10
  from transformers.agents import Agent, Tool
11
  from fastmcp import FastMCP
12
+ from huggingface_hub import snapshot_download
13
+
14
+ # --- Hugging Face Spaces GPU Decorator ---
15
+ # This is the key to making the app work on ZeroGPU
16
+ from spaces import GPU as spaces_GPU
17
 
18
  # --- Configuration ---
 
19
  MODEL_ID = "NousResearch/Meta-Llama-3-8B-Instruct-GPTQ"
 
20
  ROOT = pathlib.Path("workspace")
21
+ ROOT.mkdir(exist_ok=True)
22
 
23
  # --- 1. MCP Text-Editing Server (The "Tools" Backend) ---
24
+ # This part remains the same.
25
  server = FastMCP("DocTools")
26
 
27
+ # (All your @server.tool() functions: list_files, search_in_file, read_lines, patch_file go here)
28
+ # ... [Paste your tool functions here to keep the script self-contained] ...
29
  @server.tool()
30
  def list_files(relative_path: str = ".") -> list[str]:
31
+ """Lists all files and directories within a given subdirectory of the workspace."""
 
 
 
 
 
32
  try:
 
33
  safe_path = (ROOT / relative_path).resolve()
34
+ if not safe_path.is_relative_to(ROOT.resolve()): return ["Error: Access denied."]
35
+ if not safe_path.exists(): return [f"Error: Directory '{relative_path}' not found."]
 
 
 
 
36
  return [p.name for p in safe_path.iterdir()]
37
+ except Exception as e: return [f"An error occurred: {str(e)}"]
 
38
 
39
  @server.tool()
40
  def search_in_file(file_path: str, pattern: str, max_hits: int = 40) -> list[str]:
41
+ """Searches for a regex pattern within a specified file in the workspace."""
 
 
 
 
 
 
42
  try:
 
43
  safe_path = (ROOT / file_path).resolve()
44
+ if not safe_path.is_relative_to(ROOT.resolve()): return ["Error: Access denied."]
45
+ if not safe_path.is_file(): return [f"Error: File '{file_path}' not found."]
46
+ output, regex = [], re.compile(pattern, re.IGNORECASE)
 
 
 
 
 
47
  with open(safe_path, 'r', encoding='utf-8') as f:
48
  for i, line in enumerate(f):
49
  if regex.search(line):
50
  output.append(f"{i+1}: {line.rstrip()}")
51
+ if len(output) >= max_hits: break
 
52
  return output if output else ["No matches found."]
53
+ except Exception as e: return [f"An error occurred: {str(e)}"]
 
54
 
55
  @server.tool()
56
  def read_lines(file_path: str, start_line: int, end_line: int) -> str:
57
+ """Reads and returns a specific range of lines from a file."""
 
 
 
 
 
 
58
  try:
 
59
  safe_path = (ROOT / file_path).resolve()
60
+ if not safe_path.is_relative_to(ROOT.resolve()): return "Error: Access denied."
61
+ if not safe_path.is_file(): return f"Error: File '{file_path}' not found."
62
+ with open(safe_path, 'r', encoding='utf-8') as f: lines = f.readlines()
63
+ return "".join(lines[max(0, start_line - 1):min(len(lines), end_line)])
64
+ except Exception as e: return f"An error occurred: {str(e)}"]
 
 
 
 
 
 
 
 
 
 
 
65
 
66
  @server.tool()
67
  def patch_file(file_path: str, start_line: int, end_line: int, new_content: str) -> str:
68
+ """Replaces a range of lines in a file with new content."""
 
 
 
 
 
 
 
69
  try:
 
70
  safe_path = (ROOT / file_path).resolve()
71
+ if not safe_path.is_relative_to(ROOT.resolve()): return "Error: Access denied."
72
+ if not safe_path.is_file(): return f"Error: File '{file_path}' not found."
73
+ with open(safe_path, 'r', encoding='utf-8') as f: lines = f.readlines()
74
+ new_lines = (lines[:max(0, start_line - 1)] +
75
+ [line + '\n' for line in new_content.splitlines()] +
76
+ lines[end_line:])
77
+ with open(safe_path, 'w', encoding='utf-8') as f: f.writelines(new_lines)
78
+ return f"Success: Patched lines {start_line}-{end_line} in '{file_path}'."
79
+ except Exception as e: return f"An error occurred: {str(e)}"]
80
 
 
 
 
 
 
81
 
82
+ # --- 2. Agent and Model Loading (ZeroGPU compatible) ---
83
+
84
+ # We initialize the agent as None. It will be created on the first user request.
85
+ agent = None
86
+
87
+ # This is our GPU-accelerated function.
88
+ # It will load the model on the first run and cache it for subsequent calls.
89
+ @spaces_GPU(duration=120) # Request GPU for 120 seconds per call
90
+ def get_agent():
91
+ """
92
+ Loads and caches the LLM agent. This function runs on a GPU.
93
+ """
94
+ global agent
95
+ if agent is None:
96
+ print("--- Loading model and agent for the first time ---")
97
 
98
+ # Download the model to a persistent cache
99
+ model_path = snapshot_download(MODEL_ID)
100
+
101
+ tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)
102
+ model = AutoModelForCausalLM.from_pretrained(
103
+ model_path,
104
+ device_map="auto",
105
+ torch_dtype="auto" # Recommended for modern GPUs
106
  )
107
 
108
+ llm_pipeline = pipeline(
109
+ "text-generation",
110
+ model=model,
111
+ tokenizer=tokenizer,
112
+ return_full_text=False,
113
+ max_new_tokens=1024,
114
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
115
 
116
+ tools = [Tool(name=t, description=server.get_schema(t)["description"], inputs=server.get_schema(t)["parameters"], function=lambda **kwargs, t=t: server.invoke(t, **kwargs)) for t in server.list_tools()]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
117
 
118
+ SYSTEM_PROMPT = textwrap.dedent("""
119
+ You are an expert technical editor. You must use your tools to answer the user's request.
120
+ All file paths are relative to the '/workspace' directory.
121
+ Always verify file contents with `read_lines` or `search_in_file` before patching.
122
+ """)
123
 
124
+ agent = Agent(
125
+ llm_pipeline=llm_pipeline,
126
+ tools=tools,
127
+ system_prompt=SYSTEM_PROMPT,
128
+ max_steps=10,
129
+ memory=True
130
+ )
131
+ print("--- Agent loaded successfully ---")
132
+ return agent
133
+
134
+
135
+ # --- 3. Gradio Chat Application ---
136
+
137
+ # Using gr.ChatInterface for a cleaner UI setup
138
  with gr.Blocks(theme=gr.themes.Soft(), css="footer {display: none !important}") as demo:
139
+ gr.Markdown("# ZeroGPU Text-Editing Agent 📝")
140
  gr.Markdown(
141
  """
142
  Chat with this AI agent to perform complex edits on text documents in the workspace.
143
+ **Note:** The first request will have a delay as the model is loaded onto the GPU.
144
  """
145
  )
146
 
147
+ chatbot = gr.Chatbot(height=600, label="Agent Chat")
 
148
 
149
+ async def chat_interaction(message, history):
150
+ history.append([message, None])
151
+ yield "", history # Immediately show user message
152
 
153
+ # 1. Get the agent (this triggers the GPU)
154
+ current_agent = get_agent()
155
+
156
+ # 2. Stream the response
157
+ response = ""
158
+ async for step in current_agent.astream(message):
159
+ if isinstance(step, str):
160
+ response = step
161
+ history[-1][1] = response
162
+ yield "", history
163
+
164
+ gr.ChatInterface(
165
+ fn=chat_interaction,
166
+ chatbot=chatbot,
167
+ fill_height=False
168
+ )
169
+
170
  # Add a sample file to the workspace for easy testing
171
  with open(ROOT / "sample.txt", "w") as f:
172
+ f.write("This is a sample file for testing the ZeroGPU agent.")
173
+
174
+ demo.queue().launch()
175
+