Aditya0619 commited on
Commit
04968b6
·
verified ·
1 Parent(s): 95c1d55

Update crewai_agent.py

Browse files
Files changed (1) hide show
  1. crewai_agent.py +116 -54
crewai_agent.py CHANGED
@@ -6,10 +6,11 @@ from dotenv import load_dotenv
6
  load_dotenv()
7
 
8
  from langchain.agents import AgentType, initialize_agent, Tool
9
- from langchain.memory import ConversationBufferMemory
10
  from langchain_core.messages import BaseMessage, HumanMessage, AIMessage
11
  from langchain_google_genai import ChatGoogleGenerativeAI
12
  from langchain_huggingface import ChatHuggingFace, HuggingFaceEndpoint
 
13
  from langchain_community.tools.tavily_search import TavilySearchResults
14
  from langchain_community.document_loaders import WikipediaLoader, ArxivLoader
15
  from langchain_core.tools import tool
@@ -19,36 +20,59 @@ from langchain.chains import LLMChain
19
  # Load environment variables
20
  GOOGLE_API_KEY = os.getenv('GOOGLE_API_KEY')
21
  HUGGINGFACE_API_TOKEN = os.getenv('HUGGINGFACE_API_TOKEN')
 
22
  TAVILY_API_KEY = os.getenv('TAVILY_API_KEY')
23
 
24
 
25
  @tool
26
- def calculator_tool(operation: str, a: float, b: float) -> str:
27
- """Perform basic mathematical operations: add, subtract, multiply, divide, modulus
28
 
29
  Args:
30
- operation: The operation to perform (add, subtract, multiply, divide, modulus)
31
- a: First number
32
- b: Second number
33
 
34
  Returns:
35
- Result of the mathematical operation
36
  """
37
  try:
38
- if operation == "add":
39
- return str(a + b)
40
- elif operation == "subtract":
41
- return str(a - b)
42
- elif operation == "multiply":
43
- return str(a * b)
44
- elif operation == "divide":
45
- if b == 0:
46
- return "Error: Cannot divide by zero"
47
- return str(a / b)
48
- elif operation == "modulus":
49
- return str(a % b)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50
  else:
51
- return "Error: Unsupported operation. Use: add, subtract, multiply, divide, modulus"
 
 
 
52
  except Exception as e:
53
  return f"Error: {str(e)}"
54
 
@@ -118,17 +142,34 @@ def arxiv_search_tool(query: str) -> str:
118
  class LangChainAgent:
119
  """Multi-purpose LangChain agent with various capabilities."""
120
 
121
- def __init__(self, provider: str = "google"):
122
  """Initialize the LangChain agent with specified LLM provider."""
123
  self.provider = provider
124
  self.llm = self._get_llm(provider)
125
  self.tools = self._initialize_tools()
126
- self.memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True)
 
 
 
 
 
 
 
127
  self.agent = self._create_agent()
128
 
129
  def _get_llm(self, provider: str):
130
  """Get the specified LLM."""
131
- if provider == "google":
 
 
 
 
 
 
 
 
 
 
132
  if not GOOGLE_API_KEY:
133
  raise ValueError("GOOGLE_API_KEY not found in environment variables")
134
  return ChatGoogleGenerativeAI(
@@ -149,7 +190,7 @@ class LangChainAgent:
149
  ),
150
  )
151
  else:
152
- raise ValueError("Invalid provider. Choose 'google' or 'huggingface'.")
153
 
154
  def _initialize_tools(self) -> List[Tool]:
155
  """Initialize all available tools."""
@@ -170,8 +211,9 @@ class LangChainAgent:
170
  memory=self.memory,
171
  verbose=True,
172
  handle_parsing_errors=True,
173
- max_iterations=3,
174
- early_stopping_method="generate"
 
175
  )
176
  except Exception as e:
177
  print(f"Error creating agent: {e}")
@@ -220,37 +262,56 @@ class LangChainAgent:
220
  # Create a comprehensive prompt based on the approach
221
  if approach == 'calculation':
222
  enhanced_question = f"""
223
- Solve this mathematical problem step by step:
224
-
225
- {question}
226
-
227
- Use the calculator tool if needed for complex calculations. Show your work clearly.
 
 
 
 
 
 
228
  """
229
  elif approach == 'research':
230
  enhanced_question = f"""
231
- Research and provide comprehensive information about:
232
-
233
- {question}
234
-
235
- Use Wikipedia search and web search tools to gather current and accurate information.
236
- Cite your sources and provide detailed explanations.
 
 
 
 
237
  """
238
  elif approach == 'academic':
239
  enhanced_question = f"""
240
- Find academic and scientific information about:
241
-
242
- {question}
243
-
244
- Use ArXiv search and other research tools to find relevant academic papers and studies.
245
- Provide citations and summarize key findings.
 
 
 
246
  """
