ahmadsanafarooq commited on
Commit
38f3b7b
Β·
verified Β·
1 Parent(s): 14376b2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +114 -113
app.py CHANGED
@@ -1,134 +1,135 @@
1
  import streamlit as st
2
  import os
3
  import sys
4
- from crewai import Agent, Task, Crew, Process
 
 
5
  from crewai_tools import SerperDevTool
6
- from crewai.tools import BaseTool
7
- from langchain_openai import ChatOpenAI
8
 
9
- # 1. Page Configuration
10
- st.set_page_config(page_title="Smart Relocation Assistant", page_icon="🏘️")
11
 
12
  st.title("🏘️ Smart Relocation Assistant")
13
  st.markdown("Use AI Agents to find your perfect neighborhood based on budget and lifestyle.")
14
 
15
- # 2. Sidebar for API Keys (Optional but recommended for public spaces)
16
- with st.sidebar:
17
- st.header("API Configuration")
18
- st.info("If running locally, set keys in .env. On Hugging Face, set them in 'Settings' -> 'Secrets'.")
19
-
20
- # Check if keys are already in environment (HF Secrets)
21
- openai_api_key = os.getenv("OPENAI_API_KEY")
22
- serper_api_key = os.getenv("SERPER_API_KEY")
 
 
 
 
 
 
 
23
 
24
- # If not found in env, ask user to input them
25
- if not openai_api_key:
26
- openai_api_key = st.text_input("OpenAI API Key", type="password")
27
- if not serper_api_key:
28
- serper_api_key = st.text_input("Serper API Key", type="password")
29
 
30
- # 3. Define Tools
31
  class CalculatorTool(BaseTool):
32
  name: str = "Budget Calculator"
33
- description: str = "Useful for calculating if a rent price fits within a budget."
34
 
35
  def _run(self, expression: str) -> str:
36
  try:
 
37
  return str(eval(expression))
38
  except:
39
  return "Error in calculation"
40
 
41
- # 4. Main Application Logic
42
- if openai_api_key and serper_api_key:
43
- # Set keys for the libraries
44
- os.environ["OPENAI_API_KEY"] = openai_api_key
45
- os.environ["SERPER_API_KEY"] = serper_api_key
 
 
 
 
 
 
 
 
 
 
 
 
 
46
 
47
- # Initialize Tools
48
- search_tool = SerperDevTool()
49
- calc_tool = CalculatorTool()
50
-
51
- # Inputs
52
- col1, col2 = st.columns(2)
53
- with col1:
54
- city = st.text_input("Target City", "Austin, TX")
55
- budget = st.number_input("Max Monthly Rent ($)", min_value=500, value=2500)
56
- with col2:
57
- work_location = st.text_input("Work Location", "Downtown")
58
-
59
- preferences = st.text_area("Lifestyle Preferences", "Walkable, near coffee shops, safe, good for young professionals")
60
-
61
- if st.button("Start Research"):
62
- with st.spinner('πŸ€– AI Agents are scouting neighborhoods and crunching numbers...'):
63
- try:
64
- # --- AGENT DEFINITIONS ---
65
- city_scout = Agent(
66
- role='City Neighborhood Scout',
67
- goal=f'Identify the top 3 neighborhoods in {city} that match: {preferences}.',
68
- backstory="You are a local expert who knows every corner of the city. You prioritize safety, commute, and lifestyle fit.",
69
- tools=[search_tool],
70
- verbose=True,
71
- allow_delegation=False
72
- )
73
-
74
- budget_analyst = Agent(
75
- role='Relocation Financial Advisor',
76
- goal=f'Assess affordability and ensure rent is within {budget}.',
77
- backstory="You are a pragmatic financial advisor. You find average rent prices and filter out options that exceed the budget.",
78
- tools=[search_tool, calc_tool],
79
- verbose=True,
80
- allow_delegation=False
81
- )
82
-
83
- # --- TASK DEFINITIONS ---
84
- scout_task = Task(
85
- description=f"""
86
- 1. Search for neighborhoods in {city} that are: {preferences}.
87
- 2. Consider commute to {work_location}.
88
- 3. Select top 5 candidates.
89
- """,
90
- expected_output="List of 5 neighborhoods with vibe descriptions.",
91
- agent=city_scout
92
- )
93
-
94
- analysis_task = Task(
95
- description=f"""
96
- 1. For the neighborhoods found, search current average rent for 1-bedroom.
97
- 2. Filter out any where rent > {budget}.
98
- 3. Calculate remaining budget.
99
- """,
100
- expected_output="Filtered list of affordable neighborhoods with costs.",
101
- agent=budget_analyst
102
- )
103
-
104
- report_task = Task(
105
- description="""
106
- Compile a final report. Rank top 3 affordable neighborhoods.
107
- Include: Neighborhood Name, Vibe, Rent Cost, Remaining Budget, and one Local Highlight.
108
- Format as clear Markdown.
109
- """,
110
- expected_output="Markdown formatted relocation guide.",
111
- agent=budget_analyst
112
- )
113
- gpt_4o_mini = ChatOpenAI(model="gpt-4o-mini",temperature=0.7)
114
-
115
- # --- CREW EXECUTION ---
116
- relocation_crew = Crew(agents=[city_scout, budget_analyst],
117
- tasks=[scout_task, analysis_task, report_task],
118
- process=Process.sequential,
119
- # PASS THE LLM HERE
120
- llm=gpt_4o_mini
121
- )
122
-
123
- result = relocation_crew.kickoff()
124
-
125
- # Display Results
126
- st.success("Research Complete!")
127
- st.markdown("### πŸ“‹ Your Relocation Plan")
128
- st.markdown(result)
129
-
130
- except Exception as e:
131
- st.error(f"An error occurred: {e}")
132
-
133
- else:
134
- st.warning("Please provide your API Keys to proceed.")
 
