import os import math from dotenv import load_dotenv from langchain_groq import ChatGroq from langchain.agents import initialize_agent from langchain.agents import Tool from langchain.agents import AgentType from langchain_community.tools import DuckDuckGoSearchRun # ----------------------------------- # Load environment variables # ----------------------------------- load_dotenv() GROQ_API_KEY = os.getenv("GROQ_API_KEY") if not GROQ_API_KEY: raise ValueError( "Missing GROQ_API_KEY in .env file" ) # ----------------------------------- # LLM # ----------------------------------- llm = ChatGroq( groq_api_key=GROQ_API_KEY, model_name="llama-3.1-8b-instant", temperature=0.3 ) # ----------------------------------- # Simple Calculator Tool # ----------------------------------- def calculator(expression): try: allowed_names = { "sqrt": math.sqrt, "pow": pow, "abs": abs, "round": round } result = eval( expression, {"__builtins__": {}}, allowed_names ) return str(result) except Exception as e: return f"Calculation error: {str(e)}" calculator_tool = Tool( name="Calculator", func=calculator, description=( "Useful for solving math calculations. " "Input should be a valid math expression." ) ) # ----------------------------------- # Web Search Tool # ----------------------------------- search = DuckDuckGoSearchRun() search_tool = Tool( name="Web Search", func=search.run, description=( "Useful for searching current information " "from the internet." ) ) # ----------------------------------- # Agent # ----------------------------------- agent = initialize_agent( tools=[ calculator_tool, search_tool ], llm=llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True, handle_parsing_errors=True ) # ----------------------------------- # Ask Agent # ----------------------------------- def ask_agent(prompt): try: response = agent.run(prompt) return response except Exception as e: return f"❌ Error: {str(e)}"