anilvt commited on
Commit
b9eee4c
·
verified ·
1 Parent(s): 8793d4f

Upload 2 files

Browse files
Files changed (2) hide show
  1. app.py +145 -0
  2. requirements.txt +3 -0
app.py ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ import requests
4
+ from openai import OpenAI
5
+ import gradio as gr
6
+
7
+ # --- Environment Variables (set these in your Hugging Face Space settings) ---
8
+ # Add under "Settings → Variables":
9
+ # OPENAI_API_KEY = your_openai_key
10
+ # STOCK_API_KEY = your_alphavantage_key
11
+
12
+ os.environ["OPENAI_API_KEY"] = os.getenv("OPENAI_API_KEY")
13
+ os.environ["STOCK_API_KEY"] = os.getenv("STOCK_API_KEY")
14
+
15
+ client = OpenAI()
16
+
17
+ # --- Tool Function: Fetch latest stock price ---
18
+ def get_latest_stock_price(symbol: str) -> str:
19
+ api_key = os.environ.get("STOCK_API_KEY")
20
+ base_url = "https://www.alphavantage.co/query"
21
+ params = {
22
+ "function": "TIME_SERIES_DAILY",
23
+ "symbol": symbol,
24
+ "apikey": api_key,
25
+ }
26
+ response = requests.get(base_url, params=params)
27
+ data = response.json()
28
+
29
+ if "Time Series (Daily)" in data and data["Time Series (Daily)"]:
30
+ latest_day_data = list(data["Time Series (Daily)"].values())[0]
31
+ if "4. close" in latest_day_data:
32
+ latest_price = latest_day_data["4. close"]
33
+ return latest_price
34
+ else:
35
+ return "Price data not available."
36
+ else:
37
+ return "Price data not available."
38
+
39
+ # --- Define Tools for OpenAI Function Calling ---
40
+ tools = [
41
+ {
42
+ "type": "function",
43
+ "function": {
44
+ "name": "get_latest_stock_price",
45
+ "description": "Get the latest stock price for a given symbol",
46
+ "parameters": {
47
+ "type": "object",
48
+ "properties": {
49
+ "symbol": {
50
+ "type": "string",
51
+ "description": "The symbol of the stock",
52
+ },
53
+ },
54
+ "required": ["symbol"],
55
+ },
56
+ },
57
+ }
58
+ ]
59
+
60
+ # --- Chat Logic ---
61
+ def stock_chat(user_message: str) -> str:
62
+ messages = [
63
+ {
64
+ "role": "user",
65
+ "content": "You are a stock bot. Answer only finance stock related questions.",
66
+ },
67
+ {"role": "user", "content": user_message},
68
+ ]
69
+
70
+ response = client.chat.completions.create(
71
+ model="gpt-3.5-turbo-1106",
72
+ messages=messages,
73
+ tools=tools,
74
+ tool_choice="auto",
75
+ )
76
+
77
+ msg = response.choices[0].message
78
+
79
+ # --- If model calls tool ---
80
+ if hasattr(msg, "tool_calls") and msg.tool_calls:
81
+ for call in msg.tool_calls:
82
+ if call.function.name == "get_latest_stock_price":
83
+ try:
84
+ args = json.loads(call.function.arguments or "{}")
85
+ except json.JSONDecodeError:
86
+ args = {}
87
+
88
+ if "symbol" in args:
89
+ symbol = args["symbol"]
90
+ price = get_latest_stock_price(symbol)
91
+
92
+ # Add assistant tool call + tool result
93
+ messages.append(
94
+ {
95
+ "role": "assistant",
96
+ "tool_calls": [
97
+ {
98
+ "id": call.id,
99
+ "type": "function",
100
+ "function": {
101
+ "name": "get_latest_stock_price",
102
+ "arguments": json.dumps({"symbol": symbol}),
103
+ },
104
+ }
105
+ ],
106
+ "content": None,
107
+ }
108
+ )
109
+
110
+ messages.append(
111
+ {
112
+ "role": "tool",
113
+ "tool_call_id": call.id,
114
+ "content": f"The latest stock price for {symbol} is {price}",
115
+ }
116
+ )
117
+
118
+ # Model crafts the final user-facing answer
119
+ final = client.chat.completions.create(
120
+ model="gpt-3.5-turbo-1106",
121
+ messages=messages,
122
+ )
123
+ return final.choices[0].message.content or "No reply"
124
+ else:
125
+ return "Symbol not found in tool call arguments."
126
+ else:
127
+ return "Unknown tool called."
128
+ else:
129
+ # Model answered directly — no tool required
130
+ return msg.content or "No reply"
131
+
132
+ # --- Gradio UI for Hugging Face ---
133
+ def chatbot_interface(message):
134
+ return stock_chat(message)
135
+
136
+ iface = gr.Interface(
137
+ fn=chatbot_interface,
138
+ inputs=gr.Textbox(label="Ask about a stock (e.g., 'What is the latest stock price for AAPL?')"),
139
+ outputs=gr.Textbox(label="Response"),
140
+ title="📈 StockBot - AI Stock Assistant",
141
+ description="Ask questions about stock prices. Data provided by AlphaVantage and OpenAI GPT-3.5.",
142
+ )
143
+
144
+ if __name__ == "__main__":
145
+ iface.launch()
requirements.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ openai
2
+ requests
3
+ gradio