acecalisto3 commited on
Commit
60045aa
·
verified ·
1 Parent(s): 03bd4ac

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +11 -54
app.py CHANGED
@@ -7,7 +7,6 @@ from abc import ABC, abstractmethod
7
  import gradio as gr
8
  from langchain_community.llms import HuggingFaceHub
9
  from dotenv import load_dotenv
10
- from langchain.llms import HuggingFaceHub
11
  from langchain.agents import initialize_agent, AgentType
12
  from langchain.chains import LLMChain
13
  from langchain.prompts import PromptTemplate
@@ -50,21 +49,6 @@ def load_config() -> Dict:
50
  config['api_key'] = os.getenv('HUGGINGFACE_API_KEY', config['api_key'])
51
  return config
52
 
53
- @spaces.GPU()
54
- def stream_chat(
55
- message: str,
56
- history: list,
57
- tools: str,
58
- temperature: float = 0.3,
59
- max_tokens: int = 1024,
60
- ):
61
- # Define persona attributes
62
- persona_greeting = "Hello! I'm your friendly assistant. How can I help you today?"
63
-
64
- # Start conversation with persona greeting
65
- if not history:
66
- history.append(("AI", persona_greeting)) # Assuming history is a list of tuples
67
-
68
  def setup_logging() -> logging.Logger:
69
  """Set up logging configuration."""
70
  logging.basicConfig(
@@ -184,11 +168,16 @@ class Agent:
184
  logger.error(f"Error initializing agent: {e}")
185
  raise AgentInitializationError(f"Failed to initialize agent: {e}")
186
 
187
- async def act(self, prompt: str, context: str) -> str:
188
  """Perform an action based on the given prompt and context."""
189
  self.memory.append((prompt, context))
190
  try:
191
- action = await self.agent.arun(prompt, context)
 
 
 
 
 
192
  return action
193
  except Exception as e:
194
  logger.error(f"Error during agent action: {e}")
@@ -198,7 +187,7 @@ class Agent:
198
  return f"Agent: {self.name} (Role: {self.role})"
199
 
200
  # Main application functions
201
- async def run(message: str, history: List[Tuple[str, str]]) -> str:
202
  """Process user input and generate a response using the agent system."""
203
  agent = Agent(
204
  name="CodeFusion",
@@ -207,7 +196,7 @@ async def run(message: str, history: List[Tuple[str, str]]) -> str:
207
  )
208
  context = "\n".join([f"Human: {h[0]}\nAI: {h[1]}" for h in history])
209
  try:
210
- response = await agent.act(message, context)
211
  return response
212
  except Exception as e:
213
  logger.error(f"Error processing request: {e}")
@@ -224,46 +213,14 @@ async def main():
224
  gr.ChatInterface(
225
  fn=run,
226
  title="CodeFusion: Your AI Coding Assistant",
227
- description="Ask me about code generation, explanation, debugging, or any other coding task!",
228
  examples=examples,
229
  theme="default"
230
  ).launch()
231
 
232
- async def test_code_generation():
233
- tool = CodeGenerationTool()
234
- result = await tool.run({"language": "python", "code_description": "function to add two numbers"})
235
- assert "def" in result["output"], "Code generation failed to produce a function"
236
- print("Code Generation Test: Passed")
237
-
238
- async def test_code_explanation():
239
- tool = CodeExplanationTool()
240
- result = await tool.run({"code": "def factorial(n):\n return 1 if n == 0 else n * factorial(n-1)"})
241
- assert "recursive" in result["output"].lower(), "Code explanation failed to mention recursion"
242
- print("Code Explanation Test: Passed")
243
-
244
- async def test_debugging():
245
- tool = DebuggingTool()
246
- result = await tool.run({"code": "def divide(a, b):\n return a / b", "error_message": "ZeroDivisionError"})
247
- assert "zero" in result["output"].lower(), "Debugging failed to address division by zero"
248
- print("Debugging Test: Passed")
249
-
250
- async def test_agent():
251
- agent = Agent("TestAgent", "Tester", [CodeGenerationTool(), CodeExplanationTool(), DebuggingTool()])
252
- result = await agent.act("Generate a Python function to calculate the square of a number", "")
253
- assert "def" in result and "return" in result, "Agent failed to generate a proper function"
254
- print("Agent Test: Passed")
255
-
256
- async def run_all_tests():
257
- await test_code_generation()
258
- await test_code_explanation()
259
- await test_debugging()
260
- await test_agent()
261
-
262
- asyncio.run(run_all_tests())
263
-
264
  if __name__ == "__main__":
265
  import sys
266
  if len(sys.argv) > 1 and sys.argv[1] == "--test":
267
  run_tests()
268
  else:
269
- asyncio.run(main())
 
7
  import gradio as gr
8
  from langchain_community.llms import HuggingFaceHub
9
  from dotenv import load_dotenv
 
10
  from langchain.agents import initialize_agent, AgentType
11
  from langchain.chains import LLMChain
12
  from langchain.prompts import PromptTemplate
 
49
  config['api_key'] = os.getenv('HUGGINGFACE_API_KEY', config['api_key'])
50
  return config
51
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52
  def setup_logging() -> logging.Logger:
53
  """Set up logging configuration."""
54
  logging.basicConfig(
 
168
  logger.error(f"Error initializing agent: {e}")
169
  raise AgentInitializationError(f"Failed to initialize agent: {e}")
170
 
171
+ async def act(self, prompt: str, context: str, mode: str) -> str:
172
  """Perform an action based on the given prompt and context."""
173
  self.memory.append((prompt, context))
174
  try:
175
+ if mode == "full":
176
+ action = await self.agent.arun(prompt, context)
177
+ elif mode == "half":
178
+ action = f"Please follow these instructions: {prompt}. Then, let me know what you did."
179
+ else: # mode == "none"
180
+ action = "I'm here if you need assistance. Just ask!"
181
  return action
182
  except Exception as e:
183
  logger.error(f"Error during agent action: {e}")
 
187
  return f"Agent: {self.name} (Role: {self.role})"
188
 
189
  # Main application functions
190
+ async def run(message: str, history: List[Tuple[str, str]], mode: str) -> str:
191
  """Process user input and generate a response using the agent system."""
192
  agent = Agent(
193
  name="CodeFusion",
 
196
  )
197
  context = "\n".join([f"Human: {h[0]}\nAI: {h[1]}" for h in history])
198
  try:
199
+ response = await agent.act(message, context, mode)
200
  return response
201
  except Exception as e:
202
  logger.error(f"Error processing request: {e}")
 
213
  gr.ChatInterface(
214
  fn=run,
215
  title="CodeFusion: Your AI Coding Assistant",
216
+ description="Ask me about code generation, explanation, debugging, or any other coding task! Choose a mode: full autonomy, 50% engagement, or user-referred assistance.",
217
  examples=examples,
218
  theme="default"
219
  ).launch()
220
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
221
  if __name__ == "__main__":
222
  import sys
223
  if len(sys.argv) > 1 and sys.argv[1] == "--test":
224
  run_tests()
225
  else:
226
+ asyncio.run(main())