jh-didero commited on
Commit
350b367
verified
1 Parent(s): ccef7af

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +166 -47
app.py CHANGED
@@ -1,51 +1,170 @@
1
- import os
 
 
2
  import gradio as gr
3
  from openai import OpenAI
4
- from langfuse.openai import openai
5
- from langfuse.decorators import observe
6
-
7
  client = OpenAI()
8
- assistant_id=os.environ["OPENAI_ASSISTANT_ID"]
9
-
10
- def get_thread_id(streaming_chat_thread_id_state):
11
- if not streaming_chat_thread_id_state:
12
- streaming_chat_thread_id_state = gr.State({ "thread_id": None})
13
- print("======thread_id======")
14
- thread_id = streaming_chat_thread_id_state["thread_id"]
15
- print(thread_id)
16
-
17
- if not thread_id:
18
- thread = client.beta.threads.create()
19
- thread_id = thread.id
20
- print(f"new thread_id: {thread_id}")
21
- streaming_chat_thread_id_state["thread_id"] = thread_id
22
  else:
23
- print(f"old thread_id: {thread_id}")
24
- return thread_id
25
-
26
- @observe()
27
- def openai_chat(user_message, thread_id):
28
-
29
- client.beta.threads.messages.create(
30
- thread_id=thread_id,
31
- role="user",
32
- content=user_message
33
- )
34
-
35
- with client.beta.threads.runs.stream(
36
- thread_id=thread_id,
37
- assistant_id=assistant_id,
38
- ) as stream:
39
- total = ''
40
- for delta in stream.text_deltas:
41
- total += delta
42
- yield total
43
-
44
- def chat(user_message, history, streaming_chat_thread_id_state):
45
- thread_id =get_thread_id(streaming_chat_thread_id_state)
46
- yield from openai_chat(user_message, thread_id)
47
-
48
- history = []
49
- streaming_chat_thread_id_state = gr.State({ "thread_id": None})
50
- additional_inputs = [streaming_chat_thread_id_state]
51
- gr.ChatInterface(chat, examples=[["What are the troy rack mounting options?"], ["what are the steps for helen"], ["what are the main comparison between troy and janus specs"]], title="User Support Bot", additional_inputs=additional_inputs).launch(debug=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from os import getenv as os_getenv, path as os_path
2
+ from time import sleep
3
+ from json import loads as json_loads
4
  import gradio as gr
5
  from openai import OpenAI
 
 
 
6
  client = OpenAI()
7
+
8
+ assistant_id = os_getenv("OPENAI_ASSISTANT_ID")
9
+ vector_id = os_getenv("OPENAI_VECTOR_ID")
10
+
11
+ ANS_SHORT = "Resumida"
12
+ ANS_REGULAR = "Normal"
13
+ ANS_LONG = "Detallada"
14
+
15
+ def chat(user_message, history, state, long_or_short):
16
+ if (state is None) or (not state['user']):
17
+ gr.Warning("You need to authenticate first")
18
+ yield "You need to authenticate first"
 
 
19
  else:
20
+ thread = state['thread']
21
+ if thread is None:
22
+ thread = client.beta.threads.create(
23
+ tool_resources={
24
+ "file_search": {
25
+ "vector_store_ids": [vector_id]
26
+ }
27
+ },
28
+ )
29
+ state['thread'] = thread
30
+
31
+ client.beta.threads.messages.create(
32
+ thread_id=thread.id,
33
+ role="user",
34
+ content=user_message,
35
+ )
36
+
37
+ details = ""
38
+ if state["user"] != "anonymous":
39
+ details += f"User's name is {state['user']}."
40
+
41
+ if long_or_short == ANS_SHORT:
42
+ details = "Please make a complete but short answer"
43
+ elif long_or_short == ANS_LONG:
44
+ details = "Please make complete and detailed answer. Long is better than short. Use tables and lists if you need it"
45
+
46
+ with client.beta.threads.runs.stream(
47
+ thread_id=thread.id,
48
+ assistant_id=assistant_id,
49
+ additional_instructions=details,
50
+ ) as stream:
51
+ total = ''
52
+ for delta in stream.text_deltas:
53
+ total += delta
54
+ yield total
55
+
56
+ def chat_nostream(user_message, history, state):
57
+ if (state is None) or (not state['user']):
58
+ gr.Warning("You need to authenticate first")
59
+ yield "You need to authenticate first"
60
+ else:
61
+ thread = state['thread']
62
+ if thread is None:
63
+ thread = client.beta.threads.create(
64
+ tool_resources={
65
+ "file_search": {
66
+ "vector_store_ids": [vector_id]
67
+ }
68
+ }
69
+ )
70
+ state['thread'] = thread
71
+
72
+ # Add the user's message to the thread
73
+ client.beta.threads.messages.create(
74
+ thread_id=thread.id,
75
+ role="user",
76
+ content=user_message,
77
+ )
78
+
79
+ # Run the Assistant
80
+ run = client.beta.threads.runs.create(thread_id=thread.id,
81
+ assistant_id=assistant_id)
82
+
83
+ while True:
84
+ run_status = client.beta.threads.runs.retrieve(thread_id=thread.id,
85
+ run_id=run.id)
86
+ print(f"Run status: {run_status.status}")
87
+ if run_status.status == 'completed':
88
+ break
89
+ sleep(5)
90
+
91
+ messages = client.beta.threads.messages.list(thread_id=thread.id)
92
+ response = messages.data[0].content[0].text.value
93
+
94
+ yield response
95
+
96
+ def new_state():
97
+ return gr.State({
98
+ "user": None,
99
+ "thread": None,
100
+ })
101
+
102
+ def auth(token, state):
103
+ tokens=os_getenv("APP_TOKENS", None)
104
+ if tokens is None:
105
+ state["user"] = "anonymous"
106
+ else:
107
+ tokens=json_loads(tokens)
108
+ state["user"] = tokens.get(token, None)
109
+ return "", state
110
+
111
+ AUTH_JS = """function auth_js(token, state) {
112
+ if (!!document.location.hash) {
113
+ token = document.location.hash
114
+ document.location.hash=""
115
+ }
116
+ return [token, state]
117
+ }
118
+ """
119
+
120
+ theme = gr.Theme.from_hub("freddyaboulton/dracula_revamped@0.3.9")
121
+ theme.set(
122
+ color_accent_soft="#818eb6", # ChatBot.svelte / .message-row.panel.user-row
123
+ background_fill_secondary="#6272a4", # ChatBot.svelte / .message-row.panel.bot-row
124
+ button_primary_text_color="*button_secondary_text_color",
125
+ button_primary_background_fill="*button_secondary_background_fill")
126
+
127
+ with gr.Blocks(
128
+ title="Dr. Luis Chiozza - Medicina y Psicoanalisis",
129
+ fill_height=True,
130
+ theme=theme) as demo:
131
+ state = new_state()
132
+
133
+ gr.HTML("""
134
+ <h1>Dr. Luis Chiozza - Medicina y Psicoanalisis</h1>
135
+ <p>Habla con la colecci贸n de Libros de Medicina y Psicoanalisis del Dr. Luis Chiozza</p>
136
+ """)
137
+ with gr.Row(variant="compact"):
138
+ gr.HTML("Largo de la respuesta")
139
+ long_or_short = gr.Radio(
140
+ choices = [ANS_SHORT, ANS_REGULAR, ANS_LONG],
141
+ value = ANS_REGULAR,
142
+ show_label=False,
143
+ container=False,
144
+ label = "Largo de la respuesta",
145
+ scale=3)
146
+
147
+ gr.ChatInterface(
148
+ chat,
149
+ chatbot=gr.Chatbot(show_label=False, render=False, layout = "panel"),
150
+ additional_inputs=[state, long_or_short],
151
+ examples=[
152
+ ["Qu茅 diferencias hay entre el cuerpo y el Alma?"],
153
+ ["Cu谩les son las distintas funciones de los 贸rganos del cuerpo y su relaci贸n con el alma?"],
154
+ ],
155
+ submit_btn="Enviar",
156
+ stop_btn="Detener",
157
+ undo_btn=None,
158
+ clear_btn="Borrar",
159
+ retry_btn=None
160
+ )
161
+
162
+ token = gr.Textbox(visible=False)
163
+ demo.load(auth,
164
+ [token,state],
165
+ [token,state],
166
+ js=AUTH_JS)
167
+
168
+ demo.launch(
169
+ height=700,
170
+ allowed_paths=["."])