Update crewai_agent.py
Browse files- 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
|
| 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(
|
| 27 |
-
"""Perform
|
| 28 |
|
| 29 |
Args:
|
| 30 |
-
|
| 31 |
-
a: First number
|
| 32 |
-
b: Second number
|
| 33 |
|
| 34 |
Returns:
|
| 35 |
-
Result of the mathematical
|
| 36 |
"""
|
| 37 |
try:
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 50 |
else:
|
| 51 |
-
return "Error:
|
|
|
|
|
|
|
|
|
|
| 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 = "
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 127 |
self.agent = self._create_agent()
|
| 128 |
|
| 129 |
def _get_llm(self, provider: str):
|
| 130 |
"""Get the specified LLM."""
|
| 131 |
-
if provider == "
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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=
|
| 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 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 228 |
"""
|
| 229 |
elif approach == 'research':
|
| 230 |
enhanced_question = f"""
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 237 |
"""
|
| 238 |
elif approach == 'academic':
|
| 239 |
enhanced_question = f"""
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
|
|
|
|
|
|
|
|
|
| 246 |
"""
|
| 247 |
else:
|
| 248 |
enhanced_question = f"""
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
-
|
|
|
|
| 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
|
| 287 |
]
|
| 288 |
|
| 289 |
for question in test_questions:
|
| 290 |
print(f"\nQuestion: {question}")
|
|
|
|
| 291 |
answer = agent(question)
|
| 292 |
print(f"Answer: {answer}")
|
| 293 |
-
print("
|
| 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()
|
|
|