forestcalled/text-generation-webui
0
1# Extensions2 3Extensions are defined by files named `script.py` inside subfolders of `text-generation-webui/extensions`. They are loaded at startup if the folder name is specified after the `--extensions` flag.4 5For instance, `extensions/silero_tts/script.py` gets loaded with `python server.py --extensions silero_tts`.6 7## [text-generation-webui-extensions](https://github.com/oobabooga/text-generation-webui-extensions)8 9The repository above contains a directory of user extensions.10 11If you create an extension, you are welcome to host it in a GitHub repository and submit a PR adding it to the list.12 13## Built-in extensions14 15|Extension|Description|16|---------|-----------|17|[openai](https://github.com/oobabooga/text-generation-webui/tree/main/extensions/openai)| Creates an API that mimics the OpenAI API and can be used as a drop-in replacement. |18|[multimodal](https://github.com/oobabooga/text-generation-webui/tree/main/extensions/multimodal) | Adds multimodality support (text+images). For a detailed description see [README.md](https://github.com/oobabooga/text-generation-webui/tree/main/extensions/multimodal/README.md) in the extension directory. |19|[google_translate](https://github.com/oobabooga/text-generation-webui/tree/main/extensions/google_translate)| Automatically translates inputs and outputs using Google Translate.|20|[silero_tts](https://github.com/oobabooga/text-generation-webui/tree/main/extensions/silero_tts)| Text-to-speech extension using [Silero](https://github.com/snakers4/silero-models). When used in chat mode, responses are replaced with an audio widget. |21|[whisper_stt](https://github.com/oobabooga/text-generation-webui/tree/main/extensions/whisper_stt)| Allows you to enter your inputs in chat mode using your microphone. |22|[sd_api_pictures](https://github.com/oobabooga/text-generation-webui/tree/main/extensions/sd_api_pictures)| Allows you to request pictures from the bot in chat mode, which will be generated using the AUTOMATIC1111 Stable Diffusion API. See examples [here](https://github.com/oobabooga/text-generation-webui/pull/309). |23|[character_bias](https://github.com/oobabooga/text-generation-webui/tree/main/extensions/character_bias)| Just a very simple example that adds a hidden string at the beginning of the bot's reply in chat mode. |24|[send_pictures](https://github.com/oobabooga/text-generation-webui/blob/main/extensions/send_pictures/)| Creates an image upload field that can be used to send images to the bot in chat mode. Captions are automatically generated using BLIP. |25|[gallery](https://github.com/oobabooga/text-generation-webui/blob/main/extensions/gallery/)| Creates a gallery with the chat characters and their pictures. |26|[superbooga](https://github.com/oobabooga/text-generation-webui/tree/main/extensions/superbooga)| An extension that uses ChromaDB to create an arbitrarily large pseudocontext, taking as input text files, URLs, or pasted text. Based on https://github.com/kaiokendev/superbig. |27|[ngrok](https://github.com/oobabooga/text-generation-webui/tree/main/extensions/ngrok)| Allows you to access the web UI remotely using the ngrok reverse tunnel service (free). It's an alternative to the built-in Gradio `--share` feature. |28|[perplexity_colors](https://github.com/oobabooga/text-generation-webui/tree/main/extensions/perplexity_colors)| Colors each token in the output text by its associated probability, as derived from the model logits. |29 30## How to write an extension31 32The extensions framework is based on special functions and variables that you can define in `script.py`. The functions are the following:33 34| Function | Description |35|-------------|-------------|36| `def setup()` | Is executed when the extension gets imported. |37| `def ui()` | Creates custom gradio elements when the UI is launched. | 38| `def custom_css()` | Returns custom CSS as a string. It is applied whenever the web UI is loaded. |39| `def custom_js()` | Same as above but for javascript. |40| `def input_modifier(string, state, is_chat=False)` | Modifies the input string before it enters the model. In chat mode, it is applied to the user message. Otherwise, it is applied to the entire prompt. |41| `def output_modifier(string, state, is_chat=False)` | Modifies the output string before it is presented in the UI. In chat mode, it is applied to the bot's reply. Otherwise, it is applied to the entire output. |42| `def chat_input_modifier(text, visible_text, state)` | Modifies both the visible and internal inputs in chat mode. Can be used to hijack the chat input with custom content. |43| `def bot_prefix_modifier(string, state)` | Applied in chat mode to the prefix for the bot's reply. |44| `def state_modifier(state)` | Modifies the dictionary containing the UI input parameters before it is used by the text generation functions. |45| `def history_modifier(history)` | Modifies the chat history before the text generation in chat mode begins. |46| `def custom_generate_reply(...)` | Overrides the main text generation function. |47| `def custom_generate_chat_prompt(...)` | Overrides the prompt generator in chat mode. |48| `def tokenizer_modifier(state, prompt, input_ids, input_embeds)` | Modifies the `input_ids`/`input_embeds` fed to the model. Should return `prompt`, `input_ids`, `input_embeds`. See the `multimodal` extension for an example. |49| `def custom_tokenized_length(prompt)` | Used in conjunction with `tokenizer_modifier`, returns the length in tokens of `prompt`. See the `multimodal` extension for an example. |50 51Additionally, you can define a special `params` dictionary. In it, the `display_name` key is used to define the displayed name of the extension in the UI, and the `is_tab` key is used to define whether the extension should appear in a new tab. By default, extensions appear at the bottom of the "Text generation" tab.52 53Example:54 55```python56params = {57 "display_name": "Google Translate",58 "is_tab": True,59}60```61 62The `params` dict may also contain variables that you want to be customizable through a `settings.yaml` file. For instance, assuming the extension is in `extensions/google_translate`, the variable `language string` in63 64```python65params = {66 "display_name": "Google Translate",67 "is_tab": True,68 "language string": "jp"69}70```71 72can be customized by adding a key called `google_translate-language string` to `settings.yaml`:73 74```python75google_translate-language string: 'fr'76``` 77 78That is, the syntax for the key is `extension_name-variable_name`.79 80## Using multiple extensions at the same time81 82You can activate more than one extension at a time by providing their names separated by spaces after `--extensions`. The input, output, and bot prefix modifiers will be applied in the specified order. 83 84Example:85 86```87python server.py --extensions enthusiasm translate # First apply enthusiasm, then translate88python server.py --extensions translate enthusiasm # First apply translate, then enthusiasm89```90 91Do note, that for:92- `custom_generate_chat_prompt`93- `custom_generate_reply`94- `custom_tokenized_length`95 96only the first declaration encountered will be used and the rest will be ignored. 97 98## A full example99 100The source code below can be found at [extensions/example/script.py](https://github.com/oobabooga/text-generation-webui/tree/main/extensions/example/script.py).101 102```python103"""104An example of extension. It does nothing, but you can add transformations105before the return statements to customize the webui behavior.106 107Starting from history_modifier and ending in output_modifier, the108functions are declared in the same order that they are called at109generation time.110"""111 112import gradio as gr113import torch114from transformers import LogitsProcessor115 116from modules import chat, shared117from modules.text_generation import (118 decode,119 encode,120 generate_reply,121)122 123params = {124 "display_name": "Example Extension",125 "is_tab": False,126}127 128class MyLogits(LogitsProcessor):129 """130 Manipulates the probabilities for the next token before it gets sampled.131 Used in the logits_processor_modifier function below.132 """133 def __init__(self):134 pass135 136 def __call__(self, input_ids, scores):137 # probs = torch.softmax(scores, dim=-1, dtype=torch.float)138 # probs[0] /= probs[0].sum()139 # scores = torch.log(probs / (1 - probs))140 return scores141 142def history_modifier(history):143 """144 Modifies the chat history.145 Only used in chat mode.146 """147 return history148 149def state_modifier(state):150 """151 Modifies the state variable, which is a dictionary containing the input152 values in the UI like sliders and checkboxes.153 """154 return state155 156def chat_input_modifier(text, visible_text, state):157 """158 Modifies the user input string in chat mode (visible_text).159 You can also modify the internal representation of the user160 input (text) to change how it will appear in the prompt.161 """162 return text, visible_text163 164def input_modifier(string, state, is_chat=False):165 """166 In default/notebook modes, modifies the whole prompt.167 168 In chat mode, it is the same as chat_input_modifier but only applied169 to "text", here called "string", and not to "visible_text".170 """171 return string172 173def bot_prefix_modifier(string, state):174 """175 Modifies the prefix for the next bot reply in chat mode.176 By default, the prefix will be something like "Bot Name:".177 """178 return string179 180def tokenizer_modifier(state, prompt, input_ids, input_embeds):181 """182 Modifies the input ids and embeds.183 Used by the multimodal extension to put image embeddings in the prompt.184 Only used by loaders that use the transformers library for sampling.185 """186 return prompt, input_ids, input_embeds187 188def logits_processor_modifier(processor_list, input_ids):189 """190 Adds logits processors to the list, allowing you to access and modify191 the next token probabilities.192 Only used by loaders that use the transformers library for sampling.193 """194 processor_list.append(MyLogits())195 return processor_list196 197def output_modifier(string, state, is_chat=False):198 """199 Modifies the LLM output before it gets presented.200 201 In chat mode, the modified version goes into history['visible'],202 and the original version goes into history['internal'].203 """204 return string205 206def custom_generate_chat_prompt(user_input, state, **kwargs):207 """208 Replaces the function that generates the prompt from the chat history.209 Only used in chat mode.210 """211 result = chat.generate_chat_prompt(user_input, state, **kwargs)212 return result213 214def custom_css():215 """216 Returns a CSS string that gets appended to the CSS for the webui.217 """218 return ''219 220def custom_js():221 """222 Returns a javascript string that gets appended to the javascript223 for the webui.224 """225 return ''226 227def setup():228 """229 Gets executed only once, when the extension is imported.230 """231 pass232 233def ui():234 """235 Gets executed when the UI is drawn. Custom gradio elements and236 their corresponding event handlers should be defined here.237 238 To learn about gradio components, check out the docs:239 https://gradio.app/docs/240 """241 pass242```243 