Spaces:
Sleeping
Sleeping
File size: 2,253 Bytes
56ed1da cee93d0 56ed1da 97f6554 56ed1da 3acbe6f c42f7be 56ed1da cee93d0 56ed1da cee93d0 56ed1da cee93d0 56ed1da cee93d0 56ed1da 97f6554 d00fd71 97f6554 56ed1da 97f6554 56ed1da 97f6554 56ed1da 97f6554 56ed1da 97f6554 56ed1da | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 | 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)}" |