Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,29 +1,17 @@
|
|
1 |
-
import os
|
2 |
-
import subprocess
|
3 |
-
from huggingface_hub import InferenceClient
|
4 |
import gradio as gr
|
5 |
import random
|
6 |
import time
|
7 |
from typing import List, Dict
|
|
|
8 |
|
9 |
-
#
|
10 |
AGENT_TYPES = ["Task Executor", "Information Retriever", "Decision Maker", "Data Analyzer"]
|
11 |
TOOL_TYPES = ["Web Scraper", "Database Connector", "API Caller", "File Handler", "Text Processor"]
|
12 |
|
13 |
-
#
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
MAX_HISTORY = 100
|
18 |
-
MODEL = "mistralai/Mixtral-8x7B-Instruct-v0.1"
|
19 |
-
|
20 |
-
# Import necessary prompts and functions from the existing code
|
21 |
-
from .prompts import (
|
22 |
-
ACTION_PROMPT, ADD_PROMPT, COMPRESS_HISTORY_PROMPT, LOG_PROMPT,
|
23 |
-
LOG_RESPONSE, MODIFY_PROMPT, PREFIX, READ_PROMPT, TASK_PROMPT,
|
24 |
-
UNDERSTAND_TEST_RESULTS_PROMPT,
|
25 |
-
)
|
26 |
-
from .utils import parse_action, parse_file_content, read_python_module_structure
|
27 |
|
28 |
class Agent:
|
29 |
def __init__(self, name: str, agent_type: str, complexity: int):
|
@@ -31,10 +19,36 @@ class Agent:
|
|
31 |
self.type = agent_type
|
32 |
self.complexity = complexity
|
33 |
self.tools = []
|
|
|
|
|
|
|
|
|
|
|
|
|
34 |
|
35 |
def add_tool(self, tool):
|
36 |
self.tools.append(tool)
|
37 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
38 |
def __str__(self):
|
39 |
return f"{self.name} ({self.type}) - Complexity: {self.complexity}"
|
40 |
|
@@ -42,6 +56,38 @@ class Tool:
|
|
42 |
def __init__(self, name: str, tool_type: str):
|
43 |
self.name = name
|
44 |
self.type = tool_type
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
45 |
|
46 |
def __str__(self):
|
47 |
return f"{self.name} ({self.type})"
|
@@ -50,10 +96,6 @@ class Pypelyne:
|
|
50 |
def __init__(self):
|
51 |
self.agents: List[Agent] = []
|
52 |
self.tools: List[Tool] = []
|
53 |
-
self.history = ""
|
54 |
-
self.task = None
|
55 |
-
self.purpose = None
|
56 |
-
self.directory = None
|
57 |
|
58 |
def add_agent(self, agent: Agent):
|
59 |
self.agents.append(agent)
|
@@ -62,208 +104,18 @@ class Pypelyne:
|
|
62 |
self.tools.append(tool)
|
63 |
|
64 |
def generate_chat_app(self):
|
65 |
-
|
|
|
66 |
return f"Chat app generated with {len(self.agents)} agents and {len(self.tools)} tools."
|
67 |
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
stream = client.text_generation(
|
78 |
-
prompt=content,
|
79 |
-
max_new_tokens=max_tokens,
|
80 |
-
stop_sequences=stop_tokens if stop_tokens else None,
|
81 |
-
do_sample=True,
|
82 |
-
temperature=0.7,
|
83 |
-
)
|
84 |
-
|
85 |
-
resp = "".join(token for token in stream)
|
86 |
-
|
87 |
-
if VERBOSE:
|
88 |
-
print(LOG_RESPONSE.format(resp))
|
89 |
-
return resp
|
90 |
-
|
91 |
-
def compress_history(self):
|
92 |
-
resp = self.run_gpt(
|
93 |
-
COMPRESS_HISTORY_PROMPT,
|
94 |
-
stop_tokens=["observation:", "task:", "action:", "thought:"],
|
95 |
-
max_tokens=512,
|
96 |
-
task=self.task,
|
97 |
-
history=self.history,
|
98 |
-
)
|
99 |
-
self.history = f"observation: {resp}\n"
|
100 |
-
|
101 |
-
def run_action(self, action_name, action_input):
|
102 |
-
if action_name == "COMPLETE":
|
103 |
-
return "Task completed."
|
104 |
-
|
105 |
-
if len(self.history.split("\n")) > MAX_HISTORY:
|
106 |
-
if VERBOSE:
|
107 |
-
print("COMPRESSING HISTORY")
|
108 |
-
self.compress_history()
|
109 |
-
|
110 |
-
action_funcs = {
|
111 |
-
"MAIN": self.call_main,
|
112 |
-
"UPDATE-TASK": self.call_set_task,
|
113 |
-
"MODIFY-FILE": self.call_modify,
|
114 |
-
"READ-FILE": self.call_read,
|
115 |
-
"ADD-FILE": self.call_add,
|
116 |
-
"TEST": self.call_test,
|
117 |
-
}
|
118 |
-
|
119 |
-
if action_name not in action_funcs:
|
120 |
-
return f"Unknown action: {action_name}"
|
121 |
-
|
122 |
-
print(f"RUN: {action_name} {action_input}")
|
123 |
-
return action_funcs[action_name](action_input)
|
124 |
-
|
125 |
-
def call_main(self, action_input):
|
126 |
-
resp = self.run_gpt(
|
127 |
-
ACTION_PROMPT,
|
128 |
-
stop_tokens=["observation:", "task:"],
|
129 |
-
max_tokens=256,
|
130 |
-
task=self.task,
|
131 |
-
history=self.history,
|
132 |
-
)
|
133 |
-
lines = resp.strip().strip("\n").split("\n")
|
134 |
-
for line in lines:
|
135 |
-
if line == "":
|
136 |
-
continue
|
137 |
-
if line.startswith("thought: "):
|
138 |
-
self.history += f"{line}\n"
|
139 |
-
elif line.startswith("action: "):
|
140 |
-
action_name, action_input = parse_action(line)
|
141 |
-
self.history += f"{line}\n"
|
142 |
-
return self.run_action(action_name, action_input)
|
143 |
-
return "No valid action found."
|
144 |
-
|
145 |
-
def call_set_task(self, action_input):
|
146 |
-
self.task = self.run_gpt(
|
147 |
-
TASK_PROMPT,
|
148 |
-
stop_tokens=[],
|
149 |
-
max_tokens=64,
|
150 |
-
task=self.task,
|
151 |
-
history=self.history,
|
152 |
-
).strip("\n")
|
153 |
-
self.history += f"observation: task has been updated to: {self.task}\n"
|
154 |
-
return f"Task updated: {self.task}"
|
155 |
-
|
156 |
-
def call_modify(self, action_input):
|
157 |
-
if not os.path.exists(action_input):
|
158 |
-
self.history += "observation: file does not exist\n"
|
159 |
-
return "File does not exist."
|
160 |
-
|
161 |
-
content = read_python_module_structure(self.directory)[1]
|
162 |
-
f_content = content[action_input] if content[action_input] else "< document is empty >"
|
163 |
-
|
164 |
-
resp = self.run_gpt(
|
165 |
-
MODIFY_PROMPT,
|
166 |
-
stop_tokens=["action:", "thought:", "observation:"],
|
167 |
-
max_tokens=2048,
|
168 |
-
task=self.task,
|
169 |
-
history=self.history,
|
170 |
-
file_path=action_input,
|
171 |
-
file_contents=f_content,
|
172 |
-
)
|
173 |
-
new_contents, description = parse_file_content(resp)
|
174 |
-
if new_contents is None:
|
175 |
-
self.history += "observation: failed to modify file\n"
|
176 |
-
return "Failed to modify file."
|
177 |
-
|
178 |
-
with open(action_input, "w") as f:
|
179 |
-
f.write(new_contents)
|
180 |
-
|
181 |
-
self.history += f"observation: file successfully modified\n"
|
182 |
-
self.history += f"observation: {description}\n"
|
183 |
-
return f"File modified: {action_input}"
|
184 |
-
|
185 |
-
def call_read(self, action_input):
|
186 |
-
if not os.path.exists(action_input):
|
187 |
-
self.history += "observation: file does not exist\n"
|
188 |
-
return "File does not exist."
|
189 |
-
|
190 |
-
content = read_python_module_structure(self.directory)[1]
|
191 |
-
f_content = content[action_input] if content[action_input] else "< document is empty >"
|
192 |
-
|
193 |
-
resp = self.run_gpt(
|
194 |
-
READ_PROMPT,
|
195 |
-
stop_tokens=[],
|
196 |
-
max_tokens=256,
|
197 |
-
task=self.task,
|
198 |
-
history=self.history,
|
199 |
-
file_path=action_input,
|
200 |
-
file_contents=f_content,
|
201 |
-
).strip("\n")
|
202 |
-
self.history += f"observation: {resp}\n"
|
203 |
-
return f"File read: {action_input}"
|
204 |
-
|
205 |
-
def call_add(self, action_input):
|
206 |
-
d = os.path.dirname(action_input)
|
207 |
-
if not d.startswith(self.directory):
|
208 |
-
self.history += f"observation: files must be under directory {self.directory}\n"
|
209 |
-
return f"Invalid directory: {d}"
|
210 |
-
elif not action_input.endswith(".py"):
|
211 |
-
self.history += "observation: can only write .py files\n"
|
212 |
-
return "Only .py files are allowed."
|
213 |
-
else:
|
214 |
-
if d and not os.path.exists(d):
|
215 |
-
os.makedirs(d)
|
216 |
-
if not os.path.exists(action_input):
|
217 |
-
resp = self.run_gpt(
|
218 |
-
ADD_PROMPT,
|
219 |
-
stop_tokens=["action:", "thought:", "observation:"],
|
220 |
-
max_tokens=2048,
|
221 |
-
task=self.task,
|
222 |
-
history=self.history,
|
223 |
-
file_path=action_input,
|
224 |
-
)
|
225 |
-
new_contents, description = parse_file_content(resp)
|
226 |
-
if new_contents is None:
|
227 |
-
self.history += "observation: failed to write file\n"
|
228 |
-
return "Failed to write file."
|
229 |
-
|
230 |
-
with open(action_input, "w") as f:
|
231 |
-
f.write(new_contents)
|
232 |
-
|
233 |
-
self.history += "observation: file successfully written\n"
|
234 |
-
self.history += f"observation: {description}\n"
|
235 |
-
return f"File added: {action_input}"
|
236 |
-
else:
|
237 |
-
self.history += "observation: file already exists\n"
|
238 |
-
return "File already exists."
|
239 |
-
|
240 |
-
def call_test(self, action_input):
|
241 |
-
result = subprocess.run(
|
242 |
-
["python", "-m", "pytest", "--collect-only", self.directory],
|
243 |
-
capture_output=True,
|
244 |
-
text=True,
|
245 |
-
)
|
246 |
-
if result.returncode != 0:
|
247 |
-
self.history += f"observation: there are no tests! Test should be written in a test folder under {self.directory}\n"
|
248 |
-
return "No tests found."
|
249 |
-
result = subprocess.run(
|
250 |
-
["python", "-m", "pytest", self.directory], capture_output=True, text=True
|
251 |
-
)
|
252 |
-
if result.returncode == 0:
|
253 |
-
self.history += "observation: tests pass\n"
|
254 |
-
return "All tests passed."
|
255 |
-
|
256 |
-
resp = self.run_gpt(
|
257 |
-
UNDERSTAND_TEST_RESULTS_PROMPT,
|
258 |
-
stop_tokens=[],
|
259 |
-
max_tokens=256,
|
260 |
-
task=self.task,
|
261 |
-
history=self.history,
|
262 |
-
stdout=result.stdout[:5000],
|
263 |
-
stderr=result.stderr[:5000],
|
264 |
-
)
|
265 |
-
self.history += f"observation: tests failed: {resp}\n"
|
266 |
-
return f"Tests failed: {resp}"
|
267 |
|
268 |
pypelyne = Pypelyne()
|
269 |
|
@@ -280,7 +132,7 @@ def create_tool(name: str, tool_type: str) -> str:
|
|
280 |
def assign_tool(agent_name: str, tool_name: str) -> str:
|
281 |
agent = next((a for a in pypelyne.agents if a.name == agent_name), None)
|
282 |
tool = next((t for t in pypelyne.tools if t.name == tool_name), None)
|
283 |
-
|
284 |
if agent and tool:
|
285 |
agent.add_tool(tool)
|
286 |
return f"Tool '{tool.name}' assigned to agent '{agent.name}'"
|
@@ -296,25 +148,10 @@ def list_agents() -> str:
|
|
296 |
def list_tools() -> str:
|
297 |
return "\n".join(str(tool) for tool in pypelyne.tools) or "No tools created yet."
|
298 |
|
299 |
-
def chat_with_pypelyne(message: str) -> str:
|
300 |
-
return pypelyne.run_action("MAIN", message)
|
301 |
-
|
302 |
-
def set_purpose_and_directory(purpose: str, directory: str) -> str:
|
303 |
-
pypelyne.purpose = purpose
|
304 |
-
pypelyne.directory = directory
|
305 |
-
return f"Purpose set to: {purpose}\nWorking directory set to: {directory}"
|
306 |
-
|
307 |
with gr.Blocks() as app:
|
308 |
gr.Markdown("# Welcome to Pypelyne")
|
309 |
gr.Markdown("Create your custom pipeline with agents and tools, then chat with it!")
|
310 |
|
311 |
-
with gr.Tab("Setup"):
|
312 |
-
purpose_input = gr.Textbox(label="Set Purpose")
|
313 |
-
directory_input = gr.Textbox(label="Set Working Directory")
|
314 |
-
setup_btn = gr.Button("Set Purpose and Directory")
|
315 |
-
setup_output = gr.Textbox(label="Setup Output")
|
316 |
-
setup_btn.click(set_purpose_and_directory, inputs=[purpose_input, directory_input], outputs=setup_output)
|
317 |
-
|
318 |
with gr.Tab("Create Agents"):
|
319 |
agent_name = gr.Textbox(label="Agent Name")
|
320 |
agent_type = gr.Dropdown(choices=AGENT_TYPES, label="Agent Type")
|
|
|
|
|
|
|
|
|
1 |
import gradio as gr
|
2 |
import random
|
3 |
import time
|
4 |
from typing import List, Dict
|
5 |
+
import transformers
|
6 |
|
7 |
+
# Define constants
|
8 |
AGENT_TYPES = ["Task Executor", "Information Retriever", "Decision Maker", "Data Analyzer"]
|
9 |
TOOL_TYPES = ["Web Scraper", "Database Connector", "API Caller", "File Handler", "Text Processor"]
|
10 |
|
11 |
+
# Load the language model
|
12 |
+
model_name = "t5-small"
|
13 |
+
model = transformers.T5ForConditionalGeneration.from_pretrained(model_name)
|
14 |
+
tokenizer = transformers.T5Tokenizer.from_pretrained(model_name)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
15 |
|
16 |
class Agent:
|
17 |
def __init__(self, name: str, agent_type: str, complexity: int):
|
|
|
19 |
self.type = agent_type
|
20 |
self.complexity = complexity
|
21 |
self.tools = []
|
22 |
+
self.behavior = {
|
23 |
+
"Task Executor": self.execute_task,
|
24 |
+
"Information Retriever": self.retrieve_information,
|
25 |
+
"Decision Maker": self.make_decision,
|
26 |
+
"Data Analyzer": self.analyze_data,
|
27 |
+
}
|
28 |
|
29 |
def add_tool(self, tool):
|
30 |
self.tools.append(tool)
|
31 |
|
32 |
+
def execute_task(self, task: str):
|
33 |
+
# Simulate task execution
|
34 |
+
time.sleep(2)
|
35 |
+
return f"Task '{task}' executed successfully."
|
36 |
+
|
37 |
+
def retrieve_information(self, query: str):
|
38 |
+
# Simulate information retrieval
|
39 |
+
time.sleep(2)
|
40 |
+
return f"Information retrieved for query '{query}'."
|
41 |
+
|
42 |
+
def make_decision(self, decision: str):
|
43 |
+
# Simulate decision making
|
44 |
+
time.sleep(2)
|
45 |
+
return f"Decision '{decision}' made successfully."
|
46 |
+
|
47 |
+
def analyze_data(self, data: str):
|
48 |
+
# Simulate data analysis
|
49 |
+
time.sleep(2)
|
50 |
+
return f"Data '{data}' analyzed successfully."
|
51 |
+
|
52 |
def __str__(self):
|
53 |
return f"{self.name} ({self.type}) - Complexity: {self.complexity}"
|
54 |
|
|
|
56 |
def __init__(self, name: str, tool_type: str):
|
57 |
self.name = name
|
58 |
self.type = tool_type
|
59 |
+
self.functionality = {
|
60 |
+
"Web Scraper": self.scrape_web,
|
61 |
+
"Database Connector": self.connect_database,
|
62 |
+
"API Caller": self.call_api,
|
63 |
+
"File Handler": self.handle_file,
|
64 |
+
"Text Processor": self.process_text,
|
65 |
+
}
|
66 |
+
|
67 |
+
def scrape_web(self, url: str):
|
68 |
+
# Simulate web scraping
|
69 |
+
time.sleep(2)
|
70 |
+
return f"Web scraped for URL '{url}'."
|
71 |
+
|
72 |
+
def connect_database(self, database: str):
|
73 |
+
# Simulate database connection
|
74 |
+
time.sleep(2)
|
75 |
+
return f"Connected to database '{database}'."
|
76 |
+
|
77 |
+
def call_api(self, api: str):
|
78 |
+
# Simulate API call
|
79 |
+
time.sleep(2)
|
80 |
+
return f"API '{api}' called successfully."
|
81 |
+
|
82 |
+
def handle_file(self, file: str):
|
83 |
+
# Simulate file handling
|
84 |
+
time.sleep(2)
|
85 |
+
return f"File '{file}' handled successfully."
|
86 |
+
|
87 |
+
def process_text(self, text: str):
|
88 |
+
# Simulate text processing
|
89 |
+
time.sleep(2)
|
90 |
+
return f"Text '{text}' processed successfully."
|
91 |
|
92 |
def __str__(self):
|
93 |
return f"{self.name} ({self.type})"
|
|
|
96 |
def __init__(self):
|
97 |
self.agents: List[Agent] = []
|
98 |
self.tools: List[Tool] = []
|
|
|
|
|
|
|
|
|
99 |
|
100 |
def add_agent(self, agent: Agent):
|
101 |
self.agents.append(agent)
|
|
|
104 |
self.tools.append(tool)
|
105 |
|
106 |
def generate_chat_app(self):
|
107 |
+
# Simulate chat app generation
|
108 |
+
time.sleep(2)
|
109 |
return f"Chat app generated with {len(self.agents)} agents and {len(self.tools)} tools."
|
110 |
|
111 |
+
def chat_with_pypelyne(message: str) -> str:
|
112 |
+
# Tokenize the input message
|
113 |
+
inputs = tokenizer.encode("translate English to Spanish: " + message, return_tensors="pt")
|
114 |
+
# Generate the response
|
115 |
+
outputs = model.generate(inputs)
|
116 |
+
# Decode the response
|
117 |
+
response = tokenizer.decode(outputs[0], skip_special_tokens=True)
|
118 |
+
return response
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
119 |
|
120 |
pypelyne = Pypelyne()
|
121 |
|
|
|
132 |
def assign_tool(agent_name: str, tool_name: str) -> str:
|
133 |
agent = next((a for a in pypelyne.agents if a.name == agent_name), None)
|
134 |
tool = next((t for t in pypelyne.tools if t.name == tool_name), None)
|
135 |
+
|
136 |
if agent and tool:
|
137 |
agent.add_tool(tool)
|
138 |
return f"Tool '{tool.name}' assigned to agent '{agent.name}'"
|
|
|
148 |
def list_tools() -> str:
|
149 |
return "\n".join(str(tool) for tool in pypelyne.tools) or "No tools created yet."
|
150 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
151 |
with gr.Blocks() as app:
|
152 |
gr.Markdown("# Welcome to Pypelyne")
|
153 |
gr.Markdown("Create your custom pipeline with agents and tools, then chat with it!")
|
154 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
155 |
with gr.Tab("Create Agents"):
|
156 |
agent_name = gr.Textbox(label="Agent Name")
|
157 |
agent_type = gr.Dropdown(choices=AGENT_TYPES, label="Agent Type")
|