oleksandrburlakov commited on
Commit
56506e9
·
1 Parent(s): ff2c5a2

Added ability to save record into dynamodb

Browse files

Refactored code
Updated logic for getting suggestions from stream

Files changed (3) hide show
  1. __pycache__/bot_actions.cpython-38.pyc +0 -0
  2. app.py +109 -101
  3. bot_actions.py +11 -0
__pycache__/bot_actions.cpython-38.pyc ADDED
Binary file (554 Bytes). View file
 
app.py CHANGED
@@ -1,21 +1,43 @@
1
  from openai import OpenAI
2
  import gradio as gr
 
 
3
  import os
4
 
 
 
 
 
 
 
5
  client = OpenAI(api_key=os.environ['openAIToken'])
6
  assistantId = os.environ['assistantId']
7
  initial_message = os.environ['initialMessage']
8
 
9
- # client = OpenAI(api_key="sk-proj-4GPZmEnOFsZx0fZeQ9B3T3BlbkFJkXHmGCuW0rGmK0RAavtY")
10
- # assistantId = "asst_Rce5MptxfyEwp4NjImSDvXGD"
11
- # initial_message = "Hello. Let's start defining new facility. Also provide options."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
 
13
- def createThread(sessionStorage):
14
  streaming_thread = client.beta.threads.create()
15
- sessionStorage.append(streaming_thread.id)
16
  return sessionStorage
17
 
18
- def addMessage(text, threadId):
19
  print("User message: ", text)
20
  return client.beta.threads.messages.create(
21
  thread_id=threadId,
@@ -23,13 +45,10 @@ def addMessage(text, threadId):
23
  content=text
24
  )
25
 
26
- list_of_suggestions = []
27
- latest_suggestions = ""
28
-
29
- def handle_suggestions(string_of_suggestions):
30
  local_message = None
31
  parts = string_of_suggestions.split('#s#')
32
- list_of_suggestions = [x.strip('"') for x in parts[0].strip('][').split('", ') if x.strip('"')]
33
  list_of_suggestions = [ x for x in list_of_suggestions if x]
34
  if len(parts) > 1:
35
  local_message = parts[1]
@@ -40,52 +59,84 @@ def create_suggestions_list(suggestions):
40
  update_hide = [gr.update(visible=False, value="") for _ in range(6-len(suggestions))]
41
  return update_show + update_hide
42
 
43
- btn_list = []
44
- list_of_suggestions = ""
45
-
46
- CSS ="""
47
- .contain { display: flex; flex-direction: column; }
48
- .gradio-container { height: 100vh !important; }
49
- #chatbot { flex-grow: 1; overflow: auto;}
50
- """
 
 
 
 
 
 
 
 
 
 
 
51
 
52
- def initiate_chatting(storage):
53
- threadId = storage[0]
54
- addMessage(initial_message, threadId)
55
- global list_of_suggestions
56
  list_of_suggestions = []
57
  string_of_suggestions = ""
58
  is_loading_suggestions = False
59
- is_it_first_response = True
60
- response_message = ""
61
- with client.beta.threads.runs.stream(
62
- thread_id=threadId,
63
- assistant_id=assistantId,
64
- ) as stream:
65
- for text in stream.text_deltas:
66
- local_message = None
67
- if "[" in text and is_it_first_response:
68
- is_loading_suggestions = True
69
-
70
- is_it_first_response = False
71
-
72
- if is_loading_suggestions != True:
73
- local_message = text
74
- else:
75
- string_of_suggestions = string_of_suggestions + text
76
- if "#s#" in string_of_suggestions:
77
- is_loading_suggestions = False
78
- list_of_suggestions, local_message = handle_suggestions(string_of_suggestions)
79
- if local_message is not None:
80
- response_message += local_message
81
- stream.until_done()
82
-
83
- return [[None, response_message]]
84
-
85
- def createDemo():
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86
  with gr.Blocks(css=CSS, fill_height=True) as demo:
87
- storage = gr.State([])
88
  chatbot = gr.Chatbot(label="Facility managment bot", elem_id="chatbot")
 
89
  with gr.Row():
90
  for i in range(6):
91
  btn = gr.Button(visible=False)
@@ -95,54 +146,11 @@ def createDemo():
95
  clear_btn = gr.ClearButton(chatbot)
96
  btn = gr.Button("Submit")
97
 
98
-
99
  def user(user_message, history):
100
  return "", history + [[user_message, None]]
101
 
