-
Notifications
You must be signed in to change notification settings - Fork 0
/
chat_interface.py
595 lines (548 loc) · 25.6 KB
/
chat_interface.py
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
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
"""
This file defines a useful high-level abstraction to build Gradio chatbots: ChatInterface.
"""
from __future__ import annotations
import inspect
from typing import AsyncGenerator, Callable
import anyio
from gradio_client import utils as client_utils
from gradio_client.documentation import document, set_documentation_group
from gradio.blocks import Blocks
from gradio.components import (
Button,
UploadButton,
Chatbot,
IOComponent,
Markdown,
State,
Textbox,
get_component_instance,
)
from gradio.events import Dependency, EventListenerMethod
from gradio.helpers import create_examples as Examples # noqa: N812
from gradio.layouts import Accordion, Column, Group, Row
from gradio.themes import ThemeClass as Theme
from gradio.utils import SyncToAsyncIterator, async_iteration
set_documentation_group("chatinterface")
@document()
class ChatInterface(Blocks):
"""
ChatInterface is Gradio's high-level abstraction for creating chatbot UIs, and allows you to create
a web-based demo around a chatbot model in a few lines of code. Only one parameter is required: fn, which
takes a function that governs the response of the chatbot based on the user input and chat history. Additional
parameters can be used to control the appearance and behavior of the demo.
Example:
import gradio as gr
def echo(message, history):
return message
demo = gr.ChatInterface(fn=echo, examples=["hello", "hola", "merhaba"], title="Echo Bot")
demo.launch()
Demos: chatinterface_random_response, chatinterface_streaming_echo
Guides: creating-a-chatbot-fast, sharing-your-app
"""
def __init__(
self,
fn: Callable,
*,
chatbot: Chatbot | None = None,
textbox: Textbox | None = None,
additional_inputs: str | IOComponent | list[str | IOComponent] | None = None,
additional_inputs_accordion_name: str = "Additional Inputs",
additional_outputs: str | IOComponent | list[str | IOComponent] | None = None,
examples: list[str] | None = None,
cache_examples: bool | None = None,
title: str | None = None,
description: str | None = None,
theme: Theme | str | None = None,
css: str | None = None,
analytics_enabled: bool | None = None,
upload_btn: str | None | Button = None, # "📁",
audio_btn: str | None | Button = None, # "🎤",
submit_btn: str | None | Button = "Submit",
stop_btn: str | None | Button = "Stop",
retry_btn: str | None | Button = "🔄 Retry",
undo_btn: str | None | Button = "↩️ Undo",
clear_btn: str | None | Button = "🗑️ Clear",
autofocus: bool = True,
):
"""
Parameters:
fn: the function to wrap the chat interface around. Should accept two parameters: a string input message and list of two-element lists of the form [[user_message, bot_message], ...] representing the chat history, and return a string response. See the Chatbot documentation for more information on the chat history format.
chatbot: an instance of the gr.Chatbot component to use for the chat interface, if you would like to customize the chatbot properties. If not provided, a default gr.Chatbot component will be created.
textbox: an instance of the gr.Textbox component to use for the chat interface, if you would like to customize the textbox properties. If not provided, a default gr.Textbox component will be created.
additional_inputs: an instance or list of instances of gradio components (or their string shortcuts) to use as additional inputs to the chatbot. If components are not already rendered in a surrounding Blocks, then the components will be displayed under the chatbot, in an accordion.
additional_inputs_accordion_name: the label of the accordion to use for additional inputs, only used if additional_inputs is provided.
examples: sample inputs for the function; if provided, appear below the chatbot and can be clicked to populate the chatbot input.
cache_examples: If True, caches examples in the server for fast runtime in examples. The default option in HuggingFace Spaces is True. The default option elsewhere is False.
title: a title for the interface; if provided, appears above chatbot in large font. Also used as the tab title when opened in a browser window.
description: a description for the interface; if provided, appears above the chatbot and beneath the title in regular font. Accepts Markdown and HTML content.
theme: Theme to use, loaded from gradio.themes.
css: custom css or path to custom css file to use with interface.
analytics_enabled: Whether to allow basic telemetry. If None, will use GRADIO_ANALYTICS_ENABLED environment variable if defined, or default to True.
submit_btn: Text to display on the submit button. If None, no button will be displayed. If a Button object, that button will be used.
stop_btn: Text to display on the stop button, which replaces the submit_btn when the submit_btn or retry_btn is clicked and response is streaming. Clicking on the stop_btn will halt the chatbot response. If set to None, stop button functionality does not appear in the chatbot. If a Button object, that button will be used as the stop button.
retry_btn: Text to display on the retry button. If None, no button will be displayed. If a Button object, that button will be used.
undo_btn: Text to display on the delete last button. If None, no button will be displayed. If a Button object, that button will be used.
clear_btn: Text to display on the clear button. If None, no button will be displayed. If a Button object, that button will be used.
autofocus: If True, autofocuses to the textbox when the page loads.
"""
super().__init__(
analytics_enabled=analytics_enabled,
mode="chat_interface",
css=css,
title=title or "Gradio",
theme=theme,
)
self.fn = fn
self.is_async = inspect.iscoroutinefunction(
self.fn
) or inspect.isasyncgenfunction(self.fn)
self.is_generator = inspect.isgeneratorfunction(
self.fn
) or inspect.isasyncgenfunction(self.fn)
self.examples = examples
if self.space_id and cache_examples is None:
self.cache_examples = True
else:
self.cache_examples = cache_examples or False
self.buttons: list[Button] = []
if additional_inputs:
if not isinstance(additional_inputs, list):
additional_inputs = [additional_inputs]
self.additional_inputs = [
get_component_instance(i, render=False) for i in additional_inputs # type: ignore
]
else:
self.additional_inputs = []
self.additional_inputs_accordion_name = additional_inputs_accordion_name
if additional_outputs:
if not isinstance(additional_outputs, list):
additional_outputs = [additional_outputs]
self.additional_outputs = [
get_component_instance(i, render=False) for i in additional_outputs # type: ignore
]
else:
self.additional_outputs = []
with self:
if title:
Markdown(
f"<h1 style='text-align: center; margin-bottom: 1rem'>{self.title}</h1>"
)
if description:
Markdown(description)
with Column(variant="panel"):
if chatbot:
self.chatbot = chatbot.render()
else:
self.chatbot = Chatbot(label="Chatbot")
with Group():
with Row():
if upload_btn:
if isinstance(upload_btn, UploadButton):
upload_btn.render()
elif isinstance(upload_btn, str):
upload_btn = UploadButton(
upload_btn, scale=0.1, min_width=0
)
else:
raise ValueError(
f"The upload_btn parameter must be a gr.UploadButton, string, or None, not {type(upload_btn)}"
)
self.buttons.append(upload_btn)
if audio_btn:
if isinstance(audio_btn, Button):
audio_btn.render()
elif isinstance(audio_btn, str):
audio_btn = Button(
audio_btn, scale=0.1, min_width=0
)
else:
raise ValueError(
f"The audio_btn parameter must be a gr.Button, string, or None, not {type(audio_btn)}"
)
self.buttons.append(audio_btn)
if textbox:
textbox.container = False
textbox.show_label = False
self.textbox = textbox.render()
else:
self.textbox = Textbox(
container=False,
show_label=False,
label="Message",
placeholder="Type a message...",
scale=7,
autofocus=autofocus,
)
if submit_btn:
if isinstance(submit_btn, Button):
submit_btn.render()
elif isinstance(submit_btn, str):
submit_btn = Button(
submit_btn,
variant="primary",
scale=1,
min_width=0,
)
else:
raise ValueError(
f"The submit_btn parameter must be a gr.Button, string, or None, not {type(submit_btn)}"
)
if stop_btn:
if isinstance(stop_btn, Button):
stop_btn.visible = False
stop_btn.render()
elif isinstance(stop_btn, str):
stop_btn = Button(
stop_btn,
variant="stop",
visible=False,
scale=1,
min_width=0,
)
else:
raise ValueError(
f"The stop_btn parameter must be a gr.Button, string, or None, not {type(stop_btn)}"
)
self.buttons.extend([submit_btn, stop_btn])
with Row():
for btn in [retry_btn, undo_btn, clear_btn]:
if btn:
if isinstance(btn, Button):
btn.render()
elif isinstance(btn, str):
btn = Button(btn, variant="secondary", min_width=0)
else:
raise ValueError(
f"All the _btn parameters must be a gr.Button, string, or None, not {type(btn)}"
)
self.buttons.append(btn)
self.fake_api_btn = Button("Fake API", visible=False)
self.fake_response_textbox = Textbox(
label="Response", visible=False
)
(
self.upload_btn,
self.audio_btn,
self.submit_btn,
self.stop_btn,
self.retry_btn,
self.undo_btn,
self.clear_btn,
) = self.buttons
if examples:
if self.is_generator:
examples_fn = self._examples_stream_fn
else:
examples_fn = self._examples_fn
self.examples_handler = Examples(
examples=examples,
inputs=[self.textbox] + self.additional_inputs,
outputs=self.chatbot,
fn=examples_fn,
)
any_unrendered_inputs = any(
not inp.is_rendered for inp in self.additional_inputs
)
if self.additional_inputs and any_unrendered_inputs:
with Accordion(self.additional_inputs_accordion_name, open=False):
for input_component in self.additional_inputs:
if not input_component.is_rendered:
input_component.render()
# The example caching must happen after the input components have rendered
if cache_examples:
client_utils.synchronize_async(self.examples_handler.cache)
self.saved_input = State()
self.chatbot_state = State([])
self._setup_events()
self._setup_api()
def _setup_events(self) -> None:
submit_fn = self._stream_fn if self.is_generator else self._submit_fn
submit_event = (
self.textbox.submit(
self._clear_and_save_textbox,
[self.textbox],
[self.textbox, self.saved_input],
api_name=False,
queue=False,
)
.then(
self._display_input,
[self.saved_input, self.chatbot_state],
[self.chatbot, self.chatbot_state],
api_name=False,
queue=False,
)
.then(
submit_fn,
[self.saved_input, self.chatbot_state] + self.additional_inputs,
[self.chatbot, self.chatbot_state] + self.additional_outputs,
api_name=False,
)
)
self._setup_stop_events(self.textbox.submit, submit_event)
if self.upload_btn:
self.upload_btn.upload(
self._upload_fn,
[self.textbox, self.upload_btn],
[self.textbox], queue=False, api_name='upload')
if self.audio_btn:
pass # transcribe function is proccessed outside of this code
if self.submit_btn:
click_event = (
self.submit_btn.click(
self._clear_and_save_textbox,
[self.textbox],
[self.textbox, self.saved_input],
api_name=False,
queue=False,
)
.then(
self._display_input,
[self.saved_input, self.chatbot_state],
[self.chatbot, self.chatbot_state],
api_name=False,
queue=False,
)
.then(
submit_fn,
[self.saved_input, self.chatbot_state] + self.additional_inputs,
[self.chatbot, self.chatbot_state] + self.additional_outputs,
api_name=False,
)
)
self._setup_stop_events(self.submit_btn.click, click_event)
if self.retry_btn:
retry_event = (
self.retry_btn.click(
self._delete_prev_fn,
[self.chatbot_state],
[self.chatbot, self.saved_input, self.chatbot_state],
api_name=False,
queue=False,
)
.then(
self._display_input,
[self.saved_input, self.chatbot_state],
[self.chatbot, self.chatbot_state],
api_name=False,
queue=False,
)
.then(
submit_fn,
[self.saved_input, self.chatbot_state] + self.additional_inputs,
[self.chatbot, self.chatbot_state] + self.additional_outputs,
api_name=False,
)
)
self._setup_stop_events(self.retry_btn.click, retry_event)
if self.undo_btn:
self.undo_btn.click(
self._delete_prev_fn,
[self.chatbot_state],
[self.chatbot, self.saved_input, self.chatbot_state],
api_name=False,
queue=False,
).then(
lambda x: x,
[self.saved_input],
[self.textbox],
api_name=False,
queue=False,
)
if self.clear_btn:
self.clear_btn.click(
lambda: ([], [], None),
None,
[self.chatbot, self.chatbot_state, self.saved_input],
queue=False,
api_name=False,
)
def _setup_stop_events(
self, event_trigger: EventListenerMethod, event_to_cancel: Dependency
) -> None:
if self.stop_btn and self.is_generator:
if self.submit_btn:
event_trigger(
lambda: (Button.update(visible=False), Button.update(visible=True)),
None,
[self.submit_btn, self.stop_btn],
api_name=False,
queue=False,
)
event_to_cancel.then(
lambda: (Button.update(visible=True), Button.update(visible=False)),
None,
[self.submit_btn, self.stop_btn],
api_name=False,
queue=False,
)
else:
event_trigger(
lambda: Button.update(visible=True),
None,
[self.stop_btn],
api_name=False,
queue=False,
)
event_to_cancel.then(
lambda: Button.update(visible=False),
None,
[self.stop_btn],
api_name=False,
queue=False,
)
self.stop_btn.click(
None,
None,
None,
cancels=event_to_cancel,
api_name=False,
)
def _setup_api(self) -> None:
api_fn = self._api_stream_fn if self.is_generator else self._api_submit_fn
self.fake_api_btn.click(
api_fn,
[self.textbox, self.chatbot_state] + self.additional_inputs,
[self.textbox, self.chatbot_state],
api_name="chat",
)
def _clear_and_save_textbox(self, message: str) -> tuple[str, str]:
return "", message
def _display_input(
self, message: str, history: list[list[str | None]]
) -> tuple[list[list[str | None]], list[list[str | None]]]:
history.append([message, None])
return history, history
def __additional_outputs_return(self, message, history, response, mode='submit'):
response, additional = (response[0], response[1:]) if len(self.additional_outputs) > 0 else (response, tuple())
if mode in ['submit', 'api_submit']:
history.append([message, response])
return (history, history) + additional
elif mode == 'stream':
update = history + [[message, response]]
return (update, update) + additional
elif mode == 'api_stream':
return (response, history + [[message, response]]) + additional
else:
raise ValueError(f"Invalid mode: {mode}")
async def _submit_fn(
self,
message: str,
history_with_input: list[list[str | None]],
*args,
) -> tuple[list[list[str | None]], list[list[str | None]]]:
history = history_with_input[:-1]
if self.is_async:
response = await self.fn(message, history, *args)
else:
response = await anyio.to_thread.run_sync(
self.fn, message, history, *args, limiter=self.limiter
)
return self.__additional_outputs_return(message, history, response, mode='submit')
# history.append([message, response])
# return history, history
async def _stream_fn(
self,
message: str,
history_with_input: list[list[str | None]],
*args,
) -> AsyncGenerator:
history = history_with_input[:-1]
if self.is_async:
generator = self.fn(message, history, *args)
else:
generator = await anyio.to_thread.run_sync(
self.fn, message, history, *args, limiter=self.limiter
)
generator = SyncToAsyncIterator(generator, self.limiter)
try:
first_response = await async_iteration(generator)
yield self.__additional_outputs_return(message, history, first_response, mode='stream')
# update = history + [[message, first_response]]
# yield update, update
except StopIteration:
yield self.__additional_outputs_return(message, history, None, mode='stream')
# update = history + [[message, None]]
# yield update, update
async for response in generator:
yield self.__additional_outputs_return(message, history, response, mode='stream')
# update = history + [[message, response]]
# yield update, update
async def _api_submit_fn(
self, message: str, history: list[list[str | None]], *args
) -> tuple[str, list[list[str | None]]]:
if self.is_async:
response = await self.fn(message, history, *args)
else:
response = await anyio.to_thread.run_sync(
self.fn, message, history, *args, limiter=self.limiter
)
return self.__additional_outputs_return(message, history, response, mode='api_submit')
# history.append([message, response])
# return response, history
async def _api_stream_fn(
self, message: str, history: list[list[str | None]], *args
) -> AsyncGenerator:
if self.is_async:
generator = self.fn(message, history, *args)
else:
generator = await anyio.to_thread.run_sync(
self.fn, message, history, *args, limiter=self.limiter
)
generator = SyncToAsyncIterator(generator, self.limiter)
try:
first_response = await async_iteration(generator)
yield self.__additional_outputs_return(message, history, first_response, mode='api_stream')
# yield first_response, history + [[message, first_response]]
except StopIteration:
yield self.__additional_outputs_return(message, history, None, mode='api_stream')
# yield None, history + [[message, None]]
async for response in generator:
yield self.__additional_outputs_return(message, history, response, mode='api_stream')
# yield response, history + [[message, response]]
async def _examples_fn(self, message: str, *args) -> list[list[str | None]]:
if self.is_async:
response = await self.fn(message, [], *args)
else:
response = await anyio.to_thread.run_sync(
self.fn, message, [], *args, limiter=self.limiter
)
return [[message, response]]
async def _examples_stream_fn(
self,
message: str,
*args,
) -> AsyncGenerator:
if self.is_async:
generator = self.fn(message, [], *args)
else:
generator = await anyio.to_thread.run_sync(
self.fn, message, [], *args, limiter=self.limiter
)
generator = SyncToAsyncIterator(generator, self.limiter)
async for response in generator:
yield [[message, response]]
def _delete_prev_fn(
self, history: list[list[str | None]]
) -> tuple[list[list[str | None]], str, list[list[str | None]]]:
try:
message, _ = history.pop()
except IndexError:
message = ""
return history, message or "", history
def _upload_fn(self, msg, filepath_or_filename):
if filepath_or_filename is None:
return msg
filename = filepath_or_filename.name if hasattr(filepath_or_filename, 'name') else filepath_or_filename
import os, mimetypes
mtype = mimetypes.guess_type(filename)[0]
if mtype.startswith('image'):
msg += f'<img src="\\file={filename}" alt="{os.path.basename(filename)}"/>'
elif mtype.startswith('audio'):
msg += f'<audio controls><source src="\\file={filename}">{os.path.basename(filename)}</audio>'
elif mtype.startswith('video'):
msg += f'<video controls><source src="\\file={filename}">{os.path.basename(filename)}</video>'
else:
msg += f'<a href="\\file={filename}">📁 {os.path.basename(filename)}</a>'
return msg