Manojkumarpandi commited on
Commit
1ccd1be
·
verified ·
1 Parent(s): d905289

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +77 -23
app.py CHANGED
@@ -2,21 +2,25 @@ import streamlit as st
2
  import os
3
  import json
4
  import requests
5
- import google.generativeai as genai
 
 
6
 
7
- # Load environment variables
8
- api_key = os.getenv("GOOGLE_API_KEY")
9
- finance_key = os.getenv("FINANCE_KEY")
10
 
11
- if not api_key or not finance_key:
12
- st.error("API keys not found. Please check your configuration.")
13
- st.stop()
 
 
 
14
 
15
  # Initialize Gemini client
16
- genai.configure(api_key=api_key)
 
17
 
18
  # Indian Stock Market API base configuration
19
- INDIAN_API_KEY = finance_key
20
  INDIAN_API_BASE_URL = "https://stock.indianapi.in"
21
 
22
  # Define API endpoints and their parameters
@@ -27,7 +31,50 @@ API_ENDPOINTS = {
27
  "param_mapping": {"stock_name": "name"},
28
  "description": "Get details for a specific stock"
29
  },
30
- # ... (rest of your code)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31
  }
32
 
33
  # Unified API call function
@@ -86,6 +133,7 @@ def call_api_by_name(api_name, **kwargs):
86
  mapped_params[param] = value
87
 
88
  return call_indian_api(endpoint, mapped_params)
 
89
  # Improved orchestrator function
90
  def orchestrator(query):
91
  """
@@ -95,21 +143,17 @@ def orchestrator(query):
95
  # Create a more precise prompt for the orchestrator
96
  orchestrator_prompt = """
97
  You are an orchestrator for a financial assistant specialized in Indian markets. Your job is to analyze user queries and determine if they need real-time market data.
98
-
99
  IMPORTANT: Be very precise in your analysis. Only return TRUE for "needs_api" when the query EXPLICITLY asks for current market data, stock prices, or listings.
100
-
101
  Examples where needs_api should be TRUE:
102
  - "Show me the most active stocks on NSE today" → get_nse_most_active
103
  - "What is the current price of Reliance?" → get_stock_details with stock_name="Reliance"
104
  - "Tell me about trending stocks" → get_trending_stocks
105
  - "What are the latest IPOs?" → get_ipo_data
106
-
107
  Examples where needs_api should be FALSE:
108
  - "What is compound interest?"
109
  - "How should I start investing?"
110
  - "What are the tax benefits of PPF?"
111
  - "Explain mutual funds to me"
112
-
113
  Available API functions:
114
  - get_stock_details(stock_name): Get details for a specific stock
115
  - get_trending_stocks(): Get trending stocks in the market
@@ -119,9 +163,7 @@ def orchestrator(query):
119
  - get_bse_most_active(): Get BSE most active stocks
120
  - get_nse_most_active(): Get NSE most active stocks
121
  - get_historical_data(stock_name, period="1m"): Get historical data for a stock
122
-
123
  User query: """ + query + """
124
-
125
  Respond in JSON format with the following structure:
