Create agent.py
Browse files
agent.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from typing import Dict
|
| 3 |
+
from langchain.agents import initialize_agent, AgentType
|
| 4 |
+
from langchain.agents.tools import Tool
|
| 5 |
+
from langchain_community.tools import DuckDuckGoSearchRun
|
| 6 |
+
from langchain.tools import WikipediaQueryRun
|
| 7 |
+
from langchain.utilities import WikipediaAPIWrapper
|
| 8 |
+
from langchain_experimental.tools.python.tool import PythonREPLTool
|
| 9 |
+
from langchain_google_genai import ChatGoogleGenerativeAI
|
| 10 |
+
|
| 11 |
+
class Agent:
|
| 12 |
+
def __init__(self):
|
| 13 |
+
api_key = os.getenv("GEMINI_API_KEY")
|
| 14 |
+
if not api_key:
|
| 15 |
+
raise ValueError("GEMINI_API_KEY not found in environment variables.")
|
| 16 |
+
|
| 17 |
+
llm = ChatGoogleGenerativeAI(
|
| 18 |
+
model="gemini-1.5-pro",
|
| 19 |
+
google_api_key=api_key,
|
| 20 |
+
convert_system_message_to_human=True
|
| 21 |
+
)
|
| 22 |
+
|
| 23 |
+
search = DuckDuckGoSearchRun()
|
| 24 |
+
wiki = WikipediaQueryRun(api_wrapper=WikipediaAPIWrapper())
|
| 25 |
+
python_tool = PythonREPLTool()
|
| 26 |
+
|
| 27 |
+
tools = [
|
| 28 |
+
Tool(
|
| 29 |
+
name="DuckDuckGo Search",
|
| 30 |
+
func=search.run,
|
| 31 |
+
description="Useful for answering factual, current event, or open-domain questions."
|
| 32 |
+
),
|
| 33 |
+
Tool(
|
| 34 |
+
name="Wikipedia",
|
| 35 |
+
func=wiki.run,
|
| 36 |
+
description="Useful for general knowledge and encyclopedic questions."
|
| 37 |
+
),
|
| 38 |
+
Tool(
|
| 39 |
+
name="Calculator",
|
| 40 |
+
func=python_tool.run,
|
| 41 |
+
description="Useful for solving math and logical problems through Python."
|
| 42 |
+
)
|
| 43 |
+
]
|
| 44 |
+
|
| 45 |
+
self.agent = initialize_agent(
|
| 46 |
+
tools=tools,
|
| 47 |
+
llm=llm,
|
| 48 |
+
agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
|
| 49 |
+
verbose=True,
|
| 50 |
+
handle_parsing_errors=True
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
def __call__(self, input_data: Dict) -> str:
|
| 54 |
+
question = input_data.get("question", "")
|
| 55 |
+
if not question:
|
| 56 |
+
return "No question provided."
|
| 57 |
+
try:
|
| 58 |
+
result = self.agent.run(question)
|
| 59 |
+
return result.strip()
|
| 60 |
+
except Exception as e:
|
| 61 |
+
return f"AGENT ERROR: {str(e)}"
|