Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,579 +1,121 @@
|
|
| 1 |
import streamlit as st
|
| 2 |
-
from
|
| 3 |
-
import
|
| 4 |
-
import pickle
|
| 5 |
-
from langchain.memory import ConversationBufferMemory
|
| 6 |
-
from langchain_community.tools import Tool
|
| 7 |
-
from langchain_community.agents import initialize_agent, AgentType
|
| 8 |
-
from langchain_community.chains import LLMChain
|
| 9 |
-
from langchain_community.prompts import PromptTemplate
|
| 10 |
-
from langchain_community.chains.question_answering import load_qa_chain
|
| 11 |
-
from langchain_community.document_loaders import TextLoader
|
| 12 |
-
from langchain_community.text_splitter import CharacterTextSplitter
|
| 13 |
-
from langchain_community.embeddings import HuggingFaceEmbeddings # Use Hugging Face Embeddings
|
| 14 |
-
from langchain_community.vectorstores import FAISS
|
| 15 |
-
from langchain_community.chains import RetrievalQA
|
| 16 |
-
from langchain_community.chains.conversational_retrieval_qa import ConversationalRetrievalQAChain
|
| 17 |
-
from langchain_community.chains.summarization import load_summarization_chain
|
| 18 |
from langchain_community.llms import HuggingFaceHub
|
|
|
|
|
|
|
| 19 |
from typing import List, Dict, Any, Optional
|
| 20 |
|
| 21 |
-
|
| 22 |
|
| 23 |
-
# ---
|
| 24 |
-
class
|
| 25 |
-
def __init__(self, name, description, model_link):
|
| 26 |
-
self.name = name
|
| 27 |
-
self.description = description
|
| 28 |
-
self.model_link = model_link
|
| 29 |
-
self.inference_client = InferenceClient(model=model_link)
|
| 30 |
-
|
| 31 |
-
def generate_text(self, prompt, temperature=0.5, max_new_tokens=4096):
|
| 32 |
-
try:
|
| 33 |
-
output = self.inference_client.text_generation(
|
| 34 |
-
prompt,
|
| 35 |
-
temperature=temperature,
|
| 36 |
-
max_new_tokens=max_new_tokens,
|
| 37 |
-
stream=True
|
| 38 |
-
)
|
| 39 |
-
response = "".join(output)
|
| 40 |
-
except ValueError as e:
|
| 41 |
-
if "Input validation error" in str(e):
|
| 42 |
-
return "Error: The input prompt is too long. Please try a shorter prompt."
|
| 43 |
-
else:
|
| 44 |
-
return f"An error occurred: {e}"
|
| 45 |
-
return response
|
| 46 |
-
|
| 47 |
-
# --- Model Examples ---
|
| 48 |
-
class FrontendForgeModel(Model):
|
| 49 |
-
def __init__(self):
|
| 50 |
-
super().__init__("FrontendForge🚀", "The FrontendForge model is a Large Language Model (LLM) that's able to handle frontend development tasks such as UI design and user interaction logic.", "mistralai/Mistral-7B-Instruct-v0.2")
|
| 51 |
-
|
| 52 |
-
class BackendBuilderModel(Model):
|
| 53 |
-
def __init__(self):
|
| 54 |
-
super().__init__("BackendBuilder⭐", "The BackendBuilder model is a Large Language Model (LLM) that's specialized in backend development tasks including API creation, database management, and server-side logic.", "mistralai/Mixtral-8x7B-Instruct-v0.1")
|
| 55 |
-
|
| 56 |
-
class IntegratorModel(Model):
|
| 57 |
-
def __init__(self):
|
| 58 |
-
super().__init__("Integrator🔄", "The Integrator model is a Large Language Model (LLM) that's best suited for integrating frontend and backend components, handling business logic, and ensuring seamless communication between different parts of the application.", "microsoft/Phi-3-mini-4k-instruct")
|
| 59 |
-
|
| 60 |
-
# --- Streamlit Interface ---
|
| 61 |
-
model_links = {
|
| 62 |
-
"FrontendForge🚀": "mistralai/Mistral-7B-Instruct-v0.2",
|
| 63 |
-
"BackendBuilder⭐": "mistralai/Mixtral-8x7B-Instruct-v0.1",
|
| 64 |
-
"Integrator🔄": "microsoft/Phi-3-mini-4k-instruct"
|
| 65 |
-
}
|
| 66 |
-
|
| 67 |
-
model_info = {
|
| 68 |
-
"FrontendForge🚀": {
|
| 69 |
-
'description': "The FrontendForge model is a Large Language Model (LLM) that's able to handle frontend development tasks such as UI design and user interaction logic.",
|
| 70 |
-
'logo': './11.jpg'
|
| 71 |
-
},
|
| 72 |
-
"BackendBuilder⭐": {
|
| 73 |
-
'description': "The BackendBuilder model is a Large Language Model (LLM) that's specialized in backend development tasks including API creation, database management, and server-side logic.",
|
| 74 |
-
'logo': './2.jpg'
|
| 75 |
-
},
|
| 76 |
-
"Integrator🔄": {
|
| 77 |
-
'description': "The Integrator model is a Large Language Model (LLM) that's best suited for integrating frontend and backend components, handling business logic, and ensuring seamless communication between different parts of the application.",
|
| 78 |
-
'logo': './3.jpg'
|
| 79 |
-
},
|
| 80 |
-
}
|
| 81 |
-
|
| 82 |
-
def format_prompt(message, conversation_history, custom_instructions=None):
|
| 83 |
-
prompt = ""
|
| 84 |
-
if custom_instructions:
|
| 85 |
-
prompt += "[INST] {} [/INST]\n".format(custom_instructions)
|
| 86 |
-
|
| 87 |
-
# Add conversation history to the prompt
|
| 88 |
-
prompt += "[CONV_HISTORY]\n"
|
| 89 |
-
for role, content in conversation_history:
|
| 90 |
-
prompt += "{}: {}\n".format(role.upper(), content)
|
| 91 |
-
prompt += "[/CONV_HISTORY]\n"
|
| 92 |
-
|
| 93 |
-
# Add the current message
|
| 94 |
-
prompt += "[INST] {} [/INST]\n".format(message)
|
| 95 |
-
|
| 96 |
-
# Add the response format
|
| 97 |
-
prompt += "[RESPONSE]\n"
|
| 98 |
-
|
| 99 |
-
return prompt
|
| 100 |
-
|
| 101 |
-
def reset_conversation():
|
| 102 |
-
'''
|
| 103 |
-
Resets Conversation
|
| 104 |
-
'''
|
| 105 |
-
st.session_state.conversation = []
|
| 106 |
-
st.session_state.messages = []
|
| 107 |
-
st.session_state.chat_state = "reset"
|
| 108 |
-
|
| 109 |
-
def load_conversation_history():
|
| 110 |
-
history_file = "conversation_history.pickle"
|
| 111 |
-
if os.path.exists(history_file):
|
| 112 |
-
with open(history_file, "rb") as f:
|
| 113 |
-
conversation_history = pickle.load(f)
|
| 114 |
-
else:
|
| 115 |
-
conversation_history = []
|
| 116 |
-
return conversation_history
|
| 117 |
-
|
| 118 |
-
def save_conversation_history(conversation_history):
|
| 119 |
-
history_file = "conversation_history.pickle"
|
| 120 |
-
with open(history_file, "wb") as f:
|
| 121 |
-
pickle.dump(conversation_history, f)
|
| 122 |
-
|
| 123 |
-
models = [key for key in model_links.keys()]
|
| 124 |
-
selected_model = st.sidebar.selectbox("Select Model", models)
|
| 125 |
-
temp_values = st.sidebar.slider('Select a temperature value', 0.0, 1.0, (0.5))
|
| 126 |
-
st.sidebar.button('Reset Chat', on_click=reset_conversation) # Reset button
|
| 127 |
-
|
| 128 |
-
st.sidebar.write(f"You're now chatting with **{selected_model}**")
|
| 129 |
-
st.sidebar.markdown(model_info[selected_model]['description'])
|
| 130 |
-
st.sidebar.image(model_info[selected_model]['logo'])
|
| 131 |
-
|
| 132 |
-
st.sidebar.markdown("*Generating the code might go slow if you are using low power resources*")
|
| 133 |
-
|
| 134 |
-
if "prev_option" not in st.session_state:
|
| 135 |
-
st.session_state.prev_option = selected_model
|
| 136 |
-
|
| 137 |
-
if st.session_state.prev_option != selected_model:
|
| 138 |
-
st.session_state.messages = []
|
| 139 |
-
st.session_state.prev_option = selected_model
|
| 140 |
-
|
| 141 |
-
if "chat_state" not in st.session_state:
|
| 142 |
-
st.session_state.chat_state = "normal"
|
| 143 |
-
|
| 144 |
-
# Load the conversation history from the file
|
| 145 |
-
if "messages" not in st.session_state:
|
| 146 |
-
st.session_state.messages = load_conversation_history()
|
| 147 |
-
|
| 148 |
-
repo_id = model_links[selected_model]
|
| 149 |
-
st.subheader(f'{selected_model}')
|
| 150 |
-
|
| 151 |
-
if st.session_state.chat_state == "normal":
|
| 152 |
-
for message in st.session_state.messages:
|
| 153 |
-
with st.chat_message(message["role"]):
|
| 154 |
-
st.markdown(message["content"])
|
| 155 |
-
|
| 156 |
-
if prompt := st.chat_input(f"Hi I'm {selected_model}, How can I help you today?"):
|
| 157 |
-
custom_instruction = "Act like a Human in conversation"
|
| 158 |
-
with st.chat_message("user"):
|
| 159 |
-
st.markdown(prompt)
|
| 160 |
-
|
| 161 |
-
st.session_state.messages.append({"role": "user", "content": prompt})
|
| 162 |
-
conversation_history = [(message["role"], message["content"]) for message in st.session_state.messages]
|
| 163 |
-
|
| 164 |
-
formated_text = format_prompt(prompt, conversation_history, custom_instruction)
|
| 165 |
-
|
| 166 |
-
with st.chat_message("assistant"):
|
| 167 |
-
# Select the appropriate model based on the user's choice
|
| 168 |
-
if selected_model == "FrontendForge🚀":
|
| 169 |
-
model = FrontendForgeModel()
|
| 170 |
-
elif selected_model == "BackendBuilder⭐":
|
| 171 |
-
model = BackendBuilderModel()
|
| 172 |
-
elif selected_model == "Integrator🔄":
|
| 173 |
-
model = IntegratorModel()
|
| 174 |
-
else:
|
| 175 |
-
st.error("Invalid model selection.")
|
| 176 |
-
st.stop() # Stop the Streamlit app execution
|
| 177 |
-
|
| 178 |
-
response = model.generate_text(formated_text, temperature=temp_values)
|
| 179 |
-
st.markdown(response)
|
| 180 |
-
st.session_state.messages.append({"role": "assistant", "content": response})
|
| 181 |
-
save_conversation_history(st.session_state.messages)
|
| 182 |
-
|
| 183 |
-
elif st.session_state.chat_state == "reset":
|
| 184 |
-
st.session_state.chat_state = "normal"
|
| 185 |
-
st.experimental_rerun()
|
| 186 |
-
|
| 187 |
-
# --- Agent Definitions ---
|
| 188 |
-
class Agent:
|
| 189 |
def __init__(self, name, role, tools, knowledge_base=None):
|
| 190 |
-
|
| 191 |
-
self.
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
llm=self.llm,
|
| 198 |
-
tools=self.tools,
|
| 199 |
-
agent_type=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
|
| 200 |
-
verbose=True
|
| 201 |
)
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
def observe(self, observation):
|
| 209 |
-
# Process observation based on the agent's capabilities and the nature of the observation
|
| 210 |
-
self.memory.append(observation)
|
| 211 |
-
|
| 212 |
-
def learn(self, data):
|
| 213 |
-
# Implement learning logic based on the agent's capabilities and the type of data
|
| 214 |
-
pass
|
| 215 |
-
|
| 216 |
-
def __str__(self):
|
| 217 |
-
return f"Agent: {self.name} (Role: {self.role})"
|
| 218 |
-
|
| 219 |
-
# --- Tool Definitions ---
|
| 220 |
-
class Tool:
|
| 221 |
-
def __init__(self, name, description):
|
| 222 |
-
self.name = name
|
| 223 |
-
self.description = description
|
| 224 |
-
|
| 225 |
-
def run(self, arguments):
|
| 226 |
-
# Implement tool execution logic based on the specific tool's functionality and the provided arguments
|
| 227 |
-
return {"output": "Tool Output"}
|
| 228 |
-
|
| 229 |
-
# --- Tool Examples ---
|
| 230 |
-
class CodeGenerationTool(Tool):
|
| 231 |
-
def __init__(self):
|
| 232 |
-
super().__init__("Code Generation", "Generates code snippets in various languages.")
|
| 233 |
-
self.llm = HuggingFaceHub(repo_id="google/flan-t5-xl", model_kwargs={"temperature": 0.5})
|
| 234 |
-
self.prompt_template = PromptTemplate(
|
| 235 |
-
input_variables=["language", "code_description"],
|
| 236 |
-
template="Generate {language} code for: {code_description}"
|
| 237 |
)
|
| 238 |
-
self.chain = LLMChain(llm=self.llm, prompt=self.prompt_template)
|
| 239 |
-
|
| 240 |
-
def run(self, arguments):
|
| 241 |
-
language = arguments.get("language", "python")
|
| 242 |
-
code_description = arguments.get("code_description", "print('Hello, World!')")
|
| 243 |
-
code = self.chain.run(language=language, code_description=code_description)
|
| 244 |
-
return {"output": code}
|
| 245 |
|
| 246 |
-
class
|
| 247 |
def __init__(self):
|
| 248 |
-
super().__init__("
|
| 249 |
-
self.llm = HuggingFaceHub(repo_id="google/flan-t5-xl", model_kwargs={"temperature": 0.5})
|
| 250 |
-
self.prompt_template = PromptTemplate(
|
| 251 |
-
input_variables=["data_source", "data_query"],
|
| 252 |
-
template="Retrieve data from {data_source} based on: {data_query}"
|
| 253 |
-
)
|
| 254 |
-
self.chain = LLMChain(llm=self.llm, prompt=self.prompt_template)
|
| 255 |
-
|
| 256 |
-
def run(self, arguments):
|
| 257 |
-
data_source = arguments.get("data_source", "https://example.com/data")
|
| 258 |
-
data_query = arguments.get("data_query", "some information")
|
| 259 |
-
data = self.chain.run(data_source=data_source, data_query=data_query)
|
| 260 |
-
return {"output": data}
|
| 261 |
|
| 262 |
-
class
|
| 263 |
def __init__(self):
|
| 264 |
-
super().__init__("
|
| 265 |
-
self.llm = HuggingFaceHub(repo_id="google/flan-t5-xl", model_kwargs={"temperature": 0.5})
|
| 266 |
-
self.prompt_template = PromptTemplate(
|
| 267 |
-
input_variables=["text_prompt"],
|
| 268 |
-
template="Generate text based on: {text_prompt}"
|
| 269 |
-
)
|
| 270 |
-
self.chain = LLMChain(llm=self.llm, prompt=self.prompt_template)
|
| 271 |
-
|
| 272 |
-
def run(self, arguments):
|
| 273 |
-
text_prompt = arguments.get("text_prompt", "Write a short story about a cat.")
|
| 274 |
-
text = self.chain.run(text_prompt=text_prompt)
|
| 275 |
-
return {"output": text}
|
| 276 |
|
| 277 |
-
class
|
| 278 |
def __init__(self):
|
| 279 |
-
super().__init__("
|
| 280 |
|
| 281 |
-
|
| 282 |
-
code = arguments.get("code", "print('Hello, World!')")
|
| 283 |
-
try:
|
| 284 |
-
exec(code)
|
| 285 |
-
return {"output": f"Code executed: {code}"}
|
| 286 |
-
except Exception as e:
|
| 287 |
-
return {"output": f"Error executing code: {e}"}
|
| 288 |
-
|
| 289 |
-
class CodeDebuggingTool(Tool):
|
| 290 |
def __init__(self):
|
| 291 |
-
super().__init__("
|
| 292 |
-
self.llm = HuggingFaceHub(repo_id="google/flan-t5-xl", model_kwargs={"temperature": 0.5})
|
| 293 |
-
self.prompt_template = PromptTemplate(
|
| 294 |
-
input_variables=["code", "error_message"],
|
| 295 |
-
template="Debug the following code:\n{code}\n\nError message: {error_message}"
|
| 296 |
-
)
|
| 297 |
-
self.chain = LLMChain(llm=self.llm, prompt=self.prompt_template)
|
| 298 |
-
|
| 299 |
-
def run(self, arguments):
|
| 300 |
-
code = arguments.get("code", "print('Hello, World!')")
|
| 301 |
-
try:
|
| 302 |
-
exec(code)
|
| 303 |
-
return {"output": f"Code debugged: {code}"}
|
| 304 |
-
except Exception as e:
|
| 305 |
-
error_message = str(e)
|
| 306 |
-
debugged_code = self.chain.run(code=code, error_message=error_message)
|
| 307 |
-
return {"output": f"Debugged code:\n{debugged_code}"}
|
| 308 |
|
| 309 |
-
class
|
| 310 |
def __init__(self):
|
| 311 |
-
super().__init__("
|
| 312 |
-
self.llm = HuggingFaceHub(repo_id="google/flan-t5-xl", model_kwargs={"temperature": 0.5})
|
| 313 |
-
self.prompt_template = PromptTemplate(
|
| 314 |
-
input_variables=["code"],
|
| 315 |
-
template="Summarize the functionality of the following code:\n{code}"
|
| 316 |
-
)
|
| 317 |
-
self.chain = LLMChain(llm=self.llm, prompt=self.prompt_template)
|
| 318 |
-
|
| 319 |
-
def run(self, arguments):
|
| 320 |
-
code = arguments.get("code", "print('Hello, World!')")
|
| 321 |
-
summary = self.chain.run(code=code)
|
| 322 |
-
return {"output": f"Code summary: {summary}"}
|
| 323 |
|
| 324 |
-
class
|
| 325 |
def __init__(self):
|
| 326 |
-
super().__init__("
|
| 327 |
-
self.llm = HuggingFaceHub(repo_id="google/flan-t5-xl", model_kwargs={"temperature": 0.5})
|
| 328 |
-
self.prompt_template = PromptTemplate(
|
| 329 |
-
input_variables=["code", "target_language"],
|
| 330 |
-
template="Translate the following code to {target_language}:\n{code}"
|
| 331 |
-
)
|
| 332 |
-
self.chain = LLMChain(llm=self.llm, prompt=self.prompt_template)
|
| 333 |
|
| 334 |
-
|
| 335 |
-
code = arguments.get("code", "print('Hello, World!')")
|
| 336 |
-
target_language = arguments.get("target_language", "javascript")
|
| 337 |
-
translated_code = self.chain.run(code=code, target_language=target_language)
|
| 338 |
-
return {"output": f"Translated code:\n{translated_code}"}
|
| 339 |
-
|
| 340 |
-
class CodeOptimizationTool(Tool):
|
| 341 |
def __init__(self):
|
| 342 |
-
super().__init__("
|
| 343 |
-
self.llm = HuggingFaceHub(repo_id="google/flan-t5-xl", model_kwargs={"temperature": 0.5})
|
| 344 |
-
self.prompt_template = PromptTemplate(
|
| 345 |
-
input_variables=["code"],
|
| 346 |
-
template="Optimize the following code for performance and efficiency:\n{code}"
|
| 347 |
-
)
|
| 348 |
-
self.chain = LLMChain(llm=self.llm, prompt=self.prompt_template)
|
| 349 |
-
|
| 350 |
-
def run(self, arguments):
|
| 351 |
-
code = arguments.get("code", "print('Hello, World!')")
|
| 352 |
-
optimized_code = self.chain.run(code=code)
|
| 353 |
-
return {"output": f"Optimized code:\n{optimized_code}"}
|
| 354 |
|
| 355 |
-
|
|
|
|
| 356 |
def __init__(self):
|
| 357 |
-
|
| 358 |
-
|
| 359 |
-
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
|
| 366 |
-
|
| 367 |
-
documentation = self.chain.run(code=code)
|
| 368 |
-
return {"output": f"Code documentation:\n{documentation}"}
|
| 369 |
-
|
| 370 |
-
class ImageGenerationTool(Tool):
|
| 371 |
-
def __init__(self):
|
| 372 |
-
super().__init__("Image Generation", "Generates images based on text descriptions.")
|
| 373 |
-
self.llm = HuggingFaceHub(repo_id="google/flan-t5-xl", model_kwargs={"temperature": 0.5})
|
| 374 |
-
self.prompt_template = PromptTemplate(
|
| 375 |
-
input_variables=["description"],
|
| 376 |
-
template="Generate an image based on the description: {description}"
|
| 377 |
-
)
|
| 378 |
-
self.chain = LLMChain(llm=self.llm, prompt=self.prompt_template)
|
| 379 |
-
|
| 380 |
-
def run(self, arguments):
|
| 381 |
-
description = arguments.get("description", "A cat sitting on a couch")
|
| 382 |
-
image_url = self.chain.run(description=description)
|
| 383 |
-
return {"output": f"Generated image: {image_url}"}
|
| 384 |
-
|
| 385 |
-
class ImageEditingTool(Tool):
|
| 386 |
-
def __init__(self):
|
| 387 |
-
super().__init__("Image Editing", "Modifying existing images.")
|
| 388 |
-
self.llm = HuggingFaceHub(repo_id="google/flan-t5-xl", model_kwargs={"temperature": 0.5})
|
| 389 |
-
self.prompt_template = PromptTemplate(
|
| 390 |
-
input_variables=["image_url", "editing_instructions"],
|
| 391 |
-
template="Edit the image at {image_url} according to the instructions: {editing_instructions}"
|
| 392 |
-
)
|
| 393 |
-
self.chain = LLMChain(llm=self.llm, prompt=self.prompt_template)
|
| 394 |
-
|
| 395 |
-
def run(self, arguments):
|
| 396 |
-
image_url = arguments.get("image_url", "https://example.com/image.jpg")
|
| 397 |
-
editing_instructions = arguments.get("editing_instructions", "Make the cat smile")
|
| 398 |
-
edited_image_url = self.chain.run(image_url=image_url, editing_instructions=editing_instructions)
|
| 399 |
-
return {"output": f"Edited image: {edited_image_url}"}
|
| 400 |
-
|
| 401 |
-
class ImageAnalysisTool(Tool):
|
| 402 |
-
def __init__(self):
|
| 403 |
-
super().__init__("Image Analysis", "Extracting information from images, such as objects, scenes, and emotions.")
|
| 404 |
-
self.llm = HuggingFaceHub(repo_id="google/flan-t5-xl", model_kwargs={"temperature": 0.5})
|
| 405 |
-
self.prompt_template = PromptTemplate(
|
| 406 |
-
input_variables=["image_url"],
|
| 407 |
-
template="Analyze the image at {image_url} and provide information about objects, scenes, and emotions."
|
| 408 |
-
)
|
| 409 |
-
self.chain = LLMChain(llm=self.llm, prompt=self.prompt_template)
|
| 410 |
|
| 411 |
-
def
|
| 412 |
-
|
| 413 |
-
analysis_results = self.chain.run(image_url=image_url)
|
| 414 |
-
return {"output": f"Image analysis results:\n{analysis_results}"}
|
| 415 |
-
|
| 416 |
-
class QuestionAnsweringTool(Tool):
|
| 417 |
-
def __init__(self):
|
| 418 |
-
super().__init__("Question Answering", "Answers questions based on provided context.")
|
| 419 |
-
self.llm = HuggingFaceHub(repo_id="google/flan-t5-xl", model_kwargs={"temperature": 0.5})
|
| 420 |
-
self.qa_chain = load_qa_chain(self.llm) # Use a question answering chain
|
| 421 |
-
|
| 422 |
-
def run(self, arguments):
|
| 423 |
-
question = arguments.get("question", "What is the capital of France?")
|
| 424 |
-
context = arguments.get("context", "France is a country in Western Europe. Its capital is Paris.")
|
| 425 |
-
answer = self.qa_chain.run(question=question, context=context)
|
| 426 |
-
return {"output": answer}
|
| 427 |
-
|
| 428 |
-
# --- Agent Pool ---
|
| 429 |
-
agent_pool = {
|
| 430 |
-
"IdeaIntake": Agent("IdeaIntake", "Idea Intake", [DataRetrievalTool(), CodeGenerationTool(), TextGenerationTool(), QuestionAnsweringTool()], knowledge_base=""),
|
| 431 |
-
"CodeBuilder": Agent("CodeBuilder", "Code Builder", [CodeGenerationTool(), CodeDebuggingTool(), CodeOptimizationTool(), CodeExecutionTool(), CodeSummarizationTool(), CodeTranslationTool(), CodeDocumentationTool()], knowledge_base=""),
|
| 432 |
-
"ImageCreator": Agent("ImageCreator", "Image Creator", [ImageGenerationTool(), ImageEditingTool(), ImageAnalysisTool()], knowledge_base=""),
|
| 433 |
-
}
|
| 434 |
-
|
| 435 |
-
# --- Workflow Definitions ---
|
| 436 |
-
class Workflow:
|
| 437 |
-
def __init__(self, name, agents, task, description):
|
| 438 |
-
self.name = name
|
| 439 |
-
self.agents = agents
|
| 440 |
-
self.task = task
|
| 441 |
-
self.description = description
|
| 442 |
-
|
| 443 |
-
def run(self, prompt, context):
|
| 444 |
for agent in self.agents:
|
| 445 |
-
|
| 446 |
-
|
| 447 |
-
|
| 448 |
-
|
| 449 |
-
|
| 450 |
-
|
| 451 |
-
|
| 452 |
-
|
| 453 |
-
|
| 454 |
-
|
| 455 |
-
|
| 456 |
-
|
| 457 |
-
|
| 458 |
-
|
| 459 |
-
|
| 460 |
-
|
| 461 |
-
|
| 462 |
-
|
| 463 |
-
|
| 464 |
-
|
| 465 |
-
|
| 466 |
-
|
| 467 |
-
|
| 468 |
-
|
| 469 |
-
super().__init__("Plugin Build", [agent_pool["IdeaIntake"], agent_pool["CodeBuilder"]], "Build a plugin", "A workflow for building a plugin.")
|
| 470 |
-
|
| 471 |
-
class DevSandboxWorkflow(Workflow):
|
| 472 |
-
def __init__(self):
|
| 473 |
-
super().__init__("Dev Sandbox", [agent_pool["IdeaIntake"], agent_pool["CodeBuilder"]], "Experiment with code", "A workflow for experimenting with code.")
|
| 474 |
-
|
| 475 |
-
# --- Agent-Based Workflow Execution ---
|
| 476 |
-
def execute_workflow(workflow, prompt, context):
|
| 477 |
-
# Execute the workflow
|
| 478 |
-
context = workflow.run(prompt, context)
|
| 479 |
-
# Display the output
|
| 480 |
-
for agent in workflow.agents:
|
| 481 |
-
st.write(f"{agent}: {agent.memory}")
|
| 482 |
-
for action in agent.memory:
|
| 483 |
-
st.write(f" Action: {action}")
|
| 484 |
-
return context
|
| 485 |
-
|
| 486 |
-
# --- Example Usage ---
|
| 487 |
-
if st.button("Build an App"):
|
| 488 |
-
app_build_workflow = AppBuildWorkflow()
|
| 489 |
-
context = {"task": "Build a mobile application"}
|
| 490 |
-
context = execute_workflow(app_build_workflow, "Build a mobile app for ordering food.", context)
|
| 491 |
-
st.write(f"Workflow Output: {context}")
|
| 492 |
-
|
| 493 |
-
if st.button("Build a Website"):
|
| 494 |
-
website_build_workflow = WebsiteBuildWorkflow()
|
| 495 |
-
context = {"task": "Build a website"}
|
| 496 |
-
context = execute_workflow(website_build_workflow, "Build a website for a restaurant.", context)
|
| 497 |
-
st.write(f"Workflow Output: {context}")
|
| 498 |
-
|
| 499 |
-
if st.button("Build a Game"):
|
| 500 |
-
game_build_workflow = GameBuildWorkflow()
|
| 501 |
-
context = {"task": "Build a game"}
|
| 502 |
-
context = execute_workflow(game_build_workflow, "Build a simple 2D platformer game.", context)
|
| 503 |
-
st.write(f"Workflow Output: {context}")
|
| 504 |
-
|
| 505 |
-
if st.button("Build a Plugin"):
|
| 506 |
-
plugin_build_workflow = PluginBuildWorkflow()
|
| 507 |
-
context = {"task": "Build a plugin"}
|
| 508 |
-
context = execute_workflow(plugin_build_workflow, "Build a plugin for a text editor that adds a new syntax highlighting theme.", context)
|
| 509 |
-
st.write(f"Workflow Output: {context}")
|
| 510 |
-
|
| 511 |
-
if st.button("Dev Sandbox"):
|
| 512 |
-
dev_sandbox_workflow = DevSandboxWorkflow()
|
| 513 |
-
context = {"task": "Experiment with code"}
|
| 514 |
-
context = execute_workflow(dev_sandbox_workflow, "Write a Python function to reverse a string.", context)
|
| 515 |
-
st.write(f"Workflow Output: {context}")
|
| 516 |
-
|
| 517 |
-
# --- Displaying Agent and Tool Information ---
|
| 518 |
-
st.subheader("Agent Pool")
|
| 519 |
-
for agent_name, agent in agent_pool.items():
|
| 520 |
-
st.write(f"**{agent_name}**")
|
| 521 |
-
st.write(f" Role: {agent.role}")
|
| 522 |
-
st.write(f" Tools: {', '.join([tool.name for tool in agent.tools])}")
|
| 523 |
-
|
| 524 |
-
st.subheader("Workflows")
|
| 525 |
-
st.write("**App Build**")
|
| 526 |
-
st.write(f""" Description: {AppBuildWorkflow().description}""")
|
| 527 |
-
st.write("**Website Build**")
|
| 528 |
-
st.write(f""" Description: {WebsiteBuildWorkflow().description}""")
|
| 529 |
-
st.write("**Game Build**")
|
| 530 |
-
st.write(f""" Description: {GameBuildWorkflow().description}""")
|
| 531 |
-
st.write("**Plugin Build**")
|
| 532 |
-
st.write(f""" Description: {PluginBuildWorkflow().description}""")
|
| 533 |
-
st.write("**Dev Sandbox**")
|
| 534 |
-
st.write(f""" Description: {DevSandboxWorkflow().description}""")
|
| 535 |
-
|
| 536 |
-
# --- Displaying Tool Definitions ---
|
| 537 |
-
st.subheader("Tool Definitions")
|
| 538 |
-
for tool_class in [CodeGenerationTool, DataRetrievalTool, CodeExecutionTool, CodeDebuggingTool, CodeSummarizationTool, CodeTranslationTool, CodeOptimizationTool, CodeDocumentationTool, ImageGenerationTool, ImageEditingTool, ImageAnalysisTool, TextGenerationTool, QuestionAnsweringTool]:
|
| 539 |
-
tool = tool_class()
|
| 540 |
-
st.write(f"**{tool.name}**")
|
| 541 |
-
st.write(f" Description: {tool.description}")
|
| 542 |
-
|
| 543 |
-
# --- Displaying Example Output ---
|
| 544 |
-
st.subheader("Example Output")
|
| 545 |
-
code_generation_tool = CodeGenerationTool()
|
| 546 |
-
st.write(f"""Code Generation Tool Output: {code_generation_tool.run({'language': 'python', 'code_description': "print('Hello, World!')"})}""")
|
| 547 |
-
|
| 548 |
-
data_retrieval_tool = DataRetrievalTool()
|
| 549 |
-
st.write(f"""Data Retrieval Tool Output: {data_retrieval_tool.run({'data_source': 'https://example.com/data', 'data_query': 'some information'})}""")
|
| 550 |
-
|
| 551 |
-
code_execution_tool = CodeExecutionTool()
|
| 552 |
-
st.write(f"""Code Execution Tool Output: {code_execution_tool.run({'code': "print('Hello, World!')"})}""")
|
| 553 |
-
|
| 554 |
-
code_debugging_tool = CodeDebuggingTool()
|
| 555 |
-
st.write(f"""Code Debugging Tool Output: {code_debugging_tool.run({'code': "print('Hello, World!')"})}""")
|
| 556 |
-
|
| 557 |
-
code_summarization_tool = CodeSummarizationTool()
|
| 558 |
-
st.write(f"""Code Summarization Tool Output: {code_summarization_tool.run({'code': "print('Hello, World!')"})}""")
|
| 559 |
-
|
| 560 |
-
code_translation_tool = CodeTranslationTool()
|
| 561 |
-
st.write(f"""Code Translation Tool Output: {code_translation_tool.run({'code': "print('Hello, World!')", 'target_language': 'javascript'})}""")
|
| 562 |
-
|
| 563 |
-
code_optimization_tool = CodeOptimizationTool()
|
| 564 |
-
st.write(f"""Code Optimization Tool Output: {code_optimization_tool.run({'code': "print('Hello, World!')"})}""")
|
| 565 |
-
|
| 566 |
-
code_documentation_tool = CodeDocumentationTool()
|
| 567 |
-
st.write(f"""Code Documentation Tool Output: {code_documentation_tool.run({'code': "print('Hello, World!')"})}""")
|
| 568 |
-
|
| 569 |
-
image_generation_tool = ImageGenerationTool()
|
| 570 |
-
st.write(f"""Image Generation Tool Output: {image_generation_tool.run({'description': 'A cat sitting on a couch'})}""")
|
| 571 |
|
| 572 |
-
|
| 573 |
-
st.
|
| 574 |
|
| 575 |
-
|
| 576 |
-
st.write(f"""Image Analysis Tool Output: {image_analysis_tool.run({'image_url': 'https://example.com/image.jpg'})}""")
|
| 577 |
|
| 578 |
-
|
| 579 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import streamlit as st
|
| 2 |
+
from langchain.agents import create_react_agent, AgentExecutor
|
| 3 |
+
from langchain.prompts import PromptTemplate
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
from langchain_community.llms import HuggingFaceHub
|
| 5 |
+
from langchain.tools import Tool
|
| 6 |
+
from langchain.chains import LLMChain
|
| 7 |
from typing import List, Dict, Any, Optional
|
| 8 |
|
| 9 |
+
# Base Tool and specific tools (CodeGenerationTool, DataRetrievalTool, TextGenerationTool) remain the same as in the previous version
|
| 10 |
|
| 11 |
+
# --- Specialized Agent Definitions ---
|
| 12 |
+
class SpecializedAgent(Agent):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
def __init__(self, name, role, tools, knowledge_base=None):
|
| 14 |
+
super().__init__(name, role, tools, knowledge_base)
|
| 15 |
+
self.prompt = PromptTemplate.from_template(
|
| 16 |
+
"You are a specialized AI assistant named {name} with the role of {role}. "
|
| 17 |
+
"Use the following tools to complete your task: {tools}\n\n"
|
| 18 |
+
"Task: {input}\n"
|
| 19 |
+
"Thought: Let's approach this step-by-step:\n"
|
| 20 |
+
"{agent_scratchpad}"
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
)
|
| 22 |
+
self.react_agent = create_react_agent(self.llm, self.tools, self.prompt)
|
| 23 |
+
self.agent_executor = AgentExecutor(
|
| 24 |
+
agent=self.react_agent,
|
| 25 |
+
tools=self.tools,
|
| 26 |
+
verbose=True,
|
| 27 |
+
max_iterations=5
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
|
| 30 |
+
class RequirementsAgent(SpecializedAgent):
|
| 31 |
def __init__(self):
|
| 32 |
+
super().__init__("RequirementsAnalyst", "Analyzing and refining project requirements", [TextGenerationTool()])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
|
| 34 |
+
class ArchitectureAgent(SpecializedAgent):
|
| 35 |
def __init__(self):
|
| 36 |
+
super().__init__("SystemArchitect", "Designing system architecture", [TextGenerationTool()])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
|
| 38 |
+
class FrontendAgent(SpecializedAgent):
|
| 39 |
def __init__(self):
|
| 40 |
+
super().__init__("FrontendDeveloper", "Developing the frontend", [CodeGenerationTool()])
|
| 41 |
|
| 42 |
+
class BackendAgent(SpecializedAgent):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 43 |
def __init__(self):
|
| 44 |
+
super().__init__("BackendDeveloper", "Developing the backend", [CodeGenerationTool(), DataRetrievalTool()])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 45 |
|
| 46 |
+
class DatabaseAgent(SpecializedAgent):
|
| 47 |
def __init__(self):
|
| 48 |
+
super().__init__("DatabaseEngineer", "Designing and implementing the database", [CodeGenerationTool(), DataRetrievalTool()])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 49 |
|
| 50 |
+
class TestingAgent(SpecializedAgent):
|
| 51 |
def __init__(self):
|
| 52 |
+
super().__init__("QAEngineer", "Creating and executing test plans", [CodeGenerationTool(), TextGenerationTool()])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 53 |
|
| 54 |
+
class DeploymentAgent(SpecializedAgent):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
def __init__(self):
|
| 56 |
+
super().__init__("DevOpsEngineer", "Handling deployment and infrastructure", [CodeGenerationTool(), TextGenerationTool()])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 57 |
|
| 58 |
+
# --- Application Building Sequence ---
|
| 59 |
+
class ApplicationBuilder:
|
| 60 |
def __init__(self):
|
| 61 |
+
self.agents = [
|
| 62 |
+
RequirementsAgent(),
|
| 63 |
+
ArchitectureAgent(),
|
| 64 |
+
FrontendAgent(),
|
| 65 |
+
BackendAgent(),
|
| 66 |
+
DatabaseAgent(),
|
| 67 |
+
TestingAgent(),
|
| 68 |
+
DeploymentAgent()
|
| 69 |
+
]
|
| 70 |
+
self.project_state = {}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 71 |
|
| 72 |
+
def build_application(self, project_description):
|
| 73 |
+
st.write("Starting application building process...")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 74 |
for agent in self.agents:
|
| 75 |
+
st.write(f"\n--- {agent.name}'s Turn ---")
|
| 76 |
+
task = self.get_task_for_agent(agent, project_description)
|
| 77 |
+
response = agent.act(task, self.project_state)
|
| 78 |
+
self.project_state[agent.role] = response
|
| 79 |
+
st.write(f"{agent.name}'s output:")
|
| 80 |
+
st.write(response)
|
| 81 |
+
st.write("\nApplication building process completed!")
|
| 82 |
+
|
| 83 |
+
def get_task_for_agent(self, agent, project_description):
|
| 84 |
+
tasks = (
|
| 85 |
+
(RequirementsAgent, f"Analyze and refine the requirements for this project: {project_description}"),
|
| 86 |
+
(ArchitectureAgent, f"Design the system architecture based on these requirements: {self.project_state.get('Analyzing and refining project requirements', '')}"),
|
| 87 |
+
(FrontendAgent, f"Develop the frontend based on this architecture: {self.project_state.get('Designing system architecture', '')}"),
|
| 88 |
+
(BackendAgent, f"Develop the backend based on this architecture: {self.project_state.get('Designing system architecture', '')}"),
|
| 89 |
+
(DatabaseAgent, f"Design and implement the database based on this architecture: {self.project_state.get('Designing system architecture', '')}"),
|
| 90 |
+
(TestingAgent, f"Create a test plan for this application: {project_description}"),
|
| 91 |
+
(DeploymentAgent, f"Create a deployment plan for this application: {project_description}")
|
| 92 |
+
)
|
| 93 |
+
|
| 94 |
+
for agent_class, task in tasks:
|
| 95 |
+
if isinstance(agent, agent_class):
|
| 96 |
+
return task
|
| 97 |
+
|
| 98 |
+
return f"Contribute to the project: {project_description}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 99 |
|
| 100 |
+
# --- Streamlit App ---
|
| 101 |
+
st.title("CODEFUSSION ☄ - Full-Stack Application Builder")
|
| 102 |
|
| 103 |
+
project_description = st.text_area("Enter your project description:")
|
|
|
|
| 104 |
|
| 105 |
+
if st.button("Build Application"):
|
| 106 |
+
if project_description:
|
| 107 |
+
app_builder = ApplicationBuilder()
|
| 108 |
+
app_builder.build_application(project_description)
|
| 109 |
+
else:
|
| 110 |
+
st.write("Please enter a project description.")
|
| 111 |
+
|
| 112 |
+
# Display information about the agents
|
| 113 |
+
st.sidebar.title("Agent Information")
|
| 114 |
+
app_builder = ApplicationBuilder()
|
| 115 |
+
for agent in app_builder.agents:
|
| 116 |
+
st.sidebar.write(f"--- {agent.name} ---")
|
| 117 |
+
st.sidebar.write(f"Role: {agent.role}")
|
| 118 |
+
st.sidebar.write("Tools:")
|
| 119 |
+
for tool in agent.tools:
|
| 120 |
+
st.sidebar.write(f"- {tool.name}")
|
| 121 |
+
st.sidebar.write("")
|