247
  else:
248
  enhanced_question = f"""
249
- Provide a comprehensive answer to:
250
-
251
- {question}
252
-
253
- Use appropriate tools as needed (calculator, search tools) to provide accurate information.
 
 
 
 
 
 
254
  """
255
 
256
  # Use the agent to process the question
@@ -277,22 +338,23 @@ class LangChainAgent:
277
  # Test function
278
  def test_langchain_agent():
279
  """Test the LangChain agent with sample questions."""
280
- agent = LangChainAgent(provider="google")
 
281
 
282
  test_questions = [
283
- "What is 25 * 34?",
284
- "Who was Albert Einstein?",
285
  "Search for recent developments in artificial intelligence",
286
- "What is the theory of relativity?"
287
  ]
288
 
289
  for question in test_questions:
290
  print(f"\nQuestion: {question}")
 
291
  answer = agent(question)
292
  print(f"Answer: {answer}")
293
- print("-" * 50)
294
  agent.reset_memory() # Reset memory between questions for testing
295
 
296
  if __name__ == "__main__":
297
  test_langchain_agent()
298
-
 
6
  load_dotenv()
7
 
8
  from langchain.agents import AgentType, initialize_agent, Tool
9
+ from langchain.memory import ConversationBufferWindowMemory, ConversationSummaryBufferMemory
10
  from langchain_core.messages import BaseMessage, HumanMessage, AIMessage
11
  from langchain_google_genai import ChatGoogleGenerativeAI
12
  from langchain_huggingface import ChatHuggingFace, HuggingFaceEndpoint
13
+ from langchain_groq import ChatGroq
14
  from langchain_community.tools.tavily_search import TavilySearchResults
15
  from langchain_community.document_loaders import WikipediaLoader, ArxivLoader
16
  from langchain_core.tools import tool
 
20
  # Load environment variables
21
  GOOGLE_API_KEY = os.getenv('GOOGLE_API_KEY')
22
  HUGGINGFACE_API_TOKEN = os.getenv('HUGGINGFACE_API_TOKEN')
23
+ GROQ_API_KEY = os.getenv('GROQ_API_KEY')
24
  TAVILY_API_KEY = os.getenv('TAVILY_API_KEY')
25
 
26
 
27
  @tool
28
+ def calculator_tool(expression: str) -> str:
29
+ """Perform mathematical calculations and evaluate expressions
30
 
31
  Args:
32
+ expression: A mathematical expression to evaluate (e.g., "2+2", "25*34", "sqrt(16)", "sin(0.5)")
 
 
33
 
34
  Returns:
35
+ Result of the mathematical expression
36
  """
37
  try:
38
+ import math
39
+ import re
40
+
41
+ # Clean the expression and make it safe
42
+ expression = expression.strip()
43
+
44
+ # Replace common mathematical functions
45
+ expression = expression.replace('sqrt', 'math.sqrt')
46
+ expression = expression.replace('sin', 'math.sin')
47
+ expression = expression.replace('cos', 'math.cos')
48
+ expression = expression.replace('tan', 'math.tan')
49
+ expression = expression.replace('log', 'math.log')
50
+ expression = expression.replace('ln', 'math.log')
51
+ expression = expression.replace('log10', 'math.log10')
52
+ expression = expression.replace('pi', 'math.pi')
53
+ expression = expression.replace('e', 'math.e')
54
+ expression = expression.replace('^', '**') # Python uses ** for power
55
+ expression = expression.replace('pow', '**')
56
+
57
+ # More comprehensive regex for mathematical expressions
58
+ safe_pattern = r'^[0-9+\-*/.() mathsqrtsincolgtanpienpow]+$'
59
+ if re.match(safe_pattern, expression.replace(' ', '')):
60
+ # Create a safe namespace for eval
61
+ safe_dict = {
62
+ "__builtins__": {},
63
+ "math": math,
64
+ "abs": abs,
65
+ "round": round,
66
+ "min": min,
67
+ "max": max
68
+ }
69
+ result = eval(expression, safe_dict)
70
+ return str(result)
71
  else:
72
+ return "Error: Invalid characters in expression. Use only numbers and basic math operations."
73
+
74
+ except ZeroDivisionError:
75
+ return "Error: Cannot divide by zero"
76
  except Exception as e:
77
  return f"Error: {str(e)}"
78
 
 
142
  class LangChainAgent:
143
  """Multi-purpose LangChain agent with various capabilities."""
144
 
145
+ def __init__(self, provider: str = "groq"):
146
  """Initialize the LangChain agent with specified LLM provider."""
147
  self.provider = provider
148
  self.llm = self._get_llm(provider)
149
  self.tools = self._initialize_tools()
