Spaces:
Runtime error
Runtime error
Update crewai_agent.py
Browse files5 unmodified lines67891011121314153 unmodified lines19202122232425262728293031323334353637383940414243444546474849505152535463 unmodified lines11811912012112212312412512612712812913013113213313414 unmodified lines14915015115215315415514 unmodified lines17017117217317417517617742 unmodified lines22022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525620 unmodified lines2772782792802812822832842852862872882892902912922932942952962972985 unmodified linesload_dotenv()from langchain.agents import AgentType, initialize_agent, Toolfrom langchain.memory import ConversationBufferMemoryfrom langchain_core.messages import BaseMessage, HumanMessage, AIMessagefrom langchain_google_genai import ChatGoogleGenerativeAIfrom langchain_huggingface import ChatHuggingFace, HuggingFaceEndpointfrom langchain_community.tools.tavily_search import TavilySearchResultsfrom langchain_community.document_loaders import WikipediaLoader, ArxivLoaderfrom langchain_core.tools import tool3 unmodified lines# Load environment variablesGOOGLE_API_KEY = os.getenv('GOOGLE_API_KEY')HUGGINGFACE_API_TOKEN = os.getenv('HUGGINGFACE_API_TOKEN')TAVILY_API_KEY = os.getenv('TAVILY_API_KEY')@tooldef calculator_tool(operation: str, a: float, b: float) -> str:"""Perform basic mathematical operations: add, subtract, multiply, divide, modulusArgs:operation: The operation to perform (add, subtract, multiply, divide, modulus)a: First numberb: Second numberReturns:Result of the mathematical operation"""try:if operation == "add":return str(a + b)elif operation == "subtract":return str(a - b)elif operation == "multiply":return str(a * b)elif operation == "divide":if b == 0:return "Error: Cannot divide by zero"return str(a / b)elif operation == "modulus":return str(a % b)else:return "Error: Unsupported operation. Use: add, subtract, multiply, divide, modulus"except Exception as e:return f"Error: {str(e)}"63 unmodified linesclass LangChainAgent:"""Multi-purpose LangChain agent with various capabilities."""def __init__(self, provider: str = "google"):"""Initialize the LangChain agent with specified LLM provider."""self.provider = providerself.llm = self._get_llm(provider)self.tools = self._initialize_tools()self.memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True)self.agent = self._create_agent()def _get_llm(self, provider: str):"""Get the specified LLM."""if provider == "google":if not GOOGLE_API_KEY:raise ValueError("GOOGLE_API_KEY not found in environment variables")return ChatGoogleGenerativeAI(14 unmodified lines),)else:raise ValueError("Invalid provider. Choose 'google' or 'huggingface'.")def _initialize_tools(self) -> List[Tool]:"""Initialize all available tools."""14 unmodified linesmemory=self.memory,verbose=True,handle_parsing_errors=True,max_iterations=3,early_stopping_method="generate")except Exception as e:print(f"Error creating agent: {e}")42 unmodified lines# Create a comprehensive prompt based on the approachif approach == 'calculation':enhanced_question = f"""Solve this mathematical problem step by step:{question}Use the calculator tool if needed for complex calculations. Show your work clearly."""elif approach == 'research':enhanced_question = f"""Research and provide comprehensive information about:{question}Use Wikipedia search and web search tools to gather current and accurate information.Cite your sources and provide detailed explanations."""elif approach == 'academic':enhanced_question = f"""Find academic and scientific information about:{question}Use ArXiv search and other research tools to find relevant academic papers and studies.Provide citations and summarize key findings."""else:enhanced_question = f"""Provide a comprehensive answer to:{question}Use appropriate tools as needed (calculator, search tools) to provide accurate information."""# Use the agent to process the question20 unmodified lines# Test functiondef test_langchain_agent():"""Test the LangChain agent with sample questions."""agent = LangChainAgent(provider="google")test_questions = ["What is 25 * 34?","Who was Albert Einstein?","Search for recent developments in artificial intelligence","What is the theory of relativity?"]for question in test_questions:print(f"\nQuestion: {question}")answer = agent(question)print(f"Answer: {answer}")print("-" * 50)agent.reset_memory() # Reset memory between questions for testingif __name__ == "__main__":test_langchain_agent()5 unmodified lines6789101112131415163 unmodified lines202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777863 unmodified lines14214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417514 unmodified lines19019119219319419519614 unmodified lines21121221321421521621721821942 unmodified lines26226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631720 unmodified lines3383393403413423433443453463473483493503513523533543553563573583593605 unmodified linesload_dotenv()from langchain.agents import AgentType, initialize_agent, Toolfrom langchain.memory import ConversationBufferWindowMemory, ConversationSummaryBufferMemoryfrom langchain_core.messages import BaseMessage, HumanMessage, AIMessagefrom langchain_google_genai import ChatGoogleGenerativeAIfrom langchain_huggingface import ChatHuggingFace, HuggingFaceEndpointfrom langchain_groq import ChatGroqfrom langchain_community.tools.tavily_search import TavilySearchResultsfrom langchain_community.document_loaders import WikipediaLoader, ArxivLoaderfrom langchain_core.tools import tool3 unmodified lines# Load environment variablesGOOGLE_API_KEY = os.getenv('GOOGLE_API_KEY')HUGGINGFACE_API_TOKEN = os.getenv('HUGGINGFACE_API_TOKEN')GROQ_API_KEY = os.getenv('GROQ_API_KEY')TAVILY_API_KEY = os.getenv('TAVILY_API_KEY')@tooldef calculator_tool(expression: str) -> str:"""Perform mathematical calculations and evaluate expressionsArgs:expression: A mathematical expression to evaluate (e.g., "2+2", "25*34", "sqrt(16)", "sin(0.5)")Returns:Result of the mathematical expression"""try:import mathimport re# Clean the expression and make it safeexpression = expression.strip()# Replace common mathematical functionsexpression = expression.replace('sqrt', 'math.sqrt')expression = expression.replace('sin', 'math.sin')expression = expression.replace('cos', 'math.cos')expression = expression.replace('tan', 'math.tan')expression = expression.replace('log', 'math.log')expression = expression.replace('ln', 'math.log')expression = expression.replace('log10', 'math.log10')expression = expression.replace('pi', 'math.pi')expression = expression.replace('e', 'math.e')expression = expression.replace('^', '**') # Python uses ** for powerexpression = expression.replace('pow', '**')# More comprehensive regex for mathematical expressionssafe_pattern = r'^[0-9+\-*/.() mathsqrtsincolgtanpienpow]+$'if re.match(safe_pattern, expression.replace(' ', '')):# Create a safe namespace for evalsafe_dict = {"__builtins__": {},"math": math,"abs": abs,"round": round,"min": min,"max": max}result = eval(expression, safe_dict)return str(result)else:return "Error: Invalid characters in expression. Use only numbers and basic math operations."except ZeroDivisionError:return "Error: Cannot divide by zero"except Exception as e:return f"Error: {str(e)}"63 unmodified linesclass LangChainAgent:"""Multi-purpose LangChain agent with various capabilities."""def __init__(self, provider: str = "groq"):"""Initialize the LangChain agent with specified LLM provider."""self.provider = providerself.llm = self._get_llm(provider)self.tools = self._initialize_tools()# Use ConversationSummaryBufferMemory for better long-term memory managementself.memory = ConversationSummaryBufferMemory(llm=self.llm,memory_key="chat_history",return_messages=True,max_token_limit=2000, # Limit memory to prevent token overflowmoving_summary_buffer="The human and AI are having a conversation about various topics.")self.agent = self._create_agent()def _get_llm(self, provider: str):"""Get the specified LLM."""if provider == "groq":if not GROQ_API_KEY:raise ValueError("GROQ_API_KEY not found in environment variables")return ChatGroq(model="llama-3.3-70b-versatile", # Latest Llama model available on Groqtemperature=0.1,max_tokens=8192, # Increased token limit for better responsesapi_key=GROQ_API_KEY,streaming=False)elif provider == "google":if not GOOGLE_API_KEY:raise ValueError("GOOGLE_API_KEY not found in environment variables")return ChatGoogleGenerativeAI(14 unmodified lines),)else:raise ValueError("Invalid provider. Choose 'groq', 'google' or 'huggingface'.")def _initialize_tools(self) -> List[Tool]:"""Initialize all available tools."""14 unmodified linesmemory=self.memory,verbose=True,handle_parsing_errors=True,max_iterations=4,early_stopping_method="generate",return_intermediate_steps=False)except Exception as e:print(f"Error creating agent: {e}")42 unmodified lines# Create a comprehensive prompt based on the approachif approach == 'calculation':enhanced_question = f"""You are a mathematical assistant. Solve this problem step by step:{question}IMPORTANT: Use the calculator_tool for ALL mathematical calculations, even simple ones.Examples:- For "25 * 34", use: calculator_tool("25 * 34")- For "sqrt(16)", use: calculator_tool("sqrt(16)")- For "2 + 2", use: calculator_tool("2 + 2")Always show your work and use the tools provided."""elif approach == 'research':enhanced_question = f"""You are a research assistant. Provide comprehensive information about:{question}IMPORTANT: Use the appropriate search tools to gather information:- wikipedia_search_tool("your search query") for general knowledge- web_search_tool("your search query") for current information- arxiv_search_tool("your search query") for academic papersAlways cite your sources and provide detailed explanations."""elif approach == 'academic':enhanced_question = f"""You are an academic research assistant. Find scholarly information about:{question}IMPORTANT: Use research tools to find information:- arxiv_search_tool("your search query") for academic papers- wikipedia_search_tool("your search query") for background informationProvide citations and summarize key findings."""else:enhanced_question = f"""You are a helpful assistant. Answer this question comprehensively:{question}IMPORTANT: Use the appropriate tools as needed:- calculator_tool("expression") for mathematical calculations- wikipedia_search_tool("query") for general information- web_search_tool("query") for current information- arxiv_search_tool("query") for academic researchAlways use tools when they can help provide better answers."""# Use the agent to process the question20 unmodified lines# Test functiondef test_langchain_agent():"""Test the LangChain agent with sample questions."""print("Testing LangChain Agent with Groq Llama...")agent = LangChainAgent(provider="groq")test_questions = ["What is 25 * 34 + 100?","Who was Albert Einstein and what were his major contributions?","Search for recent developments in artificial intelligence","What is quantum computing?"]for question in test_questions:print(f"\nQuestion: {question}")print("-" * 50)answer = agent(question)print(f"Answer: {answer}")print("=" * 80)agent.reset_memory() # Reset memory between questions for testingif __name__ == "__main__":test_langchain_agent()
crewai_agent.py+116-54