Spaces:
Paused
Paused
Upload folder using huggingface_hub
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .github/ISSUE_TEMPLATE/bug_report_template.ymlAdded+53
- .github/ISSUE_TEMPLATE/feature_request.mdAdded+16
- .github/dependabot.ymlAdded+14
- .github/pull_request_template.mdAdded+3
- .github/workflows/build-everything-tgw.ymlAdded+63
- .github/workflows/build-portable-release-cuda.ymlAdded+189
- .github/workflows/build-portable-release-vulkan.ymlAdded+177
- .github/workflows/build-portable-release.ymlAdded+203
- .gitignoreAdded+33
- LICENSEAdded+661
- README.md+440-8
- cmd_linux.shAdded+22
- cmd_macos.shAdded+24
- cmd_windows.batAdded+34
- docker/.dockerignoreAdded+8
- docker/.env.exampleAdded+24
- docker/TensorRT-LLM/DockerfileAdded+27
- docker/amd/DockerfileAdded+21
- docker/amd/docker-compose.ymlAdded+44
- docker/cpu/DockerfileAdded+25
- docker/cpu/docker-compose.ymlAdded+44
- docker/intel/DockerfileAdded+21
- docker/intel/docker-compose.ymlAdded+44
- docker/nvidia/DockerfileAdded+21
- docker/nvidia/docker-compose.ymlAdded+41
- docs/01 - Chat Tab.mdAdded+148
- docs/02 - Default and Notebook Tabs.mdAdded+35
- docs/03 - Parameters Tab.mdAdded+128
- docs/04 - Model Tab.mdAdded+129
- docs/05 - Training Tab.mdAdded+139
- docs/06 - Session Tab.mdAdded+32
- docs/07 - Extensions.mdAdded+248
- docs/08 - Additional Tips.mdAdded+60
- docs/09 - Docker.mdAdded+208
- docs/11 - AMD Setup.mdAdded+13
- docs/12 - OpenAI API.mdAdded+550
- docs/13 - Keyboard Shortcuts.mdAdded+19
- docs/Multimodal Tutorial.mdAdded+66
- docs/README.mdAdded+5
- docs/What Works.mdAdded+20
- download-model.pyAdded+427
- js/dark_theme.jsAdded+20
- js/global_scope_js.jsAdded+389
- js/highlightjs/highlight.min.jsAdded
- js/highlightjs/highlightjs-copy.min.jsAdded+1
- js/katex/auto-render.min.jsAdded+1
- js/katex/katex.min.jsAdded
- js/main.jsAdded+1107
- js/morphdom/morphdom-umd.min.jsAdded+1
- js/save_files.jsAdded+40
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253name: "Bug report"description: Report a buglabels: [ "bug" ]body: - type: markdown attributes: value: | Thanks for taking the time to fill out this bug report! - type: textarea id: bug-description attributes: label: Describe the bug description: A clear and concise description of what the bug is. placeholder: Bug description validations: required: true - type: checkboxes attributes: label: Is there an existing issue for this? description: Please search to see if an issue already exists for the issue you encountered. options: - label: I have searched the existing issues required: true - type: textarea id: reproduction attributes: label: Reproduction description: Please provide the steps necessary to reproduce your issue. placeholder: Reproduction validations: required: true - type: textarea id: screenshot attributes: label: Screenshot description: "If possible, please include screenshot(s) so that we can understand what the issue is." - type: textarea id: logs attributes: label: Logs description: "Please include the full stacktrace of the errors you get in the command-line (if any)." render: shell validations: required: true - type: textarea id: system-info attributes: label: System Info description: "Please share your operating system and GPU type (NVIDIA/AMD/Intel/Apple). If you are using a Google Colab notebook, mention that instead." render: shell placeholder: validations: required: true12345678910111213141516---name: Feature requestabout: Suggest an improvement or new feature for the web UItitle: ''labels: 'enhancement'assignees: ''
---
**Description**
A clear and concise description of what you want to be implemented.
**Additional Context**
If applicable, please provide any extra information, external links, or screenshots that could be useful.1234567891011121314# To get started with Dependabot version updates, you'll need to specify which# package ecosystems to update and where the package manifests are located.# Please see the documentation for all configuration options:# https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates
version: 2updates: - package-ecosystem: "pip" directories: - "/requirements/full/" - "/requirements/portable/" target-branch: "dev" schedule: interval: "weekly"123## Checklist:
- [ ] I have read the [Contributing guidelines](https://github.com/oobabooga/text-generation-webui/wiki/Contributing-guidelines).123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263name: Build Everything TGW
on: workflow_dispatch: inputs: version: description: 'Version tag of text-generation-webui to build: v3.0' default: 'v3.0' required: true type: string
permissions: contents: write
jobs: build_release_cuda_windows: name: CUDA Windows uses: ./.github/workflows/build-portable-release-cuda.yml with: version: ${{ inputs.version }} config: 'os:windows-2022'
build_release_cuda_linux: name: CUDA Linux uses: ./.github/workflows/build-portable-release-cuda.yml with: version: ${{ inputs.version }} config: 'os:ubuntu-22.04'
build_release_vulkan_windows: name: Vulkan Windows uses: ./.github/workflows/build-portable-release-vulkan.yml with: version: ${{ inputs.version }} config: 'os:windows-2022'
build_release_vulkan_linux: name: Vulkan Linux uses: ./.github/workflows/build-portable-release-vulkan.yml with: version: ${{ inputs.version }} config: 'os:ubuntu-22.04'
build_release_cpu_windows: name: CPU Windows uses: ./.github/workflows/build-portable-release.yml with: version: ${{ inputs.version }} config: 'os:windows-2022'
build_release_cpu_linux: name: CPU Linux uses: ./.github/workflows/build-portable-release.yml with: version: ${{ inputs.version }} config: 'os:ubuntu-22.04'
build_release_macos: name: macOS uses: ./.github/workflows/build-portable-release.yml with: version: ${{ inputs.version }} config: 'os:macos-13,macos-14'123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189name: Build CUDA
on: workflow_dispatch: inputs: version: description: 'Version tag of text-generation-webui to build: v3.0' default: 'v3.0' required: true type: string config: description: 'Override configurations to build: key1:item1-1,item1-2;key2:item2-1,item2-2' default: 'Default' required: false type: string exclude: description: 'Exclude build configurations: key1-1:item1-1,key1-2:item1-2;key2-1:item2-1,key2-2:item2-2' default: 'None' required: false type: string workflow_call: inputs: version: description: 'Version tag of text-generation-webui to build: v3.0' default: 'v3.0' required: true type: string config: description: 'Configurations to build: key1:item1-1,item1-2;key2:item2-1,item2-2' default: 'Default' required: false type: string exclude: description: 'Exclude build configurations: key1-1:item1-1,key1-2:item1-2;key2-1:item2-1,key2-2:item2-2' default: 'None' required: false type: string
permissions: contents: write
jobs: define_matrix: name: Define Build Matrix runs-on: ubuntu-latest outputs: matrix: ${{ steps.set-matrix.outputs.matrix }} defaults: run: shell: pwsh env: CONFIGIN: ${{ inputs.config }} EXCLUDEIN: ${{ inputs.exclude }}
steps: - name: Define Job Output id: set-matrix run: | $matrix = @{ 'os' = @('ubuntu-22.04', 'windows-2022') 'pyver' = @("3.11") 'avx' = @("AVX2") 'cuda' = @("11.7", "12.4") }
if ($env:CONFIGIN -ne 'Default') {$env:CONFIGIN.split(';').foreach({$matrix[$_.split(':')[0]] = $_.split(':')[1].split(',')})}
if ($env:EXCLUDEIN -ne 'None') { $exclusions = @() $exclusions += $env:EXCLUDEIN.split(';').replace(':','=').replace(',',"`n") | ConvertFrom-StringData $matrix['exclude'] = $exclusions }
$matrixOut = ConvertTo-Json $matrix -Compress Write-Output ('matrix=' + $matrixOut) >> $env:GITHUB_OUTPUT
build_wheels: name: ${{ matrix.os }} ${{ matrix.pyver }} CPU ${{ matrix.avx }} CUDA ${{ matrix.cuda }} needs: define_matrix runs-on: ${{ matrix.os }} strategy: matrix: ${{ fromJSON(needs.define_matrix.outputs.matrix) }} defaults: run: shell: pwsh env: AVXVER: ${{ matrix.avx }} PCKGVER: ${{ inputs.version }}
steps: - uses: actions/checkout@v4 with: repository: 'oobabooga/text-generation-webui' ref: ${{ inputs.version }} submodules: 'recursive'
- uses: actions/setup-python@v4 with: python-version: ${{ matrix.pyver }}
- name: Build Package shell: bash run: | VERSION_CLEAN="${{ inputs.version }}" VERSION_CLEAN="${VERSION_CLEAN#v}" cd .. cp -r text-generation-webui "text-generation-webui-${VERSION_CLEAN}" cd "text-generation-webui-${VERSION_CLEAN}"
# Remove extensions that need additional requirements allowed=("character_bias" "gallery" "openai" "sd_api_pictures") find extensions/ -mindepth 1 -maxdepth 1 -type d | grep -v -E "$(printf '%s|' "${allowed[@]}" | sed 's/|$//')" | xargs rm -rf
# Define common variables CUDA_VERSION="${{ matrix.cuda }}" AVX_SUPPORT="${{ matrix.avx }}" VERSION="${{ inputs.version }}"
# 1. Set platform-specific variables if [[ "$RUNNER_OS" == "Windows" ]]; then PLATFORM="windows" PYTHON_URL="https://github.com/astral-sh/python-build-standalone/releases/download/20250409/cpython-3.11.12+20250409-x86_64-pc-windows-msvc-install_only.tar.gz" PIP_PATH="portable_env/python.exe -m pip" PACKAGES_PATH="portable_env/Lib/site-packages" rm start_linux.sh start_macos.sh else PLATFORM="linux" PYTHON_URL="https://github.com/astral-sh/python-build-standalone/releases/download/20250409/cpython-3.11.12+20250409-x86_64-unknown-linux-gnu-install_only.tar.gz" PIP_PATH="portable_env/bin/python -m pip" PACKAGES_PATH="portable_env/lib/python3.11/site-packages" rm start_macos.sh start_windows.bat fi
# 2. Download and extract Python cd .. echo "Downloading Python for $PLATFORM..." curl -L -o python-build.tar.gz "$PYTHON_URL" tar -xzf python-build.tar.gz mv python "text-generation-webui-${VERSION_CLEAN}/portable_env"
# 3. Prepare requirements file based on AVX and CUDA if [[ "$AVX_SUPPORT" == "AVX2" ]]; then BASE_REQ_FILE="requirements/portable/requirements.txt" else BASE_REQ_FILE="requirements/portable/requirements_noavx2.txt" fi
# Create CUDA-specific requirements file if needed cd "text-generation-webui-${VERSION_CLEAN}" if [[ "$CUDA_VERSION" == "11.7" ]]; then echo "Creating CUDA 11.7 specific requirements file" sed 's/cu124/cu117/g' "$BASE_REQ_FILE" > requirements_cuda_temp.txt REQ_FILE="requirements_cuda_temp.txt" else REQ_FILE="$BASE_REQ_FILE" fi
# 4. Install packages echo "Installing Python packages from $REQ_FILE..." $PIP_PATH install --target="./$PACKAGES_PATH" -r "$REQ_FILE"
# 5. Clean up if [[ "$CUDA_VERSION" == "11.7" ]]; then rm requirements_cuda_temp.txt fi rm -rf .git cmd* update_wizard* Colab-TextGen-GPU.ipynb docker setup.cfg .github .gitignore requirements/ one_click.py
# 6. Create ZIP file cd .. ZIP_NAME="textgen-portable-${VERSION_CLEAN}-${PLATFORM}-cuda${CUDA_VERSION}.zip" echo "Creating archive: $ZIP_NAME"
if [[ "$RUNNER_OS" == "Windows" ]]; then powershell -Command "Compress-Archive -Path text-generation-webui-${VERSION_CLEAN} -DestinationPath $ZIP_NAME" else zip -r "$ZIP_NAME" "text-generation-webui-${VERSION_CLEAN}" fi
- name: Upload files to a GitHub release id: upload-release uses: svenstaro/upload-release-action@2.7.0 continue-on-error: true with: repo_token: ${{ secrets.GITHUB_TOKEN }} file: ../textgen-portable-*.zip tag: ${{ inputs.version }} file_glob: true make_latest: false overwrite: true123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177name: Build Vulkan
on: workflow_dispatch: inputs: version: description: 'Version tag of text-generation-webui to build: v3.0' default: 'v3.0' required: true type: string config: description: 'Override configurations to build: key1:item1-1,item1-2;key2:item2-1,item2-2' default: 'Default' required: false type: string exclude: description: 'Exclude build configurations: key1-1:item1-1,key1-2:item1-2;key2-1:item2-1,key2-2:item2-2' default: 'None' required: false type: string workflow_call: inputs: version: description: 'Version tag of text-generation-webui to build: v3.0' default: 'v3.0' required: true type: string config: description: 'Configurations to build: key1:item1-1,item1-2;key2:item2-1,item2-2' default: 'Default' required: false type: string exclude: description: 'Exclude build configurations: key1-1:item1-1,key1-2:item1-2;key2-1:item2-1,key2-2:item2-2' default: 'None' required: false type: string
permissions: contents: write
jobs: define_matrix: name: Define Build Matrix runs-on: ubuntu-latest outputs: matrix: ${{ steps.set-matrix.outputs.matrix }} defaults: run: shell: pwsh env: CONFIGIN: ${{ inputs.config }} EXCLUDEIN: ${{ inputs.exclude }}
steps: - name: Define Job Output id: set-matrix run: | $matrix = @{ 'os' = @('ubuntu-22.04', 'windows-2022') 'pyver' = @("3.11") 'avx' = @("AVX2") }
if ($env:CONFIGIN -ne 'Default') {$env:CONFIGIN.split(';').foreach({$matrix[$_.split(':')[0]] = $_.split(':')[1].split(',')})}
if ($env:EXCLUDEIN -ne 'None') { $exclusions = @() $exclusions += $env:EXCLUDEIN.split(';').replace(':','=').replace(',',"`n") | ConvertFrom-StringData $matrix['exclude'] = $exclusions }
$matrixOut = ConvertTo-Json $matrix -Compress Write-Output ('matrix=' + $matrixOut) >> $env:GITHUB_OUTPUT
build_wheels: name: ${{ matrix.os }} ${{ matrix.pyver }} CPU ${{ matrix.avx }} needs: define_matrix runs-on: ${{ matrix.os }} strategy: matrix: ${{ fromJSON(needs.define_matrix.outputs.matrix) }} defaults: run: shell: pwsh env: AVXVER: ${{ matrix.avx }} PCKGVER: ${{ inputs.version }}
steps: - uses: actions/checkout@v4 with: repository: 'oobabooga/text-generation-webui' ref: ${{ inputs.version }} submodules: 'recursive'
- uses: actions/setup-python@v4 with: python-version: ${{ matrix.pyver }}
- name: Build Package shell: bash run: | VERSION_CLEAN="${{ inputs.version }}" VERSION_CLEAN="${VERSION_CLEAN#v}" cd .. cp -r text-generation-webui "text-generation-webui-${VERSION_CLEAN}" cd "text-generation-webui-${VERSION_CLEAN}"
# Remove extensions that need additional requirements allowed=("character_bias" "gallery" "openai" "sd_api_pictures") find extensions/ -mindepth 1 -maxdepth 1 -type d | grep -v -E "$(printf '%s|' "${allowed[@]}" | sed 's/|$//')" | xargs rm -rf
# Define common variables AVX_SUPPORT="${{ matrix.avx }}" VERSION="${{ inputs.version }}"
# 1. Set platform-specific variables if [[ "$RUNNER_OS" == "Windows" ]]; then PLATFORM="windows" PYTHON_URL="https://github.com/astral-sh/python-build-standalone/releases/download/20250409/cpython-3.11.12+20250409-x86_64-pc-windows-msvc-install_only.tar.gz" PIP_PATH="portable_env/python.exe -m pip" PACKAGES_PATH="portable_env/Lib/site-packages" rm start_linux.sh start_macos.sh else PLATFORM="linux" PYTHON_URL="https://github.com/astral-sh/python-build-standalone/releases/download/20250409/cpython-3.11.12+20250409-x86_64-unknown-linux-gnu-install_only.tar.gz" PIP_PATH="portable_env/bin/python -m pip" PACKAGES_PATH="portable_env/lib/python3.11/site-packages" rm start_macos.sh start_windows.bat fi
# 2. Download and extract Python cd .. echo "Downloading Python for $PLATFORM..." curl -L -o python-build.tar.gz "$PYTHON_URL" tar -xzf python-build.tar.gz mv python "text-generation-webui-${VERSION_CLEAN}/portable_env"
# 3. Prepare requirements file based on AVX if [[ "$AVX_SUPPORT" == "AVX2" ]]; then BASE_REQ_FILE="requirements/portable/requirements_vulkan.txt" else BASE_REQ_FILE="requirements/portable/requirements_vulkan_noavx2.txt" fi REQ_FILE="$BASE_REQ_FILE"
cd "text-generation-webui-${VERSION_CLEAN}"
# 4. Install packages echo "Installing Python packages from $REQ_FILE..." $PIP_PATH install --target="./$PACKAGES_PATH" -r "$REQ_FILE"
# 5. Clean up rm -rf .git cmd* update_wizard* Colab-TextGen-GPU.ipynb docker setup.cfg .github .gitignore requirements/ one_click.py
# 6. Create ZIP file cd .. ZIP_NAME="textgen-portable-${VERSION_CLEAN}-${PLATFORM}-vulkan.zip" echo "Creating archive: $ZIP_NAME"
if [[ "$RUNNER_OS" == "Windows" ]]; then powershell -Command "Compress-Archive -Path text-generation-webui-${VERSION_CLEAN} -DestinationPath $ZIP_NAME" else zip -r "$ZIP_NAME" "text-generation-webui-${VERSION_CLEAN}" fi
- name: Upload files to a GitHub release id: upload-release uses: svenstaro/upload-release-action@2.7.0 continue-on-error: true with: repo_token: ${{ secrets.GITHUB_TOKEN }} file: ../textgen-portable-*.zip tag: ${{ inputs.version }} file_glob: true make_latest: false overwrite: true123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203name: Build CPU and macOS
on: workflow_dispatch: inputs: version: description: 'Version tag of text-generation-webui to build: v3.0' default: 'v3.0' required: true type: string config: description: 'Override configurations to build: key1:item1-1,item1-2;key2:item2-1,item2-2' default: 'Default' required: false type: string exclude: description: 'Exclude build configurations: key1-1:item1-1,key1-2:item1-2;key2-1:item2-1,key2-2:item2-2' default: 'None' required: false type: string workflow_call: inputs: version: description: 'Version tag of text-generation-webui to build: v3.0' default: 'v3.0' required: true type: string config: description: 'Configurations to build: key1:item1-1,item1-2;key2:item2-1,item2-2' default: 'Default' required: false type: string exclude: description: 'Exclude build configurations: key1-1:item1-1,key1-2:item1-2;key2-1:item2-1,key2-2:item2-2' default: 'None' required: false type: string
permissions: contents: write
jobs: define_matrix: name: Define Build Matrix runs-on: ubuntu-latest outputs: matrix: ${{ steps.set-matrix.outputs.matrix }} defaults: run: shell: pwsh env: CONFIGIN: ${{ inputs.config }} EXCLUDEIN: ${{ inputs.exclude }}
steps: - name: Define Job Output id: set-matrix run: | $matrix = @{ 'os' = @('ubuntu-22.04', 'windows-2022', 'macos-13', 'macos-14') 'pyver' = @("3.11") 'avx' = @("AVX2") }
if ($env:CONFIGIN -ne 'Default') {$env:CONFIGIN.split(';').foreach({$matrix[$_.split(':')[0]] = $_.split(':')[1].split(',')})}
if ($env:EXCLUDEIN -ne 'None') { $exclusions = @() $exclusions += $env:EXCLUDEIN.split(';').replace(':','=').replace(',',"`n") | ConvertFrom-StringData $matrix['exclude'] = $exclusions }
$matrixOut = ConvertTo-Json $matrix -Compress Write-Output ('matrix=' + $matrixOut) >> $env:GITHUB_OUTPUT
build_wheels: name: ${{ matrix.os }} ${{ matrix.pyver }} CPU ${{ matrix.avx }} needs: define_matrix runs-on: ${{ matrix.os }} strategy: matrix: ${{ fromJSON(needs.define_matrix.outputs.matrix) }} defaults: run: shell: pwsh env: AVXVER: ${{ matrix.avx }} PCKGVER: ${{ inputs.version }}
steps: - uses: actions/checkout@v4 with: repository: 'oobabooga/text-generation-webui' ref: ${{ inputs.version }} submodules: 'recursive'
- uses: actions/setup-python@v4 with: python-version: ${{ matrix.pyver }}
- name: Build Package shell: bash run: | VERSION_CLEAN="${{ inputs.version }}" VERSION_CLEAN="${VERSION_CLEAN#v}" cd .. cp -r text-generation-webui "text-generation-webui-${VERSION_CLEAN}" cd "text-generation-webui-${VERSION_CLEAN}"
# Remove extensions that need additional requirements allowed=("character_bias" "gallery" "openai" "sd_api_pictures") find extensions/ -mindepth 1 -maxdepth 1 -type d | grep -v -E "$(printf '%s|' "${allowed[@]}" | sed 's/|$//')" | xargs rm -rf
# Define common variables AVX_SUPPORT="${{ matrix.avx }}" VERSION="${{ inputs.version }}" OS_TYPE="${{ matrix.os }}"
# 1. Set platform-specific variables if [[ "$RUNNER_OS" == "Windows" ]]; then PLATFORM="windows-cpu" PYTHON_URL="https://github.com/astral-sh/python-build-standalone/releases/download/20250409/cpython-3.11.12+20250409-x86_64-pc-windows-msvc-install_only.tar.gz" PIP_PATH="portable_env/python.exe -m pip" PACKAGES_PATH="portable_env/Lib/site-packages" rm start_linux.sh start_macos.sh elif [[ "$RUNNER_OS" == "macOS" ]]; then if [[ "$OS_TYPE" == "macos-13" ]]; then PLATFORM="macos-x86_64" PYTHON_URL="https://github.com/astral-sh/python-build-standalone/releases/download/20250409/cpython-3.11.12+20250409-x86_64-apple-darwin-install_only.tar.gz" REQ_TYPE="apple_intel" else PLATFORM="macos-arm64" PYTHON_URL="https://github.com/astral-sh/python-build-standalone/releases/download/20250409/cpython-3.11.12+20250409-aarch64-apple-darwin-install_only.tar.gz" REQ_TYPE="apple_silicon" fi PIP_PATH="portable_env/bin/python -m pip" PACKAGES_PATH="portable_env/lib/python3.11/site-packages" rm start_linux.sh start_windows.bat else # Linux case PLATFORM="linux-cpu" PYTHON_URL="https://github.com/astral-sh/python-build-standalone/releases/download/20250409/cpython-3.11.12+20250409-x86_64-unknown-linux-gnu-install_only.tar.gz" PIP_PATH="portable_env/bin/python -m pip" PACKAGES_PATH="portable_env/lib/python3.11/site-packages" rm start_macos.sh start_windows.bat fi
# 2. Download and extract Python echo "Downloading Python for $PLATFORM..." cd .. curl -L -o python-build.tar.gz "$PYTHON_URL" tar -xzf python-build.tar.gz mv python "text-generation-webui-${VERSION_CLEAN}/portable_env"
# 3. Prepare requirements file based on platform and AVX cd "text-generation-webui-${VERSION_CLEAN}"
# Select requirements file based on platform if [[ "$RUNNER_OS" == "macOS" ]]; then if [[ "$OS_TYPE" == "macos-13" ]]; then REQ_FILE="requirements/portable/requirements_apple_intel.txt" else REQ_FILE="requirements/portable/requirements_apple_silicon.txt" fi else # For Windows and Linux, check AVX support if [[ "$AVX_SUPPORT" == "AVX2" ]]; then REQ_FILE="requirements/portable/requirements_cpu_only.txt" else REQ_FILE="requirements/portable/requirements_cpu_only_noavx2.txt" fi fi
echo "Using requirements file: $REQ_FILE"
# 4. Install packages echo "Installing Python packages from $REQ_FILE..." $PIP_PATH install --target="./$PACKAGES_PATH" -r "$REQ_FILE"
# 5. Clean up rm -rf .git cmd* update_wizard* Colab-TextGen-GPU.ipynb docker setup.cfg .github .gitignore requirements/ one_click.py
# 6. Create ZIP file cd .. ZIP_NAME="textgen-portable-${VERSION_CLEAN}-${PLATFORM}.zip" echo "Creating archive: $ZIP_NAME"
if [[ "$RUNNER_OS" == "Windows" ]]; then powershell -Command "Compress-Archive -Path text-generation-webui-${VERSION_CLEAN} -DestinationPath $ZIP_NAME" else zip -r "$ZIP_NAME" "text-generation-webui-${VERSION_CLEAN}" fi
- name: Upload files to a GitHub release id: upload-release uses: svenstaro/upload-release-action@2.7.0 continue-on-error: true with: repo_token: ${{ secrets.GITHUB_TOKEN }} file: ../textgen-portable-*.zip tag: ${{ inputs.version }} file_glob: true make_latest: false overwrite: true123456789101112131415161718192021222324252627282930313233/css/extensions/installer_files/repositories/user_data
.chroma.DS_Store.eslintrc.js.idea.installer_state.json.venvvenv.envrc.direnv.vs.vscode*.bak*.ipynb*.log*pycache*cert.pemkey.pempackage.jsonpackage-lock.jsonThumbs.dbwandb
# ignore user docker config and top level links to docker files/docker-compose.yaml/docker-compose.yml/Dockerfile.env123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661 GNU AFFERO GENERAL PUBLIC LICENSE Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/> Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license forsoftware and other kinds of works, specifically designed to ensurecooperation with the community in the case of network server software.
The licenses for most software and other practical works are designedto take away your freedom to share and change the works. By contrast,our General Public Licenses are intended to guarantee your freedom toshare and change all versions of a program--to make sure it remains freesoftware for all its users.
When we speak of free software, we are referring to freedom, notprice. Our General Public Licenses are designed to make sure that youhave the freedom to distribute copies of free software (and charge forthem if you wish), that you receive source code or can get it if youwant it, that you can change the software or use pieces of it in newfree programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rightswith two steps: (1) assert copyright on the software, and (2) offeryou this License which gives you legal permission to copy, distributeand/or modify the software.
A secondary benefit of defending all users' freedom is thatimprovements made in alternate versions of the program, if theyreceive widespread use, become available for other developers toincorporate. Many developers of free software are heartened andencouraged by the resulting cooperation. However, in the case ofsoftware used on network servers, this result may fail to come about.The GNU General Public License permits making a modified version andletting the public access it on a server without ever releasing itssource code to the public.
The GNU Affero General Public License is designed specifically toensure that, in such cases, the modified source code becomes availableto the community. It requires the operator of a network server toprovide the source code of the modified version running there to theusers of that server. Therefore, public use of a modified version, ona publicly accessible server, gives the public access to the sourcecode of the modified version.
An older license, called the Affero General Public License andpublished by Affero, was designed to accomplish similar goals. This isa different license, not a version of the Affero GPL, but Affero hasreleased a new version of the Affero GPL which permits relicensing underthis license.
The precise terms and conditions for copying, distribution andmodification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds ofworks, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under thisLicense. Each licensee is addressed as "you". "Licensees" and"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the workin a fashion requiring copyright permission, other than the making of anexact copy. The resulting work is called a "modified version" of theearlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work basedon the Program.
To "propagate" a work means to do anything with it that, withoutpermission, would make you directly or secondarily liable forinfringement under applicable copyright law, except executing it on acomputer or modifying a private copy. Propagation includes copying,distribution (with or without modification), making available to thepublic, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables otherparties to make or receive copies. Mere interaction with a user througha computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"to the extent that it includes a convenient and prominently visiblefeature that (1) displays an appropriate copyright notice, and (2)tells the user that there is no warranty for the work (except to theextent that warranties are provided), that licensees may convey thework under this License, and how to view a copy of this License. Ifthe interface presents a list of user commands or options, such as amenu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the workfor making modifications to it. "Object code" means any non-sourceform of a work.
A "Standard Interface" means an interface that either is an officialstandard defined by a recognized standards body, or, in the case ofinterfaces specified for a particular programming language, one thatis widely used among developers working in that language.
The "System Libraries" of an executable work include anything, otherthan the work as a whole, that (a) is included in the normal form ofpackaging a Major Component, but which is not part of that MajorComponent, and (b) serves only to enable use of the work with thatMajor Component, or to implement a Standard Interface for which animplementation is available to the public in source code form. A"Major Component", in this context, means a major essential component(kernel, window system, and so on) of the specific operating system(if any) on which the executable work runs, or a compiler used toproduce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means allthe source code needed to generate, install, and (for an executablework) run the object code and to modify the work, including scripts tocontrol those activities. However, it does not include the work'sSystem Libraries, or general-purpose tools or generally available freeprograms which are used unmodified in performing those activities butwhich are not part of the work. For example, Corresponding Sourceincludes interface definition files associated with source files forthe work, and the source code for shared libraries and dynamicallylinked subprograms that the work is specifically designed to require,such as by intimate data communication or control flow between thosesubprograms and other parts of the work.
The Corresponding Source need not include anything that userscan regenerate automatically from other parts of the CorrespondingSource.
The Corresponding Source for a work in source code form is thatsame work.
2. Basic Permissions.
All rights granted under this License are granted for the term ofcopyright on the Program, and are irrevocable provided the statedconditions are met. This License explicitly affirms your unlimitedpermission to run the unmodified Program. The output from running acovered work is covered by this License only if the output, given itscontent, constitutes a covered work. This License acknowledges yourrights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do notconvey, without conditions so long as your license otherwise remainsin force. You may convey covered works to others for the sole purposeof having them make modifications exclusively for you, or provide youwith facilities for running those works, provided that you comply withthe terms of this License in conveying all material for which you donot control copyright. Those thus making or running the covered worksfor you must do so exclusively on your behalf, under your directionand control, on terms that prohibit them from making any copies ofyour copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely underthe conditions stated below. Sublicensing is not allowed; section 10makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technologicalmeasure under any applicable law fulfilling obligations under article11 of the WIPO copyright treaty adopted on 20 December 1996, orsimilar laws prohibiting or restricting circumvention of suchmeasures.
When you convey a covered work, you waive any legal power to forbidcircumvention of technological measures to the extent such circumventionis effected by exercising rights under this License with respect tothe covered work, and you disclaim any intention to limit operation ormodification of the work as a means of enforcing, against the work'susers, your or third parties' legal rights to forbid circumvention oftechnological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as youreceive it, in any medium, provided that you conspicuously andappropriately publish on each copy an appropriate copyright notice;keep intact all notices stating that this License and anynon-permissive terms added in accord with section 7 apply to the code;keep intact all notices of the absence of any warranty; and give allrecipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications toproduce it from the Program, in the form of source code under theterms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices".
c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.
A compilation of a covered work with other separate and independentworks, which are not by their nature extensions of the covered work,and which are not combined with it such as to form a larger program,in or on a volume of a storage or distribution medium, is called an"aggregate" if the compilation and its resulting copyright are notused to limit the access or legal rights of the compilation's usersbeyond what the individual works permit. Inclusion of a covered workin an aggregate does not cause this License to apply to the otherparts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the termsof sections 4 and 5, provided that you also convey themachine-readable Corresponding Source under the terms of this License,in one of these ways:
a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.
A separable portion of the object code, whose source code is excludedfrom the Corresponding Source as a System Library, need not beincluded in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means anytangible personal property which is normally used for personal, family,or household purposes, or (2) anything designed or sold for incorporationinto a dwelling. In determining whether a product is a consumer product,doubtful cases shall be resolved in favor of coverage. For a particularproduct received by a particular user, "normally used" refers to atypical or common use of that class of product, regardless of the statusof the particular user or of the way in which the particular useractually uses, or expects or is expected to use, the product. A productis a consumer product regardless of whether the product has substantialcommercial, industrial or non-consumer uses, unless such uses representthe only significant mode of use of the product.
"Installation Information" for a User Product means any methods,procedures, authorization keys, or other information required to installand execute modified versions of a covered work in that User Product froma modified version of its Corresponding Source. The information mustsuffice to ensure that the continued functioning of the modified objectcode is in no case prevented or interfered with solely becausemodification has been made.
If you convey an object code work under this section in, or with, orspecifically for use in, a User Product, and the conveying occurs aspart of a transaction in which the right of possession and use of theUser Product is transferred to the recipient in perpetuity or for afixed term (regardless of how the transaction is characterized), theCorresponding Source conveyed under this section must be accompaniedby the Installation Information. But this requirement does not applyif neither you nor any third party retains the ability to installmodified object code on the User Product (for example, the work hasbeen installed in ROM).
The requirement to provide Installation Information does not include arequirement to continue to provide support service, warranty, or updatesfor a work that has been modified or installed by the recipient, or forthe User Product in which it has been modified or installed. Access to anetwork may be denied when the modification itself materially andadversely affects the operation of the network or violates the rules andprotocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,in accord with this section must be in a format that is publiclydocumented (and with an implementation available to the public insource code form), and must require no special password or key forunpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of thisLicense by making exceptions from one or more of its conditions.Additional permissions that are applicable to the entire Program shallbe treated as though they were included in this License, to the extentthat they are valid under applicable law. If additional permissionsapply only to part of the Program, that part may be used separatelyunder those permissions, but the entire Program remains governed bythis License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your optionremove any additional permissions from that copy, or from any part ofit. (Additional permissions may be written to require their ownremoval in certain cases when you modify the work.) You may placeadditional permissions on material, added by you to a covered work,for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material youadd to a covered work, you may (if authorized by the copyright holders ofthat material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.
All other non-permissive additional terms are considered "furtherrestrictions" within the meaning of section 10. If the Program as youreceived it, or any part of it, contains a notice stating that it isgoverned by this License along with a term that is a furtherrestriction, you may remove that term. If a license document containsa further restriction but permits relicensing or conveying under thisLicense, you may add to a covered work material governed by the termsof that license document, provided that the further restriction doesnot survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, youmust place, in the relevant source files, a statement of theadditional terms that apply to those files, or a notice indicatingwhere to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in theform of a separately written license, or stated as exceptions;the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expresslyprovided under this License. Any attempt otherwise to propagate ormodify it is void, and will automatically terminate your rights underthis License (including any patent licenses granted under the thirdparagraph of section 11).
However, if you cease all violation of this License, then yourlicense from a particular copyright holder is reinstated (a)provisionally, unless and until the copyright holder explicitly andfinally terminates your license, and (b) permanently, if the copyrightholder fails to notify you of the violation by some reasonable meansprior to 60 days after the cessation.
Moreover, your license from a particular copyright holder isreinstated permanently if the copyright holder notifies you of theviolation by some reasonable means, this is the first time you havereceived notice of violation of this License (for any work) from thatcopyright holder, and you cure the violation prior to 30 days afteryour receipt of the notice.
Termination of your rights under this section does not terminate thelicenses of parties who have received copies or rights from you underthis License. If your rights have been terminated and not permanentlyreinstated, you do not qualify to receive new licenses for the samematerial under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive orrun a copy of the Program. Ancillary propagation of a covered workoccurring solely as a consequence of using peer-to-peer transmissionto receive a copy likewise does not require acceptance. However,nothing other than this License grants you permission to propagate ormodify any covered work. These actions infringe copyright if you donot accept this License. Therefore, by modifying or propagating acovered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automaticallyreceives a license from the original licensors, to run, modify andpropagate that work, subject to this License. You are not responsiblefor enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of anorganization, or substantially all assets of one, or subdividing anorganization, or merging organizations. If propagation of a coveredwork results from an entity transaction, each party to thattransaction who receives a copy of the work also receives whateverlicenses to the work the party's predecessor in interest had or couldgive under the previous paragraph, plus a right to possession of theCorresponding Source of the work from the predecessor in interest, ifthe predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of therights granted or affirmed under this License. For example, you maynot impose a license fee, royalty, or other charge for exercise ofrights granted under this License, and you may not initiate litigation(including a cross-claim or counterclaim in a lawsuit) alleging thatany patent claim is infringed by making, using, selling, offering forsale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under thisLicense of the Program or a work on which the Program is based. Thework thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claimsowned or controlled by the contributor, whether already acquired orhereafter acquired, that would be infringed by some manner, permittedby this License, of making, using, or selling its contributor version,but do not include claims that would be infringed only as aconsequence of further modification of the contributor version. Forpurposes of this definition, "control" includes the right to grantpatent sublicenses in a manner consistent with the requirements ofthis License.
Each contributor grants you a non-exclusive, worldwide, royalty-freepatent license under the contributor's essential patent claims, tomake, use, sell, offer for sale, import and otherwise run, modify andpropagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any expressagreement or commitment, however denominated, not to enforce a patent(such as an express permission to practice a patent or covenant not tosue for patent infringement). To "grant" such a patent license to aparty means to make such an agreement or commitment not to enforce apatent against the party.
If you convey a covered work, knowingly relying on a patent license,and the Corresponding Source of the work is not available for anyoneto copy, free of charge and under the terms of this License, through apublicly available network server or other readily accessible means,then you must either (1) cause the Corresponding Source to be soavailable, or (2) arrange to deprive yourself of the benefit of thepatent license for this particular work, or (3) arrange, in a mannerconsistent with the requirements of this License, to extend the patentlicense to downstream recipients. "Knowingly relying" means you haveactual knowledge that, but for the patent license, your conveying thecovered work in a country, or your recipient's use of the covered workin a country, would infringe one or more identifiable patents in thatcountry that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction orarrangement, you convey, or propagate by procuring conveyance of, acovered work, and grant a patent license to some of the partiesreceiving the covered work authorizing them to use, propagate, modifyor convey a specific copy of the covered work, then the patent licenseyou grant is automatically extended to all recipients of the coveredwork and works based on it.
A patent license is "discriminatory" if it does not include withinthe scope of its coverage, prohibits the exercise of, or isconditioned on the non-exercise of one or more of the rights that arespecifically granted under this License. You may not convey a coveredwork if you are a party to an arrangement with a third party that isin the business of distributing software, under which you make paymentto the third party based on the extent of your activity of conveyingthe work, and under which the third party grants, to any of theparties who would receive the covered work from you, a discriminatorypatent license (a) in connection with copies of the covered workconveyed by you (or copies made from those copies), or (b) primarilyfor and in connection with specific products or compilations thatcontain the covered work, unless you entered into that arrangement,or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limitingany implied license or other defenses to infringement that mayotherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement orotherwise) that contradict the conditions of this License, they do notexcuse you from the conditions of this License. If you cannot convey acovered work so as to satisfy simultaneously your obligations under thisLicense and any other pertinent obligations, then as a consequence you maynot convey it at all. For example, if you agree to terms that obligate youto collect a royalty for further conveying from those to whom you conveythe Program, the only way you could satisfy both those terms and thisLicense would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify theProgram, your modified version must prominently offer all usersinteracting with it remotely through a computer network (if your versionsupports such interaction) an opportunity to receive the CorrespondingSource of your version by providing access to the Corresponding Sourcefrom a network server at no charge, through some standard or customarymeans of facilitating copying of software. This Corresponding Sourceshall include the Corresponding Source for any work covered by version 3of the GNU General Public License that is incorporated pursuant to thefollowing paragraph.
Notwithstanding any other provision of this License, you havepermission to link or combine any covered work with a work licensedunder version 3 of the GNU General Public License into a singlecombined work, and to convey the resulting work. The terms of thisLicense will continue to apply to the part which is the covered work,but the work with which it is combined will remain governed by version3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions ofthe GNU Affero General Public License from time to time. Such new versionswill be similar in spirit to the present version, but may differ in detail toaddress new problems or concerns.
Each version is given a distinguishing version number. If theProgram specifies that a certain numbered version of the GNU Affero GeneralPublic License "or any later version" applies to it, you have theoption of following the terms and conditions either of that numberedversion or of any later version published by the Free SoftwareFoundation. If the Program does not specify a version number of theGNU Affero General Public License, you may choose any version ever publishedby the Free Software Foundation.
If the Program specifies that a proxy can decide which futureversions of the GNU Affero General Public License can be used, that proxy'spublic statement of acceptance of a version permanently authorizes youto choose that version for the Program.
Later license versions may give you additional or differentpermissions. However, no additional obligations are imposed on anyauthor or copyright holder as a result of your choosing to follow alater version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BYAPPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHTHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTYOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULARPURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAMIS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OFALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITINGWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYSTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANYGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THEUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OFDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRDPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OFSUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability providedabove cannot be given local legal effect according to their terms,reviewing courts shall apply local law that most closely approximatesan absolute waiver of all civil liability in connection with theProgram, unless a warranty or assumption of liability accompanies acopy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatestpossible use to the public, the best way to achieve this is to make itfree software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safestto attach them to the start of each source file to most effectivelystate the exclusion of warranty; and each file should have at leastthe "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.> Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computernetwork, you should also make sure that it provides a way for users toget its source. For example, if your program is a web application, itsinterface could display a "Source" link that leads users to an archiveof the code. There are many ways you could offer source, and differentsolutions will be better for different programs; see section 13 for thespecific requirements.
You should also get your employer (if you work as a programmer) or school,if any, to sign a "copyright disclaimer" for the program, if necessary.For more information on this, and how to apply and follow the GNU AGPL, see<https://www.gnu.org/licenses/>.123456789101112---title: Testing123emoji: 👁colorFrom: greencolorTo: yellowsdk: gradiosdk_version: 5.49.1app_file: app.pypinned: false---Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444---title: testing123app_file: server.pysdk: gradiosdk_version: 5.41.1---<div align="center" markdown="1"><sup>Special thanks to:</sup><br><br><a href="https://go.warp.dev/text-generation-webui"><img alt="Warp sponsorship" width="400" src="https://raw.githubusercontent.com/warpdotdev/brand-assets/refs/heads/main/Github/Sponsor/Warp-Github-LG-02.png"></a>### [Warp, built for coding with multiple AI agents](https://go.warp.dev/text-generation-webui)[Available for macOS, Linux, & Windows](https://go.warp.dev/text-generation-webui)<br></div><hr># Text Generation Web UIA Gradio web UI for Large Language Models.[Try the Deep Reason extension](https://oobabooga.gumroad.com/l/deep_reason)| |  ||:---:|:---:|| |  |## Features- Supports multiple local text generation backends, including [llama.cpp](https://github.com/ggerganov/llama.cpp), [Transformers](https://github.com/huggingface/transformers), [ExLlamaV3](https://github.com/turboderp-org/exllamav3), [ExLlamaV2](https://github.com/turboderp-org/exllamav2), and [TensorRT-LLM](https://github.com/NVIDIA/TensorRT-LLM) (the latter via its own [Dockerfile](https://github.com/oobabooga/text-generation-webui/blob/main/docker/TensorRT-LLM/Dockerfile)).- Easy setup: Choose between **portable builds** (zero setup, just unzip and run) for GGUF models on Windows/Linux/macOS, or the one-click installer that creates a self-contained `installer_files` directory.- 100% offline and private, with zero telemetry, external resources, or remote update requests.- **File attachments**: Upload text files, PDF documents, and .docx documents to talk about their contents.- **Vision (multimodal models)**: Attach images to messages for visual understanding ([tutorial](https://github.com/oobabooga/text-generation-webui/wiki/Multimodal-Tutorial)).- **Web search**: Optionally search the internet with LLM-generated queries to add context to the conversation.- Aesthetic UI with dark and light themes.- Syntax highlighting for code blocks and LaTeX rendering for mathematical expressions.- `instruct` mode for instruction-following (like ChatGPT), and `chat-instruct`/`chat` modes for talking to custom characters.- Automatic prompt formatting using Jinja2 templates. You don't need to ever worry about prompt formats.- Edit messages, navigate between message versions, and branch conversations at any point.- Multiple sampling parameters and generation options for sophisticated text generation control.- Switch between different models in the UI without restarting.- Automatic GPU layers for GGUF models (on NVIDIA GPUs).- Free-form text generation in the Notebook tab without being limited to chat turns.- OpenAI-compatible API with Chat and Completions endpoints, including tool-calling support – see [examples](https://github.com/oobabooga/text-generation-webui/wiki/12-%E2%80%90-OpenAI-API#examples).- Extension support, with numerous built-in and user-contributed extensions available. See the [wiki](https://github.com/oobabooga/text-generation-webui/wiki/07-%E2%80%90-Extensions) and [extensions directory](https://github.com/oobabooga/text-generation-webui-extensions) for details.## How to install#### ✅ Option 1: Portable builds (get started in 1 minute)No installation needed – just download, unzip and run. All dependencies included.Compatible with GGUF (llama.cpp) models on Windows, Linux, and macOS.Download from here: **https://github.com/oobabooga/text-generation-webui/releases**#### Option 2: Manual portable install with venvVery fast setup that should work on any Python 3.9+:```bash# Clone repositorygit clone https://github.com/oobabooga/text-generation-webuicd text-generation-webui# Create virtual environmentpython -m venv venv# Activate virtual environment# On Windows:venv\Scripts\activate# On macOS/Linux:source venv/bin/activate# Install dependencies (choose appropriate file under requirements/portable for your hardware)pip install -r requirements/portable/requirements.txt --upgrade# Launch server (basic command)python server.py --portable --api --auto-launch# When done working, deactivatedeactivate```#### Option 3: One-click installerFor users who need additional backends (ExLlamaV3, Transformers) or extensions (TTS, voice input, translation, etc). Requires ~10GB disk space and downloads PyTorch.1. Clone the repository, or [download its source code](https://github.com/oobabooga/text-generation-webui/archive/refs/heads/main.zip) and extract it.2. Run the startup script for your OS: `start_windows.bat`, `start_linux.sh`, or `start_macos.sh`.3. When prompted, select your GPU vendor.4. After installation, open `http://127.0.0.1:7860` in your browser.To restart the web UI later, run the same `start_` script.You can pass command-line flags directly (e.g., `./start_linux.sh --help`), or add them to `user_data/CMD_FLAGS.txt` (e.g., `--api` to enable the API).To update, run the update script for your OS: `update_wizard_windows.bat`, `update_wizard_linux.sh`, or `update_wizard_macos.sh`.To reinstall with a fresh Python environment, delete the `installer_files` folder and run the `start_` script again.<details><summary>One-click installer details</summary>### One-click-installerThe script uses Miniforge to set up a Conda environment in the `installer_files` folder.If you ever need to install something manually in the `installer_files` environment, you can launch an interactive shell using the cmd script: `cmd_linux.sh`, `cmd_windows.bat`, or `cmd_macos.sh`.* There is no need to run any of those scripts (`start_`, `update_wizard_`, or `cmd_`) as admin/root.* To install requirements for extensions, it is recommended to use the update wizard script with the "Install/update extensions requirements" option. At the end, this script will install the main requirements for the project to make sure that they take precedence in case of version conflicts.* For automated installation, you can use the `GPU_CHOICE`, `LAUNCH_AFTER_INSTALL`, and `INSTALL_EXTENSIONS` environment variables. For instance: `GPU_CHOICE=A LAUNCH_AFTER_INSTALL=FALSE INSTALL_EXTENSIONS=TRUE ./start_linux.sh`.</details><details><summary>Manual full installation with conda or docker</summary>### Full installation with Conda#### 0. Install Condahttps://github.com/conda-forge/miniforgeOn Linux or WSL, Miniforge can be automatically installed with these two commands:```curl -sL "https://github.com/conda-forge/miniforge/releases/latest/download/Miniforge3-Linux-x86_64.sh" > "Miniforge3.sh"bash Miniforge3.sh```For other platforms, download from: https://github.com/conda-forge/miniforge/releases/latest#### 1. Create a new conda environment```conda create -n textgen python=3.11conda activate textgen```#### 2. Install Pytorch| System | GPU | Command ||--------|---------|---------|| Linux/WSL | NVIDIA | `pip3 install torch==2.7.1 --index-url https://download.pytorch.org/whl/cu128` || Linux/WSL | CPU only | `pip3 install torch==2.7.1 --index-url https://download.pytorch.org/whl/cpu` || Linux | AMD | `pip3 install torch==2.7.1 --index-url https://download.pytorch.org/whl/rocm6.2.4` || MacOS + MPS | Any | `pip3 install torch==2.7.1` || Windows | NVIDIA | `pip3 install torch==2.7.1 --index-url https://download.pytorch.org/whl/cu128` || Windows | CPU only | `pip3 install torch==2.7.1` |The up-to-date commands can be found here: https://pytorch.org/get-started/locally/.If you need `nvcc` to compile some library manually, you will additionally need to install this:```conda install -y -c "nvidia/label/cuda-12.8.1" cuda```#### 3. Install the web UI```git clone https://github.com/oobabooga/text-generation-webuicd text-generation-webuipip install -r <requirements file according to table below>```Requirements file to use:| GPU | CPU | requirements file to use ||--------|---------|---------|| NVIDIA | has AVX2 | `requirements.txt` || NVIDIA | no AVX2 | `requirements_noavx2.txt` || AMD | has AVX2 | `requirements_amd.txt` || AMD | no AVX2 | `requirements_amd_noavx2.txt` || CPU only | has AVX2 | `requirements_cpu_only.txt` || CPU only | no AVX2 | `requirements_cpu_only_noavx2.txt` || Apple | Intel | `requirements_apple_intel.txt` || Apple | Apple Silicon | `requirements_apple_silicon.txt` |### Start the web UI```conda activate textgencd text-generation-webuipython server.py```Then browse to`http://127.0.0.1:7860`#### Manual installThe `requirements*.txt` above contain various wheels precompiled through GitHub Actions. If you wish to compile things manually, or if you need to because no suitable wheels are available for your hardware, you can use `requirements_nowheels.txt` and then install your desired loaders manually.### Alternative: Docker```For NVIDIA GPU:ln -s docker/{nvidia/Dockerfile,nvidia/docker-compose.yml,.dockerignore} .For AMD GPU:ln -s docker/{amd/Dockerfile,amd/docker-compose.yml,.dockerignore} .For Intel GPU:ln -s docker/{intel/Dockerfile,amd/docker-compose.yml,.dockerignore} .For CPU onlyln -s docker/{cpu/Dockerfile,cpu/docker-compose.yml,.dockerignore} .cp docker/.env.example .env#Create logs/cache dir :mkdir -p user_data/logs user_data/cache# Edit .env and set:# TORCH_CUDA_ARCH_LIST based on your GPU model# APP_RUNTIME_GID your host user's group id (run `id -g` in a terminal)# BUILD_EXTENIONS optionally add comma separated list of extensions to build# Edit user_data/CMD_FLAGS.txt and add in it the options you want to execute (like --listen --cpu)#docker compose up --build```* You need to have Docker Compose v2.17 or higher installed. See [this guide](https://github.com/oobabooga/text-generation-webui/wiki/09-%E2%80%90-Docker) for instructions.* For additional docker files, check out [this repository](https://github.com/Atinoda/text-generation-webui-docker).### Updating the requirementsFrom time to time, the `requirements*.txt` change. To update, use these commands:```conda activate textgencd text-generation-webuipip install -r <requirements file that you have used> --upgrade```</details><details><summary>List of command-line flags</summary>```txtusage: server.py [-h] [--multi-user] [--model MODEL] [--lora LORA [LORA ...]] [--model-dir MODEL_DIR] [--lora-dir LORA_DIR] [--model-menu] [--settings SETTINGS][--extensions EXTENSIONS [EXTENSIONS ...]] [--verbose] [--idle-timeout IDLE_TIMEOUT] [--loader LOADER] [--cpu] [--cpu-memory CPU_MEMORY] [--disk] [--disk-cache-dir DISK_CACHE_DIR][--load-in-8bit] [--bf16] [--no-cache] [--trust-remote-code] [--force-safetensors] [--no_use_fast] [--attn-implementation IMPLEMENTATION] [--load-in-4bit] [--use_double_quant][--compute_dtype COMPUTE_DTYPE] [--quant_type QUANT_TYPE] [--flash-attn] [--threads THREADS] [--threads-batch THREADS_BATCH] [--batch-size BATCH_SIZE] [--no-mmap] [--mlock][--gpu-layers N] [--tensor-split TENSOR_SPLIT] [--numa] [--no-kv-offload] [--row-split] [--extra-flags EXTRA_FLAGS] [--streaming-llm] [--mmproj MMPROJ] [--ctx-size N] [--cache-type N][--model-draft MODEL_DRAFT] [--draft-max DRAFT_MAX] [--gpu-layers-draft GPU_LAYERS_DRAFT] [--device-draft DEVICE_DRAFT] [--ctx-size-draft CTX_SIZE_DRAFT] [--enable-tp][--tp-backend TP_BACKEND] [--gpu-split GPU_SPLIT] [--autosplit] [--cfg-cache] [--no_flash_attn] [--no_xformers] [--no_sdpa] [--num_experts_per_token N] [--cpp-runner] [--deepspeed][--nvme-offload-dir NVME_OFFLOAD_DIR] [--local_rank LOCAL_RANK] [--alpha_value ALPHA_VALUE] [--rope_freq_base ROPE_FREQ_BASE] [--compress_pos_emb COMPRESS_POS_EMB] [--listen][--listen-port LISTEN_PORT] [--listen-host LISTEN_HOST] [--share] [--auto-launch] [--gradio-auth GRADIO_AUTH] [--gradio-auth-path GRADIO_AUTH_PATH] [--ssl-keyfile SSL_KEYFILE][--ssl-certfile SSL_CERTFILE] [--subpath SUBPATH] [--old-colors] [--portable] [--api] [--public-api] [--public-api-id PUBLIC_API_ID] [--api-port API_PORT] [--api-key API_KEY][--admin-key ADMIN_KEY] [--api-enable-ipv6] [--api-disable-ipv4] [--nowebui]Text Generation Web UIoptions:-h, --help show this help message and exitBasic settings:--multi-user Multi-user mode. Chat histories are not saved or automatically loaded. Warning: this is likely not safe for sharing publicly.--model MODEL Name of the model to load by default.--lora LORA [LORA ...] The list of LoRAs to load. If you want to load more than one LoRA, write the names separated by spaces.--model-dir MODEL_DIR Path to directory with all the models.--lora-dir LORA_DIR Path to directory with all the loras.--model-menu Show a model menu in the terminal when the web UI is first launched.--settings SETTINGS Load the default interface settings from this yaml file. See user_data/settings-template.yaml for an example. If you create a file calleduser_data/settings.yaml, this file will be loaded by default without the need to use the --settings flag.--extensions EXTENSIONS [EXTENSIONS ...] The list of extensions to load. If you want to load more than one extension, write the names separated by spaces.--verbose Print the prompts to the terminal.--idle-timeout IDLE_TIMEOUT Unload model after this many minutes of inactivity. It will be automatically reloaded when you try to use it again.Model loader:--loader LOADER Choose the model loader manually, otherwise, it will get autodetected. Valid options: Transformers, llama.cpp, ExLlamav3_HF, ExLlamav2_HF, ExLlamav2,TensorRT-LLM.Transformers/Accelerate:--cpu Use the CPU to generate text. Warning: Training on CPU is extremely slow.--cpu-memory CPU_MEMORY Maximum CPU memory in GiB. Use this for CPU offloading.--disk If the model is too large for your GPU(s) and CPU combined, send the remaining layers to the disk.--disk-cache-dir DISK_CACHE_DIR Directory to save the disk cache to. Defaults to "user_data/cache".--load-in-8bit Load the model with 8-bit precision (using bitsandbytes).--bf16 Load the model with bfloat16 precision. Requires NVIDIA Ampere GPU.--no-cache Set use_cache to False while generating text. This reduces VRAM usage slightly, but it comes at a performance cost.--trust-remote-code Set trust_remote_code=True while loading the model. Necessary for some models.--force-safetensors Set use_safetensors=True while loading the model. This prevents arbitrary code execution.--no_use_fast Set use_fast=False while loading the tokenizer (it's True by default). Use this if you have any problems related to use_fast.--attn-implementation IMPLEMENTATION Attention implementation. Valid options: sdpa, eager, flash_attention_2.bitsandbytes 4-bit:--load-in-4bit Load the model with 4-bit precision (using bitsandbytes).--use_double_quant use_double_quant for 4-bit.--compute_dtype COMPUTE_DTYPE compute dtype for 4-bit. Valid options: bfloat16, float16, float32.--quant_type QUANT_TYPE quant_type for 4-bit. Valid options: nf4, fp4.llama.cpp:--flash-attn Use flash-attention.--threads THREADS Number of threads to use.--threads-batch THREADS_BATCH Number of threads to use for batches/prompt processing.--batch-size BATCH_SIZE Maximum number of prompt tokens to batch together when calling llama_eval.--no-mmap Prevent mmap from being used.--mlock Force the system to keep the model in RAM.--gpu-layers N, --n-gpu-layers N Number of layers to offload to the GPU.--tensor-split TENSOR_SPLIT Split the model across multiple GPUs. Comma-separated list of proportions. Example: 60,40.--numa Activate NUMA task allocation for llama.cpp.--no-kv-offload Do not offload the K, Q, V to the GPU. This saves VRAM but reduces the performance.--row-split Split the model by rows across GPUs. This may improve multi-gpu performance.--extra-flags EXTRA_FLAGS Extra flags to pass to llama-server. Format: "flag1=value1,flag2,flag3=value3". Example: "override-tensor=exps=CPU"--streaming-llm Activate StreamingLLM to avoid re-evaluating the entire prompt when old messages are removed.--mmproj MMPROJ Path to the mmproj file for vision models.Context and cache:--ctx-size N, --n_ctx N, --max_seq_len N Context size in tokens.--cache-type N, --cache_type N KV cache type; valid options: llama.cpp - fp16, q8_0, q4_0; ExLlamaV2 - fp16, fp8, q8, q6, q4; ExLlamaV3 - fp16, q2 to q8 (can specify k_bits and v_bitsseparately, e.g. q4_q8).Speculative decoding:--model-draft MODEL_DRAFT Path to the draft model for speculative decoding.--draft-max DRAFT_MAX Number of tokens to draft for speculative decoding.--gpu-layers-draft GPU_LAYERS_DRAFT Number of layers to offload to the GPU for the draft model.--device-draft DEVICE_DRAFT Comma-separated list of devices to use for offloading the draft model. Example: CUDA0,CUDA1--ctx-size-draft CTX_SIZE_DRAFT Size of the prompt context for the draft model. If 0, uses the same as the main model.ExLlamaV3:--enable-tp, --enable_tp Enable Tensor Parallelism (TP) to split the model across GPUs.--tp-backend TP_BACKEND The backend for tensor parallelism. Valid options: native, nccl. Default: native.ExLlamaV2:--gpu-split GPU_SPLIT Comma-separated list of VRAM (in GB) to use per GPU device for model layers. Example: 20,7,7.--autosplit Autosplit the model tensors across the available GPUs. This causes --gpu-split to be ignored.--cfg-cache ExLlamav2_HF: Create an additional cache for CFG negative prompts. Necessary to use CFG with that loader.--no_flash_attn Force flash-attention to not be used.--no_xformers Force xformers to not be used.--no_sdpa Force Torch SDPA to not be used.--num_experts_per_token N Number of experts to use for generation. Applies to MoE models like Mixtral.TensorRT-LLM:--cpp-runner Use the ModelRunnerCpp runner, which is faster than the default ModelRunner but doesn't support streaming yet.DeepSpeed:--deepspeed Enable the use of DeepSpeed ZeRO-3 for inference via the Transformers integration.--nvme-offload-dir NVME_OFFLOAD_DIR DeepSpeed: Directory to use for ZeRO-3 NVME offloading.--local_rank LOCAL_RANK DeepSpeed: Optional argument for distributed setups.RoPE:--alpha_value ALPHA_VALUE Positional embeddings alpha factor for NTK RoPE scaling. Use either this or compress_pos_emb, not both.--rope_freq_base ROPE_FREQ_BASE If greater than 0, will be used instead of alpha_value. Those two are related by rope_freq_base = 10000 * alpha_value ^ (64 / 63).--compress_pos_emb COMPRESS_POS_EMB Positional embeddings compression factor. Should be set to (context length) / (model's original context length). Equal to 1/rope_freq_scale.Gradio:--listen Make the web UI reachable from your local network.--listen-port LISTEN_PORT The listening port that the server will use.--listen-host LISTEN_HOST The hostname that the server will use.--share Create a public URL. This is useful for running the web UI on Google Colab or similar.--auto-launch Open the web UI in the default browser upon launch.--gradio-auth GRADIO_AUTH Set Gradio authentication password in the format "username:password". Multiple credentials can also be supplied with "u1:p1,u2:p2,u3:p3".--gradio-auth-path GRADIO_AUTH_PATH Set the Gradio authentication file path. The file should contain one or more user:password pairs in the same format as above.--ssl-keyfile SSL_KEYFILE The path to the SSL certificate key file.--ssl-certfile SSL_CERTFILE The path to the SSL certificate cert file.--subpath SUBPATH Customize the subpath for gradio, use with reverse proxy--old-colors Use the legacy Gradio colors, before the December/2024 update.--portable Hide features not available in portable mode like training.API:--api Enable the API extension.--public-api Create a public URL for the API using Cloudfare.--public-api-id PUBLIC_API_ID Tunnel ID for named Cloudflare Tunnel. Use together with public-api option.--api-port API_PORT The listening port for the API.--api-key API_KEY API authentication key.--admin-key ADMIN_KEY API authentication key for admin tasks like loading and unloading models. If not set, will be the same as --api-key.--api-enable-ipv6 Enable IPv6 for the API--api-disable-ipv4 Disable IPv4 for the API--nowebui Do not launch the Gradio UI. Useful for launching the API in standalone mode.```</details>## Downloading modelsModels should be placed in the folder `text-generation-webui/user_data/models`. They are usually downloaded from [Hugging Face](https://huggingface.co/models?pipeline_tag=text-generation&sort=downloads&search=gguf).To check if a GGUF model will fit in your hardware before downloading it, you can use this tool I created:[Accurate GGUF VRAM Calculator](https://huggingface.co/spaces/oobabooga/accurate-gguf-vram-calculator)* GGUF models are a single file and should be placed directly into `user_data/models`. Example:```text-generation-webui└── user_data└── models└── llama-2-13b-chat.Q4_K_M.gguf```* The remaining model types (like 16-bit Transformers models and EXL3 models) are made of several files and must be placed in a subfolder. Example:```text-generation-webui└── user_data└── models└── lmsys_vicuna-33b-v1.3├── config.json├── generation_config.json├── pytorch_model-00001-of-00007.bin├── pytorch_model-00002-of-00007.bin├── pytorch_model-00003-of-00007.bin├── pytorch_model-00004-of-00007.bin├── pytorch_model-00005-of-00007.bin├── pytorch_model-00006-of-00007.bin├── pytorch_model-00007-of-00007.bin├── pytorch_model.bin.index.json├── special_tokens_map.json├── tokenizer_config.json└── tokenizer.model```In both cases, you can use the "Model" tab of the UI to download the model from Hugging Face automatically. It is also possible to download it via the command-line with:```python download-model.py organization/model```Run `python download-model.py --help` to see all the options.## Documentationhttps://github.com/oobabooga/text-generation-webui/wiki## Google Colab notebookhttps://colab.research.google.com/github/oobabooga/text-generation-webui/blob/main/Colab-TextGen-GPU.ipynb## Communityhttps://www.reddit.com/r/Oobabooga/## AcknowledgmentIn August 2023, [Andreessen Horowitz](https://a16z.com/) (a16z) provided a generous grant to encourage and support my independent work on this project. I am **extremely** grateful for their trust and recognition.
12345678910111213141516171819202122#!/usr/bin/env bash
cd "$(dirname "${BASH_SOURCE[0]}")"
if [[ "$(pwd)" =~ " " ]]; then echo This script relies on Miniforge which can not be silently installed under a path with spaces. && exit; fi
# deactivate existing conda envs as needed to avoid conflicts{ conda deactivate && conda deactivate && conda deactivate; } 2> /dev/null
# configCONDA_ROOT_PREFIX="$(pwd)/installer_files/conda"INSTALL_ENV_DIR="$(pwd)/installer_files/env"
# environment isolationexport PYTHONNOUSERSITE=1unset PYTHONPATHunset PYTHONHOMEexport CUDA_PATH="$INSTALL_ENV_DIR"export CUDA_HOME="$CUDA_PATH"
# activate envbash --init-file <(echo "source \"$CONDA_ROOT_PREFIX/etc/profile.d/conda.sh\" && conda activate \"$INSTALL_ENV_DIR\"")123456789101112131415161718192021222324#!/bin/bash
cd "$(dirname "${BASH_SOURCE[0]}")"
if [[ "$(pwd)" =~ " " ]]; then echo This script relies on Miniforge which can not be silently installed under a path with spaces. && exit; fi
# deactivate existing conda envs as needed to avoid conflicts{ conda deactivate && conda deactivate && conda deactivate; } 2> /dev/null
# configCONDA_ROOT_PREFIX="$(pwd)/installer_files/conda"INSTALL_ENV_DIR="$(pwd)/installer_files/env"
# environment isolationexport PYTHONNOUSERSITE=1unset PYTHONPATHunset PYTHONHOMEexport CUDA_PATH="$INSTALL_ENV_DIR"export CUDA_HOME="$CUDA_PATH"
# activate envsource $CONDA_ROOT_PREFIX/etc/profile.d/conda.shconda activate $INSTALL_ENV_DIRexec bash --norc12345678910111213141516171819202122232425262728293031323334@echo off
cd /D "%~dp0"
set PATH=%PATH%;%SystemRoot%\system32
echo "%CD%"| findstr /C:" " >nul && echo This script relies on Miniforge which can not be silently installed under a path with spaces. && goto end
@rem fix failed install when installing to a separate driveset TMP=%cd%\installer_filesset TEMP=%cd%\installer_files
@rem deactivate existing conda envs as needed to avoid conflicts(call conda deactivate && call conda deactivate && call conda deactivate) 2>nul
@rem configset CONDA_ROOT_PREFIX=%cd%\installer_files\condaset INSTALL_ENV_DIR=%cd%\installer_files\env
@rem environment isolationset PYTHONNOUSERSITE=1set PYTHONPATH=set PYTHONHOME=set "CUDA_PATH=%INSTALL_ENV_DIR%"set "CUDA_HOME=%CUDA_PATH%"
@rem activate installer envcall "%CONDA_ROOT_PREFIX%\condabin\conda.bat" activate "%INSTALL_ENV_DIR%" || ( echo. && echo Miniforge hook not found. && goto end )
@rem enter commandscmd /k "%*"
:endpause12345678.envDockerfile/characters/loras/models/presets/prompts/training123456789101112131415161718192021222324# by default the Dockerfile specifies these versions: 3.5;5.0;6.0;6.1;7.0;7.5;8.0;8.6+PTX# however for me to work i had to specify the exact version for my card ( 2060 ) it was 7.5# https://developer.nvidia.com/cuda-gpus you can find the version for your card here# Or for a programatic approach run `nvidia-smi --query-gpu=name,compute_cap --format=csv`TORCH_CUDA_ARCH_LIST=7.5# the port the webui binds to on the hostHOST_PORT=7860# the port the webui binds to inside the containerCONTAINER_PORT=7860# the port the api binds to on the hostHOST_API_PORT=5000# the port the api binds to inside the containerCONTAINER_API_PORT=5000# Comma separated extensions to buildBUILD_EXTENSIONS=""# Set APP_RUNTIME_GID to an appropriate host system group to enable access to mounted volumes # You can find your current host user group id with the command `id -g`APP_RUNTIME_GID=6972# override default app build permissions (handy for deploying to cloud)#APP_GID=6972#APP_UID=6972# Set cache envTRANSFORMERS_CACHE=/home/app/text-generation-webui/cache/HF_HOME=/home/app/text-generation-webui/cache/123456789101112131415161718192021222324252627FROM pytorch/pytorch:2.2.1-cuda12.1-cudnn8-runtime
# Install GitRUN apt update && apt install -y git
# System-wide TensorRT-LLM requirementsRUN apt install -y openmpi-bin libopenmpi-dev
# Set the working directoryWORKDIR /app
# Install text-generation-webuiRUN git clone https://github.com/oobabooga/text-generation-webuiWORKDIR /app/text-generation-webuiRUN pip install -r requirements.txt
# This is needed to avoid an error about "Failed to build mpi4py" in the next commandENV LD_LIBRARY_PATH=/usr/lib/x86_64-linux-gnu:$LD_LIBRARY_PATH
# Install TensorRT-LLMRUN pip3 install tensorrt_llm==0.10.0 -U --pre --extra-index-url https://pypi.nvidia.com
# Expose the necessary port for the Python serverEXPOSE 7860 5000
# Run the Python server.py script with the specified commandCMD ["python", "server.py", "--api", "--listen"]123456789101112131415161718192021# BUILDERFROM ubuntu:22.04WORKDIR /builderARG TORCH_CUDA_ARCH_LIST="${TORCH_CUDA_ARCH_LIST:-3.5;5.0;6.0;6.1;7.0;7.5;8.0;8.6+PTX}"ARG BUILD_EXTENSIONS="${BUILD_EXTENSIONS:-}"ARG APP_UID="${APP_UID:-6972}"ARG APP_GID="${APP_GID:-6972}"
RUN --mount=type=cache,target=/var/cache/apt,sharing=locked,rw \ apt update && \ apt install --no-install-recommends -y git vim build-essential python3-dev pip bash curl && \ rm -rf /var/lib/apt/lists/*WORKDIR /home/app/RUN git clone https://github.com/oobabooga/text-generation-webui.git WORKDIR /home/app/text-generation-webuiRUN GPU_CHOICE=B LAUNCH_AFTER_INSTALL=FALSE INSTALL_EXTENSIONS=TRUE ./start_linux.sh --verboseCOPY /user_data/CMD_FLAGS.txt /home/app/text-generation-webui/user_dataEXPOSE ${CONTAINER_PORT:-7860} ${CONTAINER_API_PORT:-5000} ${CONTAINER_API_STREAM_PORT:-5005}WORKDIR /home/app/text-generation-webui# set umask to ensure group read / write at runtimeCMD umask 0002 && export HOME=/home/app/text-generation-webui && ./start_linux.sh1234567891011121314151617181920212223242526272829303132333435363738394041424344version: "3.3"services: text-generation-webui: build: context: . args: # Requirements file to use: # | GPU | requirements file to use | # |--------|---------| # | NVIDIA | `requirements.txt` | # | AMD | `requirements_amd.txt` | # | CPU only | `requirements_cpu_only.txt` | # | Apple Intel | `requirements_apple_intel.txt` | # | Apple Silicon | `requirements_apple_silicon.txt` | # Default: requirements.txt` # BUILD_REQUIREMENTS: requirements.txt # Extension requirements to build: # BUILD_EXTENSIONS: # specify which cuda version your card supports: https://developer.nvidia.com/cuda-gpus TORCH_CUDA_ARCH_LIST: ${TORCH_CUDA_ARCH_LIST:-7.5} BUILD_EXTENSIONS: ${BUILD_EXTENSIONS:-} APP_GID: ${APP_GID:-6972} APP_UID: ${APP_UID:-6972} env_file: .env user: "${APP_RUNTIME_UID:-6972}:${APP_RUNTIME_GID:-6972}" ports: - "${HOST_PORT:-7860}:${CONTAINER_PORT:-7860}" - "${HOST_API_PORT:-5000}:${CONTAINER_API_PORT:-5000}" stdin_open: true group_add: - video tty: true ipc: host devices: - /dev/kfd - /dev/dri cap_add: - SYS_PTRACE security_opt: - seccomp=unconfined volumes: - ./user_data:/home/app/text-generation-webui/user_data12345678910111213141516171819202122232425# BUILDERFROM ubuntu:22.04WORKDIR /builderARG TORCH_CUDA_ARCH_LIST="${TORCH_CUDA_ARCH_LIST:-3.5;5.0;6.0;6.1;7.0;7.5;8.0;8.6+PTX}"ARG BUILD_EXTENSIONS="${BUILD_EXTENSIONS:-}"ARG APP_UID="${APP_UID:-6972}"ARG APP_GID="${APP_GID:-6972}"ARG GPU_CHOICE=AARG USE_CUDA118=FALSE ARG LAUNCH_AFTER_INSTALL=FALSE ARG INSTALL_EXTENSIONS=TRUE
RUN --mount=type=cache,target=/var/cache/apt,sharing=locked,rw \ apt update && \ apt install --no-install-recommends -y git vim build-essential python3-dev pip bash curl && \ rm -rf /var/lib/apt/lists/*WORKDIR /home/app/RUN git clone https://github.com/oobabooga/text-generation-webui.git WORKDIR /home/app/text-generation-webuiRUN GPU_CHOICE=N LAUNCH_AFTER_INSTALL=FALSE INSTALL_EXTENSIONS=TRUE ./start_linux.sh --verboseCOPY CMD_FLAGS.txt /home/app/text-generation-webui/EXPOSE ${CONTAINER_PORT:-7860} ${CONTAINER_API_PORT:-5000} ${CONTAINER_API_STREAM_PORT:-5005}# set umask to ensure group read / write at runtimeWORKDIR /home/app/text-generation-webuiCMD umask 0002 && export HOME=/home/app/text-generation-webui && ./start_linux.sh1234567891011121314151617181920212223242526272829303132333435363738394041424344version: "3.3"services: text-generation-webui: build: context: . args: # Requirements file to use: # | GPU | requirements file to use | # |--------|---------| # | NVIDIA | `requirements.txt` | # | AMD | `requirements_amd.txt` | # | CPU only | `requirements_cpu_only.txt` | # | Apple Intel | `requirements_apple_intel.txt` | # | Apple Silicon | `requirements_apple_silicon.txt` | # Default: requirements.txt` # BUILD_REQUIREMENTS: requirements.txt # Extension requirements to build: # BUILD_EXTENSIONS: # specify which cuda version your card supports: https://developer.nvidia.com/cuda-gpus TORCH_CUDA_ARCH_LIST: ${TORCH_CUDA_ARCH_LIST:-7.5} BUILD_EXTENSIONS: ${BUILD_EXTENSIONS:-} APP_GID: ${APP_GID:-6972} APP_UID: ${APP_UID:-6972} env_file: .env user: "${APP_RUNTIME_UID:-6972}:${APP_RUNTIME_GID:-6972}" ports: - "${HOST_PORT:-7860}:${CONTAINER_PORT:-7860}" - "${HOST_API_PORT:-5000}:${CONTAINER_API_PORT:-5000}" stdin_open: true tty: true volumes: - ./cache:/home/app/text-generation-webui/cache - ./characters:/home/app/text-generation-webui/characters - ./extensions:/home/app/text-generation-webui/extensions - ./loras:/home/app/text-generation-webui/loras - ./logs:/home/app/text-generation-webui/logs - ./models:/home/app/text-generation-webui/models - ./presets:/home/app/text-generation-webui/presets - ./prompts:/home/app/text-generation-webui/prompts - ./softprompts:/home/app/text-generation-webui/softprompts - ./training:/home/app/text-generation-webui/training - ./cloudflared:/etc/cloudflared123456789101112131415161718192021# BUILDERFROM ubuntu:22.04WORKDIR /builderARG TORCH_CUDA_ARCH_LIST="${TORCH_CUDA_ARCH_LIST:-3.5;5.0;6.0;6.1;7.0;7.5;8.0;8.6+PTX}"ARG BUILD_EXTENSIONS="${BUILD_EXTENSIONS:-}"ARG APP_UID="${APP_UID:-6972}"ARG APP_GID="${APP_GID:-6972}"
RUN --mount=type=cache,target=/var/cache/apt,sharing=locked,rw \ apt update && \ apt install --no-install-recommends -y git vim build-essential python3-dev pip bash curl && \ rm -rf /var/lib/apt/lists/*WORKDIR /home/app/RUN git clone https://github.com/oobabooga/text-generation-webui.git WORKDIR /home/app/text-generation-webuiRUN GPU_CHOICE=D LAUNCH_AFTER_INSTALL=FALSE INSTALL_EXTENSIONS=TRUE ./start_linux.sh --verboseCOPY /user_data/CMD_FLAGS.txt /home/app/text-generation-webui/user_dataEXPOSE ${CONTAINER_PORT:-7860} ${CONTAINER_API_PORT:-5000} ${CONTAINER_API_STREAM_PORT:-5005}# set umask to ensure group read / write at runtimeWORKDIR /home/app/text-generation-webuiCMD umask 0002 && export HOME=/home/app/text-generation-webui && ./start_linux.sh1234567891011121314151617181920212223242526272829303132333435363738394041424344version: "3.3"services: text-generation-webui: build: context: . args: # Requirements file to use: # | GPU | requirements file to use | # |--------|---------| # | NVIDIA | `requirements.txt` | # | AMD | `requirements_amd.txt` | # | CPU only | `requirements_cpu_only.txt` | # | Apple Intel | `requirements_apple_intel.txt` | # | Apple Silicon | `requirements_apple_silicon.txt` | # Default: requirements.txt` # BUILD_REQUIREMENTS: requirements.txt
# Extension requirements to build: # BUILD_EXTENSIONS:
# specify which cuda version your card supports: https://developer.nvidia.com/cuda-gpus TORCH_CUDA_ARCH_LIST: ${TORCH_CUDA_ARCH_LIST:-7.5} BUILD_EXTENSIONS: ${BUILD_EXTENSIONS:-} APP_GID: ${APP_GID:-6972} APP_UID: ${APP_UID:-6972} env_file: .env user: "${APP_RUNTIME_UID:-6972}:${APP_RUNTIME_GID:-6972}" ports: - "${HOST_PORT:-7860}:${CONTAINER_PORT:-7860}" - "${HOST_API_PORT:-5000}:${CONTAINER_API_PORT:-5000}" stdin_open: true group_add: - video tty: true ipc: host devices: - /dev/kfd - /dev/dri cap_add: - SYS_PTRACE security_opt: - seccomp=unconfined volumes: - ./user_data:/home/app/text-generation-webui/user_data123456789101112131415161718192021# BUILDERFROM ubuntu:22.04WORKDIR /builderARG TORCH_CUDA_ARCH_LIST="${TORCH_CUDA_ARCH_LIST:-3.5;5.0;6.0;6.1;7.0;7.5;8.0;8.6+PTX}"ARG BUILD_EXTENSIONS="${BUILD_EXTENSIONS:-}"ARG APP_UID="${APP_UID:-6972}"ARG APP_GID="${APP_GID:-6972}"
RUN --mount=type=cache,target=/var/cache/apt,sharing=locked,rw \ apt update && \ apt install --no-install-recommends -y git vim build-essential python3-dev pip bash curl && \ rm -rf /var/lib/apt/lists/*WORKDIR /home/app/RUN git clone https://github.com/oobabooga/text-generation-webui.git WORKDIR /home/app/text-generation-webuiRUN GPU_CHOICE=A LAUNCH_AFTER_INSTALL=FALSE INSTALL_EXTENSIONS=TRUE ./start_linux.sh --verboseCOPY /user_data/CMD_FLAGS.txt /home/app/text-generation-webui/user_dataEXPOSE ${CONTAINER_PORT:-7860} ${CONTAINER_API_PORT:-5000} ${CONTAINER_API_STREAM_PORT:-5005}WORKDIR /home/app/text-generation-webui# set umask to ensure group read / write at runtimeCMD umask 0002 && export HOME=/home/app/text-generation-webui && ./start_linux.sh --listen1234567891011121314151617181920212223242526272829303132333435363738394041version: "3.3"services: text-generation-webui: build: context: . args: # Requirements file to use: # | GPU | requirements file to use | # |--------|---------| # | NVIDIA | `requirements.txt` | # | AMD | `requirements_amd.txt` | # | CPU only | `requirements_cpu_only.txt` | # | Apple Intel | `requirements_apple_intel.txt` | # | Apple Silicon | `requirements_apple_silicon.txt` | # Default: requirements.txt` # BUILD_REQUIREMENTS: requirements.txt
# Extension requirements to build: # BUILD_EXTENSIONS:
# specify which cuda version your card supports: https://developer.nvidia.com/cuda-gpus TORCH_CUDA_ARCH_LIST: ${TORCH_CUDA_ARCH_LIST:-7.5} BUILD_EXTENSIONS: ${BUILD_EXTENSIONS:-} APP_GID: ${APP_GID:-6972} APP_UID: ${APP_UID:-6972} env_file: .env user: "${APP_RUNTIME_UID:-6972}:${APP_RUNTIME_GID:-6972}" ports: - "${HOST_PORT:-7860}:${CONTAINER_PORT:-7860}" - "${HOST_API_PORT:-5000}:${CONTAINER_API_PORT:-5000}" stdin_open: true tty: true volumes: - ./user_data:/home/app/text-generation-webui/user_data deploy: resources: reservations: devices: - driver: nvidia count: all capabilities: [gpu]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148Used to have multi-turn conversations with the model.
## Input area
The following buttons can be found. Note that the hover menu can be replaced with always-visible buttons with the `--chat-buttons` flag.
* **Generate**: sends your message and makes the model start a reply.* **Stop**: stops an ongoing generation as soon as the next token is generated (which can take a while for a slow model).* **Continue**: makes the model attempt to continue the existing reply. In some cases, the model may simply end the existing turn immediately without generating anything new, but in other cases, it may generate a longer reply.* **Regenerate**: similar to Generate, but your last message is used as input instead of the text in the input field. Note that if the temperature/top_p/top_k parameters are low in the "Parameters" tab of the UI, the new reply may end up identical to the previous one.* **Remove last reply**: removes the last input/output pair from the history and sends your last message back into the input field.* **Replace last reply**: replaces the last reply with whatever you typed into the input field. Useful in conjunction with "Copy last reply" if you want to edit the bot response.* **Copy last reply**: sends the contents of the bot's last reply to the input field.* **Impersonate**: makes the model generate a new message on your behalf in the input field, taking into consideration the existing chat history.* **Send dummy message**: adds a new message to the chat history without causing the model to generate a reply.* **Send dummy reply**: adds a new reply to the chat history as if the model had generated this reply. Useful in conjunction with "Send dummy message".* **Start new chat**: starts a new conversation while keeping the old one saved. If you are talking to a character that has a "Greeting" message defined, this message will be automatically added to the new history.* **Send to default**: sends the entire chat prompt up to now to the "Default" tab.* **Send to notebook**: sends the entire chat prompt up to now to the "Notebook" tab.
The **Show controls** checkbox causes the input fields below the input textbox to disappear. It is useful for making the page fit entirely into view and not scroll.
## Past chats
Allows you to switch between the current and previous conversations with the current character, or between the current and previous instruct conversations (if in "instruct" mode). The **Rename** menu can be used to give a unique name to the selected conversation, and the 🗑️ button allows you to delete it.
## Start reply with
Whatever you type there will appear at the start of every reply by the bot. This is useful to guide the response in the desired direction.
## Mode
The most important input field. It defines how the chat prompt is formatted. There are 3 options: chat, chat-instruct, and instruct. It is worth going into more detail about this because it seems to not be obvious to a lot of people.
### Instruction-following models
There are two kinds of models: base models, like Llama and GPT-J, and fine-tuned models, like Alpaca and Vicuna. Fine-tuned models are trained starting from base models, most often with the goal of getting the model to understand and respond to instructions just like ChatGPT does. Let's call such models *instruction-following models*.
Each instruction-following model was trained on a specific prompt format, and you have to use that exact prompt format if you want the model to follow your instructions as accurately as it can.
As an example, this is the Alpaca format:
```Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:Hi there!
### Response:Hello! It's nice to meet you. What can I help with?
### Instruction:How are you?
### Response:I'm doing well, thank you for asking! Is there something specific you would like to talk about or ask me? I'm here to help answer any questions you may have.```
This format is characterized by a context string at the top, and alternating turns where each user input starts with `### Instruction:` and each bot turn starts with `### Response:`. There are also weirder formats, like the one used by the Llama-2-chat models released by Meta AI:
```[INST] <<SYS>>Answer the questions.<</SYS>>Hi there! [/INST] Hello! It's nice to meet you. What can I help with? </s><s>[INST] How are you? [/INST] I'm doing well, thank you for asking! Is there something specific you would like to talk about or ask me? I'm here to help answer any questions you may have.```
In this format, there are special tokens at the end of each bot reply (`</s>`, the end of sequence token, and `<s>`, the beginning of sequence token); no new lines separating the turns; and the context string is written between `<<SYS>>` and `<</SYS>>`. Despite the intimidating look of this format, the logic is the same: there are user turns and bot turns, and each one appears in a specific place in the template.
It is important to emphasize that instruction-following models **have to be used with the exact prompt format that they were trained on**. Using those models with any other prompt format should be considered undefined behavior. The model will still generate replies, but they will be less accurate to your inputs.
Now that an instruction-following model is defined, we can move on to describing the 3 chat modes.
### Chat
Used for talking to the character defined under "Parameters" > "Character" using a simple chat prompt in this format:
```Chiharu Yamada's Persona: Chiharu Yamada is a young, computer engineer-nerd with a knack for problem solving and a passion for technology.You: Hi there!Chiharu Yamada: Hello! It's nice to meet you. What can I help with?You: How are you?Chiharu Yamada: I'm doing well, thank you for asking! Is there something specific you would like to talk about or ask me? I'm here to help answer any questions you may have.```
There are 3 adjustable parameters in "Parameters" > "Character" being used in this prompt:
* The **Context** string appears at the top of the prompt. Most often it describes the bot's personality and adds a few example messages to guide the model towards the desired reply length and format. This string never gets truncated: as the prompt size increases, old messages get removed one at a time until the prompt becomes smaller than the truncation length set under "Parameters" > "Generation" > "Truncate the prompt up to this length".* The **Your name** string appears at the beginning of each user reply. By default, this string is "You".* The **Character's name** string appears at the beginning of each bot reply.
Additionally, the **Greeting** string appears as the bot's opening message whenever the history is cleared.
The "Chat" option should typically be used only for base models or non-instruct fine tunes, and should not be used for instruction-following models.
### Instruct
Used for talking to an instruction-following model using the prompt format defined under "Parameters" > "Instruction template". Think of this option as an offline ChatGPT.
The prompt format is defined by the **Instruction template** parameter in "Parameters" > "Instruction template", which represents a Jinja2 template.
Note that when you load a model in the "Model" tab, the web UI will try to automatically detect its instruction template (if any), and will update the values under "Parameters" > "Instruction template" accordingly. This is done using a set of regular expressions defined in `models/config.yaml`. This detection is not guaranteed to be accurate. You should check the model card on Hugging Face to see if you are using the correct prompt format.
### Chat-instruct
As said above, instruction-following models are meant to be used with their specific prompt templates. The chat-instruct mode allows you to use those templates to generate a chat reply, thus mixing Chat and Instruct modes (hence the name).
It works by creating a single instruction-following turn where a command is given followed by the regular chat prompt. Here is an example in Alpaca format:
```Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:Continue the chat dialogue below. Write a single reply for the character "Chiharu Yamada".Chiharu Yamada's Persona: Chiharu Yamada is a young, computer engineer-nerd with a knack for problem solving and a passion for technology.You: Hi there!Chiharu Yamada: Hello! It's nice to meet you. What can I help with?You: How are you?
### Response:Chiharu Yamada:```
Here, the command is
> Continue the chat dialogue below. Write a single reply for the character "Chiharu Yamada".
Below this command, the regular chat prompt is added, including its Context string and the chat history, and then the user turn ends. The bot turn starts with the "Character's name" string followed by `:`, thus prompting the instruction-following model to write a single reply for the character.
The chat-instruct command can be customized under "Parameters" > "Instruction template" > "Command for chat-instruct mode". Inside that command string, `<|character|>` is a placeholder that gets replaced with the bot name, and `<|prompt|>` is a placeholder that gets replaced with the full chat prompt.
Note that you can get creative: instead of writing something trivial like "Write a single reply for the character", you could add more complex instructions like
> This is an adventure game, and your task is to write a reply in name of "<|character|>" where 3 options are given for the user to then choose from.
And it works:

## Chat style
This defines the visual style of the chat UI. Each option is a CSS file defined under `text-generation-webui/css/chat_style-name.css`, where "name" is how this style is called in the dropdown menu. You can add new styles by simply copying `chat_style-cai-chat.css` to `chat_style-myNewStyle.css` and editing the contents of this new file. If you end up with a style that you like, you are highly encouraged to submit it to the repository.
The styles are only applied to chat and chat-instruct modes. Instruct mode has its separate style defined in `text-generation-webui/css/html_instruct_style.css`.
## Character gallery
This menu is a built-in extension defined under `text-generation-webui/extensions/gallery`. It displays a gallery with your characters, and if you click on a character, it will be automatically selected in the menu under "Parameters" > "Character".1234567891011121314151617181920212223242526272829303132333435Used to generate raw completions starting from your prompt.
## Default tab
This tab contains two main text boxes: Input, where you enter your prompt, and Output, where the model output will appear.
### Input
The number on the lower right of the Input box counts the number of tokens in the input. It gets updated whenever you update the input text as long as a model is loaded (otherwise there is no tokenizer to count the tokens).
Below the Input box, the following buttons can be found:
* **Generate**: starts a new generation.* **Stop**: stops an ongoing generation as soon as the next token is generated (which can take a while for a slow model).* **Continue**: starts a new generation taking as input the text in the "Output" box.
In the **Prompt** menu, you can select from some predefined prompts defined under `text-generation-webui/prompts`. The 💾 button saves your current input as a new prompt, the 🗑️ button deletes the selected prompt, and the 🔄 button refreshes the list. If you come up with an interesting prompt for a certain task, you are welcome to submit it to the repository.
### Output
Five tabs can be found:
* **Raw**: where the raw text generated by the model appears.* **Markdown**: it contains a "Render" button. You can click on it at any time to render the current output as markdown. This is particularly useful for models that generate LaTeX equations like GALACTICA.* **HTML**: displays the output in an HTML style that is meant to be easier to read. Its style is defined under `text-generation-webui/css/html_readable_style.css`.* **Logits**: when you click on "Get next token probabilities", this tab displays the 50 most likely next tokens and their probabilities based on your current input. If "Use samplers" is checked, the probabilities will be the ones after the sampling parameters in the "Parameters" > "Generation" tab are applied. Otherwise, they will be the raw probabilities generated by the model.* **Tokens**: allows you to tokenize your prompt and see the ID numbers for the individual tokens.
## Notebook tab
Precisely the same thing as the Default tab, with the difference that the output appears in the same text box as the input.
It contains the following additional button:
* **Regenerate**: uses your previous input for generation while discarding the last output.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128## Generation
Contains parameters that control the text generation.
### Quick rundown
LLMs work by generating one token at a time. Given your prompt, the model calculates the probabilities for every possible next token. The actual token generation is done after that.
* In *greedy decoding*, the most likely token is always picked.* Most commonly, *sampling* techniques are used to choose from the next-token distribution in a more non-trivial way with the goal of improving the quality of the generated text.
### Preset menu
Can be used to save and load combinations of parameters for reuse.
* **🎲 button**: creates a random yet interpretable preset. Only 1 parameter of each category is included for the categories: removing tail tokens, avoiding repetition, and flattening the distribution. That is, top_p and top_k are not mixed, and neither are repetition_penalty and frequency_penalty. You can use this button to break out of a loop of bad generations after multiple "Regenerate" attempts.
#### Built-in presets
These were obtained after a blind contest called "Preset Arena" where hundreds of people voted. The full results can be found [here](https://github.com/oobabooga/oobabooga.github.io/blob/main/arena/results.md).
A key takeaway is that the best presets are:
* **For Instruct**: Divine Intellect, Big O, simple-1.* **For Chat**: Midnight Enigma, Yara, Shortwave.
The other presets are:
* Mirostat: a special decoding technique first implemented in llama.cpp and then adapted into this repository for all loaders. Many people have obtained positive results with it for chat.* LLaMA-Precise: a legacy preset that was the default for the web UI before the Preset Arena.* Debug-deterministic: disables sampling. It is useful for debugging, or if you intentionally want to use greedy decoding.
### Parameters description
For more information about the parameters, the [transformers documentation](https://huggingface.co/docs/transformers/main_classes/text_generation#transformers.GenerationConfig) is a good reference.
* **max_new_tokens**: Maximum number of tokens to generate. Don't set it higher than necessary: it is used in the truncation calculation through the formula `(prompt_length) = min(truncation_length - max_new_tokens, prompt_length)`, so your prompt will get truncated if you set it too high.* **temperature**: Primary factor to control the randomness of outputs. 0 = deterministic (only the most likely token is used). Higher value = more randomness.* **top_p**: If not set to 1, select tokens with probabilities adding up to less than this number. Higher value = higher range of possible random results.* **min_p**: Tokens with probability smaller than `(min_p) * (probability of the most likely token)` are discarded. This is the same as top_a but without squaring the probability.* **top_k**: Similar to top_p, but select instead only the top_k most likely tokens. Higher value = higher range of possible random results.* **repetition_penalty**: Penalty factor for repeating prior tokens. 1 means no penalty, higher value = less repetition, lower value = more repetition.* **presence_penalty**: Similar to repetition_penalty, but with an additive offset on the raw token scores instead of a multiplicative factor. It may generate better results. 0 means no penalty, higher value = less repetition, lower value = more repetition. Previously called "additive_repetition_penalty".* **frequency_penalty**: Repetition penalty that scales based on how many times the token has appeared in the context. Be careful with this; there's no limit to how much a token can be penalized.* **repetition_penalty_range**: The number of most recent tokens to consider for repetition penalty. 0 makes all tokens be used.* **typical_p**: If not set to 1, select only tokens that are at least this much more likely to appear than random tokens, given the prior text.* **tfs**: Tries to detect a tail of low-probability tokens in the distribution and removes those tokens. See [this blog post](https://www.trentonbricken.com/Tail-Free-Sampling/) for details. The closer to 0, the more discarded tokens.* **top_a**: Tokens with probability smaller than `(top_a) * (probability of the most likely token)^2` are discarded.* **epsilon_cutoff**: In units of 1e-4; a reasonable value is 3. This sets a probability floor below which tokens are excluded from being sampled.* **eta_cutoff**: In units of 1e-4; a reasonable value is 3. The main parameter of the special Eta Sampling technique. See [this paper](https://arxiv.org/pdf/2210.15191.pdf) for a description.* **guidance_scale**: The main parameter for Classifier-Free Guidance (CFG). [The paper](https://arxiv.org/pdf/2306.17806.pdf) suggests that 1.5 is a good value. It can be used in conjunction with a negative prompt or not.* **Negative prompt**: Only used when `guidance_scale != 1`. It is most useful for instruct models and custom system messages. You place your full prompt in this field with the system message replaced with the default one for the model (like "You are Llama, a helpful assistant...") to make the model pay more attention to your custom system message.* **penalty_alpha**: Contrastive Search is enabled by setting this to greater than zero and unchecking "do_sample". It should be used with a low value of top_k, for instance, top_k = 4.* **mirostat_mode**: Activates Mirostat sampling, an adaptive decoding method that dynamically controls output perplexity for higher-quality text generation. 0 is disabled. 1 is the classic Mirostat algorithm described in [the paper](https://arxiv.org/abs/2007.14966), but can be less stable, or “wobbly,” and produce less coherent text. 2 is the improved version that is more stable and has lower perplexity, recommended for most use cases. *Note: Use either mirostat or dynamic_temperature, not both at the same time.** **mirostat_tau**: Target perplexity for Mirostat sampling. Controls how “surprising” the text is. Higher values = more diverse, lower = more predictable. Preset Arena suggests 8 as a good value.* **mirostat_eta**: Learning rate for Mirostat’s perplexity adjustment. Higher values = adapts faster but less stable, lower values = slower but more stable. Preset Arena suggests 0.1 as a good value.* **dynamic_temperature**: Activates Dynamic Temperature. This modifies temperature to range between "dynatemp_low" (minimum) and "dynatemp_high" (maximum), with an entropy-based scaling. The steepness of the curve is controlled by "dynatemp_exponent". *Note: Use either dynamic_temperature or mirostat, not both at the same time.** **smoothing_factor**: Activates Quadratic Sampling. When `0 < smoothing_factor < 1`, the logits distribution becomes flatter. When `smoothing_factor > 1`, it becomes more peaked.* **temperature_last**: Makes temperature the last sampler instead of the first. With this, you can remove low probability tokens with a sampler like min_p and then use a high temperature to make the model creative without losing coherency. Note: this parameter takes precedence over "Sampler priority". That means that `temperature`/`dynamic_temperature`/`quadratic_sampling` will be removed from wherever they are and moved to the end of the stack.* **do_sample**: When unchecked, sampling is entirely disabled, and greedy decoding is used instead (the most likely token is always picked).* **Seed**: Set the Pytorch seed to this number. Note that some loaders do not use Pytorch (notably llama.cpp), and others are not deterministic (ExLlamaV2). For these loaders, the seed has no effect.* **encoder_repetition_penalty**: Also known as the "Hallucinations filter". Used to penalize tokens that are *not* in the prior text. Higher value = more likely to stay in context, lower value = more likely to diverge.* **no_repeat_ngram_size**: If not set to 0, specifies the length of token sets that are completely blocked from repeating at all. Higher values = blocks larger phrases, lower values = blocks words or letters from repeating. Only 0 or high values are a good idea in most cases.
To the right (or below if you are on mobile), the following parameters are present:
* **Truncate the prompt up to this length**: Used to prevent the prompt from getting bigger than the model's context length. In the case of the transformers loader, which allocates memory dynamically, this parameter can also be used to set a VRAM ceiling and prevent out-of-memory errors. This parameter is automatically updated with the model's context length (from "n_ctx" or "max_seq_len" for loaders that use these parameters, and from the model metadata directly for loaders that do not) when you load a model.* **Maximum number of tokens/second**: to make text readable in real-time in case the model is generating too fast. Good if you want to flex and tell everyone how good your GPU is.* **Custom stopping strings**: The model stops generating as soon as any of the strings set in this field is generated. Note that when generating text in the Chat tab, some default stopping strings are set regardless of this parameter, like "\nYour Name:" and "\nBot name:" for chat mode. That's why this parameter has a "Custom" in its name.* **Custom token bans**: Allows you to ban the model from generating certain tokens altogether. You need to find the token IDs under "Default" > "Tokens" or "Notebook" > "Tokens", or by looking at the `tokenizer.json` for the model directly.* **auto_max_new_tokens**: When checked, the max_new_tokens parameter is expanded in the backend to the available context length. The maximum length is given by the "truncation_length" parameter. This is useful for getting long replies in the Chat tab without having to click on "Continue" many times.* **Ban the eos_token**: One of the possible tokens that a model can generate is the EOS (End of Sequence) token. When it is generated, the generation stops prematurely. When this parameter is checked, that token is banned from being generated, and the generation will always generate "max_new_tokens" tokens.* **Add the bos_token to the beginning of prompts**: By default, the tokenizer will add a BOS (Beginning of Sequence) token to your prompt. During training, BOS tokens are used to separate different documents. If unchecked, no BOS token will be added, and the model will interpret your prompt as being in the middle of a document instead of at the start of one. This significantly changes the output and can make it more creative.* **Skip special tokens**: When decoding the generated tokens, skip special tokens from being converted to their text representation. Otherwise, BOS appears as `<s>`, EOS as `</s>`, etc.* **Activate text streaming**: When unchecked, the full response is outputted at once, without streaming the words one at a time. I recommend unchecking this parameter on high latency networks like running the webui on Google Colab or using `--share`.* **Sampler priority**: Allows you to customize the order in which the different samplers are applied. The first sampler on the list gets applied first. With this, custom orders like `top_p -> temperature -> top_k` can be defined.* **Load grammar from file**: Loads a GBNF grammar from a file under `text-generation-webui/grammars`. The output is written to the "Grammar" box below. You can also save and delete custom grammars using this menu.* **Grammar**: Allows you to constrain the model output to a particular format. For instance, you can make the model generate lists, JSON, specific words, etc. Grammar is extremely powerful and I highly recommend it. The syntax looks a bit daunting at first sight, but it gets very easy once you understand it. See the [GBNF Guide](https://github.com/ggerganov/llama.cpp/blob/master/grammars/README.md) for details.
## Character
Parameters that define the character that is used in the Chat tab when "chat" or "chat-instruct" are selected under "Mode".
* **Character**: A dropdown menu where you can select from saved characters, save a new character (💾 button), and delete the selected character (🗑️).* **Your name**: Your name as it appears in the prompt.* **Character's name**: The bot name as it appears in the prompt.* **Context**: A string that is always at the top of the prompt. It never gets truncated. It usually defines the bot's personality and some key elements of the conversation.* **Greeting**: An opening message for the bot. When set, it appears whenever you start a new chat.* **Character picture**: A profile picture for the bot. To make it apply, you need to save the bot by clicking on 💾.* **Your picture**: Your profile picture. It will be used in all conversations.
Note: the following replacements take place in the context and greeting fields when the chat prompt is generated:
* `{{char}}` and `<BOT>` get replaced with "Character's name".* `{{user}}` and `<USER>` get replaced with "Your name".
So you can use those special placeholders in your character definitions. They are commonly found in TavernAI character cards.
## Instruction template
Defines the instruction template that is used in the Chat tab when "instruct" or "chat-instruct" are selected under "Mode".
* **Saved instruction templates**: A dropdown menu where you can load a saved template, save a new template (💾 button), and delete the currently selected template (🗑️).* **Custom system message**: A message that defines the personality of the chatbot, replacing its default "System message" string. Example: "You are a duck."* **Instruction template**: A Jinja2 template that defines the prompt format for the instruction-following conversation.* **Send to default**: Send the full instruction template in string format to the Default tab.* **Send to notebook**: Send the full instruction template in string format to the Notebook tab.* **Send to negative prompt**: Send the full instruction template in string format to the "Negative prompt" field under "Parameters" > "Generation".* **Chat template**: A Jinja2 template that defines the prompt format for regular chat conversations with characters.* **Command for chat-instruct mode**: The command that is used in chat-instruct mode to query the model to generate a reply on behalf of the character. Can be used creatively to generate specific kinds of responses.
## Chat history
In this tab, you can download the current chat history in JSON format and upload a previously saved chat history.
When a history is uploaded, a new chat is created to hold it. That is, you don't lose your current chat in the Chat tab.
## Upload character
### YAML or JSON
Allows you to upload characters in the YAML format used by the web UI, including optionally a profile picture.
### TavernAI PNG
Allows you to upload a TavernAI character card. It will be converted to the internal YAML format of the web UI after upload.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129This is where you load models, apply LoRAs to a loaded model, and download new models.
## Model loaders
### Transformers
Loads: full precision (16-bit or 32-bit) models. The repository usually has a clean name without GGUF, EXL2, GPTQ, or AWQ in its name, and the model files are named `pytorch_model.bin` or `model.safetensors`.
Example: [https://huggingface.co/lmsys/vicuna-7b-v1.5](https://huggingface.co/lmsys/vicuna-7b-v1.5).
Full precision models use a ton of VRAM, so you will usually want to select the "load_in_4bit" and "use_double_quant" options to load the model in 4-bit precision using bitsandbytes.
This loader can also load GPTQ models and train LoRAs with them. For that, make sure to check the "auto-devices" and "disable_exllama" options before loading the model.
Options:
* **gpu-memory**: When set to greater than 0, activates CPU offloading using the accelerate library, where part of the layers go to the CPU. The performance is very bad. Note that accelerate doesn't treat this parameter very literally, so if you want the VRAM usage to be at most 10 GiB, you may need to set this parameter to 9 GiB or 8 GiB. It can be used in conjunction with "load_in_8bit" but not with "load-in-4bit" as far as I'm aware.* **cpu-memory**: Similarly to the parameter above, you can also set a limit on the amount of CPU memory used. Whatever doesn't fit either in the GPU or the CPU will go to a disk cache, so to use this option you should also check the "disk" checkbox.* **compute_dtype**: Used when "load-in-4bit" is checked. I recommend leaving the default value.* **quant_type**: Used when "load-in-4bit" is checked. I recommend leaving the default value.* **alpha_value**: Used to extend the context length of a model with a minor loss in quality. I have measured 1.75 to be optimal for 1.5x context, and 2.5 for 2x context. That is, with alpha = 2.5 you can make a model with 4096 context length go to 8192 context length.* **rope_freq_base**: Originally another way to write "alpha_value", it ended up becoming a necessary parameter for some models like CodeLlama, which was fine-tuned with this set to 1000000 and hence needs to be loaded with it set to 1000000 as well.* **compress_pos_emb**: The first and original context-length extension method, discovered by [kaiokendev](https://kaiokendev.github.io/til). When set to 2, the context length is doubled, 3 and it's tripled, etc. It should only be used for models that have been fine-tuned with this parameter set to different than 1. For models that have not been tuned to have greater context length, alpha_value will lead to a smaller accuracy loss.* **cpu**: Loads the model in CPU mode using Pytorch. The model will be loaded in 32-bit precision, so a lot of RAM will be used. CPU inference with transformers is older than llama.cpp and it works, but it's a lot slower. Note: this parameter has a different interpretation in the llama.cpp loader (see below).* **load-in-8bit**: Load the model in 8-bit precision using bitsandbytes. The 8-bit kernel in that library has been optimized for training and not inference, so load-in-8bit is slower than load-in-4bit (but more accurate).* **bf16**: Use bfloat16 precision instead of float16 (the default). Only applies when quantization is not used.* **auto-devices**: When checked, the backend will try to guess a reasonable value for "gpu-memory" to allow you to load a model with CPU offloading. I recommend just setting "gpu-memory" manually instead. This parameter is also needed for loading GPTQ models, in which case it needs to be checked before loading the model.* **disk**: Enable disk offloading for layers that don't fit into the GPU and CPU combined.* **load-in-4bit**: Load the model in 4-bit precision using bitsandbytes.* **trust-remote-code**: Some models use custom Python code to load the model or the tokenizer. For such models, this option needs to be set. It doesn't download any remote content: all it does is execute the .py files that get downloaded with the model. Those files can potentially include malicious code; I have never seen it happen, but it is in principle possible.* **no_use_fast**: Do not use the "fast" version of the tokenizer. Can usually be ignored; only check this if you can't load the tokenizer for your model otherwise.* **use_flash_attention_2**: Set use_flash_attention_2=True while loading the model. Possibly useful for training.* **disable_exllama**: Only applies when you are loading a GPTQ model through the transformers loader. It needs to be checked if you intend to train LoRAs with the model.
### ExLlamav2_HF
Loads: GPTQ and EXL2 models. EXL2 models usually have "EXL2" in the model name, while GPTQ models usually have GPTQ in the model name, or alternatively something like "-4bit-128g" in the name.
Examples:
* https://huggingface.co/turboderp/Llama2-70B-exl2* https://huggingface.co/TheBloke/Llama-2-13B-chat-GPTQ
* **gpu-split**: If you have multiple GPUs, the amount of memory to allocate per GPU should be set in this field. Make sure to set a lower value for the first GPU, as that's where the cache is allocated.* **max_seq_len**: The maximum sequence length for the model. In ExLlamaV2, the cache is preallocated, so the higher this value, the higher the VRAM. It is automatically set to the maximum sequence length for the model based on its metadata, but you may need to lower this value be able to fit the model into your GPU. After loading the model, the "Truncate the prompt up to this length" parameter under "Parameters" > "Generation" is automatically set to your chosen "max_seq_len" so that you don't have to set the same thing twice.* **cfg-cache**: Creates a second cache to hold the CFG negative prompts. You need to set this if and only if you intend to use CFG in the "Parameters" > "Generation" tab. Checking this parameter doubles the cache VRAM usage.* **no_flash_attn**: Disables flash attention. Otherwise, it is automatically used as long as the library is installed.* **cache_8bit**: Create a 8-bit precision cache instead of a 16-bit one. This saves VRAM but increases perplexity (I don't know by how much).* **cache_4bit**: Creates a Q4 cache using grouped quantization.
### ExLlamav2
The same as ExLlamav2_HF but using the internal samplers of ExLlamav2 instead of the ones in the Transformers library.
### AutoGPTQ
Loads: GPTQ models.
* **wbits**: For ancient models without proper metadata, sets the model precision in bits manually. Can usually be ignored.* **groupsize**: For ancient models without proper metadata, sets the model group size manually. Can usually be ignored.* **triton**: Only available on Linux. Necessary to use models with both act-order and groupsize simultaneously. Note that ExLlamaV2 can load these same models on Windows without triton.* **no_inject_fused_attention**: Improves performance while increasing the VRAM usage.* **no_inject_fused_mlp**: Similar to the previous parameter but for Triton only.* **no_use_cuda_fp16**: On some systems, the performance can be very bad with this unset. Can usually be ignored.* **desc_act**: For ancient models without proper metadata, sets the model "act-order" parameter manually. Can usually be ignored.
### llama.cpp
Loads: GGUF models. Note: GGML models have been deprecated and do not work anymore.
Example: https://huggingface.co/TheBloke/Llama-2-7b-Chat-GGUF
* **n-gpu-layers**: The number of layers to allocate to the GPU. If set to 0, only the CPU will be used. If you want to offload all layers, you can simply set this to the maximum value.* **n_ctx**: Context length of the model. In llama.cpp, the cache is preallocated, so the higher this value, the higher the VRAM. It is automatically set to the maximum sequence length for the model based on the metadata inside the GGUF file, but you may need to lower this value be able to fit the model into your GPU. After loading the model, the "Truncate the prompt up to this length" parameter under "Parameters" > "Generation" is automatically set to your chosen "n_ctx" so that you don't have to set the same thing twice.* **tensor_split**: For multi-gpu only. Sets the amount of memory to allocate per GPU as proportions. Not to be confused with other loaders where this is set in GB; here you can set something like `30,70` for 30%/70%.* **n_batch**: Batch size for prompt processing. Higher values are supposed to make generation faster, but I have never obtained any benefit from changing this value.* **threads**: Number of threads. Recommended value: your number of physical cores. * **threads_batch**: Number of threads for batch processing. Recommended value: your total number of cores (physical + virtual).* **tensorcores**: Use llama.cpp compiled with "tensor cores" support, which improves performance on NVIDIA RTX cards in most cases.* **streamingllm**: Experimental feature to avoid re-evaluating the entire prompt when part of it is removed, for instance, when you hit the context length for the model in chat mode and an old message is removed.* **cpu**: Force a version of llama.cpp compiled without GPU acceleration to be used. Can usually be ignored. Only set this if you want to use CPU only and llama.cpp doesn't work otherwise. * **no_mul_mat_q**: Disable the mul_mat_q kernel. This kernel usually improves generation speed significantly. This option to disable it is included in case it doesn't work on some system.* **no-mmap**: Loads the model into memory at once, possibly preventing I/O operations later on at the cost of a longer load time.* **mlock**: Force the system to keep the model in RAM rather than swapping or compressing (no idea what this means, never used it).* **numa**: May improve performance on certain multi-cpu systems.
### llamacpp_HF
The same as llama.cpp but with transformers samplers, and using the transformers tokenizer instead of the internal llama.cpp tokenizer.
To use it, you need to download a tokenizer. There are two options:
1) Download `oobabooga/llama-tokenizer` under "Download model or LoRA". That's a default Llama tokenizer.2) Place your .gguf in a subfolder of `models/` along with these 3 files: `tokenizer.model`, `tokenizer_config.json`, and `special_tokens_map.json`. This takes precedence over Option 1.
It has an additional parameter:
* **logits_all**: Needs to be checked if you want to evaluate the perplexity of the llama.cpp model using the "Training" > "Perplexity evaluation" tab. Otherwise, leave it unchecked, as it makes prompt processing slower.
### AutoAWQ
Loads: AWQ models.
Example: https://huggingface.co/TheBloke/Phind-CodeLlama-34B-v2-AWQ
The parameters are overall similar to AutoGPTQ.
## Model dropdown
Here you can select a model to be loaded, refresh the list of available models (🔄), load/unload/reload the selected model, and save the settings for the model. The "settings" are the values in the input fields (checkboxes, sliders, dropdowns) below this dropdown.
After saving, those settings will get restored whenever you select that model again in the dropdown menu.
If the **Autoload the model** checkbox is selected, the model will be loaded as soon as it is selected in this menu. Otherwise, you will have to click on the "Load" button.
## LoRA dropdown
Used to apply LoRAs to the model. Note that LoRA support is not implemented for all loaders. Check this [page](https://github.com/oobabooga/text-generation-webui/wiki) for details.
## Download model or LoRA
Here you can download a model or LoRA directly from the https://huggingface.co/ website.
* Models will be saved to `text-generation-webui/models`.* LoRAs will be saved to `text-generation-webui/loras`.
In the input field, you can enter either the Hugging Face username/model path (like `facebook/galactica-125m`) or the full model URL (like `https://huggingface.co/facebook/galactica-125m`). To specify a branch, add it at the end after a ":" character like this: `facebook/galactica-125m:main`.
To download a single file, as necessary for models in GGUF format, you can click on "Get file list" after entering the model path in the input field, and then copy and paste the desired file name in the "File name" field before clicking on "Download".123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139## Training Your Own LoRAs
The WebUI seeks to make training your own LoRAs as easy as possible. It comes down to just a few simple steps:
### **Step 1**: Make a plan.- What base model do you want to use? The LoRA you make has to be matched up to a single architecture (eg LLaMA-13B) and cannot be transferred to others (eg LLaMA-7B, StableLM, etc. would all be different). Derivatives of the same model (eg Alpaca finetune of LLaMA-13B) might be transferrable, but even then it's best to train exactly on what you plan to use.- What are you training it on? Do you want it to learn real information, a simple format, ...?
### **Step 2**: Gather a dataset.- If you use a dataset similar to the [Alpaca](https://github.com/gururise/AlpacaDataCleaned/blob/main/alpaca_data_cleaned.json) format, that is natively supported by the `Formatted Dataset` input in the WebUI, with premade formatter options.- If you use a dataset that isn't matched to Alpaca's format, but uses the same basic JSON structure, you can make your own format file by copying `training/formats/alpaca-format.json` to a new file and [editing its content](#format-files).- If you can get the dataset into a simple text file, that works too! You can train using the `Raw text file` input option. - This means you can for example just copy/paste a chatlog/documentation page/whatever you want, shove it in a plain text file, and train on it.- If you use a structured dataset not in this format, you may have to find an external way to convert it - or open an issue to request native support.
### **Step 3**: Do the training.- **3.1**: Load the WebUI, and your model. - Make sure you don't have any LoRAs already loaded (unless you want to train for multi-LoRA usage).- **3.2**: Open the `Training` tab at the top, `Train LoRA` sub-tab.- **3.3**: Fill in the name of the LoRA, select your dataset in the dataset options.- **3.4**: Select other parameters to your preference. See [parameters below](#parameters).- **3.5**: click `Start LoRA Training`, and wait. - It can take a few hours for a large dataset, or just a few minute if doing a small run. - You may want to monitor your [loss value](#loss) while it goes.
### **Step 4**: Evaluate your results.- Load the LoRA under the Models Tab.- You can go test-drive it on the `Text generation` tab, or you can use the `Perplexity evaluation` sub-tab of the `Training` tab.- If you used the `Save every n steps` option, you can grab prior copies of the model from sub-folders within the LoRA model's folder and try them instead.
### **Step 5**: Re-run if you're unhappy.- Make sure to unload the LoRA before training it.- You can simply resume a prior run - use `Copy parameters from` to select your LoRA, and edit parameters. Note that you cannot change the `Rank` of an already created LoRA. - If you want to resume from a checkpoint saved along the way, simply copy the contents of the checkpoint folder into the LoRA's folder. - (Note: `adapter_model.bin` is the important file that holds the actual LoRA content). - This will start Learning Rate and Steps back to the start. If you want to resume as if you were midway through, you can adjust your Learning Rate to the last reported LR in logs and reduce your epochs.- Or, you can start over entirely if you prefer.- If your model is producing corrupted outputs, you probably need to start over and use a lower Learning Rate.- If your model isn't learning detailed information but you want it to, you might need to just run more epochs, or you might need a higher Rank.- If your model is enforcing a format you didn't want, you may need to tweak your dataset, or start over and not train as far.
## Format Files
If using JSON formatted datasets, they are presumed to be in the following approximate format:
```json[ { "somekey": "somevalue", "key2": "value2" }, { // etc }]```
Where the keys (eg `somekey`, `key2` above) are standardized, and relatively consistent across the dataset, and the values (eg `somevalue`, `value2`) contain the content actually intended to be trained.
For Alpaca, the keys are `instruction`, `input`, and `output`, wherein `input` is sometimes blank.
A simple format file for Alpaca to be used as a chat bot is:
```json{ "instruction,output": "User: %instruction%\nAssistant: %output%", "instruction,input,output": "User: %instruction%: %input%\nAssistant: %output%"}```
Note that the keys (eg `instruction,output`) are a comma-separated list of dataset keys, and the values are a simple string that use those keys with `%%`.
So for example if a dataset has `"instruction": "answer my question"`, then the format file's `User: %instruction%\n` will be automatically filled in as `User: answer my question\n`.
If you have different sets of key inputs, you can make your own format file to match it. This format-file is designed to be as simple as possible to enable easy editing to match your needs.
## Raw Text File Settings
When using raw text files as your dataset, the text is automatically split into chunks based on your `Cutoff Length` you get a few basic options to configure them.- `Overlap Length` is how much to overlap chunks by. Overlapping chunks helps prevent the model from learning strange mid-sentence cuts, and instead learn continual sentences that flow from earlier text.- `Prefer Newline Cut Length` sets a maximum distance in characters to shift the chunk cut towards newlines. Doing this helps prevent lines from starting or ending mid-sentence, preventing the model from learning to cut off sentences randomly.- `Hard Cut String` sets a string that indicates there must be a hard cut without overlap. This defaults to `\n\n\n`, meaning 3 newlines. No trained chunk will ever contain this string. This allows you to insert unrelated sections of text in the same text file, but still ensure the model won't be taught to randomly change the subject.
## Parameters
The basic purpose and function of each parameter is documented on-page in the WebUI, so read through them in the UI to understand your options.
That said, here's a guide to the most important parameter choices you should consider:
### VRAM
- First, you must consider your VRAM availability. - Generally, under default settings, VRAM usage for training with default parameters is very close to when generating text (with 1000+ tokens of context) (ie, if you can generate text, you can train LoRAs). - Note: worse by default in the 4-bit monkeypatch currently. Reduce `Micro Batch Size` to `1` to restore this to expectations. - If you have VRAM to spare, setting higher batch sizes will use more VRAM and get you better quality training in exchange. - If you have large data, setting a higher cutoff length may be beneficial, but will cost significant VRAM. If you can spare some, set your batch size to `1` and see how high you can push your cutoff length. - If you're low on VRAM, reducing batch size or cutoff length will of course improve that. - Don't be afraid to just try it and see what happens. If it's too much, it will just error out, and you can lower settings and try again.
### Rank
- Second, you want to consider the amount of learning you want. - For example, you may wish to just learn a dialogue format (as in the case of Alpaca) in which case setting a low `Rank` value (32 or lower) works great. - Or, you might be training on project documentation you want the bot to understand and be able to understand questions about, in which case the higher the rank, the better. - Generally, higher Rank = more precise learning = more total content learned = more VRAM usage while training.
### Learning Rate and Epochs
- Third, how carefully you want it to be learned. - In other words, how okay or not you are with the model losing unrelated understandings. - You can control this with 3 key settings: the Learning Rate, its scheduler, and your total epochs. - The learning rate controls how much change is made to the model by each token it sees. - It's in scientific notation normally, so for example `3e-4` means `3 * 10^-4` which is `0.0003`. The number after `e-` controls how many `0`s are in the number. - Higher values let training run faster, but also are more likely to corrupt prior data in the model. - You essentially have two variables to balance: the LR, and Epochs. - If you make LR higher, you can set Epochs equally lower to match. High LR + low epochs = very fast, low quality training. - If you make LR low, set epochs high. Low LR + high epochs = slow but high-quality training. - The scheduler controls change-over-time as you train - it starts high, and then goes low. This helps balance getting data in, and having decent quality, at the same time. - You can see graphs of the different scheduler options [in the HuggingFace docs here](https://moon-ci-docs.huggingface.co/docs/transformers/pr_1/en/main_classes/optimizer_schedules#transformers.SchedulerType)
## Loss
When you're running training, the WebUI's console window will log reports that include, among other things, a numeric value named `Loss`. It will start as a high number, and gradually get lower and lower as it goes.
"Loss" in the world of AI training theoretically means "how close is the model to perfect", with `0` meaning "absolutely perfect". This is calculated by measuring the difference between the model outputting exactly the text you're training it to output, and what it actually outputs.
In practice, a good LLM should have a very complex variable range of ideas running in its artificial head, so a loss of `0` would indicate that the model has broken and forgotten how to think about anything other than what you trained it on.
So, in effect, Loss is a balancing game: you want to get it low enough that it understands your data, but high enough that it isn't forgetting everything else. Generally, if it goes below `1.0`, it's going to start forgetting its prior memories, and you should stop training. In some cases you may prefer to take it as low as `0.5` (if you want it to be very very predictable). Different goals have different needs, so don't be afraid to experiment and see what works best for you.
Note: if you see Loss start at or suddenly jump to exactly `0`, it is likely something has gone wrong in your training process (eg model corruption).
## Note: 4-Bit Monkeypatch
The [4-bit LoRA monkeypatch](GPTQ-models-(4-bit-mode).md#using-loras-in-4-bit-mode) works for training, but has side effects:- VRAM usage is higher currently. You can reduce the `Micro Batch Size` to `1` to compensate.- Models do funky things. LoRAs apply themselves, or refuse to apply, or spontaneously error out, or etc. It can be helpful to reload base model or restart the WebUI between training/usage to minimize chances of anything going haywire.- Loading or working with multiple LoRAs at the same time doesn't currently work.- Generally, recognize and treat the monkeypatch as the dirty temporary hack it is - it works, but isn't very stable. It will get better in time when everything is merged upstream for full official support.1234567891011121314151617181920212223242526272829303132Here you can restart the UI with new settings.
* **Available extensions**: shows a list of extensions available under `text-generation-webui/extensions`.* **Boolean command-line flags**: shows command-line flags of bool (true/false) type.
After selecting your desired flags and extensions, you can restart the UI by clicking on **Apply flags/extensions and restart**.
## Install or update an extension
In this field, you can enter the GitHub URL for an extension and press enter to either install it (i.e. cloning it into `text-generation-webui/extensions`) or update it with `git pull` in case it is already cloned.
Note that some extensions may include additional Python requirements. In this case, to install those you have to run the command
```pip install -r extensions/extension-name/requirements.txt```
or
```pip install -r extensions\extension-name\requirements.txt```
if you are on Windows.
If you used the one-click installer, this command should be executed in the terminal window that appears when you run the "cmd_" script for your OS.
## Saving UI defaults
The **Save UI defaults to settings.yaml** button gathers the visible values in the UI and saves them to settings.yaml so that your settings will persist across multiple restarts of the UI.
Note that preset parameters like temperature are not individually saved, so you need to first save your preset and select it in the preset menu before saving the defaults.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248# Extensions
Extensions are defined by files named `script.py` inside subfolders of either:- `text-generation-webui/extensions`- `text-generation-webui/user_data/extensions`
They are loaded at startup if the folder name is specified after the `--extensions` flag.
For instance, `extensions/silero_tts/script.py` or `user_data/extensions/silero_tts/script.py` gets loaded with `python server.py --extensions silero_tts`.
**Note:** Extensions in `user_data/extensions/` take priority over those in `extensions/` when both exist with the same name.
## [text-generation-webui-extensions](https://github.com/oobabooga/text-generation-webui-extensions)
The repository above contains a directory of user extensions.
If you create an extension, you are welcome to host it in a GitHub repository and submit a PR adding it to the list.
## Built-in extensions
|Extension|Description||---------|-----------||[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. ||[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. ||[google_translate](https://github.com/oobabooga/text-generation-webui/tree/main/extensions/google_translate)| Automatically translates inputs and outputs using Google Translate.||[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. ||[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. ||[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). ||[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. ||[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. ||[gallery](https://github.com/oobabooga/text-generation-webui/blob/main/extensions/gallery/)| Creates a gallery with the chat characters and their pictures. ||[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. ||[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. ||[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. |
## How to write an extension
The extensions framework is based on special functions and variables that you can define in `script.py`. The functions are the following:
| Function | Description ||-------------|-------------|| `def setup()` | Is executed when the extension gets imported. || `def ui()` | Creates custom gradio elements when the UI is launched. | | `def custom_css()` | Returns custom CSS as a string. It is applied whenever the web UI is loaded. || `def custom_js()` | Same as above but for javascript. || `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. || `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. || `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. || `def bot_prefix_modifier(string, state)` | Applied in chat mode to the prefix for the bot's reply. || `def state_modifier(state)` | Modifies the dictionary containing the UI input parameters before it is used by the text generation functions. || `def history_modifier(history)` | Modifies the chat history before the text generation in chat mode begins. || `def custom_generate_reply(...)` | Overrides the main text generation function. || `def custom_generate_chat_prompt(...)` | Overrides the prompt generator in chat mode. || `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. || `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. |
Additionally, 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.
Example:
```pythonparams = { "display_name": "Google Translate", "is_tab": True,}```
The `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` in
```pythonparams = { "display_name": "Google Translate", "is_tab": True, "language string": "jp"}```
can be customized by adding a key called `google_translate-language string` to `settings.yaml`:
```pythongoogle_translate-language string: 'fr'```
That is, the syntax for the key is `extension_name-variable_name`.
## Using multiple extensions at the same time
You 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.
Example:
```python server.py --extensions enthusiasm translate # First apply enthusiasm, then translatepython server.py --extensions translate enthusiasm # First apply translate, then enthusiasm```
Do note, that for:- `custom_generate_chat_prompt`- `custom_generate_reply`- `custom_tokenized_length`
only the first declaration encountered will be used and the rest will be ignored.
## A full example
The source code below can be found at [extensions/example/script.py](https://github.com/oobabooga/text-generation-webui/tree/main/extensions/example/script.py).
```python"""An example of extension. It does nothing, but you can add transformationsbefore the return statements to customize the webui behavior.
Starting from history_modifier and ending in output_modifier, thefunctions are declared in the same order that they are called atgeneration time."""
import gradio as grimport torchfrom transformers import LogitsProcessor
from modules import chat, sharedfrom modules.text_generation import ( decode, encode, generate_reply,)
params = { "display_name": "Example Extension", "is_tab": False,}
class MyLogits(LogitsProcessor): """ Manipulates the probabilities for the next token before it gets sampled. Used in the logits_processor_modifier function below. """ def __init__(self): pass
def __call__(self, input_ids, scores): # probs = torch.softmax(scores, dim=-1, dtype=torch.float) # probs[0] /= probs[0].sum() # scores = torch.log(probs / (1 - probs)) return scores
def history_modifier(history): """ Modifies the chat history. Only used in chat mode. """ return history
def state_modifier(state): """ Modifies the state variable, which is a dictionary containing the input values in the UI like sliders and checkboxes. """ return state
def chat_input_modifier(text, visible_text, state): """ Modifies the user input string in chat mode (visible_text). You can also modify the internal representation of the user input (text) to change how it will appear in the prompt. """ return text, visible_text
def input_modifier(string, state, is_chat=False): """ In default/notebook modes, modifies the whole prompt.
In chat mode, it is the same as chat_input_modifier but only applied to "text", here called "string", and not to "visible_text". """ return string
def bot_prefix_modifier(string, state): """ Modifies the prefix for the next bot reply in chat mode. By default, the prefix will be something like "Bot Name:". """ return string
def tokenizer_modifier(state, prompt, input_ids, input_embeds): """ Modifies the input ids and embeds. Used by the multimodal extension to put image embeddings in the prompt. Only used by loaders that use the transformers library for sampling. """ return prompt, input_ids, input_embeds
def logits_processor_modifier(processor_list, input_ids): """ Adds logits processors to the list, allowing you to access and modify the next token probabilities. Only used by loaders that use the transformers library for sampling. """ processor_list.append(MyLogits()) return processor_list
def output_modifier(string, state, is_chat=False): """ Modifies the LLM output before it gets presented.
In chat mode, the modified version goes into history['visible'], and the original version goes into history['internal']. """ return string
def custom_generate_chat_prompt(user_input, state, **kwargs): """ Replaces the function that generates the prompt from the chat history. Only used in chat mode. """ result = chat.generate_chat_prompt(user_input, state, **kwargs) return result
def custom_css(): """ Returns a CSS string that gets appended to the CSS for the webui. """ return ''
def custom_js(): """ Returns a javascript string that gets appended to the javascript for the webui. """ return ''
def setup(): """ Gets executed only once, when the extension is imported. """ pass
def ui(): """ Gets executed when the UI is drawn. Custom gradio elements and their corresponding event handlers should be defined here.
To learn about gradio components, check out the docs: https://gradio.app/docs/ """ pass```123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960## Audio notification
If your computer takes a long time to generate each response for the model that you are using, you can enable an audio notification for when the response is completed. This feature was kindly contributed by HappyWorldGames in [#1277](https://github.com/oobabooga/text-generation-webui/pull/1277).
### Installation
Simply place a file called "notification.mp3" in the same folder as `server.py`. Here you can find some examples:
* https://pixabay.com/sound-effects/search/ding/?duration=0-30* https://pixabay.com/sound-effects/search/notification/?duration=0-30
Source: https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/1126
This file will be automatically detected the next time you start the web UI.
## DeepSpeed
`DeepSpeed ZeRO-3` is an alternative offloading strategy for full-precision (16-bit) transformers models.
With this, I have been able to load a 6b model (GPT-J 6B) with less than 6GB of VRAM. The speed of text generation is very decent and much better than what would be accomplished with `--auto-devices --gpu-memory 6`.
As far as I know, DeepSpeed is only available for Linux at the moment.
### How to use it
1. Install DeepSpeed:
```conda install -c conda-forge mpi4py mpichpip install -U deepspeed```
2. Start the web UI replacing `python` with `deepspeed --num_gpus=1` and adding the `--deepspeed` flag. Example:
```deepspeed --num_gpus=1 server.py --deepspeed --chat --model gpt-j-6B```
## Miscellaneous info
### You can train LoRAs in CPU mode
Load the web UI with
```python server.py --cpu```
and start training the LoRA from the training tab as usual.
### You can check the sha256sum of downloaded models with the download script
```python download-model.py facebook/galactica-125m --check```
### The download script continues interrupted downloads by default
It doesn't start over.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208Docker Compose is a way of installing and launching the web UI in an isolated Ubuntu image using only a few commands.
## Installing Docker Compose
In order to create the image as described in the main README, you must have Docker Compose installed (2.17 or higher is recommended):
```~$ docker compose versionDocker Compose version v2.21.0```
The installation instructions for various Linux distributions can be found here:
https://docs.docker.com/engine/install/ubuntu/#install-using-the-repository
## Launching the image
Use these commands to launch the image:
```cd text-generation-webuiln -s docker/{nvidia/Dockerfile,nvidia/docker-compose.yml,.dockerignore} .cp docker/.env.example .env# Edit .env and set TORCH_CUDA_ARCH_LIST based on your GPU modeldocker compose up --build```
## More detailed installation instructions
* [Docker Compose installation instructions](#docker-compose-installation-instructions)* [Repository with additional Docker files](#dedicated-docker-repository)
By [@loeken](https://github.com/loeken).
- [Ubuntu 22.04](#ubuntu-2204) - [0. youtube video](#0-youtube-video) - [1. update the drivers](#1-update-the-drivers) - [2. reboot](#2-reboot) - [3. install docker](#3-install-docker) - [4. docker \& container toolkit](#4-docker--container-toolkit) - [5. clone the repo](#5-clone-the-repo) - [6. prepare models](#6-prepare-models) - [7. prepare .env file](#7-prepare-env-file) - [8. startup docker container](#8-startup-docker-container)- [Manjaro](#manjaro) - [update the drivers](#update-the-drivers) - [reboot](#reboot) - [docker \& container toolkit](#docker--container-toolkit) - [continue with ubuntu task](#continue-with-ubuntu-task)- [Windows](#windows) - [0. youtube video](#0-youtube-video-1) - [1. choco package manager](#1-choco-package-manager) - [2. install drivers/dependencies](#2-install-driversdependencies) - [3. install wsl](#3-install-wsl) - [4. reboot](#4-reboot) - [5. git clone \&\& startup](#5-git-clone--startup) - [6. prepare models](#6-prepare-models-1) - [7. startup](#7-startup)- [notes](#notes)
### Ubuntu 22.04
#### 0. youtube videoA video walking you through the setup can be found here:
[](https://www.youtube.com/watch?v=ELkKWYh8qOk)
#### 1. update the driversin the the “software updater” update drivers to the last version of the prop driver.
#### 2. rebootto switch using to new driver
#### 3. install docker```bashsudo apt updatesudo apt-get install curlsudo mkdir -m 0755 -p /etc/apt/keyringscurl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg --dearmor -o /etc/apt/keyrings/docker.gpgecho \ "deb [arch="$(dpkg --print-architecture)" signed-by=/etc/apt/keyrings/docker.gpg] https://download.docker.com/linux/ubuntu \ "$(. /etc/os-release && echo "$VERSION_CODENAME")" stable" | \ sudo tee /etc/apt/sources.list.d/docker.list > /dev/nullsudo apt updatesudo apt-get install docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin docker-compose -ysudo usermod -aG docker $USERnewgrp docker```
#### 4. docker & container toolkit```bashcurl -fsSL https://nvidia.github.io/libnvidia-container/gpgkey | sudo gpg --dearmor -o /usr/share/keyrings/nvidia-container-toolkit-keyring.gpgecho "deb [signed-by=/usr/share/keyrings/nvidia-container-toolkit-keyring.gpg] https://nvidia.github.io/libnvidia-container/stable/ubuntu22.04/amd64 /" | \sudo tee /etc/apt/sources.list.d/nvidia.list > /dev/null sudo apt updatesudo apt install nvidia-docker2 nvidia-container-runtime -ysudo systemctl restart docker```
#### 5. clone the repo```git clone https://github.com/oobabooga/text-generation-webuicd text-generation-webui```
#### 6. prepare modelsdownload and place the models inside the models folder. tested with:
4bithttps://github.com/oobabooga/text-generation-webui/pull/530#issuecomment-1483891617https://github.com/oobabooga/text-generation-webui/pull/530#issuecomment-1483941105
8bit:https://github.com/oobabooga/text-generation-webui/pull/530#issuecomment-1484235789
#### 7. prepare .env fileedit .env values to your needs.```bashcp .env.example .envnano .env```
#### 8. startup docker container```bashdocker compose up --build```
### Manjaromanjaro/arch is similar to ubuntu just the dependency installation is more convenient
#### update the drivers```bashsudo mhwd -a pci nonfree 0300```#### reboot```bashreboot```#### docker & container toolkit```bashyay -S docker docker-compose buildkit gcc nvidia-dockersudo usermod -aG docker $USERnewgrp dockersudo systemctl restart docker # required by nvidia-container-runtime```
#### continue with ubuntu taskcontinue at [5. clone the repo](#5-clone-the-repo)
### Windows#### 0. youtube videoA video walking you through the setup can be found here:[](https://www.youtube.com/watch?v=ejH4w5b5kFQ)
#### 1. choco package managerinstall package manager (https://chocolatey.org/ )```Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://community.chocolatey.org/install.ps1'))```
#### 2. install drivers/dependencies```choco install nvidia-display-driver cuda git docker-desktop```
#### 3. install wslwsl --install
#### 4. rebootafter reboot enter username/password in wsl
#### 5. git clone && startupclone the repo and edit .env values to your needs.```cd Desktopgit clone https://github.com/oobabooga/text-generation-webuicd text-generation-webuiCOPY .env.example .envnotepad .env```
#### 6. prepare modelsdownload and place the models inside the models folder. tested with:
4bit https://github.com/oobabooga/text-generation-webui/pull/530#issuecomment-1483891617 https://github.com/oobabooga/text-generation-webui/pull/530#issuecomment-1483941105
8bit: https://github.com/oobabooga/text-generation-webui/pull/530#issuecomment-1484235789
#### 7. startup```docker compose up```
### notes
on older ubuntus you can manually install the docker compose plugin like this:```DOCKER_CONFIG=${DOCKER_CONFIG:-$HOME/.docker}mkdir -p $DOCKER_CONFIG/cli-pluginscurl -SL https://github.com/docker/compose/releases/download/v2.17.2/docker-compose-linux-x86_64 -o $DOCKER_CONFIG/cli-plugins/docker-composechmod +x $DOCKER_CONFIG/cli-plugins/docker-composeexport PATH="$HOME/.docker/cli-plugins:$PATH"```
## Dedicated docker repository
An external repository maintains a docker wrapper for this project as well as several pre-configured 'one-click' `docker compose` variants (e.g., updated branches of GPTQ). It can be found at: [Atinoda/text-generation-webui-docker](https://github.com/Atinoda/text-generation-webui-docker).12345678910111213## Using an AMD GPU in Linux
Requires ROCm SDK 5.4.2 or 5.4.3 to be installed. Some systems may alsoneed:
```sudo apt-get install libstdc++-12-dev```
Edit the "one_click.py" script using a text editor and un-comment andmodify the lines near the top of the script according to your setup. Inparticular, modify the `os.environ["ROCM_PATH"] = '/opt/rocm'` line topoint to your ROCm installation.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550## OpenAI compatible API
The main API for this project is meant to be a drop-in replacement to the OpenAI API, including Chat and Completions endpoints.
* It is 100% offline and private.* It doesn't create any logs.* It doesn't connect to OpenAI.* It doesn't use the openai-python library.
### Starting the API
Add `--api` to your command-line flags.
* To create a public Cloudflare URL, add the `--public-api` flag.* To listen on your local network, add the `--listen` flag.* To change the port, which is 5000 by default, use `--api-port 1234` (change 1234 to your desired port number).* To use SSL, add `--ssl-keyfile key.pem --ssl-certfile cert.pem`. ⚠️ **Note**: this doesn't work with `--public-api` since Cloudflare already uses HTTPS by default.* To use an API key for authentication, add `--api-key yourkey`.
### Examples
For the documentation with all the endpoints, parameters and their types, consult `http://127.0.0.1:5000/docs` or the [typing.py](https://github.com/oobabooga/text-generation-webui/blob/main/extensions/openai/typing.py) file.
The official examples in the [OpenAI documentation](https://platform.openai.com/docs/api-reference) should also work, and the same parameters apply (although the API here has more optional parameters).
#### Completions
```shellcurl http://127.0.0.1:5000/v1/completions \ -H "Content-Type: application/json" \ -d '{ "prompt": "This is a cake recipe:\n\n1.", "max_tokens": 512, "temperature": 0.6, "top_p": 0.95, "top_k": 20 }'```
#### Chat completions
Works best with instruction-following models. If the "instruction_template" variable is not provided, it will be guessed automatically based on the model name using the regex patterns in `models/config.yaml`.
```shellcurl http://127.0.0.1:5000/v1/chat/completions \ -H "Content-Type: application/json" \ -d '{ "messages": [ { "role": "user", "content": "Hello!" } ], "temperature": 0.6, "top_p": 0.95, "top_k": 20 }'```
#### Chat completions with characters
```shellcurl http://127.0.0.1:5000/v1/chat/completions \ -H "Content-Type: application/json" \ -d '{ "messages": [ { "role": "user", "content": "Hello! Who are you?" } ], "mode": "chat-instruct", "character": "Example", "temperature": 0.6, "top_p": 0.95, "top_k": 20 }'```
#### Multimodal/vision (llama.cpp and ExLlamaV3)
##### With /v1/chat/completions (recommended!)
```shellcurl http://127.0.0.1:5000/v1/chat/completions \ -H "Content-Type: application/json" \ -d '{ "messages": [ { "role": "user", "content": [ {"type": "text", "text": "Please describe what you see in this image."}, {"type": "image_url", "image_url": {"url": "https://github.com/turboderp-org/exllamav3/blob/master/examples/media/cat.png?raw=true"}} ] } ], "temperature": 0.6, "top_p": 0.95, "top_k": 20 }'```
For base64-encoded images, just replace the inner "url" value with this format: `data:image/FORMAT;base64,BASE64_STRING` where FORMAT is the file type (png, jpeg, gif, etc.) and BASE64_STRING is your base64-encoded image data.
##### With /v1/completions
```shellcurl http://127.0.0.1:5000/v1/completions \ -H "Content-Type: application/json" \ -d '{ "messages": [ { "role": "user", "content": [ { "type": "text", "text": "About image <__media__> and image <__media__>, what I can say is that the first one" }, { "type": "image_url", "image_url": { "url": "https://github.com/turboderp-org/exllamav3/blob/master/examples/media/cat.png?raw=true" } }, { "type": "image_url", "image_url": { "url": "https://github.com/turboderp-org/exllamav3/blob/master/examples/media/strawberry.png?raw=true" } } ] } ], "temperature": 0.6, "top_p": 0.95, "top_k": 20 }'```
For base64-encoded images, just replace the inner "url" values with this format: `data:image/FORMAT;base64,BASE64_STRING` where FORMAT is the file type (png, jpeg, gif, etc.) and BASE64_STRING is your base64-encoded image data.
#### SSE streaming
```shellcurl http://127.0.0.1:5000/v1/chat/completions \ -H "Content-Type: application/json" \ -d '{ "messages": [ { "role": "user", "content": "Hello!" } ], "temperature": 0.6, "top_p": 0.95, "top_k": 20, "stream": true }'```
#### Logits
```shellcurl -k http://127.0.0.1:5000/v1/internal/logits \ -H "Content-Type: application/json" \ -d '{ "prompt": "Who is best, Asuka or Rei? Answer:", "use_samplers": false }'```
#### Logits after sampling parameters
```shellcurl -k http://127.0.0.1:5000/v1/internal/logits \ -H "Content-Type: application/json" \ -d '{ "prompt": "Who is best, Asuka or Rei? Answer:", "use_samplers": true, "top_k": 3 }'```
#### List models
```shellcurl -k http://127.0.0.1:5000/v1/internal/model/list \ -H "Content-Type: application/json"```
#### Load model
```shellcurl -k http://127.0.0.1:5000/v1/internal/model/load \ -H "Content-Type: application/json" \ -d '{ "model_name": "Qwen_Qwen3-0.6B-Q4_K_M.gguf", "args": { "ctx_size": 32768, "flash_attn": true, "cache_type": "q8_0" } }'```
#### Python chat example
```pythonimport requests
url = "http://127.0.0.1:5000/v1/chat/completions"
headers = { "Content-Type": "application/json"}
history = []
while True: user_message = input("> ") history.append({"role": "user", "content": user_message}) data = { "messages": history, "temperature": 0.6, "top_p": 0.95, "top_k": 20 }
response = requests.post(url, headers=headers, json=data, verify=False) assistant_message = response.json()['choices'][0]['message']['content'] history.append({"role": "assistant", "content": assistant_message}) print(assistant_message)```
#### Python chat example with streaming
Start the script with `python -u` to see the output in real time.
```pythonimport requestsimport sseclient # pip install sseclient-pyimport json
url = "http://127.0.0.1:5000/v1/chat/completions"
headers = { "Content-Type": "application/json"}
history = []
while True: user_message = input("> ") history.append({"role": "user", "content": user_message}) data = { "stream": True, "messages": history, "temperature": 0.6, "top_p": 0.95, "top_k": 20 }
stream_response = requests.post(url, headers=headers, json=data, verify=False, stream=True) client = sseclient.SSEClient(stream_response)
assistant_message = '' for event in client.events(): payload = json.loads(event.data) chunk = payload['choices'][0]['delta']['content'] assistant_message += chunk print(chunk, end='')
print() history.append({"role": "assistant", "content": assistant_message})```
#### Python completions example with streaming
Start the script with `python -u` to see the output in real time.
```pythonimport jsonimport requestsimport sseclient # pip install sseclient-py
url = "http://127.0.0.1:5000/v1/completions"
headers = { "Content-Type": "application/json"}
data = { "prompt": "This is a cake recipe:\n\n1.", "max_tokens": 512, "temperature": 0.6, "top_p": 0.95, "top_k": 20, "stream": True,}
stream_response = requests.post(url, headers=headers, json=data, verify=False, stream=True)client = sseclient.SSEClient(stream_response)
print(data['prompt'], end='')for event in client.events(): payload = json.loads(event.data) print(payload['choices'][0]['text'], end='')
print()```
#### Python example with API key
Replace
```pythonheaders = { "Content-Type": "application/json"}```
with
```pythonheaders = { "Content-Type": "application/json", "Authorization": "Bearer yourPassword123"}```
in any of the examples above.
#### Tool/Function Calling Example
You need to use a model with tools support. The prompt will be automatically formatted using the model's Jinja2 template.
Request:
```curl http://127.0.0.1:5000/v1/chat/completions \ -H "Content-Type: application/json" \ -d '{ "messages": [ { "role": "system", "content": "You are a helpful assistant." }, { "role": "user", "content": "What time is it currently in New York City?" } ], "tools": [ { "type": "function", "function": { "name": "get_current_time", "description": "Get current time in a specific timezones", "parameters": { "type": "object", "required": ["timezone"], "properties": { "timezone": { "type": "string", "description": "IANA timezone name (e.g., America/New_York, Europe/London). Use Europe/Berlin as local timezone if no timezone provided by the user." } } } } } ] }'```
Sample response:
```{ "id": "chatcmpl-1746532051477984256", "object": "chat.completion", "created": 1746532051, "model": "qwen2.5-coder-14b-instruct-q4_k_m.gguf", "choices": [ { "index": 0, "finish_reason": "tool_calls", "message": { "role": "assistant", "content": "```xml\n<function>\n{\n \"name\": \"get_current_time\",\n \"arguments\": {\n \"timezone\": \"America/New_York\"\n }\n}\n</function>\n```" }, "tool_calls": [ { "type": "function", "function": { "name": "get_current_time", "arguments": "{\"timezone\": \"America/New_York\"}" }, "id": "call_52ij07mh", "index": "0" } ] } ], "usage": { "prompt_tokens": 224, "completion_tokens": 38, "total_tokens": 262 }}```
### Environment variables
The following environment variables can be used (they take precedence over everything else):
| Variable Name | Description | Example Value ||------------------------|------------------------------------|----------------------------|| `OPENEDAI_PORT` | Port number | 5000 || `OPENEDAI_CERT_PATH` | SSL certificate file path | cert.pem || `OPENEDAI_KEY_PATH` | SSL key file path | key.pem || `OPENEDAI_DEBUG` | Enable debugging (set to 1) | 1 || `SD_WEBUI_URL` | WebUI URL (used by endpoint) | http://127.0.0.1:7861 || `OPENEDAI_EMBEDDING_MODEL` | Embedding model (if applicable) | sentence-transformers/all-mpnet-base-v2 || `OPENEDAI_EMBEDDING_DEVICE` | Embedding device (if applicable) | cuda |
#### Persistent settings with `settings.yaml`
You can also set the following variables in your `settings.yaml` file:
```openai-embedding_device: cudaopenai-embedding_model: "sentence-transformers/all-mpnet-base-v2"openai-sd_webui_url: http://127.0.0.1:7861openai-debug: 1```
### Third-party application setup
You can usually force an application that uses the OpenAI API to connect to the local API by using the following environment variables:
```shellOPENAI_API_HOST=http://127.0.0.1:5000```
or
```shellOPENAI_API_KEY=sk-111111111111111111111111111111111111111111111111OPENAI_API_BASE=http://127.0.0.1:5000/v1```
With the [official python openai client](https://github.com/openai/openai-python), the address can be set like this:
```pythonimport openai
openai.api_key = "..."openai.api_base = "http://127.0.0.1:5000/v1"openai.api_version = "2023-05-15"```
If using .env files to save the `OPENAI_API_BASE` and `OPENAI_API_KEY` variables, make sure the .env file is loaded before the openai module is imported:
```pythonfrom dotenv import load_dotenvload_dotenv() # make sure the environment variables are set before importimport openai```
With the [official Node.js openai client](https://github.com/openai/openai-node) it is slightly more more complex because the environment variables are not used by default, so small source code changes may be required to use the environment variables, like so:
```jsconst openai = OpenAI( Configuration({ apiKey: process.env.OPENAI_API_KEY, basePath: process.env.OPENAI_API_BASE }));```
For apps made with the [chatgpt-api Node.js client library](https://github.com/transitive-bullshit/chatgpt-api):
```jsconst api = new ChatGPTAPI({ apiKey: process.env.OPENAI_API_KEY, apiBaseUrl: process.env.OPENAI_API_BASE});```### Embeddings (alpha)
Embeddings requires `sentence-transformers` installed, but chat and completions will function without it loaded. The embeddings endpoint is currently using the HuggingFace model: `sentence-transformers/all-mpnet-base-v2` for embeddings. This produces 768 dimensional embeddings (the same as the text-davinci-002 embeddings), which is different from OpenAI's current default `text-embedding-ada-002` model which produces 1536 dimensional embeddings. The model is small-ish and fast-ish. This model and embedding size may change in the future.
| model name | dimensions | input max tokens | speed | size | Avg. performance || ---------------------- | ---------- | ---------------- | ----- | ---- | ---------------- || text-embedding-ada-002 | 1536 | 8192 | - | - | - || text-davinci-002 | 768 | 2046 | - | - | - || all-mpnet-base-v2 | 768 | 384 | 2800 | 420M | 63.3 || all-MiniLM-L6-v2 | 384 | 256 | 14200 | 80M | 58.8 |
In short, the all-MiniLM-L6-v2 model is 5x faster, 5x smaller ram, 2x smaller storage, and still offers good quality. Stats from (https://www.sbert.net/docs/pretrained_models.html). To change the model from the default you can set the environment variable `OPENEDAI_EMBEDDING_MODEL`, ex. "OPENEDAI_EMBEDDING_MODEL=all-MiniLM-L6-v2".
Warning: You cannot mix embeddings from different models even if they have the same dimensions. They are not comparable.
### Compatibility & not so compatibility
Note: the table below may be obsolete.
| API endpoint | tested with | notes || ------------------------- | ---------------------------------- | --------------------------------------------------------------------------- || /v1/chat/completions | openai.ChatCompletion.create() | Use it with instruction following models || /v1/embeddings | openai.Embedding.create() | Using SentenceTransformer embeddings || /v1/images/generations | openai.Image.create() | Bare bones, no model configuration, response_format='b64_json' only. || /v1/moderations | openai.Moderation.create() | Basic initial support via embeddings || /v1/models | openai.Model.list() | Lists models, Currently loaded model first, plus some compatibility options || /v1/models/{id} | openai.Model.get() | returns whatever you ask for || /v1/edits | openai.Edit.create() | Removed, use /v1/chat/completions instead || /v1/text_completion | openai.Completion.create() | Legacy endpoint, variable quality based on the model || /v1/completions | openai api completions.create | Legacy endpoint (v0.25) || /v1/engines/\*/embeddings | python-openai v0.25 | Legacy endpoint || /v1/engines/\*/generate | openai engines.generate | Legacy endpoint || /v1/engines | openai engines.list | Legacy Lists models || /v1/engines/{model_name} | openai engines.get -i {model_name} | You can use this legacy endpoint to load models via the api or command line || /v1/images/edits | openai.Image.create_edit() | not yet supported || /v1/images/variations | openai.Image.create_variation() | not yet supported || /v1/audio/\* | openai.Audio.\* | supported || /v1/files\* | openai.Files.\* | not yet supported || /v1/fine-tunes\* | openai.FineTune.\* | not yet supported || /v1/search | openai.search, engines.search | not yet supported |
#### Applications
Almost everything needs the `OPENAI_API_KEY` and `OPENAI_API_BASE` environment variable set, but there are some exceptions.
Note: the table below may be obsolete.
| Compatibility | Application/Library | Website | Notes || ------------- | ---------------------- | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ || ✅❌ | openai-python (v0.25+) | https://github.com/openai/openai-python | only the endpoints from above are working. OPENAI_API_BASE=http://127.0.0.1:5001/v1 || ✅❌ | openai-node | https://github.com/openai/openai-node | only the endpoints from above are working. environment variables don't work by default, but can be configured (see above) || ✅❌ | chatgpt-api | https://github.com/transitive-bullshit/chatgpt-api | only the endpoints from above are working. environment variables don't work by default, but can be configured (see above) || ✅ | anse | https://github.com/anse-app/anse | API Key & URL configurable in UI, Images also work || ✅ | shell_gpt | https://github.com/TheR1D/shell_gpt | OPENAI_API_HOST=http://127.0.0.1:5001 || ✅ | gpt-shell | https://github.com/jla/gpt-shell | OPENAI_API_BASE=http://127.0.0.1:5001/v1 || ✅ | gpt-discord-bot | https://github.com/openai/gpt-discord-bot | OPENAI_API_BASE=http://127.0.0.1:5001/v1 || ✅ | OpenAI for Notepad++ | https://github.com/Krazal/nppopenai | api_url=http://127.0.0.1:5001 in the config file, or environment variables || ✅ | vscode-openai | https://marketplace.visualstudio.com/items?itemName=AndrewButson.vscode-openai | OPENAI_API_BASE=http://127.0.0.1:5001/v1 || ✅❌ | langchain | https://github.com/hwchase17/langchain | OPENAI_API_BASE=http://127.0.0.1:5001/v1 even with a good 30B-4bit model the result is poor so far. It assumes zero shot python/json coding. Some model tailored prompt formatting improves results greatly. || ✅❌ | Auto-GPT | https://github.com/Significant-Gravitas/Auto-GPT | OPENAI_API_BASE=http://127.0.0.1:5001/v1 Same issues as langchain. Also assumes a 4k+ context || ✅❌ | babyagi | https://github.com/yoheinakajima/babyagi | OPENAI_API_BASE=http://127.0.0.1:5001/v1 || ❌ | guidance | https://github.com/microsoft/guidance | logit_bias and logprobs not yet supported |12345678910111213141516171819# Keyboard Shortcuts
#### General
| Shortcut | Description ||-------------------------|--------------------------------------------------|| Esc | Stop generation |
#### Chat tab
| Shortcut | Description ||-------------------------|--------------------------------------------------|| Ctrl + S | Show/hide chat controls || Ctrl + Enter | Regenerate || Alt + Enter | Continue || Ctrl + Shift + Backspace| Remove last || Ctrl + Shift + M | Impersonate || ← (Left Arrow) | Navigate to previous version of last assistant message || → (Right Arrow) | Navigate to next version of last assistant message (or regenerate if at latest version) |123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566## Getting started
### 1. Find a multimodal model
GGUF models with vision capabilities are uploaded along a `mmproj` file to Hugging Face.
For instance, [unsloth/gemma-3-4b-it-GGUF](https://huggingface.co/unsloth/gemma-3-4b-it-GGUF/tree/main) has this:
<img width="414" height="270" alt="print1" src="https://github.com/user-attachments/assets/ac5aeb61-f6a2-491e-a1f0-47d6e27ea286" />
### 2. Download the model to `user_data/models`
As an example, download
https://huggingface.co/unsloth/gemma-3-4b-it-GGUF/resolve/main/gemma-3-4b-it-Q4_K_S.gguf?download=true
to your `text-generation-webui/user_data/models` folder.
### 3. Download the associated mmproj file to `user_data/mmproj`
Then download
https://huggingface.co/unsloth/gemma-3-4b-it-GGUF/resolve/main/mmproj-F16.gguf?download=true
to your `text-generation-webui/user_data/mmproj` folder. Name it `mmproj-gemma-3-4b-it-F16.gguf` to give it a recognizable name.
### 4. Load the model
1. Launch the web UI2. Navigate to the Model tab3. Select the GGUF model in the Model dropdown:
<img width="545" height="92" alt="print2" src="https://github.com/user-attachments/assets/3f920f50-e6c3-4768-91e2-20828dd63a1c" />
4. Select the mmproj file in the Multimodal (vision) menu:
<img width="454" height="172" alt="print3" src="https://github.com/user-attachments/assets/a657e20f-0ceb-4d71-9fe4-2b78571d20a6" />
5. Click "Load"
### 5. Send a message with an image
Select your image by clicking on the 📎 icon and send your message:
<img width="368" height="135" alt="print5" src="https://github.com/user-attachments/assets/6175ec9f-04f4-4dba-9382-4ac80d5b0b1f" />
The model will reply with great understanding of the image contents:
<img width="809" height="884" alt="print6" src="https://github.com/user-attachments/assets/be4a8f4d-619d-49e6-86f5-012d89f8db8d" />
## Multimodal with ExLlamaV3
Multimodal also works with the ExLlamaV3 loader (the non-HF one).
No additional files are necessary, just load a multimodal EXL3 model and send an image.
Examples of models that you can use:
- https://huggingface.co/turboderp/gemma-3-27b-it-exl3- https://huggingface.co/turboderp/Mistral-Small-3.1-24B-Instruct-2503-exl3
## Multimodal API examples
In the page below you can find some ready-to-use examples:
[Multimodal/vision (llama.cpp and ExLlamaV3)](https://github.com/oobabooga/text-generation-webui/wiki/12-%E2%80%90-OpenAI-API#multimodalvision-llamacpp-and-exllamav3)12345These files are a mirror of the documentation at:
# https://github.com/oobabooga/text-generation-webui/wiki
It is recommended to browse it there. Contributions can be sent here and will later be synced with the wiki.1234567891011121314151617181920## What Works
| Loader | Loading 1 LoRA | Loading 2 or more LoRAs | Training LoRAs | Multimodal extension | Perplexity evaluation ||----------------|----------------|-------------------------|----------------|----------------------|-----------------------|| Transformers | ✅ | ✅\*\* | ✅\* | ✅ | ✅ || llama.cpp | ❌ | ❌ | ❌ | ❌ | use llamacpp_HF || llamacpp_HF | ❌ | ❌ | ❌ | ❌ | ✅ || ExLlamav2_HF | ✅ | ✅ | ❌ | ❌ | ✅ || ExLlamav2 | ✅ | ✅ | ❌ | ❌ | use ExLlamav2_HF || AutoGPTQ | ✅ | ❌ | ❌ | ✅ | ✅ || AutoAWQ | ? | ❌ | ? | ? | ✅ || HQQ | ? | ? | ? | ? | ✅ |
❌ = not implemented
✅ = implemented
\* Training LoRAs with GPTQ models also works with the Transformers loader. Make sure to check "auto-devices" and "disable_exllama" before loading the model.
\*\* Multi-LoRA in PEFT is tricky and the current implementation does not work reliably in all cases.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427'''Downloads models from Hugging Face to user_data/models/username_modelname.
Example:python download-model.py facebook/opt-1.3b
'''
import argparseimport base64import datetimeimport hashlibimport jsonimport osimport reimport sysfrom multiprocessing import Arrayfrom pathlib import Pathfrom time import sleep
import requestsimport tqdmfrom requests.adapters import HTTPAdapterfrom requests.exceptions import ConnectionError, RequestException, Timeoutfrom tqdm.contrib.concurrent import thread_map
base = os.environ.get("HF_ENDPOINT") or "https://huggingface.co"
class ModelDownloader: def __init__(self, max_retries=7): self.max_retries = max_retries self.session = self.get_session() self._progress_bar_slots = None self.progress_queue = None
def get_session(self): session = requests.Session() if self.max_retries: session.mount('https://cdn-lfs.huggingface.co', HTTPAdapter(max_retries=self.max_retries)) session.mount('https://huggingface.co', HTTPAdapter(max_retries=self.max_retries))
if os.getenv('HF_USER') is not None and os.getenv('HF_PASS') is not None: session.auth = (os.getenv('HF_USER'), os.getenv('HF_PASS'))
try: from huggingface_hub import get_token token = get_token() except ImportError: token = os.getenv("HF_TOKEN")
if token is not None: session.headers = {'authorization': f'Bearer {token}'}
return session
def sanitize_model_and_branch_names(self, model, branch): if model[-1] == '/': model = model[:-1]
if model.startswith(base + '/'): model = model[len(base) + 1:]
model_parts = model.split(":") model = model_parts[0] if len(model_parts) > 0 else model branch = model_parts[1] if len(model_parts) > 1 else branch
if branch is None: branch = "main" else: pattern = re.compile(r"^[a-zA-Z0-9._-]+$") if not pattern.match(branch): raise ValueError( "Invalid branch name. Only alphanumeric characters, period, underscore and dash are allowed.")
return model, branch
def get_download_links_from_huggingface(self, model, branch, text_only=False, specific_file=None, exclude_pattern=None): session = self.session page = f"/api/models/{model}/tree/{branch}" cursor = b""
links = [] sha256 = [] file_sizes = [] classifications = [] has_pytorch = False has_pt = False has_gguf = False has_safetensors = False is_lora = False while True: url = f"{base}{page}" + (f"?cursor={cursor.decode()}" if cursor else "") r = session.get(url, timeout=10) r.raise_for_status() content = r.content
dict = json.loads(content) if len(dict) == 0: break
for i in range(len(dict)): fname = dict[i]['path'] if specific_file not in [None, ''] and fname != specific_file: continue
# Exclude files matching the exclude pattern if exclude_pattern is not None and re.match(exclude_pattern, fname): continue
if not is_lora and fname.endswith(('adapter_config.json', 'adapter_model.bin')): is_lora = True
is_pytorch = re.match(r"(pytorch|adapter|gptq)_model.*\.bin", fname) is_safetensors = re.match(r".*\.safetensors", fname) is_pt = re.match(r".*\.pt", fname) is_gguf = re.match(r".*\.gguf", fname) is_tiktoken = re.match(r".*\.tiktoken", fname) is_tokenizer = re.match(r"(tokenizer|ice|spiece).*\.model", fname) or is_tiktoken is_text = re.match(r".*\.(txt|json|py|md)", fname) or is_tokenizer if any((is_pytorch, is_safetensors, is_pt, is_gguf, is_tokenizer, is_text)): file_size = 0 if 'lfs' in dict[i]: sha256.append([fname, dict[i]['lfs']['oid']]) file_size = dict[i]['lfs'].get('size', 0) elif 'size' in dict[i]: file_size = dict[i]['size']
file_sizes.append(file_size)
if is_text: links.append(f"{base}/{model}/resolve/{branch}/{fname}") classifications.append('text') continue
if not text_only: links.append(f"{base}/{model}/resolve/{branch}/{fname}") if is_safetensors: has_safetensors = True classifications.append('safetensors') elif is_pytorch: has_pytorch = True classifications.append('pytorch') elif is_pt: has_pt = True classifications.append('pt') elif is_gguf: has_gguf = True classifications.append('gguf')
cursor = base64.b64encode(f'{{"file_name":"{dict[-1]["path"]}"}}'.encode()) + b':50' cursor = base64.b64encode(cursor) cursor = cursor.replace(b'=', b'%3D')
# If both pytorch and safetensors are available, download safetensors only # Also if GGUF and safetensors are available, download only safetensors if (has_pytorch or has_pt or has_gguf) and has_safetensors: has_gguf = False for i in range(len(classifications) - 1, -1, -1): if classifications[i] in ['pytorch', 'pt', 'gguf']: links.pop(i) file_sizes.pop(i)
# For GGUF, try to download only the Q4_K_M if no specific file is specified. if has_gguf and specific_file is None: has_q4km = False for i in range(len(classifications) - 1, -1, -1): if 'q4_k_m' in links[i].lower(): has_q4km = True
if has_q4km: for i in range(len(classifications) - 1, -1, -1): if 'q4_k_m' not in links[i].lower(): links.pop(i) file_sizes.pop(i) else: for i in range(len(classifications) - 1, -1, -1): if links[i].lower().endswith('.gguf'): links.pop(i) file_sizes.pop(i)
is_llamacpp = has_gguf and specific_file is not None return links, sha256, is_lora, is_llamacpp, file_sizes
def get_output_folder(self, model, branch, is_lora, is_llamacpp=False, model_dir=None): if model_dir: base_folder = model_dir else: base_folder = 'user_data/models' if not is_lora else 'user_data/loras'
# If the model is of type GGUF, save directly in the base_folder if is_llamacpp: return Path(base_folder)
output_folder = f"{'_'.join(model.split('/')[-2:])}" if branch != 'main': output_folder += f'_{branch}'
output_folder = Path(base_folder) / output_folder return output_folder
@property def progress_bar_slots(self): if self._progress_bar_slots is None: raise RuntimeError("Progress bar slots not initialized. Start download threads first.")
return self._progress_bar_slots
def initialize_progress_bar_slots(self, num_threads): self._progress_bar_slots = Array("B", [0] * num_threads)
def get_progress_bar_position(self): with self.progress_bar_slots.get_lock(): for i in range(len(self.progress_bar_slots)): if self.progress_bar_slots[i] == 0: self.progress_bar_slots[i] = 1 return i
return 0 # fallback
def release_progress_bar_position(self, slot): with self.progress_bar_slots.get_lock(): self.progress_bar_slots[slot] = 0
def get_single_file(self, url, output_folder, start_from_scratch=False): filename = Path(url.rsplit('/', 1)[1]) output_path = output_folder / filename progress_bar_position = self.get_progress_bar_position()
max_retries = self.max_retries attempt = 0 file_downloaded_count_for_progress = 0
try: while attempt < max_retries: attempt += 1 session = self.session headers = {} mode = 'wb' current_file_size_on_disk = 0
try: if output_path.exists() and not start_from_scratch: current_file_size_on_disk = output_path.stat().st_size r_head = session.head(url, timeout=20) r_head.raise_for_status() total_size = int(r_head.headers.get('content-length', 0))
if current_file_size_on_disk >= total_size and total_size > 0: if self.progress_queue is not None and total_size > 0: self.progress_queue.put((1.0, str(filename))) return
headers = {'Range': f'bytes={current_file_size_on_disk}-'} mode = 'ab'
with session.get(url, stream=True, headers=headers, timeout=30) as r: r.raise_for_status() total_size_from_stream = int(r.headers.get('content-length', 0)) if mode == 'ab': effective_total_size = current_file_size_on_disk + total_size_from_stream else: effective_total_size = total_size_from_stream
block_size = 1024 * 1024 filename_str = str(filename)
tqdm_kwargs = { 'total': effective_total_size, 'initial': current_file_size_on_disk if mode == 'ab' else 0, 'unit': 'B', 'unit_scale': True, 'unit_divisor': 1024, 'bar_format': '{desc}{percentage:3.0f}%|{bar:50}| {n_fmt}/{total_fmt} [{elapsed}<{remaining}, {rate_fmt}]', 'desc': f"{filename_str}: ", 'position': progress_bar_position, 'leave': False }
if 'COLAB_GPU' in os.environ: tqdm_kwargs.update({ 'position': 0, 'leave': True })
with open(output_path, mode) as f: if mode == 'ab': f.seek(current_file_size_on_disk)
with tqdm.tqdm(**tqdm_kwargs) as t: file_downloaded_count_for_progress = current_file_size_on_disk for data in r.iter_content(block_size): f.write(data) t.update(len(data)) if effective_total_size != 0 and self.progress_queue is not None: file_downloaded_count_for_progress += len(data) progress_fraction = float(file_downloaded_count_for_progress) / float(effective_total_size) self.progress_queue.put((progress_fraction, filename_str)) break
except (RequestException, ConnectionError, Timeout) as e: print(f"Error downloading {filename}: {e}.") print(f"That was attempt {attempt}/{max_retries}.", end=' ') if attempt < max_retries: print(f"Retry begins in {2 ** attempt} seconds.") sleep(2 ** attempt) else: print("Failed to download after the maximum number of attempts.") finally: self.release_progress_bar_position(progress_bar_position)
def start_download_threads(self, file_list, output_folder, start_from_scratch=False, threads=4): self.initialize_progress_bar_slots(threads) tqdm.tqdm.set_lock(tqdm.tqdm.get_lock()) try: thread_map( lambda url: self.get_single_file(url, output_folder, start_from_scratch=start_from_scratch), file_list, max_workers=threads, disable=True ) finally: print(f"\nDownload of {len(file_list)} files to {output_folder} completed.")
def download_model_files(self, model, branch, links, sha256, output_folder, progress_queue=None, start_from_scratch=False, threads=4, specific_file=None, is_llamacpp=False): self.progress_queue = progress_queue
output_folder.mkdir(parents=True, exist_ok=True)
if not is_llamacpp: metadata = f'url: https://huggingface.co/{model}\n' \ f'branch: {branch}\n' \ f'download date: {datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")}\n'
sha256_str = '\n'.join([f' {item[1]} {item[0]}' for item in sha256]) if sha256_str: metadata += f'sha256sum:\n{sha256_str}'
metadata += '\n' (output_folder / 'huggingface-metadata.txt').write_text(metadata)
if specific_file: print(f"Downloading {specific_file} to {output_folder}") else: print(f"Downloading the model to {output_folder}")
self.start_download_threads(links, output_folder, start_from_scratch=start_from_scratch, threads=threads)
def check_model_files(self, model, branch, links, sha256, output_folder): # Validate the checksums validated = True for i in range(len(sha256)): fpath = (output_folder / sha256[i][0])
if not fpath.exists(): print(f"The following file is missing: {fpath}") validated = False continue
with open(output_folder / sha256[i][0], "rb") as f: bytes = f.read() file_hash = hashlib.sha256(bytes).hexdigest() if file_hash != sha256[i][1]: print(f'Checksum failed: {sha256[i][0]} {sha256[i][1]}') validated = False else: print(f'Checksum validated: {sha256[i][0]} {sha256[i][1]}')
if validated: print('[+] Validated checksums of all model files!') else: print('[-] Invalid checksums. Rerun download-model.py with the --clean flag.')
if __name__ == '__main__':
parser = argparse.ArgumentParser() parser.add_argument('MODEL', type=str, default=None, nargs='?') parser.add_argument('--branch', type=str, default='main', help='Name of the Git branch to download from.') parser.add_argument('--threads', type=int, default=4, help='Number of files to download simultaneously.') parser.add_argument('--text-only', action='store_true', help='Only download text files (txt/json).') parser.add_argument('--specific-file', type=str, default=None, help='Name of the specific file to download (if not provided, downloads all).') parser.add_argument('--exclude-pattern', type=str, default=None, help='Regex pattern to exclude files from download.') parser.add_argument('--output', type=str, default=None, help='Save the model files to this folder.') parser.add_argument('--model-dir', type=str, default=None, help='Save the model files to a subfolder of this folder instead of the default one (text-generation-webui/user_data/models).') parser.add_argument('--clean', action='store_true', help='Does not resume the previous download.') parser.add_argument('--check', action='store_true', help='Validates the checksums of model files.') parser.add_argument('--max-retries', type=int, default=7, help='Max retries count when get error in download time.') args = parser.parse_args()
branch = args.branch model = args.MODEL specific_file = args.specific_file exclude_pattern = args.exclude_pattern
if model is None: print("Error: Please specify the model you'd like to download (e.g. 'python download-model.py facebook/opt-1.3b').") sys.exit()
downloader = ModelDownloader(max_retries=args.max_retries) # Clean up the model/branch names try: model, branch = downloader.sanitize_model_and_branch_names(model, branch) except ValueError as err_branch: print(f"Error: {err_branch}") sys.exit()
# Get the download links from Hugging Face links, sha256, is_lora, is_llamacpp, file_sizes = downloader.get_download_links_from_huggingface( model, branch, text_only=args.text_only, specific_file=specific_file, exclude_pattern=exclude_pattern )
# Get the output folder if args.output: output_folder = Path(args.output) else: output_folder = downloader.get_output_folder(model, branch, is_lora, is_llamacpp=is_llamacpp, model_dir=args.model_dir)
if args.check: # Check previously downloaded files downloader.check_model_files(model, branch, links, sha256, output_folder) else: # Download files downloader.download_model_files( model, branch, links, sha256, output_folder, specific_file=specific_file, threads=args.threads, is_llamacpp=is_llamacpp )1234567891011121314151617181920function toggleDarkMode() { document.body.classList.toggle("dark"); var currentCSS = document.getElementById("highlight-css"); if (currentCSS.getAttribute("href") === "file/css/highlightjs/github-dark.min.css") { currentCSS.setAttribute("href", "file/css/highlightjs/github.min.css"); } else { currentCSS.setAttribute("href", "file/css/highlightjs/github-dark.min.css"); }
// Re-highlight all code blocks once stylesheet loads currentCSS.onload = function() { const messageBodies = document.getElementById("chat").querySelectorAll(".message-body"); messageBodies.forEach((messageBody) => { const codeBlocks = messageBody.querySelectorAll("pre code"); codeBlocks.forEach((codeBlock) => { hljs.highlightElement(codeBlock); }); }); };}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389// -------------------------------------------------// Event handlers// -------------------------------------------------
function copyToClipboard(element) { if (!element) return;
const messageElement = element.closest(".message, .user-message, .assistant-message"); if (!messageElement) return;
const rawText = messageElement.getAttribute("data-raw"); if (!rawText) return;
navigator.clipboard.writeText(rawText).then(function() { const originalSvg = element.innerHTML; element.innerHTML = "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"20\" height=\"20\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\" class=\"text-green-500 dark:text-green-400\"><path d=\"M5 12l5 5l10 -10\"></path></svg>"; setTimeout(() => { element.innerHTML = originalSvg; }, 1000); }).catch(function(err) { console.error("Failed to copy text: ", err); });}
function branchHere(element) { if (!element) return;
const messageElement = element.closest(".message, .user-message, .assistant-message"); if (!messageElement) return;
const index = messageElement.getAttribute("data-index"); if (!index) return;
const branchIndexInput = document.getElementById("Branch-index").querySelector("input"); if (!branchIndexInput) { console.error("Element with ID 'Branch-index' not found."); return; } const branchButton = document.getElementById("Branch");
if (!branchButton) { console.error("Required element 'Branch' not found."); return; }
branchIndexInput.value = index;
// Trigger any 'change' or 'input' events Gradio might be listening for const event = new Event("input", { bubbles: true }); branchIndexInput.dispatchEvent(event);
branchButton.click();}
// -------------------------------------------------// Message Editing Functions// -------------------------------------------------
function editHere(buttonElement) { if (!buttonElement) return;
const messageElement = buttonElement.closest(".message, .user-message, .assistant-message"); if (!messageElement) return;
const messageBody = messageElement.querySelector(".message-body"); if (!messageBody) return;
// If already editing, focus the textarea const existingTextarea = messageBody.querySelector(".editing-textarea"); if (existingTextarea) { existingTextarea.focus(); return; }
// Determine role based on message element - handle different chat modes const isUserMessage = messageElement.classList.contains("user-message") || messageElement.querySelector(".text-you") !== null || messageElement.querySelector(".circle-you") !== null;
startEditing(messageElement, messageBody, isUserMessage);}
function startEditing(messageElement, messageBody, isUserMessage) { const rawText = messageElement.getAttribute("data-raw") || messageBody.textContent; const originalHTML = messageBody.innerHTML;
// Create editing interface const editingInterface = createEditingInterface(rawText);
// Replace message content messageBody.innerHTML = ""; messageBody.appendChild(editingInterface.textarea); messageBody.appendChild(editingInterface.controls);
editingInterface.textarea.focus(); editingInterface.textarea.setSelectionRange(rawText.length, rawText.length);
// Temporarily mark as scrolled to prevent auto-scroll const wasScrolled = window.isScrolled; window.isScrolled = true;
// Scroll the textarea into view editingInterface.textarea.scrollIntoView({ behavior: "smooth", block: "center" });
// Restore the original scroll state after animation setTimeout(() => { window.isScrolled = wasScrolled; }, 500);
// Setup event handlers setupEditingHandlers(editingInterface.textarea, messageElement, originalHTML, messageBody, isUserMessage);}
function createEditingInterface(text) { const textarea = document.createElement("textarea"); textarea.value = text; textarea.className = "editing-textarea"; textarea.rows = Math.max(3, text.split("\n").length);
const controls = document.createElement("div"); controls.className = "edit-controls-container";
const saveButton = document.createElement("button"); saveButton.textContent = "Save"; saveButton.className = "edit-control-button"; saveButton.type = "button";
const cancelButton = document.createElement("button"); cancelButton.textContent = "Cancel"; cancelButton.className = "edit-control-button edit-cancel-button"; cancelButton.type = "button";
controls.appendChild(saveButton); controls.appendChild(cancelButton);
return { textarea, controls, saveButton, cancelButton };}
function setupEditingHandlers(textarea, messageElement, originalHTML, messageBody, isUserMessage) { const saveButton = messageBody.querySelector(".edit-control-button:not(.edit-cancel-button)"); const cancelButton = messageBody.querySelector(".edit-cancel-button");
const submitEdit = () => { const index = messageElement.getAttribute("data-index"); if (!index || !submitMessageEdit(index, textarea.value, isUserMessage)) { cancelEdit(); } };
const cancelEdit = () => { messageBody.innerHTML = originalHTML; };
// Event handlers saveButton.onclick = submitEdit; cancelButton.onclick = cancelEdit;
textarea.onkeydown = (e) => { if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); submitEdit(); } else if (e.key === "Escape") { e.preventDefault(); cancelEdit(); } };}
function submitMessageEdit(index, newText, isUserMessage) { const editIndexInput = document.getElementById("Edit-message-index")?.querySelector("input"); const editTextInput = document.getElementById("Edit-message-text")?.querySelector("textarea"); const editRoleInput = document.getElementById("Edit-message-role")?.querySelector("textarea"); const editButton = document.getElementById("Edit-message");
if (!editIndexInput || !editTextInput || !editRoleInput || !editButton) { console.error("Edit elements not found"); return false; }
editIndexInput.value = index; editTextInput.value = newText; editRoleInput.value = isUserMessage ? "user" : "assistant";
editIndexInput.dispatchEvent(new Event("input", { bubbles: true })); editTextInput.dispatchEvent(new Event("input", { bubbles: true })); editRoleInput.dispatchEvent(new Event("input", { bubbles: true }));
editButton.click(); return true;}
function navigateVersion(element, direction) { if (!element) return;
const messageElement = element.closest(".message, .user-message, .assistant-message"); if (!messageElement) return;
const index = messageElement.getAttribute("data-index"); if (!index) return;
// Determine role based on message element classes let role = "assistant"; // Default role if (messageElement.classList.contains("user-message") || messageElement.querySelector(".text-you") || messageElement.querySelector(".circle-you")) { role = "user"; }
const indexInput = document.getElementById("Navigate-message-index")?.querySelector("input"); const directionInput = document.getElementById("Navigate-direction")?.querySelector("textarea"); const roleInput = document.getElementById("Navigate-message-role")?.querySelector("textarea"); const navigateButton = document.getElementById("Navigate-version");
if (!indexInput || !directionInput || !roleInput || !navigateButton) { console.error("Navigation control elements (index, direction, role, or button) not found."); return; }
indexInput.value = index; directionInput.value = direction; roleInput.value = role;
// Trigger 'input' events for Gradio to pick up changes const event = new Event("input", { bubbles: true }); indexInput.dispatchEvent(event); directionInput.dispatchEvent(event); roleInput.dispatchEvent(event);
navigateButton.click();}
function regenerateClick() { document.getElementById("Regenerate").click();}
function continueClick() { document.getElementById("Continue").click();}
function removeLastClick() { document.getElementById("Remove-last").click();}
function handleMorphdomUpdate(data) { // Determine target element and use it as query scope var target_element, target_html; if (data.last_message_only) { const childNodes = document.getElementsByClassName("messages")[0].childNodes; target_element = childNodes[childNodes.length - 1]; target_html = data.html; } else { target_element = document.getElementById("chat").parentNode; target_html = "<div class=\"prose svelte-1ybaih5\">" + data.html + "</div>"; }
const queryScope = target_element;
// Track open blocks const openBlocks = new Set(); queryScope.querySelectorAll(".thinking-block").forEach(block => { const blockId = block.getAttribute("data-block-id"); // If block exists and is open, add to open set if (blockId && block.hasAttribute("open")) { openBlocks.add(blockId); } });
// Store scroll positions for any open blocks const scrollPositions = {}; queryScope.querySelectorAll(".thinking-block[open]").forEach(block => { const content = block.querySelector(".thinking-content"); const blockId = block.getAttribute("data-block-id"); if (content && blockId) { const isAtBottom = Math.abs((content.scrollHeight - content.scrollTop) - content.clientHeight) < 5; scrollPositions[blockId] = { position: content.scrollTop, isAtBottom: isAtBottom }; } });
morphdom( target_element, target_html, { onBeforeElUpdated: function(fromEl, toEl) { // Preserve code highlighting if (fromEl.tagName === "PRE" && fromEl.querySelector("code[data-highlighted]")) { const fromCode = fromEl.querySelector("code"); const toCode = toEl.querySelector("code");
if (fromCode && toCode && fromCode.textContent === toCode.textContent) { toEl.className = fromEl.className; toEl.innerHTML = fromEl.innerHTML; return false; } }
// For thinking blocks, assume closed by default if (fromEl.classList && fromEl.classList.contains("thinking-block") && toEl.classList && toEl.classList.contains("thinking-block")) { const blockId = toEl.getAttribute("data-block-id"); // Remove open attribute by default toEl.removeAttribute("open"); // If this block was explicitly opened by user, keep it open if (blockId && openBlocks.has(blockId)) { toEl.setAttribute("open", ""); } }
return !fromEl.isEqualNode(toEl); },
onElUpdated: function(el) { // Restore scroll positions for open thinking blocks if (el.classList && el.classList.contains("thinking-block") && el.hasAttribute("open")) { const blockId = el.getAttribute("data-block-id"); const content = el.querySelector(".thinking-content");
if (content && blockId && scrollPositions[blockId]) { setTimeout(() => { if (scrollPositions[blockId].isAtBottom) { content.scrollTop = content.scrollHeight; } else { content.scrollTop = scrollPositions[blockId].position; } }, 0); } } } } );
// Add toggle listeners for new blocks queryScope.querySelectorAll(".thinking-block").forEach(block => { if (!block._hasToggleListener) { block.addEventListener("toggle", function(e) { if (this.open) { const content = this.querySelector(".thinking-content"); if (content) { setTimeout(() => { content.scrollTop = content.scrollHeight; }, 0); } } }); block._hasToggleListener = true; } });}
// Wait for Gradio to finish setting its styles, then force dark themeconst observer = new MutationObserver((mutations) => { mutations.forEach((mutation) => { if (mutation.type === "attributes" && mutation.target.tagName === "GRADIO-APP" && mutation.attributeName === "style") {
// Gradio just set its styles, now force dark theme document.body.classList.add("dark"); observer.disconnect(); } });});
// Start observingobserver.observe(document.documentElement, { attributes: true, subtree: true, attributeFilter: ["style"]});
//------------------------------------------------// Suppress "Attempted to select a non-interactive or hidden tab" warning//------------------------------------------------(function() { const originalWarn = console.warn;
console.warn = function(...args) { if (args[0] && typeof args[0] === "string" && args[0].includes("Attempted to select a non-interactive or hidden tab")) { return; }
originalWarn.apply(console, args); };})();1class CopyButtonPlugin{constructor(options={}){self.hook=options.hook;self.callback=options.callback;self.lang=options.lang||document.documentElement.lang||"en"}"after:highlightElement"({el,text}){let button=Object.assign(document.createElement("button"),{innerHTML:locales[lang]?.[0]||"Copy",className:"hljs-copy-button"});button.dataset.copied=false;el.parentElement.classList.add("hljs-copy-wrapper");el.parentElement.appendChild(button);el.parentElement.style.setProperty("--hljs-theme-background",window.getComputedStyle(el).backgroundColor);button.onclick=function(){if(!navigator.clipboard)return;let newText=text;if(hook&&typeof hook==="function"){newText=hook(text,el)||text}navigator.clipboard.writeText(newText).then(function(){button.innerHTML=locales[lang]?.[1]||"Copied!";button.dataset.copied=true;let alert=Object.assign(document.createElement("div"),{role:"status",className:"hljs-copy-alert",innerHTML:locales[lang]?.[2]||"Copied to clipboard"});el.parentElement.appendChild(alert);setTimeout(()=>{button.innerHTML=locales[lang]?.[0]||"Copy";button.dataset.copied=false;el.parentElement.removeChild(alert);alert=null},2e3)}).then(function(){if(typeof callback==="function")return callback(newText,el)})}}}if(typeof module!="undefined"){module.exports=CopyButtonPlugin}const locales={en:["Copy","Copied!","Copied to clipboard"],es:["Copiar","¡Copiado!","Copiado al portapapeles"],fr:["Copier","Copié !","Copié dans le presse-papier"],de:["Kopieren","Kopiert!","In die Zwischenablage kopiert"],ja:["コピー","コピーしました!","クリップボードにコピーしました"],ko:["복사","복사됨!","클립보드에 복사됨"],ru:["Копировать","Скопировано!","Скопировано в буфер обмена"],zh:["复制","已复制!","已复制到剪贴板"],"zh-tw":["複製","已複製!","已複製到剪貼簿"]};1!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("katex")):"function"==typeof define&&define.amd?define(["katex"],t):"object"==typeof exports?exports.renderMathInElement=t(require("katex")):e.renderMathInElement=t(e.katex)}("undefined"!=typeof self?self:this,(function(e){return function(){"use strict";var t={771:function(t){t.exports=e}},n={};function r(e){var o=n[e];if(void 0!==o)return o.exports;var i=n[e]={exports:{}};return t[e](i,i.exports,r),i.exports}r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,{a:t}),t},r.d=function(e,t){for(var n in t)r.o(t,n)&&!r.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)};var o={};return function(){r.d(o,{default:function(){return d}});var e=r(771),t=r.n(e);const n=function(e,t,n){let r=n,o=0;const i=e.length;for(;r<t.length;){const n=t[r];if(o<=0&&t.slice(r,r+i)===e)return r;"\\"===n?r++:"{"===n?o++:"}"===n&&o--,r++}return-1},i=/^\\begin{/;var a=function(e,t){let r;const o=[],a=new RegExp("("+t.map((e=>e.left.replace(/[-/\\^$*+?.()|[\]{}]/g,"\\$&"))).join("|")+")");for(;r=e.search(a),-1!==r;){r>0&&(o.push({type:"text",data:e.slice(0,r)}),e=e.slice(r));const a=t.findIndex((t=>e.startsWith(t.left)));if(r=n(t[a].right,e,t[a].left.length),-1===r)break;const l=e.slice(0,r+t[a].right.length),s=i.test(l)?l:e.slice(t[a].left.length,r);o.push({type:"math",data:s,rawData:l,display:t[a].display}),e=e.slice(r+t[a].right.length)}return""!==e&&o.push({type:"text",data:e}),o};const l=function(e,n){const r=a(e,n.delimiters);if(1===r.length&&"text"===r[0].type)return null;const o=document.createDocumentFragment();for(let e=0;e<r.length;e++)if("text"===r[e].type)o.appendChild(document.createTextNode(r[e].data));else{const i=document.createElement("span");let a=r[e].data;n.displayMode=r[e].display;try{n.preProcess&&(a=n.preProcess(a)),t().render(a,i,n)}catch(i){if(!(i instanceof t().ParseError))throw i;n.errorCallback("KaTeX auto-render: Failed to parse `"+r[e].data+"` with ",i),o.appendChild(document.createTextNode(r[e].rawData));continue}o.appendChild(i)}return o},s=function(e,t){for(let n=0;n<e.childNodes.length;n++){const r=e.childNodes[n];if(3===r.nodeType){let o=r.textContent,i=r.nextSibling,a=0;for(;i&&i.nodeType===Node.TEXT_NODE;)o+=i.textContent,i=i.nextSibling,a++;const s=l(o,t);if(s){for(let e=0;e<a;e++)r.nextSibling.remove();n+=s.childNodes.length-1,e.replaceChild(s,r)}else n+=a}else if(1===r.nodeType){const e=" "+r.className+" ";-1===t.ignoredTags.indexOf(r.nodeName.toLowerCase())&&t.ignoredClasses.every((t=>-1===e.indexOf(" "+t+" ")))&&s(r,t)}}};var d=function(e,t){if(!e)throw new Error("No element provided to render");const n={};for(const e in t)t.hasOwnProperty(e)&&(n[e]=t[e]);n.delimiters=n.delimiters||[{left:"$$",right:"$$",display:!0},{left:"\\(",right:"\\)",display:!1},{left:"\\begin{equation}",right:"\\end{equation}",display:!0},{left:"\\begin{align}",right:"\\end{align}",display:!0},{left:"\\begin{alignat}",right:"\\end{alignat}",display:!0},{left:"\\begin{gather}",right:"\\end{gather}",display:!0},{left:"\\begin{CD}",right:"\\end{CD}",display:!0},{left:"\\[",right:"\\]",display:!0}],n.ignoredTags=n.ignoredTags||["script","noscript","style","textarea","pre","code","option"],n.ignoredClasses=n.ignoredClasses||[],n.errorCallback=n.errorCallback||console.error,n.macros=n.macros||{},s(e,n)}}(),o=o.default}()}));123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107// ------------------------------------------------// Main// ------------------------------------------------
let main_parent = document.getElementById("chat-tab").parentNode;let extensions = document.getElementById("extensions");
main_parent.childNodes[0].classList.add("header_bar");main_parent.style = "padding: 0; margin: 0";main_parent.parentNode.style = "gap: 0";main_parent.parentNode.parentNode.style = "padding: 0";
document.querySelector(".header_bar").addEventListener("click", function(event) { if (event.target.tagName !== "BUTTON") return;
const buttonText = event.target.textContent.trim(); const extensionsVisible = ["Chat", "Default", "Notebook"].includes(buttonText); const chatVisible = buttonText === "Chat"; const showControlsChecked = document.querySelector("#show-controls input").checked; const extensions = document.querySelector("#extensions");
if (extensionsVisible) { if (extensions) { extensions.style.display = "flex"; }
this.style.marginBottom = chatVisible ? "0px" : "19px";
if (chatVisible && !showControlsChecked) { document.querySelectorAll("#extensions").forEach(element => { element.style.display = "none"; }); }
} else { this.style.marginBottom = "19px"; if (extensions) extensions.style.display = "none"; }});
//------------------------------------------------// Keyboard shortcuts//------------------------------------------------
// --- Helper functions --- //function isModifiedKeyboardEvent() { return (event instanceof KeyboardEvent && event.shiftKey || event.ctrlKey || event.altKey || event.metaKey);}
function isFocusedOnEditableTextbox() { if (event.target.tagName === "INPUT" || event.target.tagName === "TEXTAREA") { return !!event.target.value; }}
let previousTabId = "chat-tab-button";document.addEventListener("keydown", function(event) { // Stop generation on Esc pressed if (event.key === "Escape") { // Find the element with id 'stop' and click it var stopButton = document.getElementById("stop"); if (stopButton) { stopButton.click(); } return; }
if (!document.querySelector("#chat-tab").checkVisibility() ) { return; }
// Show chat controls on Ctrl + S if (event.ctrlKey && event.key == "s") { event.preventDefault();
var showControlsElement = document.getElementById("show-controls"); if (showControlsElement && showControlsElement.childNodes.length >= 4) { showControlsElement.childNodes[3].click();
var arr = document.getElementById("chat-input").childNodes[2].childNodes; arr[arr.length - 1].focus(); } }
// Regenerate on Ctrl + Enter else if (event.ctrlKey && event.key === "Enter") { event.preventDefault(); document.getElementById("Regenerate").click(); }
// Continue on Alt + Enter else if (event.altKey && event.key === "Enter") { event.preventDefault(); document.getElementById("Continue").click(); }
// Remove last on Ctrl + Shift + Backspace else if (event.ctrlKey && event.shiftKey && event.key === "Backspace") { event.preventDefault(); document.getElementById("Remove-last").click(); }
// Impersonate on Ctrl + Shift + M else if (event.ctrlKey && event.shiftKey && event.key === "M") { event.preventDefault(); document.getElementById("Impersonate").click(); }
// --- Simple version navigation --- // if (!isFocusedOnEditableTextbox()) { // Version navigation on Arrow keys (horizontal) if (!isModifiedKeyboardEvent() && event.key === "ArrowLeft") { event.preventDefault(); navigateLastAssistantMessage("left"); }
else if (!isModifiedKeyboardEvent() && event.key === "ArrowRight") { event.preventDefault(); if (!navigateLastAssistantMessage("right")) { // If can't navigate right (last version), regenerate document.getElementById("Regenerate").click(); } } }
});
//------------------------------------------------// Position the chat typing dots//------------------------------------------------typing = document.getElementById("typing-container");typingParent = typing.parentNode;typingSibling = typing.previousElementSibling;typingSibling.insertBefore(typing, typingSibling.childNodes[2]);
//------------------------------------------------// Chat scrolling//------------------------------------------------const targetElement = document.getElementById("chat").parentNode.parentNode.parentNode;targetElement.classList.add("pretty_scrollbar");targetElement.classList.add("chat-parent");window.isScrolled = false;let scrollTimeout;
targetElement.addEventListener("scroll", function() { let diff = targetElement.scrollHeight - targetElement.clientHeight; let isAtBottomNow = Math.abs(targetElement.scrollTop - diff) <= 10 || diff == 0;
// Add scrolling class to disable hover effects if (window.isScrolled || !isAtBottomNow) { targetElement.classList.add("scrolling"); }
if(isAtBottomNow) { window.isScrolled = false; } else { window.isScrolled = true; }
// Clear previous timeout and set new one clearTimeout(scrollTimeout); scrollTimeout = setTimeout(() => { targetElement.classList.remove("scrolling"); doSyntaxHighlighting(); // Only run after scrolling stops }, 150);});
// Create a MutationObserver instanceconst observer = new MutationObserver(function(mutations) { // Check if this is just the scrolling class being toggled const isScrollingClassOnly = mutations.every(mutation => mutation.type === "attributes" && mutation.attributeName === "class" && mutation.target === targetElement );
if (targetElement.classList.contains("_generating")) { typing.parentNode.classList.add("visible-dots"); document.getElementById("stop").style.display = "flex"; document.getElementById("Generate").style.display = "none"; } else { typing.parentNode.classList.remove("visible-dots"); document.getElementById("stop").style.display = "none"; document.getElementById("Generate").style.display = "flex"; }
doSyntaxHighlighting();
if (!window.isScrolled && !isScrollingClassOnly) { const maxScroll = targetElement.scrollHeight - targetElement.clientHeight; if (maxScroll > 0 && targetElement.scrollTop < maxScroll - 1) { targetElement.scrollTop = maxScroll; } }
const chatElement = document.getElementById("chat"); if (chatElement && chatElement.getAttribute("data-mode") === "instruct") { const messagesContainer = chatElement.querySelector(".messages"); const lastChild = messagesContainer?.lastElementChild; const prevSibling = lastChild?.previousElementSibling; if (lastChild && prevSibling) { // Add padding to the messages container to create room for the last message. // The purpose of this is to avoid constant scrolling during streaming in // instruct mode. let bufferHeight = Math.max(0, Math.max(window.innerHeight - 128 - 84, window.innerHeight - prevSibling.offsetHeight - 84) - lastChild.offsetHeight);
// Subtract header height when screen width is <= 924px if (window.innerWidth <= 924) { bufferHeight = Math.max(0, bufferHeight - 32); }
messagesContainer.style.paddingBottom = `${bufferHeight}px`; } }});
// Configure the observer to watch for changes in the subtree and attributesconst config = { childList: true, subtree: true, characterData: true, attributeOldValue: true, characterDataOldValue: true};
// Start observing the target elementobserver.observe(targetElement, config);
//------------------------------------------------// Handle syntax highlighting / LaTeX//------------------------------------------------function isElementVisibleOnScreen(element) { const rect = element.getBoundingClientRect(); return ( rect.left < window.innerWidth && rect.right > 0 && rect.top < window.innerHeight && rect.bottom > 0 );}
function doSyntaxHighlighting() { const messageBodies = document.getElementById("chat").querySelectorAll(".message-body");
if (messageBodies.length > 0) { observer.disconnect();
try { let hasSeenVisible = false;
// Go from last message to first for (let i = messageBodies.length - 1; i >= 0; i--) { const messageBody = messageBodies[i];
if (isElementVisibleOnScreen(messageBody)) { hasSeenVisible = true;
// Handle both code and math in a single pass through each message const codeBlocks = messageBody.querySelectorAll("pre code:not([data-highlighted])"); codeBlocks.forEach((codeBlock) => { hljs.highlightElement(codeBlock); codeBlock.setAttribute("data-highlighted", "true"); codeBlock.classList.add("pretty_scrollbar"); });
// Only render math in visible elements const mathContainers = messageBody.querySelectorAll("p, span, li, td, th, h1, h2, h3, h4, h5, h6, blockquote, figcaption, caption, dd, dt"); mathContainers.forEach(container => { if (isElementVisibleOnScreen(container)) { renderMathInElement(container, { delimiters: [ { left: "$$", right: "$$", display: true }, { left: "\\(", right: "\\)", display: false }, { left: "\\[", right: "\\]", display: true }, ], }); } }); } else if (hasSeenVisible) { // We've seen visible messages but this one is not visible // Since we're going from last to first, we can break break; } } } finally { observer.observe(targetElement, config); } }}
//------------------------------------------------// Add some scrollbars//------------------------------------------------const textareaElements = document.querySelectorAll(".add_scrollbar textarea");for(i = 0; i < textareaElements.length; i++) { textareaElements[i].classList.remove("scroll-hide"); textareaElements[i].classList.add("pretty_scrollbar"); textareaElements[i].style.resize = "none";}
//------------------------------------------------// Remove some backgrounds//------------------------------------------------const noBackgroundelements = document.querySelectorAll(".no-background");for(i = 0; i < noBackgroundelements.length; i++) { noBackgroundelements[i].parentNode.style.border = "none"; noBackgroundelements[i].parentNode.parentNode.parentNode.style.alignItems = "center";}
const slimDropdownElements = document.querySelectorAll(".slim-dropdown");for (i = 0; i < slimDropdownElements.length; i++) { const parentNode = slimDropdownElements[i].parentNode; parentNode.style.background = "transparent"; parentNode.style.border = "0";}
//------------------------------------------------// Create the hover menu in the chat tab// The show/hide events were adapted from:// https://github.com/SillyTavern/SillyTavern/blob/6c8bd06308c69d51e2eb174541792a870a83d2d6/public/script.js//------------------------------------------------var buttonsInChat = document.querySelectorAll("#chat-tab #chat-buttons button, #chat-tab #chat-buttons #show-controls");var button = document.getElementById("hover-element-button");var menu = document.getElementById("hover-menu");var istouchscreen = (navigator.maxTouchPoints > 0) || "ontouchstart" in document.documentElement;
function showMenu() { menu.style.display = "flex"; // Show the menu}
function hideMenu() { menu.style.display = "none"; // Hide the menu if (!istouchscreen) { document.querySelector("#chat-input textarea").focus(); // Focus on the chat input }}
if (buttonsInChat.length > 0) { for (let i = buttonsInChat.length - 1; i >= 0; i--) { const thisButton = buttonsInChat[i]; menu.appendChild(thisButton);
// Only apply transformations to button elements if (thisButton.tagName.toLowerCase() === "button") { thisButton.addEventListener("click", () => { hideMenu(); });
const buttonText = thisButton.textContent; const matches = buttonText.match(/(\(.*?\))/);
if (matches && matches.length > 1) { // Apply the transparent-substring class to the matched substring const substring = matches[1]; const newText = buttonText.replace(substring, ` <span class="transparent-substring">${substring.slice(1, -1)}</span>`); thisButton.innerHTML = newText; } } }}
function isMouseOverButtonOrMenu() { return menu.matches(":hover") || button.matches(":hover");}
button.addEventListener("mouseenter", function () { if (!istouchscreen) { showMenu(); }});
button.addEventListener("click", function () { if (menu.style.display === "flex") { hideMenu(); } else { showMenu(); }});
// Add event listener for mouseleave on the buttonbutton.addEventListener("mouseleave", function () { // Delay to prevent menu hiding when the mouse leaves the button into the menu setTimeout(function () { if (!isMouseOverButtonOrMenu()) { hideMenu(); } }, 100);});
// Add event listener for mouseleave on the menumenu.addEventListener("mouseleave", function () { // Delay to prevent menu hide when the mouse leaves the menu into the button setTimeout(function () { if (!isMouseOverButtonOrMenu()) { hideMenu(); } }, 100);});
// Add event listener for click anywhere in the documentdocument.addEventListener("click", function (event) { const target = event.target;
// Check if the click is outside the button/menu and the menu is visible if (!isMouseOverButtonOrMenu() && menu.style.display === "flex") { hideMenu(); }
if (event.target.classList.contains("pfp_character")) { toggleBigPicture(); }
// Handle sidebar clicks on mobile if (isMobile()) { // Check if the click did NOT originate from any of the specified toggle buttons or elements if ( target.closest("#navigation-toggle") !== navigationToggle && target.closest("#past-chats-toggle") !== pastChatsToggle && target.closest("#chat-controls-toggle") !== chatControlsToggle && target.closest(".header_bar") !== headerBar && target.closest("#past-chats-row") !== pastChatsRow && target.closest("#chat-controls") !== chatControlsRow ) { handleIndividualSidebarClose(event); } }});
//------------------------------------------------// Position the chat input//------------------------------------------------document.getElementById("chat-input-row").classList.add("chat-input-positioned");
//------------------------------------------------// Focus on the chat input//------------------------------------------------const chatTextArea = document.getElementById("chat-input").querySelector("textarea");
function respondToChatInputVisibility(element, callback) { var options = { root: document.documentElement, };
var observer = new IntersectionObserver((entries, observer) => { entries.forEach(entry => { callback(entry.intersectionRatio > 0); }); }, options);
observer.observe(element);}
function handleChatInputVisibilityChange(isVisible) { if (isVisible) { chatTextArea.focus(); }}
respondToChatInputVisibility(chatTextArea, handleChatInputVisibilityChange);
//------------------------------------------------// Show enlarged character picture when the profile// picture is clicked on//------------------------------------------------let bigPictureVisible = false;
function addBigPicture() { var imgElement = document.createElement("img"); var timestamp = new Date().getTime(); imgElement.src = "/file/user_data/cache/pfp_character.png?time=" + timestamp; imgElement.classList.add("bigProfilePicture"); imgElement.addEventListener("load", function () { this.style.visibility = "visible"; }); imgElement.addEventListener("error", function () { this.style.visibility = "hidden"; });
var imgElementParent = document.getElementById("chat").parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode; imgElementParent.appendChild(imgElement);}
function deleteBigPicture() { var bigProfilePictures = document.querySelectorAll(".bigProfilePicture"); bigProfilePictures.forEach(function (element) { element.parentNode.removeChild(element); });}
function toggleBigPicture() { if(bigPictureVisible) { deleteBigPicture(); bigPictureVisible = false; } else { addBigPicture(); bigPictureVisible = true; }}
//------------------------------------------------// Handle the chat input box growth//------------------------------------------------
// Cache DOM elementsconst chatContainer = document.getElementById("chat").parentNode.parentNode.parentNode;const chatInput = document.querySelector("#chat-input textarea");
// Variables to store current dimensionslet currentChatInputHeight = chatInput.clientHeight;
//------------------------------------------------// Focus on the rename text area when it becomes visible//------------------------------------------------const renameTextArea = document.getElementById("rename-row").querySelector("textarea");
function respondToRenameVisibility(element, callback) { var options = { root: document.documentElement, };
var observer = new IntersectionObserver((entries, observer) => { entries.forEach(entry => { callback(entry.intersectionRatio > 0); }); }, options);
observer.observe(element);}
function handleVisibilityChange(isVisible) { if (isVisible) { renameTextArea.focus(); }}
respondToRenameVisibility(renameTextArea, handleVisibilityChange);
//------------------------------------------------// Adjust the chat tab margin if no extension UI// is present at the bottom//------------------------------------------------
if (document.getElementById("extensions") === null) { document.getElementById("chat-tab").style.marginBottom = "-29px";}
//------------------------------------------------// Focus on the chat input after starting a new chat//------------------------------------------------
document.querySelectorAll(".focus-on-chat-input").forEach(element => { element.addEventListener("click", function() { document.querySelector("#chat-input textarea").focus(); });});
//------------------------------------------------// Fix a border around the "past chats" menu//------------------------------------------------document.getElementById("past-chats").parentNode.style.borderRadius = "0px";
//------------------------------------------------// Allow the character dropdown to coexist at the// Chat tab and the Parameters > Character tab//------------------------------------------------
const headerBar = document.querySelector(".header_bar");let originalParent;let originalIndex; // To keep track of the original positionlet movedElement;
function moveToChatTab() { const characterMenu = document.getElementById("character-menu"); const grandParent = characterMenu.parentElement.parentElement;
// Save the initial location for the character dropdown if (!originalParent) { originalParent = grandParent.parentElement; originalIndex = Array.from(originalParent.children).indexOf(grandParent); movedElement = grandParent; }
// Do not show the Character dropdown in the Chat tab when "instruct" mode is selected const instructRadio = document.querySelector("#chat-mode input[value=\"instruct\"]"); if (instructRadio && instructRadio.checked) { grandParent.style.display = "none"; }
grandParent.children[0].style.minWidth = "100%";
const chatControlsFirstChild = document.querySelector("#chat-controls").firstElementChild; const newParent = chatControlsFirstChild; let newPosition = newParent.children.length - 3;
newParent.insertBefore(grandParent, newParent.children[newPosition]); document.getElementById("save-character").style.display = "none"; document.getElementById("restore-character").style.display = "none";}
function restoreOriginalPosition() { if (originalParent && movedElement) { if (originalIndex >= originalParent.children.length) { originalParent.appendChild(movedElement); } else { originalParent.insertBefore(movedElement, originalParent.children[originalIndex]); }
document.getElementById("save-character").style.display = ""; document.getElementById("restore-character").style.display = ""; movedElement.style.display = ""; movedElement.children[0].style.minWidth = ""; }}
headerBar.addEventListener("click", (e) => { if (e.target.tagName === "BUTTON") { const tabName = e.target.textContent.trim(); if (tabName === "Chat") { moveToChatTab(); } else { restoreOriginalPosition(); } }});
//------------------------------------------------// Add a confirmation dialog when leaving the page// Useful to avoid data loss//------------------------------------------------window.addEventListener("beforeunload", function (event) { // Cancel the event event.preventDefault(); // Chrome requires returnValue to be set event.returnValue = "";});
moveToChatTab();
//------------------------------------------------// Buttons to toggle the sidebars//------------------------------------------------
const leftArrowSVG = `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="tabler-icon tabler-icon-arrow-bar-left"> <path d="M4 12l10 0"></path> <path d="M4 12l4 4"></path> <path d="M4 12l4 -4"></path> <path d="M20 4l0 16"></path></svg>`;
const rightArrowSVG = `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="tabler-icon tabler-icon-arrow-bar-right"> <path d="M20 12l-10 0"></path> <path d="M20 12l-4 4"></path> <path d="M20 12l-4 -4"></path> <path d="M4 4l0 16"></path></svg>`;
const hamburgerMenuSVG = `<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="icon icon-hamburger-menu"> <line x1="3" y1="12" x2="21" y2="12"></line> <line x1="3" y1="6" x2="21" y2="6"></line> <line x1="3" y1="18" x2="21" y2="18"></line></svg>`;
const closeMenuSVG = `<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="icon icon-close-menu"> <line x1="18" y1="6" x2="6" y2="18"></line> <line x1="6" y1="6" x2="18" y2="18"></line></svg>`;
const chatTab = document.getElementById("chat-tab");const pastChatsRow = document.getElementById("past-chats-row");const chatControlsRow = document.getElementById("chat-controls");
if (chatTab) { // Create past-chats-toggle div const pastChatsToggle = document.createElement("div"); pastChatsToggle.id = "past-chats-toggle"; pastChatsToggle.innerHTML = leftArrowSVG; // Set initial icon to left arrow pastChatsToggle.classList.add("past-chats-open"); // Set initial position
// Create chat-controls-toggle div const chatControlsToggle = document.createElement("div"); chatControlsToggle.id = "chat-controls-toggle"; chatControlsToggle.innerHTML = rightArrowSVG; // Set initial icon to right arrow chatControlsToggle.classList.add("chat-controls-open"); // Set initial position
// Append both elements to the chat-tab chatTab.appendChild(pastChatsToggle); chatTab.appendChild(chatControlsToggle);}
// Create navigation toggle divconst navigationToggle = document.createElement("div");navigationToggle.id = "navigation-toggle";navigationToggle.innerHTML = leftArrowSVG; // Set initial icon to right arrownavigationToggle.classList.add("navigation-left"); // Set initial positionheaderBar.appendChild(navigationToggle);
// Retrieve the dynamically created toggle buttonsconst pastChatsToggle = document.getElementById("past-chats-toggle");const chatControlsToggle = document.getElementById("chat-controls-toggle");
function handleIndividualSidebarClose(event) { const target = event.target;
// Close navigation bar if click is outside and it is open if (!headerBar.contains(target) && !headerBar.classList.contains("sidebar-hidden")) { toggleSidebar(headerBar, navigationToggle, true); }
// Close past chats row if click is outside and it is open if (!pastChatsRow.contains(target) && !pastChatsRow.classList.contains("sidebar-hidden")) { toggleSidebar(pastChatsRow, pastChatsToggle, true); }
// Close chat controls row if click is outside and it is open if (!chatControlsRow.contains(target) && !chatControlsRow.classList.contains("sidebar-hidden")) { toggleSidebar(chatControlsRow, chatControlsToggle, true); }}
function toggleSidebar(sidebar, toggle, forceClose = false) { const isCurrentlyHidden = sidebar.classList.contains("sidebar-hidden"); const shouldClose = !isCurrentlyHidden;
// Apply visibility classes sidebar.classList.toggle("sidebar-hidden", shouldClose); sidebar.classList.toggle("sidebar-shown", !shouldClose);
if (sidebar === headerBar) { // Special handling for header bar document.documentElement.style.setProperty("--header-width", shouldClose ? "0px" : "112px"); pastChatsRow.classList.toggle("negative-header", shouldClose); pastChatsToggle.classList.toggle("negative-header", shouldClose); toggle.innerHTML = shouldClose ? hamburgerMenuSVG : closeMenuSVG; } else if (sidebar === pastChatsRow) { // Past chats sidebar toggle.classList.toggle("past-chats-closed", shouldClose); toggle.classList.toggle("past-chats-open", !shouldClose); toggle.innerHTML = shouldClose ? rightArrowSVG : leftArrowSVG; } else if (sidebar === chatControlsRow) { // Chat controls sidebar toggle.classList.toggle("chat-controls-closed", shouldClose); toggle.classList.toggle("chat-controls-open", !shouldClose); toggle.innerHTML = shouldClose ? leftArrowSVG : rightArrowSVG; }
// Mobile handling if (isMobile()) { sidebar.classList.toggle("sidebar-shown", !shouldClose); }}
// Function to check if the device is mobilefunction isMobile() { return window.innerWidth <= 924;}
// Function to initialize sidebarsfunction initializeSidebars() { const isOnMobile = isMobile();
if (isOnMobile) { // Mobile state: Hide sidebars and set closed states [pastChatsRow, chatControlsRow, headerBar].forEach(el => { el.classList.add("sidebar-hidden"); el.classList.remove("sidebar-shown"); });
document.documentElement.style.setProperty("--header-width", "0px"); pastChatsRow.classList.add("negative-header"); pastChatsToggle.classList.add("negative-header", "past-chats-closed"); pastChatsToggle.classList.remove("past-chats-open");
[chatControlsToggle, navigationToggle].forEach(el => { el.classList.add("chat-controls-closed"); el.classList.remove("chat-controls-open"); });
pastChatsToggle.innerHTML = rightArrowSVG; chatControlsToggle.innerHTML = leftArrowSVG; navigationToggle.innerHTML = hamburgerMenuSVG; } else { // Desktop state: Show sidebars and set open states [pastChatsRow, chatControlsRow].forEach(el => { el.classList.remove("sidebar-hidden", "sidebar-shown"); });
pastChatsToggle.classList.add("past-chats-open"); pastChatsToggle.classList.remove("past-chats-closed");
[chatControlsToggle, navigationToggle].forEach(el => { el.classList.add("chat-controls-open"); el.classList.remove("chat-controls-closed"); });
pastChatsToggle.innerHTML = leftArrowSVG; chatControlsToggle.innerHTML = rightArrowSVG; navigationToggle.innerHTML = closeMenuSVG; }}
// Run the initializer when the page loadsinitializeSidebars();
// Add click event listeners to toggle buttonspastChatsToggle.addEventListener("click", () => { const isCurrentlyOpen = !pastChatsRow.classList.contains("sidebar-hidden"); toggleSidebar(pastChatsRow, pastChatsToggle);
// On desktop, open/close both sidebars at the same time if (!isMobile()) { if (isCurrentlyOpen) { // If we just closed the left sidebar, also close the right sidebar if (!chatControlsRow.classList.contains("sidebar-hidden")) { toggleSidebar(chatControlsRow, chatControlsToggle, true); } } else { // If we just opened the left sidebar, also open the right sidebar if (chatControlsRow.classList.contains("sidebar-hidden")) { toggleSidebar(chatControlsRow, chatControlsToggle, false); } } }});
chatControlsToggle.addEventListener("click", () => { const isCurrentlyOpen = !chatControlsRow.classList.contains("sidebar-hidden"); toggleSidebar(chatControlsRow, chatControlsToggle);
// On desktop, open/close both sidebars at the same time if (!isMobile()) { if (isCurrentlyOpen) { // If we just closed the right sidebar, also close the left sidebar if (!pastChatsRow.classList.contains("sidebar-hidden")) { toggleSidebar(pastChatsRow, pastChatsToggle, true); } } else { // If we just opened the right sidebar, also open the left sidebar if (pastChatsRow.classList.contains("sidebar-hidden")) { toggleSidebar(pastChatsRow, pastChatsToggle, false); } } }});
navigationToggle.addEventListener("click", () => { toggleSidebar(headerBar, navigationToggle);});
//------------------------------------------------// Fixes #chat-input textarea height issue// for devices with width <= 924px//------------------------------------------------
if (isMobile()) { // Target the textarea const textarea = document.querySelector("#chat-input textarea");
if (textarea) { // Simulate adding and removing a newline textarea.value += "\n"; textarea.dispatchEvent(new Event("input", { bubbles: true })); textarea.value = textarea.value.slice(0, -1); textarea.dispatchEvent(new Event("input", { bubbles: true })); }}
//------------------------------------------------// Create a top navigation bar on mobile//------------------------------------------------
function createMobileTopBar() { const chatTab = document.getElementById("chat-tab");
// Only create the top bar if it doesn't already exist if (chatTab && !chatTab.querySelector(".mobile-top-bar")) { const topBar = document.createElement("div"); topBar.classList.add("mobile-top-bar");
// Insert the top bar as the first child of chat-tab chatTab.appendChild(topBar); }}
createMobileTopBar();
//------------------------------------------------// Simple Navigation Functions//------------------------------------------------
function navigateLastAssistantMessage(direction) { const chat = document.querySelector("#chat"); if (!chat) return false;
const messages = chat.querySelectorAll("[data-index]"); if (messages.length === 0) return false;
// Find the last assistant message (starting from the end) let lastAssistantMessage = null; for (let i = messages.length - 1; i >= 0; i--) { const msg = messages[i]; if ( msg.classList.contains("assistant-message") || msg.querySelector(".circle-bot") || msg.querySelector(".text-bot") ) { lastAssistantMessage = msg; break; } }
if (!lastAssistantMessage) return false;
const buttons = lastAssistantMessage.querySelectorAll(".version-nav-button");
for (let i = 0; i < buttons.length; i++) { const button = buttons[i]; const onclick = button.getAttribute("onclick"); const disabled = button.hasAttribute("disabled");
const isLeft = onclick && onclick.includes("'left'"); const isRight = onclick && onclick.includes("'right'");
if (!disabled) { if (direction === "left" && isLeft) { navigateVersion(button, direction); return true; } if (direction === "right" && isRight) { navigateVersion(button, direction); return true; } } }
return false;}
//------------------------------------------------// Paste Handler for Long Text//------------------------------------------------
const MAX_PLAIN_TEXT_LENGTH = 2500;
function setupPasteHandler() { const textbox = document.querySelector("#chat-input textarea[data-testid=\"textbox\"]"); const fileInput = document.querySelector("#chat-input input[data-testid=\"file-upload\"]");
if (!textbox || !fileInput) { setTimeout(setupPasteHandler, 500); return; }
textbox.addEventListener("paste", async (event) => { const text = event.clipboardData?.getData("text");
if (text && text.length > MAX_PLAIN_TEXT_LENGTH && document.querySelector("#paste_to_attachment input[data-testid=\"checkbox\"]")?.checked) { event.preventDefault();
const file = new File([text], "pasted_text.txt", { type: "text/plain", lastModified: Date.now() });
const dataTransfer = new DataTransfer(); dataTransfer.items.add(file); fileInput.files = dataTransfer.files; fileInput.dispatchEvent(new Event("change", { bubbles: true })); } });}
if (document.readyState === "loading") { document.addEventListener("DOMContentLoaded", setupPasteHandler);} else { setupPasteHandler();}
//------------------------------------------------// Tooltips//------------------------------------------------
// File upload buttondocument.querySelector("#chat-input .upload-button").title = "Upload text files, PDFs, DOCX documents, and images";
// Activate web searchdocument.getElementById("web-search").title = "Search the internet with DuckDuckGo";
//------------------------------------------------// Inline icons for deleting past chats//------------------------------------------------
function addMiniDeletes() { document.querySelectorAll("#past-chats label:not(.has-delete)").forEach(label => { const container = document.createElement("span"); container.className = "delete-container";
label.classList.add("chat-label-with-delete");
const trashBtn = document.createElement("button"); trashBtn.innerHTML = "🗑️"; trashBtn.className = "trash-btn";
const cancelBtn = document.createElement("button"); cancelBtn.innerHTML = "✕"; cancelBtn.className = "cancel-btn";
const confirmBtn = document.createElement("button"); confirmBtn.innerHTML = "✓"; confirmBtn.className = "confirm-btn";
label.addEventListener("mouseenter", () => { container.style.opacity = "1"; });
label.addEventListener("mouseleave", () => { container.style.opacity = "0"; });
trashBtn.onclick = (e) => { e.stopPropagation(); label.querySelector("input").click(); document.querySelector("#delete_chat").click(); trashBtn.style.display = "none"; cancelBtn.style.display = "flex"; confirmBtn.style.display = "flex"; };
cancelBtn.onclick = (e) => { e.stopPropagation(); document.querySelector("#delete_chat-cancel").click(); resetButtons(); };
confirmBtn.onclick = (e) => { e.stopPropagation(); document.querySelector("#delete_chat-confirm").click(); resetButtons(); };
function resetButtons() { trashBtn.style.display = "inline"; cancelBtn.style.display = "none"; confirmBtn.style.display = "none"; }
container.append(trashBtn, cancelBtn, confirmBtn); label.appendChild(container); label.classList.add("has-delete"); });}
new MutationObserver(() => addMiniDeletes()).observe( document.querySelector("#past-chats"), {childList: true, subtree: true});addMiniDeletes();
//------------------------------------------------// Fix autoscroll after fonts load//------------------------------------------------document.fonts.addEventListener("loadingdone", (event) => { setTimeout(() => { if (!window.isScrolled) { const maxScroll = targetElement.scrollHeight - targetElement.clientHeight; if (targetElement.scrollTop < maxScroll - 5) { targetElement.scrollTop = maxScroll; } } }, 50);});
(function() { const chatParent = document.querySelector(".chat-parent"); const chatInputRow = document.querySelector("#chat-input-row"); const originalMarginBottom = 75; let originalHeight = chatInputRow.offsetHeight;
function updateMargin() { const currentHeight = chatInputRow.offsetHeight; const heightDifference = currentHeight - originalHeight; chatParent.style.marginBottom = `${originalMarginBottom + heightDifference}px`; }
// Watch for changes that might affect height const observer = new MutationObserver(updateMargin); observer.observe(chatInputRow, { childList: true, subtree: true, attributes: true });
// Also listen for window resize window.addEventListener("resize", updateMargin);
// Initial call to set the margin based on current state updateMargin();})();1(function(global,factory){typeof exports==="object"&&typeof module!=="undefined"?module.exports=factory():typeof define==="function"&&define.amd?define(factory):(global=global||self,global.morphdom=factory())})(this,function(){"use strict";var DOCUMENT_FRAGMENT_NODE=11;function morphAttrs(fromNode,toNode){var toNodeAttrs=toNode.attributes;var attr;var attrName;var attrNamespaceURI;var attrValue;var fromValue;if(toNode.nodeType===DOCUMENT_FRAGMENT_NODE||fromNode.nodeType===DOCUMENT_FRAGMENT_NODE){return}for(var i=toNodeAttrs.length-1;i>=0;i--){attr=toNodeAttrs[i];attrName=attr.name;attrNamespaceURI=attr.namespaceURI;attrValue=attr.value;if(attrNamespaceURI){attrName=attr.localName||attrName;fromValue=fromNode.getAttributeNS(attrNamespaceURI,attrName);if(fromValue!==attrValue){if(attr.prefix==="xmlns"){attrName=attr.name}fromNode.setAttributeNS(attrNamespaceURI,attrName,attrValue)}}else{fromValue=fromNode.getAttribute(attrName);if(fromValue!==attrValue){fromNode.setAttribute(attrName,attrValue)}}}var fromNodeAttrs=fromNode.attributes;for(var d=fromNodeAttrs.length-1;d>=0;d--){attr=fromNodeAttrs[d];attrName=attr.name;attrNamespaceURI=attr.namespaceURI;if(attrNamespaceURI){attrName=attr.localName||attrName;if(!toNode.hasAttributeNS(attrNamespaceURI,attrName)){fromNode.removeAttributeNS(attrNamespaceURI,attrName)}}else{if(!toNode.hasAttribute(attrName)){fromNode.removeAttribute(attrName)}}}}var range;var NS_XHTML="http://www.w3.org/1999/xhtml";var doc=typeof document==="undefined"?undefined:document;var HAS_TEMPLATE_SUPPORT=!!doc&&"content"in doc.createElement("template");var HAS_RANGE_SUPPORT=!!doc&&doc.createRange&&"createContextualFragment"in doc.createRange();function createFragmentFromTemplate(str){var template=doc.createElement("template");template.innerHTML=str;return template.content.childNodes[0]}function createFragmentFromRange(str){if(!range){range=doc.createRange();range.selectNode(doc.body)}var fragment=range.createContextualFragment(str);return fragment.childNodes[0]}function createFragmentFromWrap(str){var fragment=doc.createElement("body");fragment.innerHTML=str;return fragment.childNodes[0]}function toElement(str){str=str.trim();if(HAS_TEMPLATE_SUPPORT){return createFragmentFromTemplate(str)}else if(HAS_RANGE_SUPPORT){return createFragmentFromRange(str)}return createFragmentFromWrap(str)}function compareNodeNames(fromEl,toEl){var fromNodeName=fromEl.nodeName;var toNodeName=toEl.nodeName;var fromCodeStart,toCodeStart;if(fromNodeName===toNodeName){return true}fromCodeStart=fromNodeName.charCodeAt(0);toCodeStart=toNodeName.charCodeAt(0);if(fromCodeStart<=90&&toCodeStart>=97){return fromNodeName===toNodeName.toUpperCase()}else if(toCodeStart<=90&&fromCodeStart>=97){return toNodeName===fromNodeName.toUpperCase()}else{return false}}function createElementNS(name,namespaceURI){return!namespaceURI||namespaceURI===NS_XHTML?doc.createElement(name):doc.createElementNS(namespaceURI,name)}function moveChildren(fromEl,toEl){var curChild=fromEl.firstChild;while(curChild){var nextChild=curChild.nextSibling;toEl.appendChild(curChild);curChild=nextChild}return toEl}function syncBooleanAttrProp(fromEl,toEl,name){if(fromEl[name]!==toEl[name]){fromEl[name]=toEl[name];if(fromEl[name]){fromEl.setAttribute(name,"")}else{fromEl.removeAttribute(name)}}}var specialElHandlers={OPTION:function(fromEl,toEl){var parentNode=fromEl.parentNode;if(parentNode){var parentName=parentNode.nodeName.toUpperCase();if(parentName==="OPTGROUP"){parentNode=parentNode.parentNode;parentName=parentNode&&parentNode.nodeName.toUpperCase()}if(parentName==="SELECT"&&!parentNode.hasAttribute("multiple")){if(fromEl.hasAttribute("selected")&&!toEl.selected){fromEl.setAttribute("selected","selected");fromEl.removeAttribute("selected")}parentNode.selectedIndex=-1}}syncBooleanAttrProp(fromEl,toEl,"selected")},INPUT:function(fromEl,toEl){syncBooleanAttrProp(fromEl,toEl,"checked");syncBooleanAttrProp(fromEl,toEl,"disabled");if(fromEl.value!==toEl.value){fromEl.value=toEl.value}if(!toEl.hasAttribute("value")){fromEl.removeAttribute("value")}},TEXTAREA:function(fromEl,toEl){var newValue=toEl.value;if(fromEl.value!==newValue){fromEl.value=newValue}var firstChild=fromEl.firstChild;if(firstChild){var oldValue=firstChild.nodeValue;if(oldValue==newValue||!newValue&&oldValue==fromEl.placeholder){return}firstChild.nodeValue=newValue}},SELECT:function(fromEl,toEl){if(!toEl.hasAttribute("multiple")){var selectedIndex=-1;var i=0;var curChild=fromEl.firstChild;var optgroup;var nodeName;while(curChild){nodeName=curChild.nodeName&&curChild.nodeName.toUpperCase();if(nodeName==="OPTGROUP"){optgroup=curChild;curChild=optgroup.firstChild}else{if(nodeName==="OPTION"){if(curChild.hasAttribute("selected")){selectedIndex=i;break}i++}curChild=curChild.nextSibling;if(!curChild&&optgroup){curChild=optgroup.nextSibling;optgroup=null}}}fromEl.selectedIndex=selectedIndex}}};var ELEMENT_NODE=1;var DOCUMENT_FRAGMENT_NODE$1=11;var TEXT_NODE=3;var COMMENT_NODE=8;function noop(){}function defaultGetNodeKey(node){if(node){return node.getAttribute&&node.getAttribute("id")||node.id}}function morphdomFactory(morphAttrs){return function morphdom(fromNode,toNode,options){if(!options){options={}}if(typeof toNode==="string"){if(fromNode.nodeName==="#document"||fromNode.nodeName==="HTML"||fromNode.nodeName==="BODY"){var toNodeHtml=toNode;toNode=doc.createElement("html");toNode.innerHTML=toNodeHtml}else{toNode=toElement(toNode)}}else if(toNode.nodeType===DOCUMENT_FRAGMENT_NODE$1){toNode=toNode.firstElementChild}var getNodeKey=options.getNodeKey||defaultGetNodeKey;var onBeforeNodeAdded=options.onBeforeNodeAdded||noop;var onNodeAdded=options.onNodeAdded||noop;var onBeforeElUpdated=options.onBeforeElUpdated||noop;var onElUpdated=options.onElUpdated||noop;var onBeforeNodeDiscarded=options.onBeforeNodeDiscarded||noop;var onNodeDiscarded=options.onNodeDiscarded||noop;var onBeforeElChildrenUpdated=options.onBeforeElChildrenUpdated||noop;var skipFromChildren=options.skipFromChildren||noop;var addChild=options.addChild||function(parent,child){return parent.appendChild(child)};var childrenOnly=options.childrenOnly===true;var fromNodesLookup=Object.create(null);var keyedRemovalList=[];function addKeyedRemoval(key){keyedRemovalList.push(key)}function walkDiscardedChildNodes(node,skipKeyedNodes){if(node.nodeType===ELEMENT_NODE){var curChild=node.firstChild;while(curChild){var key=undefined;if(skipKeyedNodes&&(key=getNodeKey(curChild))){addKeyedRemoval(key)}else{onNodeDiscarded(curChild);if(curChild.firstChild){walkDiscardedChildNodes(curChild,skipKeyedNodes)}}curChild=curChild.nextSibling}}}function removeNode(node,parentNode,skipKeyedNodes){if(onBeforeNodeDiscarded(node)===false){return}if(parentNode){parentNode.removeChild(node)}onNodeDiscarded(node);walkDiscardedChildNodes(node,skipKeyedNodes)}function indexTree(node){if(node.nodeType===ELEMENT_NODE||node.nodeType===DOCUMENT_FRAGMENT_NODE$1){var curChild=node.firstChild;while(curChild){var key=getNodeKey(curChild);if(key){fromNodesLookup[key]=curChild}indexTree(curChild);curChild=curChild.nextSibling}}}indexTree(fromNode);function handleNodeAdded(el){onNodeAdded(el);var curChild=el.firstChild;while(curChild){var nextSibling=curChild.nextSibling;var key=getNodeKey(curChild);if(key){var unmatchedFromEl=fromNodesLookup[key];if(unmatchedFromEl&&compareNodeNames(curChild,unmatchedFromEl)){curChild.parentNode.replaceChild(unmatchedFromEl,curChild);morphEl(unmatchedFromEl,curChild)}else{handleNodeAdded(curChild)}}else{handleNodeAdded(curChild)}curChild=nextSibling}}function cleanupFromEl(fromEl,curFromNodeChild,curFromNodeKey){while(curFromNodeChild){var fromNextSibling=curFromNodeChild.nextSibling;if(curFromNodeKey=getNodeKey(curFromNodeChild)){addKeyedRemoval(curFromNodeKey)}else{removeNode(curFromNodeChild,fromEl,true)}curFromNodeChild=fromNextSibling}}function morphEl(fromEl,toEl,childrenOnly){var toElKey=getNodeKey(toEl);if(toElKey){delete fromNodesLookup[toElKey]}if(!childrenOnly){var beforeUpdateResult=onBeforeElUpdated(fromEl,toEl);if(beforeUpdateResult===false){return}else if(beforeUpdateResult instanceof HTMLElement){fromEl=beforeUpdateResult;indexTree(fromEl)}morphAttrs(fromEl,toEl);onElUpdated(fromEl);if(onBeforeElChildrenUpdated(fromEl,toEl)===false){return}}if(fromEl.nodeName!=="TEXTAREA"){morphChildren(fromEl,toEl)}else{specialElHandlers.TEXTAREA(fromEl,toEl)}}function morphChildren(fromEl,toEl){var skipFrom=skipFromChildren(fromEl,toEl);var curToNodeChild=toEl.firstChild;var curFromNodeChild=fromEl.firstChild;var curToNodeKey;var curFromNodeKey;var fromNextSibling;var toNextSibling;var matchingFromEl;outer:while(curToNodeChild){toNextSibling=curToNodeChild.nextSibling;curToNodeKey=getNodeKey(curToNodeChild);while(!skipFrom&&curFromNodeChild){fromNextSibling=curFromNodeChild.nextSibling;if(curToNodeChild.isSameNode&&curToNodeChild.isSameNode(curFromNodeChild)){curToNodeChild=toNextSibling;curFromNodeChild=fromNextSibling;continue outer}curFromNodeKey=getNodeKey(curFromNodeChild);var curFromNodeType=curFromNodeChild.nodeType;var isCompatible=undefined;if(curFromNodeType===curToNodeChild.nodeType){if(curFromNodeType===ELEMENT_NODE){if(curToNodeKey){if(curToNodeKey!==curFromNodeKey){if(matchingFromEl=fromNodesLookup[curToNodeKey]){if(fromNextSibling===matchingFromEl){isCompatible=false}else{fromEl.insertBefore(matchingFromEl,curFromNodeChild);if(curFromNodeKey){addKeyedRemoval(curFromNodeKey)}else{removeNode(curFromNodeChild,fromEl,true)}curFromNodeChild=matchingFromEl;curFromNodeKey=getNodeKey(curFromNodeChild)}}else{isCompatible=false}}}else if(curFromNodeKey){isCompatible=false}isCompatible=isCompatible!==false&&compareNodeNames(curFromNodeChild,curToNodeChild);if(isCompatible){morphEl(curFromNodeChild,curToNodeChild)}}else if(curFromNodeType===TEXT_NODE||curFromNodeType==COMMENT_NODE){isCompatible=true;if(curFromNodeChild.nodeValue!==curToNodeChild.nodeValue){curFromNodeChild.nodeValue=curToNodeChild.nodeValue}}}if(isCompatible){curToNodeChild=toNextSibling;curFromNodeChild=fromNextSibling;continue outer}if(curFromNodeKey){addKeyedRemoval(curFromNodeKey)}else{removeNode(curFromNodeChild,fromEl,true)}curFromNodeChild=fromNextSibling}if(curToNodeKey&&(matchingFromEl=fromNodesLookup[curToNodeKey])&&compareNodeNames(matchingFromEl,curToNodeChild)){if(!skipFrom){addChild(fromEl,matchingFromEl)}morphEl(matchingFromEl,curToNodeChild)}else{var onBeforeNodeAddedResult=onBeforeNodeAdded(curToNodeChild);if(onBeforeNodeAddedResult!==false){if(onBeforeNodeAddedResult){curToNodeChild=onBeforeNodeAddedResult}if(curToNodeChild.actualize){curToNodeChild=curToNodeChild.actualize(fromEl.ownerDocument||doc)}addChild(fromEl,curToNodeChild);handleNodeAdded(curToNodeChild)}}curToNodeChild=toNextSibling;curFromNodeChild=fromNextSibling}cleanupFromEl(fromEl,curFromNodeChild,curFromNodeKey);var specialElHandler=specialElHandlers[fromEl.nodeName];if(specialElHandler){specialElHandler(fromEl,toEl)}}var morphedNode=fromNode;var morphedNodeType=morphedNode.nodeType;var toNodeType=toNode.nodeType;if(!childrenOnly){if(morphedNodeType===ELEMENT_NODE){if(toNodeType===ELEMENT_NODE){if(!compareNodeNames(fromNode,toNode)){onNodeDiscarded(fromNode);morphedNode=moveChildren(fromNode,createElementNS(toNode.nodeName,toNode.namespaceURI))}}else{morphedNode=toNode}}else if(morphedNodeType===TEXT_NODE||morphedNodeType===COMMENT_NODE){if(toNodeType===morphedNodeType){if(morphedNode.nodeValue!==toNode.nodeValue){morphedNode.nodeValue=toNode.nodeValue}return morphedNode}else{morphedNode=toNode}}}if(morphedNode===toNode){onNodeDiscarded(fromNode)}else{if(toNode.isSameNode&&toNode.isSameNode(morphedNode)){return}morphEl(morphedNode,toNode,childrenOnly);if(keyedRemovalList){for(var i=0,len=keyedRemovalList.length;i<len;i++){var elToRemove=fromNodesLookup[keyedRemovalList[i]];if(elToRemove){removeNode(elToRemove,elToRemove.parentNode,false)}}}}if(!childrenOnly&&morphedNode!==fromNode&&fromNode.parentNode){if(morphedNode.actualize){morphedNode=morphedNode.actualize(fromNode.ownerDocument||doc)}fromNode.parentNode.replaceChild(morphedNode,fromNode)}return morphedNode}}var morphdom=morphdomFactory(morphAttrs);return morphdom});12345678910111213141516171819202122232425262728293031323334353637383940// Functions for downloading JSON filesfunction getCurrentTimestamp() { const now = new Date(); const timezoneOffset = now.getTimezoneOffset() * 60000; // Convert to milliseconds const localTime = new Date(now.getTime() - timezoneOffset); const formattedTimestamp = localTime.toISOString().replace(/[-:]/g, "").slice(0, 15); return formattedTimestamp;}
function saveFile(contents, filename) { const element = document.createElement("a"); element.setAttribute("href", "data:text/plain;charset=utf-8," + encodeURIComponent(contents)); element.setAttribute("download", filename); element.style.display = "none"; document.body.appendChild(element); element.click(); document.body.removeChild(element);}
function saveHistory(history, character, mode) { let path = null;
if (["chat", "chat-instruct"].includes(mode) && character && character.trim() !== "") { path = `history_${character}_${getCurrentTimestamp()}.json`; } else { try { path = `history_${mode}_${getCurrentTimestamp()}.json`; } catch (error) { path = `history_${getCurrentTimestamp()}.json`; } } saveFile(history, path);}
function saveSession(session) { let path = null;
path = `session_${getCurrentTimestamp()}.json`; saveFile(session, path);}.github/ISSUE_TEMPLATE/bug_report_template.ymlAdded+53
.github/ISSUE_TEMPLATE/feature_request.mdAdded+16
.github/dependabot.ymlAdded+14
.github/pull_request_template.mdAdded+3
.github/workflows/build-everything-tgw.ymlAdded+63
.github/workflows/build-portable-release-cuda.ymlAdded+189
.github/workflows/build-portable-release-vulkan.ymlAdded+177
.github/workflows/build-portable-release.ymlAdded+203
.gitignoreAdded+33
LICENSEAdded+661
README.md+440-8
cmd_linux.shAdded+22
cmd_macos.shAdded+24
cmd_windows.batAdded+34
docker/.dockerignoreAdded+8
docker/.env.exampleAdded+24
docker/TensorRT-LLM/DockerfileAdded+27
docker/amd/DockerfileAdded+21
docker/amd/docker-compose.ymlAdded+44
docker/cpu/DockerfileAdded+25
docker/cpu/docker-compose.ymlAdded+44
docker/intel/DockerfileAdded+21
docker/intel/docker-compose.ymlAdded+44
docker/nvidia/DockerfileAdded+21
docker/nvidia/docker-compose.ymlAdded+41
docs/01 - Chat Tab.mdAdded+148
docs/02 - Default and Notebook Tabs.mdAdded+35
docs/03 - Parameters Tab.mdAdded+128
docs/04 - Model Tab.mdAdded+129
docs/05 - Training Tab.mdAdded+139
docs/06 - Session Tab.mdAdded+32
docs/07 - Extensions.mdAdded+248
docs/08 - Additional Tips.mdAdded+60
docs/09 - Docker.mdAdded+208
docs/11 - AMD Setup.mdAdded+13
docs/12 - OpenAI API.mdAdded+550
docs/13 - Keyboard Shortcuts.mdAdded+19
docs/Multimodal Tutorial.mdAdded+66
docs/README.mdAdded+5
docs/What Works.mdAdded+20
download-model.pyAdded+427
js/dark_theme.jsAdded+20
js/global_scope_js.jsAdded+389
js/highlightjs/highlight.min.jsAdded
js/highlightjs/highlightjs-copy.min.jsAdded+1
js/katex/auto-render.min.jsAdded+1
js/katex/katex.min.jsAdded
js/main.jsAdded+1107
js/morphdom/morphdom-umd.min.jsAdded+1
js/save_files.jsAdded+40