malimasood47 commited on
Commit
13216cc
·
verified ·
1 Parent(s): 1dc2d3e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +32 -20
app.py CHANGED
@@ -1,10 +1,9 @@
1
  import os
2
  import requests
3
  import gradio as gr
4
- # CRITICAL FIX: The import path for AgentExecutor is unstable.
5
- # For the latest versions (v0.2+), the class is often directly accessible
6
- # under the main 'langchain.agents' module.
7
- from langchain.agents import AgentExecutor # <-- MODIFIED AGAIN for latest structure
8
  from langchain.agents.react.base import create_react_agent
9
  from langchain.tools import Tool
10
  from langchain.prompts import PromptTemplate
@@ -17,31 +16,45 @@ from langchain_google_genai import ChatGoogleGenerativeAI
17
  GEMINI_API_KEY = os.environ.get("GEMINI_API_KEY")
18
 
19
  if not GEMINI_API_KEY:
20
- raise ValueError(
21
- "GEMINI_API_KEY environment variable not set. "
22
- "Please set it as a Space Secret in your Hugging Face Space."
23
- )
24
 
25
  # Initialize Gemini LLM
26
- # The model is initialized globally for faster inference after the first run.
27
- llm = ChatGoogleGenerativeAI(
28
- model="gemini-2.5-flash",
29
- temperature=0.3,
30
- google_api_key=GEMINI_API_KEY
31
- )
 
 
 
 
 
 
32
 
33
  # --- Tool Definition ---
34
 
35
  def get_crypto_price(symbol: str) -> str:
36
  """Fetches the current price of a cryptocurrency symbol."""
37
  try:
38
- url = f"https://api.coingecko.com/api/v3/simple/price?ids={symbol.lower()}&vs_currencies=usd"
 
 
39
  res = requests.get(url).json()
40
- price = res.get(symbol.lower(), {}).get('usd')
 
 
 
41
  if price:
42
  return f"💰 The current price of {symbol.capitalize()} is ${price:,.2f}"
43
  else:
44
- return f"❌ Could not find price for symbol '{symbol}'. Try using the full lowercase name (e.g., 'bitcoin', 'ethereum')."
 
 
 
 
45
  except Exception as e:
46
  return f"⚠️ Error fetching price: {str(e)}"
47
 
@@ -55,10 +68,9 @@ crypto_tool = Tool(
55
  # List of tools
56
  tools = [crypto_tool]
57
 
58
- # --- Agent Initialization (Updated Pattern) ---
59
 
60
  # 1. Define the ReAct Prompt (Standard template for zero-shot-react-description)
61
- # This prompt guides the LLM on how to use the tool and what format to output.
62
  prompt = PromptTemplate.from_template(
63
  """
64
  You are an assistant who can answer questions about cryptocurrency prices.
@@ -85,10 +97,10 @@ prompt = PromptTemplate.from_template(
85
  )
86
 
87
  # 2. Create the Agent
 
88
  agent = create_react_agent(llm, tools, prompt)
89
 
90
  # 3. Create the Agent Executor
91
- # AgentExecutor handles the loop of "Thought -> Action -> Observation -> ..."
92
  agent_executor = AgentExecutor(
93
  agent=agent,
94
  tools=tools,
 
1
  import os
2
  import requests
3
  import gradio as gr
4
+ # CRITICAL FIX: In LangChain v0.2+ (the latest version you are likely running
5
+ # after removing pins), AgentExecutor was moved to the 'langchain_core' package.
6
+ from langchain_core.agents import AgentExecutor # <-- MODIFIED for modern architecture
 
7
  from langchain.agents.react.base import create_react_agent
8
  from langchain.tools import Tool
9
  from langchain.prompts import PromptTemplate
 
16
  GEMINI_API_KEY = os.environ.get("GEMINI_API_KEY")
17
 
18
  if not GEMINI_API_KEY:
19
+ # This message helps the user set up their Hugging Face Space correctly
20
+ print("WARNING: GEMINI_API_KEY environment variable not set. Running without API key.")
21
+ # We will raise a value error later during LLM initialization if it's actually needed.
 
22
 
23
  # Initialize Gemini LLM
24
+ try:
25
+ llm = ChatGoogleGenerativeAI(
26
+ model="gemini-2.5-flash",
27
+ temperature=0.3,
28
+ google_api_key=GEMINI_API_KEY
29
+ )
30
+ except Exception as e:
31
+ # Graceful exit if API key is missing during initialization
32
+ raise RuntimeError(
33
+ "Could not initialize ChatGoogleGenerativeAI. "
34
+ "Ensure GEMINI_API_KEY is set as a Space Secret."
35
+ ) from e
36
 
37
  # --- Tool Definition ---
38
 
39
  def get_crypto_price(symbol: str) -> str:
40
  """Fetches the current price of a cryptocurrency symbol."""
41
  try:
42
+ # Use lowercase symbol for CoinGecko API lookup
43
+ lookup_symbol = symbol.lower()
44
+ url = f"https://api.coingecko.com/api/v3/simple/price?ids={lookup_symbol}&vs_currencies=usd"
45
  res = requests.get(url).json()
46
+
47
+ # Check if the symbol exists in the response
48
+ price = res.get(lookup_symbol, {}).get('usd')
49
+
50
  if price:
51
  return f"💰 The current price of {symbol.capitalize()} is ${price:,.2f}"
52
  else:
53
+ # Check for common partial matches as suggestions
54
+ if not res and len(lookup_symbol) > 3:
55
+ return f"❌ Could not find price for symbol '{symbol}'. Try the full name (e.g., 'bitcoin', 'ethereum')."
56
+ return f"❌ Could not find price for symbol '{symbol}'."
57
+
58
  except Exception as e:
59
  return f"⚠️ Error fetching price: {str(e)}"
60
 
 
68
  # List of tools
69
  tools = [crypto_tool]
70
 
71
+ # --- Agent Initialization ---
72
 
73
  # 1. Define the ReAct Prompt (Standard template for zero-shot-react-description)
 
74
  prompt = PromptTemplate.from_template(
75
  """
76
  You are an assistant who can answer questions about cryptocurrency prices.
 
97
  )
98
 
99
  # 2. Create the Agent
100
+ # Note: create_react_agent is still in langchain.agents.react.base
101
  agent = create_react_agent(llm, tools, prompt)
102
 
103
  # 3. Create the Agent Executor
 
104
  agent_executor = AgentExecutor(
105
  agent=agent,
106
  tools=tools,