Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,57 +1,124 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
# 1. CORRECTED IMPORT: create_react_agent is now imported directly from langchain.agents
|
| 5 |
-
from langchain.agents import create_react_agent, AgentExecutor
|
| 6 |
-
from langchain_core.prompts import ChatPromptTemplate
|
| 7 |
-
from langchain_core.tools import Tool
|
| 8 |
-
# Note: You would also need to import your LLM, e.g.,
|
| 9 |
-
# from langchain_google_genai import ChatGoogleGenerativeAI
|
| 10 |
-
# from langchain_community.llms import GooglePalm
|
| 11 |
-
|
| 12 |
-
# --- Mock Setup (Replace with your actual agent logic) ---
|
| 13 |
-
# Define a simple mock tool
|
| 14 |
-
def get_current_time(query: str) -> str:
|
| 15 |
-
"""Returns the current time based on the query."""
|
| 16 |
-
return "2025-11-05 16:54:00 (Mocked)"
|
| 17 |
-
|
| 18 |
-
tools = [
|
| 19 |
-
Tool(
|
| 20 |
-
name="time_checker",
|
| 21 |
-
func=get_current_time,
|
| 22 |
-
description="A tool to check the current time for planning and scheduling."
|
| 23 |
-
)
|
| 24 |
-
]
|
| 25 |
-
|
| 26 |
-
# Define the prompt (often the ReAct agent uses a specific template)
|
| 27 |
-
# This is a minimal example; you would use a more robust prompt in production.
|
| 28 |
-
prompt = ChatPromptTemplate.from_messages(
|
| 29 |
-
[
|
| 30 |
-
("system", "You are a helpful assistant. Use the tools provided to answer the user's query."),
|
| 31 |
-
("human", "{input}"),
|
| 32 |
-
("placeholder", "{agent_scratchpad}"),
|
| 33 |
-
]
|
| 34 |
-
)
|
| 35 |
|
| 36 |
-
#
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
|
|
|
|
|
|
|
|
|
| 41 |
|
| 42 |
-
|
| 43 |
|
| 44 |
-
#
|
| 45 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 46 |
try:
|
| 47 |
-
|
| 48 |
-
|
|
|
|
|
|
|
|
|
|
| 49 |
except Exception as e:
|
| 50 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
|
| 52 |
-
#
|
| 53 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 54 |
|
| 55 |
-
# Example usage (uncomment and replace PlaceholderLLM with a real LLM for execution)
|
| 56 |
-
# response = agent_executor.invoke({"input": "What time is it right now?"})
|
| 57 |
-
# print(f"\nFinal Response: {response['output']}")
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import requests
|
| 3 |
+
import gradio as gr
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
|
| 5 |
+
# --- CORRECTED LANGCHAIN IMPORTS ---
|
| 6 |
+
# create_react_agent and AgentExecutor are now imported directly from langchain.agents
|
| 7 |
+
from langchain.agents import AgentExecutor, create_react_agent
|
| 8 |
+
from langchain.tools import Tool
|
| 9 |
+
# We need to import the specific ReAct prompt template from the hub
|
| 10 |
+
from langchain import hub
|
| 11 |
+
from langchain_google_genai import ChatGoogleGenerativeAI
|
| 12 |
+
from typing import List, Dict # Added for Gradio ChatInterface typing
|
| 13 |
|
| 14 |
+
# --- Configuration and Environment Setup ---
|
| 15 |
|
| 16 |
+
# IMPORTANT: Do NOT hardcode your API key.
|
| 17 |
+
# Define GEMINI_API_KEY as a Space Secret in your Hugging Face Space Settings.
|
| 18 |
+
GEMINI_API_KEY = os.environ.get("GEMINI_API_KEY")
|
| 19 |
+
|
| 20 |
+
if not GEMINI_API_KEY:
|
| 21 |
+
# This message helps the user set up their Hugging Face Space correctly
|
| 22 |
+
print("WARNING: GEMINI_API_KEY environment variable not set. Running without API key.")
|
| 23 |
+
# We will raise a value error later during LLM initialization if it's actually needed.
|
| 24 |
+
|
| 25 |
+
# Initialize Gemini LLM
|
| 26 |
try:
|
| 27 |
+
llm = ChatGoogleGenerativeAI(
|
| 28 |
+
model="gemini-2.5-flash",
|
| 29 |
+
temperature=0.3,
|
| 30 |
+
google_api_key=GEMINI_API_KEY
|
| 31 |
+
)
|
| 32 |
except Exception as e:
|
| 33 |
+
# Graceful exit if API key is missing during initialization
|
| 34 |
+
raise RuntimeError(
|
| 35 |
+
"Could not initialize ChatGoogleGenerativeAI. "
|
| 36 |
+
"Ensure GEMINI_API_KEY is set as a Space Secret."
|
| 37 |
+
) from e
|
| 38 |
+
|
| 39 |
+
# --- Tool Definition ---
|
| 40 |
+
|
| 41 |
+
def get_crypto_price(symbol: str) -> str:
|
| 42 |
+
"""Fetches the current price of a cryptocurrency symbol."""
|
| 43 |
+
try:
|
| 44 |
+
# Use lowercase symbol for CoinGecko API lookup
|
| 45 |
+
lookup_symbol = symbol.lower()
|
| 46 |
+
url = f"https://api.coingecko.com/api/v3/simple/price?ids={lookup_symbol}&vs_currencies=usd"
|
| 47 |
+
res = requests.get(url).json()
|
| 48 |
+
|
| 49 |
+
# Check if the symbol exists in the response
|
| 50 |
+
price = res.get(lookup_symbol, {}).get('usd')
|
| 51 |
+
|
| 52 |
+
if price:
|
| 53 |
+
return f"💰 The current price of {symbol.capitalize()} is ${price:,.2f}"
|
| 54 |
+
else:
|
| 55 |
+
# Check for common partial matches as suggestions
|
| 56 |
+
if not res and len(lookup_symbol) > 3:
|
| 57 |
+
return f"❌ Could not find price for symbol '{symbol}'. Try the full name (e.g., 'bitcoin', 'ethereum')."
|
| 58 |
+
return f"❌ Could not find price for symbol '{symbol}'."
|
| 59 |
+
|
| 60 |
+
except Exception as e:
|
| 61 |
+
return f"⚠️ Error fetching price: {str(e)}"
|
| 62 |
+
|
| 63 |
+
# Create a Tool for the Agent
|
| 64 |
+
crypto_tool = Tool(
|
| 65 |
+
name="Crypto Price Checker",
|
| 66 |
+
func=get_crypto_price,
|
| 67 |
+
description="Fetches the current cryptocurrency price using CoinGecko. Use this tool ONLY when the user asks for a specific crypto price (e.g., 'bitcoin', 'ethereum')."
|
| 68 |
+
)
|
| 69 |
+
|
| 70 |
+
# List of tools
|
| 71 |
+
tools = [crypto_tool]
|
| 72 |
|
| 73 |
+
# --- Agent Initialization (CORRECTED) ---
|
| 74 |
+
|
| 75 |
+
# 1. CORRECTED PROMPT: Pull the standard ReAct prompt from LangChain Hub.
|
| 76 |
+
# This prompt is guaranteed to have the required '{tools}' and '{tool_names}' variables.
|
| 77 |
+
prompt = hub.pull("hwchase17/react")
|
| 78 |
+
|
| 79 |
+
# 2. Create the Agent
|
| 80 |
+
# This uses the corrected 'create_react_agent' import
|
| 81 |
+
agent = create_react_agent(llm, tools, prompt)
|
| 82 |
+
|
| 83 |
+
# 3. Create the Agent Executor
|
| 84 |
+
# This uses the corrected 'AgentExecutor' import
|
| 85 |
+
agent_executor = AgentExecutor(
|
| 86 |
+
agent=agent,
|
| 87 |
+
tools=tools,
|
| 88 |
+
verbose=True,
|
| 89 |
+
handle_parsing_errors=True # Good practice for ReAct agents
|
| 90 |
+
)
|
| 91 |
+
|
| 92 |
+
# --- Gradio Interface Function ---
|
| 93 |
+
|
| 94 |
+
# Added 'history' for ChatInterface compatibility
|
| 95 |
+
def run_agent(user_query: str, history: List[List[str]]) -> str:
|
| 96 |
+
"""The main function called by Gradio to run the agent."""
|
| 97 |
+
if not user_query:
|
| 98 |
+
return "Please enter a question for the agent."
|
| 99 |
+
|
| 100 |
+
try:
|
| 101 |
+
# Use the AgentExecutor's invoke method
|
| 102 |
+
# The input must be a dictionary
|
| 103 |
+
response: Dict = agent_executor.invoke({"input": user_query})
|
| 104 |
+
|
| 105 |
+
# Extract the final answer text
|
| 106 |
+
return response.get("output", "Agent could not find a clear answer.")
|
| 107 |
+
|
| 108 |
+
except Exception as e:
|
| 109 |
+
# Catch and report any runtime errors gracefully
|
| 110 |
+
return f"An error occurred while running the agent: {str(e)}"
|
| 111 |
+
|
| 112 |
+
# --- Gradio App Setup (Using ChatInterface for better UX) ---
|
| 113 |
+
|
| 114 |
+
gr.ChatInterface(
|
| 115 |
+
fn=run_agent,
|
| 116 |
+
title="💰 Gemini Crypto Price Agent (ReAct Pattern)",
|
| 117 |
+
description="Ask the agent to check the current price of cryptocurrencies (e.g., bitcoin, ethereum). This agent uses the modern LangChain ReAct pattern (v0.1.0+).",
|
| 118 |
+
examples=[
|
| 119 |
+
["What is the current price of Bitcoin?"],
|
| 120 |
+
["How much is Ethereum?"],
|
| 121 |
+
["What about solana?"]
|
| 122 |
+
]
|
| 123 |
+
).launch()
|
| 124 |
|
|
|
|
|
|
|
|
|