150
+ # Use ConversationSummaryBufferMemory for better long-term memory management
151
+ self.memory = ConversationSummaryBufferMemory(
152
+ llm=self.llm,
153
+ memory_key="chat_history",
154
+ return_messages=True,
155
+ max_token_limit=2000, # Limit memory to prevent token overflow
156
+ moving_summary_buffer="The human and AI are having a conversation about various topics."
157
+ )
158
  self.agent = self._create_agent()
159
 
160
  def _get_llm(self, provider: str):
161
  """Get the specified LLM."""
162
+ if provider == "groq":
163
+ if not GROQ_API_KEY:
164
+ raise ValueError("GROQ_API_KEY not found in environment variables")
165
+ return ChatGroq(
166
+ model="llama-3.3-70b-versatile", # Latest Llama model available on Groq
167
+ temperature=0.1,
168
+ max_tokens=8192, # Increased token limit for better responses
169
+ api_key=GROQ_API_KEY,
170
+ streaming=False
171
+ )
172
+ elif provider == "google":
173
  if not GOOGLE_API_KEY:
174
  raise ValueError("GOOGLE_API_KEY not found in environment variables")
175
  return ChatGoogleGenerativeAI(
 
190
  ),
191
  )
192
  else:
193
+ raise ValueError("Invalid provider. Choose 'groq', 'google' or 'huggingface'.")
194
 
195
  def _initialize_tools(self) -> List[Tool]:
196
  """Initialize all available tools."""
 
211
  memory=self.memory,
212
  verbose=True,
213
  handle_parsing_errors=True,
214
+ max_iterations=4,
215
+ early_stopping_method="generate",
216
+ return_intermediate_steps=False
217
  )
218
  except Exception as e:
219
  print(f"Error creating agent: {e}")
 
262
  # Create a comprehensive prompt based on the approach
263
  if approach == 'calculation':
264
  enhanced_question = f"""
265
+ You are a mathematical assistant. Solve this problem step by step:
266
+
267
+ {question}
268
+
269
+ IMPORTANT: Use the calculator_tool for ALL mathematical calculations, even simple ones.
270
+ Examples:
271
+ - For "25 * 34", use: calculator_tool("25 * 34")
272
+ - For "sqrt(16)", use: calculator_tool("sqrt(16)")
273
+ - For "2 + 2", use: calculator_tool("2 + 2")
274
+
275
+ Always show your work and use the tools provided.
276
  """
277
  elif approach == 'research':
278
  enhanced_question = f"""
279
+ You are a research assistant. Provide comprehensive information about:
280
+
281
+ {question}
282
+
283
+ IMPORTANT: Use the appropriate search tools to gather information:
284
+ - wikipedia_search_tool("your search query") for general knowledge
285
+ - web_search_tool("your search query") for current information
286
+ - arxiv_search_tool("your search query") for academic papers
287
+
288
+ Always cite your sources and provide detailed explanations.
289
  """
290
  elif approach == 'academic':
291
  enhanced_question = f"""
292
+ You are an academic research assistant. Find scholarly information about:
293
+
294
+ {question}
295
+
296
+ IMPORTANT: Use research tools to find information:
297
+ - arxiv_search_tool("your search query") for academic papers
298
+ - wikipedia_search_tool("your search query") for background information
299
+
300
+ Provide citations and summarize key findings.
301
  """
302
  else:
303
  enhanced_question = f"""
304
+ You are a helpful assistant. Answer this question comprehensively:
305
+
306
+ {question}
307
+
308
+ IMPORTANT: Use the appropriate tools as needed:
309
+ - calculator_tool("expression") for mathematical calculations
310
+ - wikipedia_search_tool("query") for general information
311
+ - web_search_tool("query") for current information
312
+ - arxiv_search_tool("query") for academic research
313
+
314
+ Always use tools when they can help provide better answers.
315
  """
316
 
317
  # Use the agent to process the question
 
338
  # Test function
339
  def test_langchain_agent():
340
  """Test the LangChain agent with sample questions."""
341
+ print("Testing LangChain Agent with Groq Llama...")
342
+ agent = LangChainAgent(provider="groq")
343
 
344
  test_questions = [
345
+ "What is 25 * 34 + 100?",
346
+ "Who was Albert Einstein and what were his major contributions?",
347
  "Search for recent developments in artificial intelligence",
348
+ "What is quantum computing?"
349
  ]
350
 
351
  for question in test_questions:
352
  print(f"\nQuestion: {question}")
353
+ print("-" * 50)
354
  answer = agent(question)
355
  print(f"Answer: {answer}")
356
+ print("=" * 80)
357
  agent.reset_memory() # Reset memory between questions for testing
358
 
359
  if __name__ == "__main__":
360
  test_langchain_agent()