1
  import streamlit as st
2
  import os
3
  import sys
4
+
5
+ # FIX 1: Corrected imports for CrewAI 2.0+
6
+ from crewai import Agent, Task, Crew, Process, BaseTool
7
  from crewai_tools import SerperDevTool
8
+ from langchain_openai import ChatOpenAI
 
9
 
10
+ # --- 1. PAGE CONFIGURATION ---
11
+ st.set_page_config(page_title="Smart Relocation Assistant", page_icon="🏘️", layout="wide")
12
 
13
  st.title("🏘️ Smart Relocation Assistant")
14
  st.markdown("Use AI Agents to find your perfect neighborhood based on budget and lifestyle.")
15
 
16
+ # --- 2. API KEY SETUP ---
17
+ # Fetch keys from environment variables (Hugging Face Secrets)
18
+ openai_api_key = os.getenv("OPENAI_API_KEY")
19
+ serper_api_key = os.getenv("SERPER_API_KEY")
20
+
21
+ if not (openai_api_key and serper_api_key):
22
+ st.error("🚨 API Keys not found!")
23
+ st.warning("Please set OPENAI_API_KEY and SERPER_API_KEY in your Hugging Face Space 'Settings' -> 'Variables and secrets'.")
24
+ st.stop()
25
+
26
+ # Set keys back into environment for the tools/libraries
27
+ os.environ["OPENAI_API_KEY"] = openai_api_key
28
+ os.environ["SERPER_API_KEY"] = serper_api_key
29
+
30
+ # --- 3. TOOL DEFINITIONS ---
31
 
32
+ # The Search Tool is now initialized here
33
+ search_tool = SerperDevTool()
 
 
 
34
 
35
+ # Custom Calculator Tool (inherits from the now-correctly imported BaseTool)
36
  class CalculatorTool(BaseTool):
37
  name: str = "Budget Calculator"
38
+ description: str = "Useful for calculating if a rent price fits within a budget. Input must be a mathematical expression."
39
 
40
  def _run(self, expression: str) -> str:
41
  try:
42
+ # Safe evaluation of simple math
43
  return str(eval(expression))
44
  except:
45
  return "Error in calculation"
46
 
