Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
@@ -1,322 +1,59 @@
|
|
1 |
import torch
|
2 |
from transformers import AutoTokenizer, AutoModelForCausalLM
|
3 |
import json
|
4 |
-
import gradio as gr
|
5 |
-
from typing import Optional, Dict, Any
|
6 |
|
7 |
-
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
try:
|
29 |
-
self.model = AutoModelForCausalLM.from_pretrained(
|
30 |
-
model_name,
|
31 |
-
torch_dtype=torch.float16 if self.device == "cuda" else torch.float32,
|
32 |
-
device_map="auto" if self.device == "cuda" else None,
|
33 |
-
trust_remote_code=True
|
34 |
-
)
|
35 |
-
except Exception as e:
|
36 |
-
print(f"Error loading model: {e}")
|
37 |
-
raise
|
38 |
-
|
39 |
-
# Set padding token if not exists
|
40 |
-
if self.tokenizer.pad_token is None:
|
41 |
-
self.tokenizer.pad_token = self.tokenizer.eos_token
|
42 |
-
|
43 |
-
print("Model loaded successfully!")
|
44 |
-
|
45 |
-
def generate_n8n_workflow(
|
46 |
-
self,
|
47 |
-
prompt: str,
|
48 |
-
max_length: int = 2048,
|
49 |
-
temperature: float = 0.7,
|
50 |
-
top_p: float = 0.9,
|
51 |
-
do_sample: bool = True
|
52 |
-
) -> str:
|
53 |
-
"""
|
54 |
-
Generate n8n workflow JSON from a natural language prompt.
|
55 |
-
|
56 |
-
Args:
|
57 |
-
prompt: Natural language description of the workflow
|
58 |
-
max_length: Maximum tokens to generate
|
59 |
-
temperature: Sampling temperature
|
60 |
-
top_p: Top-p sampling parameter
|
61 |
-
do_sample: Whether to use sampling
|
62 |
-
|
63 |
-
Returns:
|
64 |
-
Generated n8n workflow JSON as string
|
65 |
-
"""
|
66 |
-
# Format prompt for the model
|
67 |
-
formatted_prompt = f"Create an n8n workflow for: {prompt}\n\nWorkflow JSON:"
|
68 |
-
|
69 |
-
# Tokenize input
|
70 |
-
inputs = self.tokenizer(
|
71 |
-
formatted_prompt,
|
72 |
-
return_tensors="pt",
|
73 |
-
truncation=True,
|
74 |
-
max_length=512
|
75 |
-
).to(self.device)
|
76 |
-
|
77 |
-
# Generate response
|
78 |
-
with torch.no_grad():
|
79 |
-
outputs = self.model.generate(
|
80 |
-
**inputs,
|
81 |
-
max_length=max_length,
|
82 |
-
temperature=temperature,
|
83 |
-
top_p=top_p,
|
84 |
-
do_sample=do_sample,
|
85 |
-
pad_token_id=self.tokenizer.eos_token_id,
|
86 |
-
eos_token_id=self.tokenizer.eos_token_id,
|
87 |
-
repetition_penalty=1.1
|
88 |
-
)
|
89 |
-
|
90 |
-
# Decode and clean output
|
91 |
-
generated_text = self.tokenizer.decode(outputs[0], skip_special_tokens=True)
|
92 |
-
|
93 |
-
# Extract JSON part (assuming it starts after the prompt)
|
94 |
-
json_start = generated_text.find('{')
|
95 |
-
if json_start != -1:
|
96 |
-
workflow_json = generated_text[json_start:]
|
97 |
-
|
98 |
-
# Try to validate JSON
|
99 |
-
try:
|
100 |
-
parsed = json.loads(workflow_json)
|
101 |
-
return json.dumps(parsed, indent=2)
|
102 |
-
except json.JSONDecodeError:
|
103 |
-
# Return raw output if JSON parsing fails
|
104 |
-
return workflow_json
|
105 |
-
|
106 |
-
return generated_text
|
107 |
-
|
108 |
-
def enhance_existing_workflow(
|
109 |
-
self,
|
110 |
-
existing_workflow: str,
|
111 |
-
enhancement_request: str,
|
112 |
-
max_length: int = 2048,
|
113 |
-
temperature: float = 0.7
|
114 |
-
) -> str:
|
115 |
-
"""
|
116 |
-
Enhance an existing n8n workflow based on a request.
|
117 |
-
|
118 |
-
Args:
|
119 |
-
existing_workflow: Existing n8n workflow JSON
|
120 |
-
enhancement_request: Description of desired enhancements
|
121 |
-
max_length: Maximum tokens to generate
|
122 |
-
temperature: Sampling temperature
|
123 |
-
|
124 |
-
Returns:
|
125 |
-
Enhanced n8n workflow JSON as string
|
126 |
-
"""
|
127 |
-
prompt = f"""Enhance this n8n workflow: {enhancement_request}
|
128 |
-
|
129 |
-
Current workflow:
|
130 |
-
{existing_workflow}
|
131 |
-
|
132 |
-
Enhanced workflow JSON:"""
|
133 |
-
|
134 |
-
inputs = self.tokenizer(
|
135 |
-
prompt,
|
136 |
-
return_tensors="pt",
|
137 |
-
truncation=True,
|
138 |
-
max_length=1024
|
139 |
-
).to(self.device)
|
140 |
-
|
141 |
-
with torch.no_grad():
|
142 |
-
outputs = self.model.generate(
|
143 |
-
**inputs,
|
144 |
-
max_length=max_length,
|
145 |
-
temperature=temperature,
|
146 |
-
top_p=0.9,
|
147 |
-
do_sample=True,
|
148 |
-
pad_token_id=self.tokenizer.eos_token_id,
|
149 |
-
repetition_penalty=1.1
|
150 |
-
)
|
151 |
-
|
152 |
-
generated_text = self.tokenizer.decode(outputs[0], skip_special_tokens=True)
|
153 |
-
|
154 |
-
# Extract enhanced workflow
|
155 |
-
json_start = generated_text.rfind('{')
|
156 |
-
if json_start != -1:
|
157 |
-
enhanced_workflow = generated_text[json_start:]
|
158 |
-
try:
|
159 |
-
parsed = json.loads(enhanced_workflow)
|
160 |
-
return json.dumps(parsed, indent=2)
|
161 |
-
except json.JSONDecodeError:
|
162 |
-
return enhanced_workflow
|
163 |
-
|
164 |
-
return generated_text
|
165 |
|
166 |
-
|
167 |
-
|
168 |
-
|
169 |
-
|
170 |
-
|
171 |
-
|
172 |
-
|
173 |
-
|
174 |
-
|
175 |
-
|
176 |
-
|
177 |
-
|
178 |
-
|
179 |
-
simple_workflow = """{
|
180 |
-
"nodes": [
|
181 |
-
{
|
182 |
-
"id": "1",
|
183 |
-
"name": "Start",
|
184 |
-
"type": "n8n-nodes-base.start"
|
185 |
-
}
|
186 |
-
],
|
187 |
-
"connections": {}
|
188 |
-
}"""
|
189 |
-
|
190 |
-
enhancement = "Add error handling and logging"
|
191 |
-
enhanced = generator.enhance_existing_workflow(simple_workflow, enhancement)
|
192 |
-
print("Enhanced Workflow:")
|
193 |
-
print(enhanced)
|
194 |
-
|
195 |
-
# Gradio Interface
|
196 |
-
def create_gradio_interface():
|
197 |
-
generator = QwenN8NGenerator()
|
198 |
-
|
199 |
-
def generate_workflow_ui(prompt, max_length, temperature):
|
200 |
-
try:
|
201 |
-
workflow = generator.generate_n8n_workflow(
|
202 |
-
prompt,
|
203 |
-
max_length=max_length,
|
204 |
-
temperature=temperature
|
205 |
-
)
|
206 |
-
return workflow
|
207 |
-
except Exception as e:
|
208 |
-
return f"Error: {str(e)}"
|
209 |
-
|
210 |
-
def enhance_workflow_ui(existing_workflow, enhancement_request, max_length, temperature):
|
211 |
-
try:
|
212 |
-
enhanced = generator.enhance_existing_workflow(
|
213 |
-
existing_workflow,
|
214 |
-
enhancement_request,
|
215 |
-
max_length=max_length,
|
216 |
-
temperature=temperature
|
217 |
-
)
|
218 |
-
return enhanced
|
219 |
-
except Exception as e:
|
220 |
-
return f"Error: {str(e)}"
|
221 |
-
|
222 |
-
# Create Gradio interface
|
223 |
-
with gr.Blocks(title="Qwen2.5-7B n8n Workflow Generator") as demo:
|
224 |
-
gr.Markdown("# n8n Workflow Generator using Qwen2.5-7B")
|
225 |
-
|
226 |
-
with gr.Tab("Generate New Workflow"):
|
227 |
-
with gr.Row():
|
228 |
-
with gr.Column():
|
229 |
-
prompt_input = gr.Textbox(
|
230 |
-
label="Workflow Description",
|
231 |
-
placeholder="Describe the workflow you want to create...",
|
232 |
-
lines=3
|
233 |
-
)
|
234 |
-
max_length_slider = gr.Slider(
|
235 |
-
minimum=512,
|
236 |
-
maximum=4096,
|
237 |
-
value=2048,
|
238 |
-
label="Max Length"
|
239 |
-
)
|
240 |
-
temperature_slider = gr.Slider(
|
241 |
-
minimum=0.1,
|
242 |
-
maximum=1.0,
|
243 |
-
value=0.7,
|
244 |
-
label="Temperature"
|
245 |
-
)
|
246 |
-
generate_btn = gr.Button("Generate Workflow", variant="primary")
|
247 |
-
|
248 |
-
with gr.Column():
|
249 |
-
workflow_output = gr.Code(
|
250 |
-
label="Generated n8n Workflow",
|
251 |
-
language="json",
|
252 |
-
lines=20
|
253 |
-
)
|
254 |
-
|
255 |
-
generate_btn.click(
|
256 |
-
generate_workflow_ui,
|
257 |
-
inputs=[prompt_input, max_length_slider, temperature_slider],
|
258 |
-
outputs=workflow_output
|
259 |
-
)
|
260 |
-
|
261 |
-
with gr.Tab("Enhance Existing Workflow"):
|
262 |
-
with gr.Row():
|
263 |
-
with gr.Column():
|
264 |
-
existing_workflow_input = gr.Code(
|
265 |
-
label="Existing Workflow JSON",
|
266 |
-
language="json",
|
267 |
-
lines=10
|
268 |
-
)
|
269 |
-
enhancement_input = gr.Textbox(
|
270 |
-
label="Enhancement Request",
|
271 |
-
placeholder="Describe how you want to enhance the workflow...",
|
272 |
-
lines=3
|
273 |
-
)
|
274 |
-
enhance_max_length = gr.Slider(
|
275 |
-
minimum=512,
|
276 |
-
maximum=4096,
|
277 |
-
value=2048,
|
278 |
-
label="Max Length"
|
279 |
-
)
|
280 |
-
enhance_temperature = gr.Slider(
|
281 |
-
minimum=0.1,
|
282 |
-
maximum=1.0,
|
283 |
-
value=0.7,
|
284 |
-
label="Temperature"
|
285 |
-
)
|
286 |
-
enhance_btn = gr.Button("Enhance Workflow", variant="primary")
|
287 |
-
|
288 |
-
with gr.Column():
|
289 |
-
enhanced_output = gr.Code(
|
290 |
-
label="Enhanced n8n Workflow",
|
291 |
-
language="json",
|
292 |
-
lines=20
|
293 |
-
)
|
294 |
-
|
295 |
-
enhance_btn.click(
|
296 |
-
enhance_workflow_ui,
|
297 |
-
inputs=[existing_workflow_input, enhancement_input, enhance_max_length, enhance_temperature],
|
298 |
-
outputs=enhanced_output
|
299 |
-
)
|
300 |
-
|
301 |
-
# Examples
|
302 |
-
gr.Markdown("## Example Prompts")
|
303 |
-
gr.Examples(
|
304 |
-
examples=[
|
305 |
-
["Create a workflow that monitors a GitHub repository for new issues and sends Slack notifications"],
|
306 |
-
["Build an automated lead scoring system that processes form submissions and updates CRM"],
|
307 |
-
["Design a workflow for social media automation that posts content across multiple platforms"],
|
308 |
-
["Create a data pipeline that fetches API data, processes it, and stores in database"],
|
309 |
-
["Build a customer support workflow that categorizes tickets and assigns to appropriate teams"]
|
310 |
-
],
|
311 |
-
inputs=prompt_input
|
312 |
)
|
313 |
|
314 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
315 |
|
|
|
316 |
if __name__ == "__main__":
|
317 |
-
|
318 |
-
|
|
|
|
|
|
|
|
|
|
|
319 |
|
320 |
-
|
321 |
-
# demo = create_gradio_interface()
|
322 |
-
# demo.launch(share=True)
|
|
|
1 |
import torch
|
2 |
from transformers import AutoTokenizer, AutoModelForCausalLM
|
3 |
import json
|
|
|
|
|
4 |
|
5 |
+
def load_qwen_n8n_model():
|
6 |
+
"""Load the Qwen2.5-7B-n8n model with fallback tokenizer"""
|
7 |
+
model_name = "npv2k1/Qwen2.5-7B-n8n"
|
8 |
+
|
9 |
+
# Load tokenizer with fallback
|
10 |
+
try:
|
11 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
|
12 |
+
except:
|
13 |
+
print("Using base Qwen tokenizer...")
|
14 |
+
tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen2.5-7B-Instruct", trust_remote_code=True)
|
15 |
+
|
16 |
+
# Load model
|
17 |
+
model = AutoModelForCausalLM.from_pretrained(
|
18 |
+
model_name,
|
19 |
+
torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
|
20 |
+
device_map="auto" if torch.cuda.is_available() else None,
|
21 |
+
trust_remote_code=True
|
22 |
+
)
|
23 |
+
|
24 |
+
return tokenizer, model
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
25 |
|
26 |
+
def generate_n8n_workflow(tokenizer, model, prompt, max_length=1024):
|
27 |
+
"""Generate n8n workflow from prompt"""
|
28 |
+
formatted_prompt = f"Create an n8n workflow: {prompt}\n\nJSON:"
|
29 |
+
|
30 |
+
inputs = tokenizer(formatted_prompt, return_tensors="pt", truncation=True)
|
31 |
+
|
32 |
+
with torch.no_grad():
|
33 |
+
outputs = model.generate(
|
34 |
+
**inputs,
|
35 |
+
max_length=max_length,
|
36 |
+
temperature=0.7,
|
37 |
+
do_sample=True,
|
38 |
+
pad_token_id=tokenizer.eos_token_id
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
39 |
)
|
40 |
|
41 |
+
result = tokenizer.decode(outputs[0], skip_special_tokens=True)
|
42 |
+
|
43 |
+
# Extract JSON
|
44 |
+
json_start = result.find('{')
|
45 |
+
if json_start != -1:
|
46 |
+
return result[json_start:]
|
47 |
+
return result
|
48 |
|
49 |
+
# Usage
|
50 |
if __name__ == "__main__":
|
51 |
+
tokenizer, model = load_qwen_n8n_model()
|
52 |
+
|
53 |
+
workflow = generate_n8n_workflow(
|
54 |
+
tokenizer,
|
55 |
+
model,
|
56 |
+
"Send email when new GitHub issue is created"
|
57 |
+
)
|
58 |
|
59 |
+
print(workflow)
|
|
|
|