102
- def respond(chat_history, storage):
103
- global btn_list
104
- message = chat_history[-1][0]
105
- threadId = storage[0]
106
- print("Responding for threadId: ", threadId)
107
- chat_history[-1][1] = ""
108
- addMessage(message, threadId)
109
- global list_of_suggestions
110
- list_of_suggestions = []
111
- string_of_suggestions = ""
112
- is_loading_suggestions = False
113
- is_it_first_response = True
114
- try:
115
- with client.beta.threads.runs.stream(
116
- thread_id=threadId,
117
- assistant_id=assistantId,
118
- ) as stream:
119
- for text in stream.text_deltas:
120
- print(text, end="")
121
- local_message = None
122
- if "[" in text and is_it_first_response:
123
- is_loading_suggestions = True
124
-
125
- is_it_first_response = False
126
-
127
- if is_loading_suggestions != True:
128
- local_message = text
129
- else:
130
- string_of_suggestions = string_of_suggestions + text
131
- if "#s#" in string_of_suggestions:
132
- is_loading_suggestions = False
133
- list_of_suggestions, local_message = handle_suggestions(string_of_suggestions)
134
- if local_message is not None:
135
- chat_history[-1][1] += local_message
136
- yield {chatbot: chat_history}
137
- stream.until_done()
138
- print("")
139
- except:
140
- list_of_suggestions = []
141
- chat_history[-1][1] = "Error occured during processing your message. Please try again"
142
- yield {chatbot: chat_history}
143
-
144
- def update_suggestions():
145
- global list_of_suggestions
146
  btn_list = create_suggestions_list(list_of_suggestions)
147
  return btn_list
148
 
@@ -158,8 +166,8 @@ def createDemo():
158
  return message_box
159
 
160
  add_user_message_flow = [user, [msg,chatbot], [msg,chatbot]]
161
- chat_response_flow = [respond, [chatbot, storage], [chatbot]]
162
- update_suggestions_flow = [update_suggestions, None, btn_list]
163
  hide_suggestions_flow = [hide_suggestions, None, btn_list]
164
  disable_msg_flow = [disable_msg, None, msg]
165
  enable_msg_flow = [enable_msg, None, msg]
@@ -185,12 +193,12 @@ def createDemo():
185
  ).then(*update_suggestions_flow
186
  ).then(*enable_msg_flow)
187
 
188
- demo.load(createThread, inputs=storage, outputs=storage
189
- ).then(initiate_chatting, inputs=storage, outputs=chatbot
190
  ).then(*update_suggestions_flow
191
  ).then(*enable_msg_flow)
192
  return demo
193
 
194
  if __name__ == "__main__":
195
- demo = createDemo()
196
  demo.launch()
 
1
  from openai import OpenAI
2
  import gradio as gr
3
+ import json
4
+ from bot_actions import functions_dictionary, save_record
5
  import os
6
 
7
+ CSS ="""
8
+ .contain { display: flex; flex-direction: column; }
9
+ .gradio-container { height: 100vh !important; }
10
+ #chatbot { flex-grow: 1; overflow: auto;}
11
+ """
12
+
13
  client = OpenAI(api_key=os.environ['openAIToken'])
14
  assistantId = os.environ['assistantId']
15
  initial_message = os.environ['initialMessage']
16
 
17
+ def handle_requires_action(data):
18
+ tool_outputs = []
19
+ for tool in data.required_action.submit_tool_outputs.tool_calls:
20
+ function_name = tool.function.name
21
+ function_args = json.loads(tool.function.arguments)
22
+ print(function_name)
23
+ print(function_args)
24
+ if tool.function.name == "save_record":
25
+ try:
26
+ result = functions_dictionary[tool.function.name](**function_args)
27
+ except Exception as e:
28
+ print(e)
29
+ tool_outputs.append({"tool_call_id": tool.id, "output": result})
30
+
31
+ # Submit all tool_outputs at the same time
32
+ return tool_outputs
33
+
34
 
35
+ def create_thread_openai(sessionStorage):
36
  streaming_thread = client.beta.threads.create()
37
+ sessionStorage["threadId"] = streaming_thread.id
38
  return sessionStorage
39
 
40
+ def add_message_to_openai(text, threadId):
41
  print("User message: ", text)
42
  return client.beta.threads.messages.create(
43
  thread_id=threadId,
 
45
  content=text
46
  )
47
 
48
+ def transform_suggestions_into_list(string_of_suggestions):
 
 
 
49
  local_message = None
50
  parts = string_of_suggestions.split('#s#')
51
+ list_of_suggestions = json.loads(parts[0])
52
  list_of_suggestions = [ x for x in list_of_suggestions if x]
53
  if len(parts) > 1:
54
  local_message = parts[1]
 
59
  update_hide = [gr.update(visible=False, value="") for _ in range(6-len(suggestions))]
60
  return update_show + update_hide
61
 
62
+ def process_text_chunk(text, list_of_suggestions, string_of_suggestions, is_loading_suggestions):
63
+ print(text, end="", flush=True)
64
+ local_message = None
65
+ if "[" in text:
66
+ is_loading_suggestions = True
67
+
68
+ if is_loading_suggestions != True:
69
+ local_message = text
70
+ else:
71
+ string_of_suggestions = string_of_suggestions + text
72
+ if "#s#" in string_of_suggestions:
73
+ is_loading_suggestions = False
74
+ list_of_suggestions, local_message = transform_suggestions_into_list(string_of_suggestions)
75
+ string_of_suggestions = ""
76
+ elif "]" in string_of_suggestions and "]#" not in string_of_suggestions and not string_of_suggestions.endswith("]"):
77
+ is_loading_suggestions = False
78
+ local_message = string_of_suggestions
79
+ string_of_suggestions = ""
80
+ return local_message, list_of_suggestions, string_of_suggestions, is_loading_suggestions
81
 
