poonampal commited on
Commit
1ad9199
1 Parent(s): e3f0157

Add application file

Browse files
Files changed (2) hide show
  1. app.py +323 -4
  2. autogen.png +0 -0
app.py CHANGED
@@ -1,7 +1,326 @@
1
  import gradio as gr
 
 
 
 
 
 
 
 
 
 
 
2
 
3
- def greet(name):
4
- return "Hello " + name + "!!"
5
 
6
- iface = gr.Interface(fn=greet, inputs="text", outputs="text")
7
- iface.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
+ import os
3
+ from pathlib import Path
4
+ import autogen
5
+ import chromadb
6
+ import multiprocessing as mp
7
+ from autogen.retrieve_utils import TEXT_FORMATS, get_file_from_url, is_url
8
+ from autogen.agentchat.contrib.retrieve_assistant_agent import RetrieveAssistantAgent
9
+ from autogen.agentchat.contrib.retrieve_user_proxy_agent import (
10
+ RetrieveUserProxyAgent,
11
+ PROMPT_CODE,
12
+ )
13
 
14
+ TIMEOUT = 60
 
15
 
16
+
17
+ def initialize_agents(config_list, docs_path=None):
18
+ if isinstance(config_list, gr.State):
19
+ _config_list = config_list.value
20
+ else:
21
+ _config_list = config_list
22
+ if docs_path is None:
23
+ docs_path = "https://raw.githubusercontent.com/microsoft/autogen/main/README.md"
24
+
25
+ assistant = RetrieveAssistantAgent(
26
+ name="assistant",
27
+ system_message="You are a helpful assistant.",
28
+ )
29
+
30
+ ragproxyagent = RetrieveUserProxyAgent(
31
+ name="ragproxyagent",
32
+ human_input_mode="NEVER",
33
+ max_consecutive_auto_reply=5,
34
+ retrieve_config={
35
+ "task": "code",
36
+ "docs_path": docs_path,
37
+ "chunk_token_size": 2000,
38
+ "model": _config_list[0]["model"],
39
+ "client": chromadb.PersistentClient(path="/tmp/chromadb"),
40
+ "embedding_model": "all-mpnet-base-v2",
41
+ "customized_prompt": PROMPT_CODE,
42
+ "get_or_create": True,
43
+ "collection_name": "autogen_rag",
44
+ },
45
+ )
46
+
47
+ return assistant, ragproxyagent
48
+
49
+
50
+ def initiate_chat(config_list, problem, queue, n_results=3):
51
+ global assistant, ragproxyagent
52
+ if isinstance(config_list, gr.State):
53
+ _config_list = config_list.value
54
+ else:
55
+ _config_list = config_list
56
+ if len(_config_list[0].get("api_key", "")) < 2:
57
+ queue.put(
58
+ ["Hi, nice to meet you! Please enter your API keys in below text boxs."]
59
+ )
60
+ return
61
+ else:
62
+ llm_config = (
63
+ {
64
+ "request_timeout": TIMEOUT,
65
+ # "seed": 42,
66
+ "config_list": _config_list,
67
+ "use_cache": False,
68
+ },
69
+ )
70
+ assistant.llm_config.update(llm_config[0])
71
+ assistant.reset()
72
+ try:
73
+ ragproxyagent.initiate_chat(
74
+ assistant, problem=problem, silent=False, n_results=n_results
75
+ )
76
+ messages = ragproxyagent.chat_messages
77
+ messages = [messages[k] for k in messages.keys()][0]
78
+ messages = [m["content"] for m in messages if m["role"] == "user"]
79
+ print("messages: ", messages)
80
+ except Exception as e:
81
+ messages = [str(e)]
82
+ queue.put(messages)
83
+
84
+
85
+ def chatbot_reply(input_text):
86
+ """Chat with the agent through terminal."""
87
+ queue = mp.Queue()
88
+ process = mp.Process(
89
+ target=initiate_chat,
90
+ args=(config_list, input_text, queue),
91
+ )
92
+ process.start()
93
+ try:
94
+ # process.join(TIMEOUT+2)
95
+ messages = queue.get(timeout=TIMEOUT)
96
+ except Exception as e:
97
+ messages = [
98
+ str(e)
99
+ if len(str(e)) > 0
100
+ else "Invalid Request to OpenAI, please check your API keys."
101
+ ]
102
+ finally:
103
+ try:
104
+ process.terminate()
105
+ except:
106
+ pass
107
+ return messages
108
+
109
+
110
+ def get_description_text():
111
+ return """
112
+ # Microsoft AutoGen: Retrieve Chat Demo
113
+
114
+ This demo shows how to use the RetrieveUserProxyAgent and RetrieveAssistantAgent to build a chatbot.
115
+
116
+ #### [AutoGen](https://github.com/microsoft/autogen) [Discord](https://discord.gg/pAbnFJrkgZ) [Blog](https://microsoft.github.io/autogen/blog/2023/10/18/RetrieveChat) [Paper](https://arxiv.org/abs/2308.08155) [SourceCode](https://github.com/thinkall/autogen-demos)
117
+ """
118
+
119
+
120
+ global assistant, ragproxyagent
121
+
122
+ with gr.Blocks() as demo:
123
+ config_list, assistant, ragproxyagent = (
124
+ gr.State(
125
+ [
126
+ {
127
+ "api_key": "",
128
+ "api_base": "",
129
+ "api_type": "azure",
130
+ "api_version": "2023-07-01-preview",
131
+ "model": "gpt-35-turbo",
132
+ }
133
+ ]
134
+ ),
135
+ None,
136
+ None,
137
+ )
138
+ assistant, ragproxyagent = initialize_agents(config_list)
139
+
140
+ gr.Markdown(get_description_text())
141
+ chatbot = gr.Chatbot(
142
+ [],
143
+ elem_id="chatbot",
144
+ bubble_full_width=False,
145
+ avatar_images=(None, (os.path.join(os.path.dirname(__file__), "autogen.png"))),
146
+ # height=600,
147
+ )
148
+
149
+ txt_input = gr.Textbox(
150
+ scale=4,
151
+ show_label=False,
152
+ placeholder="Enter text and press enter",
153
+ container=False,
154
+ )
155
+
156
+ with gr.Row():
157
+
158
+ def update_config(config_list):
159
+ global assistant, ragproxyagent
160
+ config_list = autogen.config_list_from_models(
161
+ model_list=[os.environ.get("MODEL", "gpt-35-turbo")],
162
+ )
163
+ if not config_list:
164
+ config_list = [
165
+ {
166
+ "api_key": "",
167
+ "api_base": "",
168
+ "api_type": "azure",
169
+ "api_version": "2023-07-01-preview",
170
+ "model": "gpt-35-turbo",
171
+ }
172
+ ]
173
+ llm_config = (
174
+ {
175
+ "request_timeout": TIMEOUT,
176
+ # "seed": 42,
177
+ "config_list": config_list,
178
+ },
179
+ )
180
+ assistant.llm_config.update(llm_config[0])
181
+ ragproxyagent._model = config_list[0]["model"]
182
+ return config_list
183
+
184
+
185
+ def set_params(model, oai_key, aoai_key, aoai_base):
186
+ os.environ["MODEL"] = model
187
+ os.environ["OPENAI_API_KEY"] = oai_key
188
+ os.environ["AZURE_OPENAI_API_KEY"] = aoai_key
189
+ os.environ["AZURE_OPENAI_API_BASE"] = aoai_base
190
+ return model, oai_key, aoai_key, aoai_base
191
+
192
+
193
+ txt_model = gr.Dropdown(
194
+ label="Model",
195
+ choices=[
196
+ "gpt-4",
197
+ "gpt-35-turbo",
198
+ "gpt-3.5-turbo",
199
+ ],
200
+ allow_custom_value=True,
201
+ value="gpt-35-turbo",
202
+ container=True,
203
+ )
204
+ txt_oai_key = gr.Textbox(
205
+ label="OpenAI API Key",
206
+ placeholder="Enter key and press enter",
207
+ max_lines=1,
208
+ show_label=True,
209
+ value=os.environ.get("OPENAI_API_KEY", ""),
210
+ container=True,
211
+ type="password",
212
+ )
213
+ txt_aoai_key = gr.Textbox(
214
+ label="Azure OpenAI API Key",
215
+ placeholder="Enter key and press enter",
216
+ max_lines=1,
217
+ show_label=True,
218
+ value=os.environ.get("AZURE_OPENAI_API_KEY", ""),
219
+ container=True,
220
+ type="password",
221
+ )
222
+ txt_aoai_base_url = gr.Textbox(
223
+ label="Azure OpenAI API Base",
224
+ placeholder="Enter base url and press enter",
225
+ max_lines=1,
226
+ show_label=True,
227
+ value=os.environ.get("AZURE_OPENAI_API_BASE", ""),
228
+ container=True,
229
+ type="password",
230
+ )
231
+
232
+ clear = gr.ClearButton([txt_input, chatbot])
233
+
234
+ with gr.Row():
235
+
236
+ def upload_file(file):
237
+ return update_context_url(file.name)
238
+
239
+
240
+ upload_button = gr.UploadButton(
241
+ "Click to upload a context file or enter a url in the right textbox",
242
+ file_types=[f".{i}" for i in TEXT_FORMATS],
243
+ file_count="single",
244
+ )
245
+
246
+ txt_context_url = gr.Textbox(
247
+ label="Enter the url to your context file and chat on the context",
248
+ info=f"File must be in the format of [{', '.join(TEXT_FORMATS)}]",
249
+ max_lines=1,
250
+ show_label=True,
251
+ value="https://raw.githubusercontent.com/microsoft/autogen/main/README.md",
252
+ container=True,
253
+ )
254
+
255
+ txt_prompt = gr.Textbox(
256
+ label="Enter your prompt for Retrieve Agent and press enter to replace the default prompt",
257
+ max_lines=40,
258
+ show_label=True,
259
+ value=PROMPT_CODE,
260
+ container=True,
261
+ show_copy_button=True,
262
+ )
263
+
264
+
265
+ def respond(message, chat_history, model, oai_key, aoai_key, aoai_base):
266
+ global config_list
267
+ set_params(model, oai_key, aoai_key, aoai_base)
268
+ config_list = update_config(config_list)
269
+ messages = chatbot_reply(message)
270
+ _msg = (
271
+ messages[-1]
272
+ if len(messages) > 0 and messages[-1] != "TERMINATE"
273
+ else messages[-2]
274
+ if len(messages) > 1
275
+ else "Context is not enough for answering the question. Please press `enter` in the context url textbox to make sure the context is activated for the chat."
276
+ )
277
+ chat_history.append((message, _msg))
278
+ return "", chat_history
279
+
280
+
281
+ def update_prompt(prompt):
282
+ ragproxyagent.customized_prompt = prompt
283
+ return prompt
284
+
285
+
286
+ def update_context_url(context_url):
287
+ global assistant, ragproxyagent
288
+
289
+ file_extension = Path(context_url).suffix
290
+ print("file_extension: ", file_extension)
291
+ if file_extension.lower() not in [f".{i}" for i in TEXT_FORMATS]:
292
+ return f"File must be in the format of {TEXT_FORMATS}"
293
+
294
+ if is_url(context_url):
295
+ try:
296
+ file_path = get_file_from_url(
297
+ context_url,
298
+ save_path=os.path.join("/tmp", os.path.basename(context_url)),
299
+ )
300
+ except Exception as e:
301
+ return str(e)
302
+ else:
303
+ file_path = context_url
304
+ context_url = os.path.basename(context_url)
305
+
306
+ try:
307
+ chromadb.PersistentClient(path="/tmp/chromadb").delete_collection(
308
+ name="autogen_rag"
309
+ )
310
+ except:
311
+ pass
312
+ assistant, ragproxyagent = initialize_agents(config_list, docs_path=file_path)
313
+ return context_url
314
+
315
+
316
+ txt_input.submit(
317
+ respond,
318
+ [txt_input, chatbot, txt_model, txt_oai_key, txt_aoai_key, txt_aoai_base_url],
319
+ [txt_input, chatbot],
320
+ )
321
+ txt_prompt.submit(update_prompt, [txt_prompt], [txt_prompt])
322
+ txt_context_url.submit(update_context_url, [txt_context_url], [txt_context_url])
323
+ upload_button.upload(upload_file, upload_button, [txt_context_url])
324
+
325
+ if __name__ == "__main__":
326
+ demo.launch(share=True, server_name="0.0.0.0")
autogen.png ADDED