Yannael_LB commited on
Commit
f39fdae
·
1 Parent(s): d8ff9bd

Initial commit

Browse files
Files changed (3) hide show
  1. README.md +2 -1
  2. app.py +271 -0
  3. requirements.txt +4 -0
README.md CHANGED
@@ -1,5 +1,5 @@
1
  ---
2
- title: Openai Assistant Wanderlust
3
  emoji: 🏢
4
  colorFrom: blue
5
  colorTo: green
@@ -11,3 +11,4 @@ license: cc-by-4.0
11
  ---
12
 
13
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
1
  ---
2
+ title: OpenAI Assistant Wanderlust
3
  emoji: 🏢
4
  colorFrom: blue
5
  colorTo: green
 
11
  ---
12
 
13
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
14
+
app.py ADDED
@@ -0,0 +1,271 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """OpenAI_Assistant_WanderLust.ipynb
3
+
4
+ Automatically generated by Colaboratory.
5
+
6
+ Original file is located at
7
+ https://colab.research.google.com/drive/1DLYjk07uQwF_Oqav1NtqMMCz_S2f0q8B
8
+
9
+ # OpenAI assistant Wanderlust
10
+
11
+ Basic recreation of OpenAI's DevDay Wanderlust demo app. It relies on Gradio and the new Assistants API.
12
+
13
+ This space is inspired by the implementation of Fanilo Andrianasolo using Streamlit - https://www.youtube.com/watch?v=tLeqCDKgEDU
14
+ """
15
+
16
+ #!pip install -q -U gradio openai datasets
17
+
18
+ import gradio as gr
19
+ import random
20
+ import openai
21
+ import os
22
+ import json
23
+ import plotly.graph_objects as go
24
+ import time
25
+
26
+ #os.environ["OPENAI_API_KEY"] = "..." # Replace with your key
27
+
28
+ #######################################
29
+ # TOOLS SETUP
30
+ #######################################
31
+
32
+ def update_map_state(latitude, longitude, zoom):
33
+ """OpenAI tool to update map in-app
34
+ """
35
+ session_state[map_state] = {
36
+ "latitude": latitude,
37
+ "longitude": longitude,
38
+ "zoom": zoom,
39
+ }
40
+ print(session_state[map_state])
41
+ return "Map updated"
42
+
43
+ def add_markers_state(latitudes, longitudes, labels):
44
+ """OpenAI tool to update markers in-app
45
+ """
46
+ session_state[markers_state] = {
47
+ "lat": latitudes,
48
+ "lon": longitudes,
49
+ "text": labels,
50
+ }
51
+ return "Markers added"
52
+
53
+ tool_to_function = {
54
+ "update_map": update_map_state,
55
+ "add_markers": add_markers_state,
56
+ }
57
+
58
+ ## Helpers
59
+
60
+ def get_assistant_id():
61
+ return session_state[assistant_state].id
62
+
63
+ def get_thread_id():
64
+ return session_state[thread_state].id
65
+
66
+
67
+ def get_run_id():
68
+ return session_state[last_openai_run_state].id
69
+
70
+ def submit_message(assistant_id, thread_id, user_message):
71
+ client.beta.threads.messages.create(
72
+ thread_id=thread_id, role="user", content=user_message
73
+ )
74
+ run = client.beta.threads.runs.create(
75
+ thread_id=thread_id,
76
+ assistant_id=assistant_id,
77
+ )
78
+ return run
79
+
80
+ def get_run_info(run_id, thread_id):
81
+ run = client.beta.threads.runs.retrieve(
82
+ thread_id=thread_id,
83
+ run_id=run_id,
84
+ )
85
+ return run
86
+
87
+ #######################################
88
+ # SESSION SETUP
89
+ #######################################
90
+
91
+ client = openai.OpenAI()
92
+ assistant_id = "asst_7OC3NTeyCjEZrApdLRklplE7"
93
+
94
+ session_state = {}
95
+
96
+ assistant_state = "assistant"
97
+ thread_state = "thread"
98
+ conversation_state = "conversation"
99
+ last_openai_run_state = "last_openai_run"
100
+ map_state = "map"
101
+ markers_state = "markers"
102
+
103
+ if (assistant_state not in session_state) or (thread_state not in session_state):
104
+ session_state[assistant_state] = client.beta.assistants.retrieve(assistant_id)
105
+ session_state[thread_state] = client.beta.threads.create()
106
+
107
+ if conversation_state not in session_state:
108
+ session_state[conversation_state] = []
109
+
110
+ if last_openai_run_state not in session_state:
111
+ session_state[last_openai_run_state] = None
112
+
113
+ if map_state not in session_state:
114
+ session_state[map_state] = {
115
+ "latitude": 48.85,
116
+ "longitude": 2.35,
117
+ "zoom": 12,
118
+ }
119
+
120
+ if markers_state not in session_state:
121
+ session_state[markers_state] = {
122
+ "lat": [],
123
+ "lon": [],
124
+ "text": [],
125
+ }
126
+
127
+ fig = go.Figure(go.Scattermapbox())
128
+
129
+ fig.update_layout(
130
+ mapbox_style="open-street-map",
131
+ hovermode='closest',
132
+ mapbox=dict(
133
+ center=go.layout.mapbox.Center(
134
+ lat=session_state[map_state]["latitude"],
135
+ lon=session_state[map_state]["longitude"]
136
+ ),
137
+ zoom=session_state[map_state]["zoom"]
138
+ ),
139
+ )
140
+
141
+ def respond(message, chat_history):
142
+
143
+ print(chat_history)
144
+
145
+ run = submit_message(get_assistant_id(), get_thread_id(), message)
146
+
147
+ session_state[last_openai_run_state] = run
148
+
149
+ print(run)
150
+
151
+ completed = False
152
+
153
+ # Polling
154
+ while not completed:
155
+
156
+ run = get_run_info(get_run_id(), get_thread_id())
157
+
158
+ if run.status == "requires_action":
159
+
160
+ tools_output = []
161
+
162
+ for tool_call in run.required_action.submit_tool_outputs.tool_calls:
163
+
164
+ f = tool_call.function
165
+ f_name = f.name
166
+ f_args = json.loads(f.arguments)
167
+
168
+ print(f"Launching function {f_name} with args {f_args}")
169
+
170
+ tool_result = tool_to_function[f_name](**f_args)
171
+
172
+ tools_output.append(
173
+ {
174
+ "tool_call_id": tool_call.id,
175
+ "output": tool_result,
176
+ }
177
+ )
178
+
179
+ print(f"Will submit {tools_output}")
180
+
181
+ client.beta.threads.runs.submit_tool_outputs(
182
+ thread_id=get_thread_id(),
183
+ run_id=get_run_id(),
184
+ tool_outputs=tools_output,
185
+ )
186
+
187
+ if run.status == "completed":
188
+
189
+ completed = True
190
+
191
+ else:
192
+ time.sleep(0.1)
193
+
194
+ session_state[conversation_state] = [
195
+ [m.role, m.content[0].text.value]
196
+ for m in client.beta.threads.messages.list(get_thread_id(), order="asc").data
197
+ ]
198
+
199
+ dialog = session_state[conversation_state]
200
+ formatted_dialog = []
201
+ for i in range(int(len(dialog)/2)):
202
+ formatted_dialog.append([dialog[i*2][1],dialog[i*2+1][1]])
203
+
204
+
205
+ chat_history = formatted_dialog
206
+
207
+ fig = None
208
+
209
+ if session_state[markers_state] is None:
210
+
211
+ fig = go.Figure(go.Scattermapbox())
212
+
213
+ else :
214
+ fig = go.Figure(go.Scattermapbox(
215
+ customdata=session_state[markers_state]["text"],
216
+ lat=session_state[markers_state]["lat"],
217
+ lon=session_state[markers_state]["lon"],
218
+ mode='markers',
219
+ marker=go.scattermapbox.Marker(
220
+ size=18
221
+ ),
222
+ hoverinfo="text",
223
+ hovertemplate='<b>Name</b>: %{customdata}'
224
+ ))
225
+
226
+ fig.update_layout(
227
+ mapbox_style="open-street-map",
228
+ hovermode='closest',
229
+ mapbox=dict(
230
+ center=go.layout.mapbox.Center(
231
+ lat=session_state[map_state]["latitude"],
232
+ lon=session_state[map_state]["longitude"]
233
+ ),
234
+ zoom=12
235
+ ),
236
+ )
237
+
238
+ return "", chat_history, fig
239
+
240
+ with gr.Blocks(title="OpenAI assistant Wanderlust") as demo:
241
+
242
+ gr.Markdown("# OpenAI assistant Wanderlust")
243
+
244
+ with gr.Column():
245
+ with gr.Row():
246
+
247
+ chatbot = gr.Chatbot()
248
+ map = gr.Plot(fig)
249
+
250
+ msg = gr.Textbox("Move the map to Brussels and add markers for five major attractions")
251
+
252
+ with gr.Column():
253
+ with gr.Row():
254
+ submit = gr.Button("Submit")
255
+ clear = gr.ClearButton([msg, chatbot])
256
+
257
+ msg.submit(respond, [msg, chatbot], [msg, chatbot, map])
258
+ submit.click(respond, [msg, chatbot], [msg, chatbot, map])
259
+
260
+ gr.Markdown(
261
+ """
262
+ # Description
263
+
264
+ Basic recreation of OpenAI's DevDay Wanderlust demo app. It relies on Gradio and the new Assistants API. [Github repository](https://github.com/Yannael/openai-assistant-wanderlust)
265
+
266
+ This space is inspired by the implementation of [Fanilo Andrianasolo using Streamlit](https://www.youtube.com/watch?v=tLeqCDKgEDU)
267
+ """
268
+ )
269
+
270
+ demo.launch(debug=True)
271
+
requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ gradio
2
+ openai
3
+ datasets
4
+ plotly