82
+ def handle_events(threadId, chat_history, storage):
 
 
 
83
  list_of_suggestions = []
84
  string_of_suggestions = ""
85
  is_loading_suggestions = False
86
+ try:
87
+ with client.beta.threads.runs.stream(
88
+ thread_id=threadId,
89
+ assistant_id=assistantId
90
+ ) as stream:
91
+ for event in stream:
92
+ if event.event == "thread.message.delta" and event.data.delta.content:
93
+ text = event.data.delta.content[0].text.value
94
+ local_message, list_of_suggestions, string_of_suggestions, is_loading_suggestions = process_text_chunk(text, list_of_suggestions, string_of_suggestions, is_loading_suggestions)
95
+ if local_message is not None:
96
+ chat_history[-1][1] += local_message
97
+ yield [ chat_history, storage]
98
+ if event.event == 'thread.run.requires_action':
99
+ tool_outputs = handle_requires_action(event.data)
100
+ with client.beta.threads.runs.submit_tool_outputs_stream(
101
+ thread_id=stream.current_run.thread_id,
102
+ run_id=event.data.id,
103
+ tool_outputs=tool_outputs,
104
+ ) as stream:
105
+ for text in stream.text_deltas:
106
+ local_message, list_of_suggestions, string_of_suggestions, is_loading_suggestions = process_text_chunk(text, list_of_suggestions, string_of_suggestions, is_loading_suggestions)
107
+ if local_message is not None:
108
+ chat_history[-1][1] += local_message
109
+ yield [chat_history, storage]
110
+ stream.until_done()
111
+ print("")
112
+ storage["list_of_suggestions"] = list_of_suggestions
113
+ return [chat_history, storage]
114
+ except Exception as e:
115
+ print(e)
116
+ chat_history[-1][1] = "Error occured during processing your message. Please try again"
117
+ yield [chat_history, storage]
118
+
119
+ def initiate_chatting(chat_history, storage):
120
+ threadId = storage["threadId"]
121
+ chat_history = [[None, ""]]
122
+ add_message_to_openai(initial_message, threadId)
123
+ for response in handle_events(threadId, chat_history, storage):
124
+ yield response
125
+
126
+ def respond_on_user_msg(chat_history, storage):
127
+ message = chat_history[-1][0]
128
+ threadId = storage["threadId"]
129
+ print("Responding for threadId: ", threadId)
130
+ chat_history[-1][1] = ""
131
+ add_message_to_openai(message, threadId)
132
+ for response in handle_events(threadId, chat_history, storage):
133
+ yield response
134
+
135
+ def create_application():
136
  with gr.Blocks(css=CSS, fill_height=True) as demo:
137
+ storage = gr.State({})
138
  chatbot = gr.Chatbot(label="Facility managment bot", elem_id="chatbot")
139
+ btn_list = []
140
  with gr.Row():
141
  for i in range(6):
142
  btn = gr.Button(visible=False)
 
146
  clear_btn = gr.ClearButton(chatbot)
147
  btn = gr.Button("Submit")
148
 
 
149
  def user(user_message, history):
150
  return "", history + [[user_message, None]]
151
 
152
+ def update_suggestions(storage):
153
+ list_of_suggestions = storage['list_of_suggestions'] or []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
154
  btn_list = create_suggestions_list(list_of_suggestions)
155
  return btn_list
156
 
 
166
  return message_box
167
 
168
  add_user_message_flow = [user, [msg,chatbot], [msg,chatbot]]
169
+ chat_response_flow = [respond_on_user_msg, [chatbot, storage], [chatbot, storage]]
170
+ update_suggestions_flow = [update_suggestions, storage, btn_list]
171
  hide_suggestions_flow = [hide_suggestions, None, btn_list]
172
  disable_msg_flow = [disable_msg, None, msg]
173
  enable_msg_flow = [enable_msg, None, msg]
 
193
  ).then(*update_suggestions_flow
194
  ).then(*enable_msg_flow)
195
 
196
+ demo.load(create_thread_openai, inputs=storage, outputs=storage
197
+ ).then(initiate_chatting, inputs=[chatbot, storage], outputs=[chatbot, storage]
198
  ).then(*update_suggestions_flow
199
  ).then(*enable_msg_flow)
200
  return demo
201
 
202
  if __name__ == "__main__":
203
+ demo = create_application()
204
  demo.launch()
bot_actions.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import requests
2
+ import time
3
+
4
+ def save_record(arg_json):
5
+ r = requests.post("https://ogtk5k73z8.execute-api.us-east-1.amazonaws.com/Development/facilities", json={'pk': round(time.time()), 'json': arg_json})
6
+ print(r.status_code, r.reason)
7
+ return "Done"
8
+
9
+ functions_dictionary = {
10
+ "save_record": save_record
11
+ }