47
+ calc_tool = CalculatorTool()
48
+
49
+ # --- 4. LLM DEFINITION (The "gpt-4o-mini" Fix) ---
50
+ # FIX 2: Explicitly define the gpt-4o-mini model
51
+ gpt_4o_mini = ChatOpenAI(
52
+ model="gpt-4o-mini",
53
+ temperature=0.7
54
+ )
55
+
56
+
57
+ # --- 5. STREAMLIT INPUTS ---
58
+ st.header("1. Enter Your Relocation Details")
59
+ col1, col2 = st.columns(2)
60
+ with col1:
61
+ city = st.text_input("Target City", "Austin, TX")
62
+ budget = st.number_input("Max Monthly Rent ($)", min_value=500, value=2500)
63
+ with col2:
64
+ work_location = st.text_input("Work Location", "Downtown")
65
 
66
+ preferences = st.text_area("Lifestyle Preferences", "Walkable, near coffee shops, safe, good for young professionals")
67
+
68
+ # --- 6. AGENT & TASK DEFINITIONS (Defined in the function for cleaner scope) ---
69
+
70
+ def run_crew_analysis(city, work_location, budget, preferences):
71
+ # FIX 2 (CONT.): Passing the LLM instance to the Agents
72
+ city_scout = Agent(
73
+ role='City Neighborhood Scout',
74
+ goal=f'Identify the top 3 neighborhoods in {city} that match these preferences: {preferences}.',
75
+ backstory="You are a local expert who knows every corner of the city. You prioritize safety, commute, and lifestyle fit.",
76
+ tools=[search_tool],
77
+ llm=gpt_4o_mini, # Explicit LLM setting
78
+ verbose=True,
79
+ allow_delegation=False
80
+ )
81
+
82
+ budget_analyst = Agent(
83
+ role='Relocation Financial Advisor',
84
+ goal=f'Assess the affordability of specific neighborhoods and ensure rent is within {budget}.',
85
+ backstory="You are a pragmatic financial advisor. You strictly filter out any options that exceed the user's budget.",
86
+ tools=[search_tool, calc_tool],
87
+ llm=gpt_4o_mini, # Explicit LLM setting
88
+ verbose=True,
89
+ allow_delegation=False
90
+ )
91
+
92
+ scout_task = Task(
93
+ description=f"Search for neighborhoods in {city} that are: {preferences}. Consider commute to {work_location}. Select top 5 candidates.",
94
+ expected_output="List of 5 neighborhoods with vibe descriptions.",
95
+ agent=city_scout
96
+ )
97
+
98
+ analysis_task = Task(
99
+ description=f"For the 5 neighborhoods found, search current average rent for a 1-bedroom. Filter out any where rent > {budget}. Calculate remaining budget.",
100
+ expected_output="Filtered list of affordable neighborhoods with costs.",
101
+ agent=budget_analyst
102
+ )
103
+
104
+ report_task = Task(
105
+ description="""Compile a final report. Rank top 3 affordable neighborhoods. Include: Neighborhood Name, Vibe, Rent Cost, Remaining Budget, and one Local Highlight. Format as clear Markdown.""",
106
+ expected_output="Markdown formatted relocation guide.",
107
+ agent=budget_analyst
108
+ )
109
+
110
+ # --- CREW EXECUTION ---
111
+ relocation_crew = Crew(
112
+ agents=[city_scout, budget_analyst],
113
+ tasks=[scout_task, analysis_task, report_task],
114
+ process=Process.sequential,
115
+ llm=gpt_4o_mini # Explicit LLM setting
116
+ )
117
+
118
+ return relocation_crew.kickoff()
119
+
120
+ # --- 7. BUTTON TRIGGER ---
121
+ if st.button("Start Research", type="primary"):
122
+ with st.spinner('πŸ€– AI Agents are scouting neighborhoods and crunching numbers...'):
123
+ try:
124
+ result = run_crew_analysis(city, work_location, budget, preferences)
125
+
126
+ # Display Results
127
+ st.success("Research Complete!")
128
+ st.markdown("### πŸ“‹ Your Relocation Plan")
129
+ st.markdown(result)
130
+
131
+ except Exception as e:
132
+ st.error("An error occurred during crew execution. This often means a temporary API issue or a failure to parse a search result.")
133
+ st.exception(e)
134
+ st.markdown("---")
135
+ st.warning("Please wait a few minutes (for rate limit cooldown) and try again, or check your API keys.")