File size: 7,144 Bytes
f39fdae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
# -*- coding: utf-8 -*-
"""OpenAI_Assistant_WanderLust.ipynb

Automatically generated by Colaboratory.

Original file is located at
    https://colab.research.google.com/drive/1DLYjk07uQwF_Oqav1NtqMMCz_S2f0q8B

# OpenAI assistant Wanderlust

Basic recreation of OpenAI's DevDay Wanderlust demo app. It relies on Gradio and the new Assistants API.

This space is inspired by the implementation of Fanilo Andrianasolo using Streamlit - https://www.youtube.com/watch?v=tLeqCDKgEDU
"""

#!pip install -q -U gradio openai datasets

import gradio as gr
import random
import openai
import os
import json
import plotly.graph_objects as go
import time

#os.environ["OPENAI_API_KEY"] = "..."  # Replace with your key

#######################################
# TOOLS SETUP
#######################################

def update_map_state(latitude, longitude, zoom):
    """OpenAI tool to update map in-app
    """
    session_state[map_state] = {
        "latitude": latitude,
        "longitude": longitude,
        "zoom": zoom,
    }
    print(session_state[map_state])
    return "Map updated"

def add_markers_state(latitudes, longitudes, labels):
    """OpenAI tool to update markers in-app
    """
    session_state[markers_state] = {
        "lat": latitudes,
        "lon": longitudes,
        "text": labels,
    }
    return "Markers added"

tool_to_function = {
    "update_map": update_map_state,
    "add_markers": add_markers_state,
}

## Helpers

def get_assistant_id():
    return session_state[assistant_state].id

def get_thread_id():
    return session_state[thread_state].id


def get_run_id():
    return session_state[last_openai_run_state].id

def submit_message(assistant_id, thread_id, user_message):
    client.beta.threads.messages.create(
        thread_id=thread_id, role="user", content=user_message
    )
    run = client.beta.threads.runs.create(
        thread_id=thread_id,
        assistant_id=assistant_id,
    )
    return run

def get_run_info(run_id, thread_id):
    run = client.beta.threads.runs.retrieve(
        thread_id=thread_id,
        run_id=run_id,
    )
    return run

#######################################
# SESSION SETUP
#######################################

client = openai.OpenAI()
assistant_id = "asst_7OC3NTeyCjEZrApdLRklplE7"

session_state = {}

assistant_state = "assistant"
thread_state = "thread"
conversation_state = "conversation"
last_openai_run_state = "last_openai_run"
map_state = "map"
markers_state = "markers"

if (assistant_state not in session_state) or (thread_state not in session_state):
    session_state[assistant_state] = client.beta.assistants.retrieve(assistant_id)
    session_state[thread_state] = client.beta.threads.create()

if conversation_state not in session_state:
    session_state[conversation_state] = []

if last_openai_run_state not in session_state:
    session_state[last_openai_run_state] = None

if map_state not in session_state:
    session_state[map_state] = {
        "latitude": 48.85,
        "longitude": 2.35,
        "zoom": 12,
    }

if markers_state not in session_state:
    session_state[markers_state] = {
        "lat": [],
        "lon": [],
        "text": [],
    }

fig = go.Figure(go.Scattermapbox())

fig.update_layout(
        mapbox_style="open-street-map",
        hovermode='closest',
        mapbox=dict(
            center=go.layout.mapbox.Center(
                lat=session_state[map_state]["latitude"],
                lon=session_state[map_state]["longitude"]
            ),
            zoom=session_state[map_state]["zoom"]
        ),
)

def respond(message, chat_history):

    print(chat_history)

    run = submit_message(get_assistant_id(), get_thread_id(), message)

    session_state[last_openai_run_state] = run

    print(run)

    completed = False

    # Polling
    while not completed:

        run = get_run_info(get_run_id(), get_thread_id())

        if run.status == "requires_action":

            tools_output = []

            for tool_call in run.required_action.submit_tool_outputs.tool_calls:

                f = tool_call.function
                f_name = f.name
                f_args = json.loads(f.arguments)

                print(f"Launching function {f_name} with args {f_args}")

                tool_result = tool_to_function[f_name](**f_args)

                tools_output.append(
                        {
                            "tool_call_id": tool_call.id,
                            "output": tool_result,
                        }
                    )

            print(f"Will submit {tools_output}")

            client.beta.threads.runs.submit_tool_outputs(
                    thread_id=get_thread_id(),
                    run_id=get_run_id(),
                    tool_outputs=tools_output,
            )

        if run.status == "completed":

            completed = True

        else:
            time.sleep(0.1)

    session_state[conversation_state] = [
        [m.role, m.content[0].text.value]
        for m in client.beta.threads.messages.list(get_thread_id(), order="asc").data
    ]

    dialog = session_state[conversation_state]
    formatted_dialog = []
    for i in range(int(len(dialog)/2)):
      formatted_dialog.append([dialog[i*2][1],dialog[i*2+1][1]])


    chat_history = formatted_dialog

    fig = None

    if session_state[markers_state] is None:

      fig = go.Figure(go.Scattermapbox())

    else :
      fig = go.Figure(go.Scattermapbox(
            customdata=session_state[markers_state]["text"],
            lat=session_state[markers_state]["lat"],
            lon=session_state[markers_state]["lon"],
            mode='markers',
            marker=go.scattermapbox.Marker(
                size=18
            ),
            hoverinfo="text",
            hovertemplate='<b>Name</b>: %{customdata}'
        ))

    fig.update_layout(
        mapbox_style="open-street-map",
        hovermode='closest',
        mapbox=dict(
            center=go.layout.mapbox.Center(
                lat=session_state[map_state]["latitude"],
                lon=session_state[map_state]["longitude"]
            ),
            zoom=12
        ),
    )

    return "", chat_history, fig

with gr.Blocks(title="OpenAI assistant Wanderlust") as demo:

    gr.Markdown("# OpenAI assistant Wanderlust")

    with gr.Column():
        with gr.Row():

          chatbot = gr.Chatbot()
          map = gr.Plot(fig)

    msg = gr.Textbox("Move the map to Brussels and add markers for five major attractions")

    with gr.Column():
        with gr.Row():
          submit = gr.Button("Submit")
          clear = gr.ClearButton([msg, chatbot])

    msg.submit(respond, [msg, chatbot], [msg, chatbot, map])
    submit.click(respond, [msg, chatbot], [msg, chatbot, map])

    gr.Markdown(
        """
# Description

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)

This space is inspired by the implementation of [Fanilo Andrianasolo using Streamlit](https://www.youtube.com/watch?v=tLeqCDKgEDU)
"""
    )

demo.launch(debug=True)