krrishkh12 commited on
Commit
e1ee9d9
·
verified ·
1 Parent(s): b5ef678

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +192 -0
app.py CHANGED
@@ -0,0 +1,192 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # app.py
2
+
3
+ import os
4
+ import gradio as gr
5
+ from dotenv import load_dotenv
6
+
7
+ # === All Imports ===
8
+ import datetime
9
+ import json
10
+ import requests
11
+ import pytz
12
+ from dateutil import parser
13
+ from typing import Optional, List, Dict
14
+
15
+ # === LangChain / LangGraph Imports ===
16
+ from langchain_core.messages import AIMessage
17
+ from langchain.tools import tool
18
+ from langchain_openai import ChatOpenAI
19
+ from langgraph.prebuilt import create_react_agent
20
+
21
+ # ==============================================================================
22
+ # PART 1: TOOL DEFINITIONS (from tools.py)
23
+ # ==============================================================================
24
+ @tool
25
+ def get_horoscope(sign: str, date: str = None, language: str = "EN") -> str:
26
+ """Fetches the horoscope for a given zodiac sign and date."""
27
+ # ... (Your full get_horoscope function code)
28
+ try:
29
+ if date: date_obj = parser.parse(date)
30
+ else: date_obj = datetime.datetime.now()
31
+ formatted_date = date_obj.strftime("%d-%m-%Y")
32
+ params = {"rashi": sign.upper(), "language": language, "day": formatted_date}
33
+ url = "https://api.exaweb.in:3004/api/rashi"
34
+ response = requests.get(url, params=params)
35
+ response.raise_for_status()
36
+ return json.dumps(response.json())
37
+ except Exception as e: return f"Error in get_horoscope: {e}"
38
+
39
+ @tool
40
+ def get_date_panchang(date: str = None, data_language: str = "EN") -> str:
41
+ """Fetches the Panchang data for a given date."""
42
+ # ... (Your full get_date_panchang function code)
43
+ try:
44
+ if not date: now = datetime.datetime.now()
45
+ else: now = parser.parse(date)
46
+ api_date = now.strftime("%d/%m/%y")
47
+ url = f"https://api.exaweb.in:3004/api/panchang/daily?date={api_date}&app_language=EN&data_language={data_language}"
48
+ headers = {"api_key": "anvl_bharat_cal123"}
49
+ response = requests.get(url, headers=headers)
50
+ response.raise_for_status()
51
+ return json.dumps(response.json())
52
+ except Exception as e: return f"Error in get_date_panchang: {e}"
53
+
54
+ @tool
55
+ def get_holidays(year: int = None, data_language: str = "EN") -> str:
56
+ """Fetches holidays for a given year."""
57
+ # ... (Your full get_holidays function code)
58
+ try:
59
+ if not year: year = datetime.datetime.now().year
60
+ params = {"data_language": data_language, "year": year}
61
+ headers = {"api_key": "anvl_bharat_cal123"}
62
+ response = requests.get("https://api.exaweb.in:3004/api/panchang/holiday", params=params, headers=headers)
63
+ response.raise_for_status()
64
+ return json.dumps(response.json())
65
+ except Exception as e: return f"Error in get_holidays: {e}"
66
+
67
+ @tool
68
+ def get_monthly_festivals(year: Optional[int] = None, month: Optional[str] = None, data_language: str = "EN") -> str:
69
+ """Fetches festival data for a specific month and year."""
70
+ # ... (Your full get_monthly_festivals function code)
71
+ try:
72
+ if not year: year = datetime.datetime.now().year
73
+ if not month: month = datetime.datetime.now().strftime("%B").lower()
74
+ else: month = month.lower()
75
+ api_url = "https://api.exaweb.in:3004/api/panchang/festival"
76
+ params = {"year": year, "month": month, "data_language": data_language}
77
+ headers = {"api_key": "anvl_bharat_cal123"}
78
+ response = requests.get(api_url, params=params, headers=headers)
79
+ response.raise_for_status()
80
+ return json.dumps(response.json())
81
+ except Exception as e: return f"Error in get_monthly_festivals: {e}"
82
+
83
+ all_tools = [get_horoscope, get_date_panchang, get_holidays, get_monthly_festivals]
84
+
85
+ # ==============================================================================
86
+ # PART 2: SYSTEM PROMPT (from prompt.py)
87
+ # ==============================================================================
88
+ SYSTEM_PROMPT = """ Your primary function is to use the provided tools to answer user queries accurately.
89
+ **Core Directives:**
90
+ 1. **Tool First:** You MUST use the provided tools to find information. Never answer from your own general knowledge. If the tools do not provide an answer, state that the information could not be found.
91
+ 2. **Language Match:** You MUST respond in the exact language of the user's query. You are proficient in English (EN), Hindi (HI), Bengali (BN), Gujarati (GU), Tamil (TA), Telugu (TE), Kannada (KN), Malayalam (ML), Marathi (MR), Oriya (OR), and Panjabi (PA).
92
+ 3. **Interpret, Don't Dump:** Your job is to interpret the JSON data returned by the tools and present it to the user in a clear, well-formatted, and human-readable way. Do not just output the raw JSON.
93
+
94
+ ---
95
+
96
+ **Tool Usage and Data Interpretation Guide:**
97
+
98
+ **1. `get_horoscope`**
99
+ - **When to Use:** Use this tool when a user asks for a horoscope for any zodiac sign (e.g., Aries, Leo, Gemini).
100
+ - **Data Interpretation:** The tool returns a JSON object with keys like `prediction`, `monetary_gains`, `love_life`, `health`, `lucky_number`, and `lucky_color`. Format your response using clear headings for each of these categories. For example:
101
+ "Here is the horoscope for [Sign]:
102
+ **Prediction:** [prediction text]
103
+ **Love Life:** [love life text]
104
+ **Lucky Number:** [number]"
105
+
106
+ **2. `get_date_panchang`**
107
+ - **When to Use:** Use this tool when a user asks for the "Panchang," "Panchangam," or detailed daily astrological details for a specific date.
108
+ - **Data Interpretation:** This tool returns a very large JSON object. **Do not dump the entire object.**
109
+ - If the user asks for the general Panchang, summarize the most important elements: **Sunrise, Sunset, Tithi, Nakshatra, Yoga, and Karana**.
110
+ - If the user asks for a specific detail (e.g., "What is Rahu Kalam today?"), find that specific key in the JSON (`Rahu Kalam`) and provide only that information.
111
+
112
+ **3. `get_holidays`**
113
+ - **When to Use:** Use this tool for general queries about holidays within a specific **year**. This tool provides a list of Hindu, Islamic, Christian, and Government holidays.
114
+ - **Data Interpretation:** Present the holidays in a clean list format. You can group them by month if the list is long.
115
+
116
+ **4. `get_monthly_festivals`**
117
+ - **When to Use:** Prefer this tool when a user asks for festivals in a specific **month**. It provides more detail than `get_holidays`.
118
+ - **Data Interpretation:** Format the response as a list of festivals for that month, including the date for each.
119
+
120
+ ---
121
+
122
+ **Final Response Style:**
123
+ Your final answer to the user should always be friendly, well-formatted, and directly address their question using only the data you retrieved from the tools.
124
+ """
125
+
126
+ # ==============================================================================
127
+ # PART 3: MODEL INITIALIZATION (from llm.py)
128
+ # ==============================================================================
129
+ load_dotenv()
130
+ SARVAM_API_KEY = os.getenv("SARVAM_API_KEY")
131
+
132
+ if not SARVAM_API_KEY:
133
+ print("Warning: SARVAM_API_KEY secret not found.")
134
+ # In a deployed space, we can't raise an error, so we'll let it fail later
135
+ # raise ValueError("SARVAM_API_KEY not found. Please set it in the Space secrets.")
136
+
137
+ model = ChatOpenAI(
138
+ model="sarvam-m",
139
+ api_key=SARVAM_API_KEY,
140
+ base_url="https://api.sarvam.ai/v1",
141
+ temperature=0.2,
142
+ )
143
+ print("Sarvam AI model initialized successfully.")
144
+
145
+ # ==============================================================================
146
+ # PART 4: AGENT CREATION (from agent.py)
147
+ # ==============================================================================
148
+ agent_app = create_react_agent(model=model, tools=all_tools, system_message=SYSTEM_PROMPT)
149
+ print("Pre-built ReAct agent created successfully.")
150
+
151
+ # ==============================================================================
152
+ # PART 5: GRADIO UI
153
+ # ==============================================================================
154
+ def get_agent_response(messages: list):
155
+ """This function is called by the Gradio UI."""
156
+ # Inject date context on the first turn
157
+ if len(messages) == 1:
158
+ now = datetime.datetime.now(pytz.timezone("Asia/Kolkata"))
159
+ date_context = f"For context, today's date is {now.strftime('%A, %B %d, %Y')}."
160
+ messages[0]['content'] = f"{messages[0]['content']} ({date_context})"
161
+
162
+ inputs = {"messages": messages}
163
+ final_response_content = ""
164
+
165
+ try:
166
+ for event in agent_app.stream(inputs, stream_mode="values"):
167
+ response_messages = event.get('messages', [])
168
+ if response_messages:
169
+ final_message = response_messages[-1]
170
+ if isinstance(final_message, AIMessage) and not final_message.tool_calls:
171
+ final_response_content = final_message.content
172
+ return final_response_content
173
+ except Exception as e:
174
+ print(f"Error during agent execution: {e}")
175
+ return "Sorry, an error occurred while processing your request."
176
+
177
+ # Create the Gradio Chat Interface with the fix
178
+ chatbot_ui = gr.ChatInterface(
179
+ fn=get_agent_response,
180
+ title="Jyotish AI Assistant",
181
+ description="Ask about horoscopes, panchang, holidays, and festivals.",
182
+ type="messages",
183
+ examples=[
184
+ "What is the horoscope for Leo today?",
185
+ "Tell me the panchang for today",
186
+ "What are the Indian holidays in 2025?"
187
+ ]
188
+ )
189
+
190
+ # Launch the Gradio app
191
+ chatbot_ui.launch()
192
+ print("Gradio UI is running.")