gemini_agent / app.py
azeemazam's picture
Upload 3 files
75318c0 verified
# app.py
import os
import gradio as gr
from langchain_google_genai import ChatGoogleGenerativeAI
from langchain.agents import tool, initialize_agent, AgentType
# --- 1. SET UP THE LLM ---
# Access the GOOGLE_API_KEY from Hugging Face secrets
llm = ChatGoogleGenerativeAI(
model="gemini-pro",
temperature=0,
google_api_key=os.environ.get("GOOGLE_API_KEY") # Read the key
)
# --- 2. DEFINE THE TOOLS ---
@tool
def get_weather(city: str) -> str:
"""Returns the weather forecast for a given city."""
if "new york" in city.lower():
return "The weather in New York is currently sunny with a high of 75 degrees."
elif "san francisco" in city.lower():
return "The weather in San Francisco is currently foggy with a low of 55 degrees."
else:
return "I don't have the weather for that city, but it's probably nice!"
@tool
def calculator(expression: str) -> str:
"""A simple calculator that evaluates a mathematical expression."""
try:
# Use a safer way to evaluate mathematical expressions if needed
# For this simple case, eval is fine.
return str(eval(expression))
except Exception as e:
return f"Error: {e}"
tools = [get_weather, calculator]
# --- 3. INITIALIZE THE AGENT ---
agent = initialize_agent(
tools,
llm,
agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
verbose=True, # Set to True to see agent's thoughts in the logs
handle_parsing_errors=True # Helps with occasional formatting errors
)
# --- 4. CREATE THE GRADIO INTERFACE ---
def run_agent(user_input: str) -> str:
"""
Runs the agent with the user's input and returns the final answer.
"""
try:
response = agent.run(user_input)
return response
except Exception as e:
return f"An error occurred: {str(e)}"
# Create the user interface
iface = gr.Interface(
fn=run_agent,
inputs=gr.Textbox(lines=2, placeholder="Ask the agent something... e.g., 'What is 15*24?' or 'How is the weather in New York?'"),
outputs="text",
title="🤖 Gemini Reasoning Agent",
description="This is a simple AI agent powered by Gemini Pro and LangChain. It can use tools like a calculator and a weather checker.",
allow_flagging="never"
)
# --- 5. LAUNCH THE APP ---
if __name__ == "__main__":
iface.launch()