acecalisto3 commited on
Commit
a19f8cb
·
verified ·
1 Parent(s): 22e9cdf

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +64 -16
app.py CHANGED
@@ -8,6 +8,16 @@ from typing import List
8
  import yaml
9
  import os
10
  import json
 
 
 
 
 
 
 
 
 
 
11
 
12
  def load_config():
13
  config_path = os.path.join(os.path.dirname(__file__), "config.yaml")
@@ -15,7 +25,7 @@ def load_config():
15
  with open(config_path, "r") as config_file:
16
  return yaml.safe_load(config_file)
17
  except FileNotFoundError:
18
- print("Config file not found. Using default configuration.")
19
  return {
20
  "model": "mistralai/Mixtral-8x7B-Instruct-v0.1",
21
  "hf_api_token": os.environ.get("HUGGINGFACEHUB_API_TOKEN", "your_default_token_here")
@@ -30,8 +40,9 @@ class CodeGenerationTool(BaseTool):
30
  name = "CodeGeneration"
31
  description = "Generates code based on a prompt"
32
 
 
33
  def _run(self, prompt: str) -> str:
34
- # Implement basic code generation logic
35
  if "Flask app structure" in prompt:
36
  return self.generate_flask_app_structure()
37
  elif "binary search algorithm" in prompt:
@@ -193,22 +204,23 @@ class Agent:
193
  def __init__(self, name: str, description: str, tools: List[BaseTool]):
194
  self.name = name
195
  self.description = description
196
- self.llm = HuggingFaceEndpoint(
197
- repo_id=config["model"],
198
- task="text-generation",
199
- model_kwargs={"temperature": 0.7, "max_length": 1024},
200
- huggingfacehub_api_token=config["hf_api_token"]
201
- )
202
-
203
- self.prompt_template = PromptTemplate(
204
- template="You are {name}, {description}. Respond to the following: {input}",
205
- input_variables=["name", "description", "input"]
206
- )
207
-
208
  try:
 
 
 
 
 
 
 
 
 
 
 
 
209
  self.agent = create_react_agent(self.llm, tools, self.prompt_template)
210
  self.agent_executor = AgentExecutor(agent=self.agent, tools=tools, verbose=True)
211
  except Exception as e:
 
212
  raise AgentInitializationError(f"Failed to initialize agent: {e}")
213
 
214
  async def run(self, input_text: str) -> str:
@@ -216,6 +228,7 @@ class Agent:
216
  result = await self.agent_executor.arun(input_text)
217
  return result
218
  except Exception as e:
 
219
  return f"Error: {str(e)}"
220
 
221
  class CodeFusion:
@@ -236,9 +249,43 @@ class CodeFusion:
236
 
237
  code_fusion = CodeFusion()
238
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
239
  async def chat(message, history):
 
240
  response = await code_fusion.run(message)
241
- return response
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
242
 
243
  async def main():
244
  iface = gr.ChatInterface(
@@ -248,7 +295,8 @@ async def main():
248
  examples=[
249
  "Create a basic Flask app structure",
250
  "Implement a binary search algorithm in Python",
251
- "Design a responsive navbar using HTML and CSS"
 
252
  ],
253
  retry_btn=None,
254
  undo_btn="Delete Previous",
 
8
  import yaml
9
  import os
10
  import json
11
+ import logging
12
+ from functools import lru_cache
13
+ import time
14
+ import pygments
15
+ from pygments.lexers import get_lexer_by_name
16
+ from pygments.formatters import HtmlFormatter
17
+
18
+ # Set up logging
19
+ logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
20
+ logger = logging.getLogger(__name__)
21
 
22
  def load_config():
23
  config_path = os.path.join(os.path.dirname(__file__), "config.yaml")
 
25
  with open(config_path, "r") as config_file:
26
  return yaml.safe_load(config_file)
27
  except FileNotFoundError:
28
+ logger.warning("Config file not found. Using default configuration.")
29
  return {
30
  "model": "mistralai/Mixtral-8x7B-Instruct-v0.1",
31
  "hf_api_token": os.environ.get("HUGGINGFACEHUB_API_TOKEN", "your_default_token_here")
 
40
  name = "CodeGeneration"
41
  description = "Generates code based on a prompt"
42
 
43
+ @lru_cache(maxsize=100)
44
  def _run(self, prompt: str) -> str:
45
+ logger.info(f"Generating code for prompt: {prompt}")
46
  if "Flask app structure" in prompt:
47
  return self.generate_flask_app_structure()
48
  elif "binary search algorithm" in prompt:
 
204
  def __init__(self, name: str, description: str, tools: List[BaseTool]):
205
  self.name = name
206
  self.description = description
 
 
 
 
 
 
 
 
 
 
 
 
207
  try:
208
+ self.llm = HuggingFaceEndpoint(
209
+ repo_id=config["model"],
210
+ task="text-generation",
211
+ model_kwargs={"temperature": 0.7, "max_length": 1024},
212
+ huggingfacehub_api_token=config["hf_api_token"]
213
+ )
214
+
215
+ self.prompt_template = PromptTemplate(
216
+ template="You are {name}, {description}. Respond to the following: {input}",
217
+ input_variables=["name", "description", "input"]
218
+ )
219
+
220
  self.agent = create_react_agent(self.llm, tools, self.prompt_template)
221
  self.agent_executor = AgentExecutor(agent=self.agent, tools=tools, verbose=True)
222
  except Exception as e:
223
+ logger.error(f"Failed to initialize agent: {e}")
224
  raise AgentInitializationError(f"Failed to initialize agent: {e}")
225
 
226
  async def run(self, input_text: str) -> str:
 
228
  result = await self.agent_executor.arun(input_text)
229
  return result
230
  except Exception as e:
231
+ logger.error(f"Error in agent execution: {e}")
232
  return f"Error: {str(e)}"
233
 
234
  class CodeFusion:
 
249
 
250
  code_fusion = CodeFusion()
251
 
252
+ def highlight_code(code: str, language: str) -> str:
253
+ lexer = get_lexer_by_name(language, stripall=True)
254
+ formatter = HtmlFormatter(style="monokai")
255
+ return pygments.highlight(code, lexer, formatter)
256
+
257
+ def save_code_to_file(code: str, filename: str) -> str:
258
+ try:
259
+ with open(filename, 'w') as f:
260
+ f.write(code)
261
+ return f"Code saved to {filename}"
262
+ except Exception as e:
263
+ logger.error(f"Error saving code to file: {e}")
264
+ return f"Error saving code: {str(e)}"
265
+
266
  async def chat(message, history):
267
+ start_time = time.time()
268
  response = await code_fusion.run(message)
269
+ end_time = time.time()
270
+
271
+ # Highlight code in the response
272
+ highlighted_response = response
273
+ for lang in ['python', 'html', 'css', 'javascript']:
274
+ if f"```{lang}" in response:
275
+ code = response.split(f"```{lang}")[1].split("```")[0]
276
+ highlighted_code = highlight_code(code, lang)
277
+ highlighted_response = highlighted_response.replace(f"```{lang}{code}```", highlighted_code)
278
+
279
+ # Save code to file if requested
280
+ if "save code" in message.lower():
281
+ filename = f"generated_code_{int(time.time())}.py"
282
+ save_result = save_code_to_file(response, filename)
283
+ highlighted_response += f"\n\n{save_result}"
284
+
285
+ execution_time = end_time - start_time
286
+ highlighted_response += f"\n\nExecution time: {execution_time:.2f} seconds"
287
+
288
+ return highlighted_response
289
 
290
  async def main():
291
  iface = gr.ChatInterface(
 
295
  examples=[
296
  "Create a basic Flask app structure",
297
  "Implement a binary search algorithm in Python",
298
+ "Design a responsive navbar using HTML and CSS",
299
+ "Generate a simple REST API using Flask and save the code"
300
  ],
301
  retry_btn=None,
302
  undo_btn="Delete Previous",