126
  {
127
  "needs_api": true/false,
@@ -135,16 +177,28 @@ def orchestrator(query):
135
 
136
  # Create content for the orchestrator
137
  contents = [
138
- {
139
- "role": "user",
140
- "parts": [orchestrator_prompt]
141
- }
 
 
142
  ]
143
 
 
 
 
 
 
 
 
 
 
144
  # Generate content
145
- response = genai.generate_content(
146
  model="gemini-1.5-flash",
147
  contents=contents,
 
148
  )
149
 
150
  # Parse the response
@@ -163,11 +217,11 @@ def orchestrator(query):
163
  except Exception as e:
164
  print(f"Error parsing orchestrator response: {e}")
165
  return {"needs_api": False}
 
166
  # Language setting
167
 
168
  # Financial assistant system prompt
169
  SYSTEM_PROMPT = f"""You are Flaix, a helpful and knowledgeable financial assistant designed specifically for Indian users. Your purpose is to improve financial literacy and provide guidance on investments in the Indian market.
170
-
171
  Key responsibilities:
172
  1. Explain financial concepts in simple, easy-to-understand language
173
  2. Provide information about different investment options available in India (stocks, mutual funds, bonds, PPF, FDs, etc.)
@@ -299,4 +353,4 @@ if prompt := st.chat_input("Ask me anything about finance or investing..."):
299
  message_placeholder.write(full_response)
300
 
301
  # Add assistant response to chat history
302
- st.session_state.messages.append({"role": "model", "content": full_response})
 
2
  import os
3
  import json
4
  import requests
5
+ from google import genai
6
+ from google.genai import types
7
+ from dotenv import load_dotenv
8
 
9
+ load_dotenv()
 
 
10
 
11
+ # Set page configuration
12
+ st.set_page_config(
13
+ page_title="Flaix - Financial Assistant",
14
+ page_icon="💰",
15
+ layout="centered"
16
+ )
17
 
18
  # Initialize Gemini client
19
+ api_key = st.secrets["GOOGLE_API_KEY"]
20
+ client = genai.Client(api_key=api_key)
21
 
22
  # Indian Stock Market API base configuration
23
+ INDIAN_API_KEY = st.secrets["FINANCE_KEY"]
24
  INDIAN_API_BASE_URL = "https://stock.indianapi.in"
25
 
26
  # Define API endpoints and their parameters
 
31
  "param_mapping": {"stock_name": "name"},
32
  "description": "Get details for a specific stock"
33
  },
34
+ "get_trending_stocks": {
35
+ "endpoint": "/trending",
36
+ "required_params": [],
37
+ "param_mapping": {},
38
+ "description": "Get trending stocks in the market"
39
+ },
40
+ "get_market_news": {
41
+ "endpoint": "/news",
42
+ "required_params": [],
43
+ "param_mapping": {},
44
+ "description": "Get latest stock market news"
45
+ },
46
+ "get_mutual_funds": {
47
+ "endpoint": "/mutual_funds",
48
+ "required_params": [],
49
+ "param_mapping": {},
50
+ "description": "Get mutual funds data"
51
+ },
52
+ "get_ipo_data": {
53
+ "endpoint": "/ipo",
54
+ "required_params": [],
55
+ "param_mapping": {},
56
+ "description": "Get IPO data"
57
+ },
58
+ "get_bse_most_active": {
59
+ "endpoint": "/BSE_most_active",
60
+ "required_params": [],
61
+ "param_mapping": {},
62
+ "description": "Get BSE most active stocks"
63
+ },
64
+ "get_nse_most_active": {
65
+ "endpoint": "/NSE_most_active",
66
+ "required_params": [],
67
+ "param_mapping": {},
68
+ "description": "Get NSE most active stocks"
69
+ },
70
+ "get_historical_data": {
71
+ "endpoint": "/historical_data",
72
+ "required_params": ["stock_name"],
73
+ "optional_params": ["period"],
74
+ "default_values": {"period": "1m", "filter": "default"},
75
+ "param_mapping": {},
76
+ "description": "Get historical data for a stock"
77
+ }
78
  }
79
 
80
  # Unified API call function
 
133
  mapped_params[param] = value
134
 
135
  return call_indian_api(endpoint, mapped_params)
136
+
137
  # Improved orchestrator function
138
  def orchestrator(query):
139
  """
 
143
  # Create a more precise prompt for the orchestrator
144
  orchestrator_prompt = """
145
  You are an orchestrator for a financial assistant specialized in Indian markets. Your job is to analyze user queries and determine if they need real-time market data.
 
146
  IMPORTANT: Be very precise in your analysis. Only return TRUE for "needs_api" when the query EXPLICITLY asks for current market data, stock prices, or listings.
 
147
  Examples where needs_api should be TRUE:
148
  - "Show me the most active stocks on NSE today" → get_nse_most_active
149
  - "What is the current price of Reliance?" → get_stock_details with stock_name="Reliance"
150
  - "Tell me about trending stocks" → get_trending_stocks
151
  - "What are the latest IPOs?" → get_ipo_data
 
152
  Examples where needs_api should be FALSE:
153
  - "What is compound interest?"
154
  - "How should I start investing?"
155
  - "What are the tax benefits of PPF?"
156
  - "Explain mutual funds to me"
 
157
  Available API functions:
158
  - get_stock_details(stock_name): Get details for a specific stock
159
  - get_trending_stocks(): Get trending stocks in the market
 
163
  - get_bse_most_active(): Get BSE most active stocks
164
  - get_nse_most_active(): Get NSE most active stocks
165
  - get_historical_data(stock_name, period="1m"): Get historical data for a stock
 
166
  User query: """ + query + """
 
167
  Respond in JSON format with the following structure:
168
  {
169
  "needs_api": true/false,
 
177
 
178
  # Create content for the orchestrator
179
  contents = [
180
+ types.Content(
181
+ role="user",
182
+ parts=[
183
+ types.Part.from_text(text=orchestrator_prompt)
184
+ ],
185
+ ),
186
  ]
187
 
188
+ # Configure generation parameters
189
+ generate_content_config = types.GenerateContentConfig(
190
+ temperature=0.2,
191
+ top_p=0.95,
192
+ top_k=40,
193
+ max_output_tokens=500,
194
+ response_mime_type="text/plain",
195
+ )
196
+
197
  # Generate content
198
+ response = client.models.generate_content(
199
  model="gemini-1.5-flash",
200
  contents=contents,
201
+ config=generate_content_config,
202
  )
203
 
204
  # Parse the response
 
217
  except Exception as e:
218
  print(f"Error parsing orchestrator response: {e}")
219
  return {"needs_api": False}
220
+
221
  # Language setting
222
 
223
  # Financial assistant system prompt
224
  SYSTEM_PROMPT = f"""You are Flaix, a helpful and knowledgeable financial assistant designed specifically for Indian users. Your purpose is to improve financial literacy and provide guidance on investments in the Indian market.
 
225
  Key responsibilities:
226
  1. Explain financial concepts in simple, easy-to-understand language
227
  2. Provide information about different investment options available in India (stocks, mutual funds, bonds, PPF, FDs, etc.)
 
353
  message_placeholder.write(full_response)
354
 
355
  # Add assistant response to chat history
356
+ st.session_state.messages.append({"role": "model", "content": full_response})