File size: 2,401 Bytes
75318c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# 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()