mirror of
https://github.com/open-webui/open-webui.git
synced 2026-11-15 09:31:21 +00:00
Merge 563d621854 into f7ac7ee109
This commit is contained in:
commit
e42c569d81
546 changed files with 33750 additions and 13423 deletions
132
README.ar.md
Normal file
132
README.ar.md
Normal file
|
|
@ -0,0 +1,132 @@
|
|||
<h2>Open WebUI</h2>
|
||||
|
||||
<p>Open WebUI هو <a href="https://docs.openwebui.com/"><strong>بيت للذكاء الاصطناعي</strong></a>: منصة قابلة للتوسعة وسهلة الاستخدام تستضيفها بنفسك، ومصممة للعمل بالكامل دون اتصال بالإنترنت. اربط النماذج المحلية عبر Ollama أو استخدم واجهات API المتوافقة مع OpenAI للنماذج المحلية والسحابية.</p>
|
||||
|
||||
[English](README.md) |
|
||||
[简体中文](README.zh.md) |
|
||||
[繁體中文](README.zht.md) |
|
||||
[한국어](README.ko.md) |
|
||||
[Deutsch](README.de.md) |
|
||||
[Español](README.es.md) |
|
||||
[Français](README.fr.md) |
|
||||
[Italiano](README.it.md) |
|
||||
[Dansk](README.da.md) |
|
||||
[日本語](README.ja.md) |
|
||||
[Polski](README.pl.md) |
|
||||
[Русский](README.ru.md) |
|
||||
[Bosanski](README.bs.md) |
|
||||
[العربية](README.ar.md) |
|
||||
[Norsk](README.no.md) |
|
||||
[Português (Brasil)](README.br.md) |
|
||||
[ไทย](README.th.md) |
|
||||
[Türkçe](README.tr.md) |
|
||||
[Українська](README.uk.md) |
|
||||
[বাংলা](README.bn.md) |
|
||||
[Ελληνικά](README.gr.md) |
|
||||
[Tiếng Việt](README.vi.md)
|
||||
|
||||
[](https://docs.openwebui.com/)
|
||||
|
||||

|
||||

|
||||

|
||||

|
||||

|
||||

|
||||

|
||||
[](https://discord.gg/5rJgQTnV4s)
|
||||
[](https://github.com/sponsors/open-webui)
|
||||
|
||||
[استكشف Open WebUI →](https://docs.openwebui.com/)
|
||||
|
||||
### التثبيت
|
||||
|
||||
#### Python
|
||||
|
||||
يتطلب Python 3.12.
|
||||
|
||||
```bash
|
||||
pip install open-webui
|
||||
open-webui serve
|
||||
```
|
||||
|
||||
ثم افتح [http://localhost:8080](http://localhost:8080).
|
||||
|
||||
#### Docker
|
||||
|
||||
```bash
|
||||
docker run -d -p 3000:8080 --add-host=host.docker.internal:host-gateway -v open-webui:/app/backend/data --name open-webui --restart always ghcr.io/open-webui/open-webui:main
|
||||
```
|
||||
|
||||
ثم افتح [http://localhost:3000](http://localhost:3000).
|
||||
|
||||
| وسم الصورة | المحتوى |
|
||||
| --- | --- |
|
||||
| `:main` | صورة قياسية تتضمن اعتماديات الذكاء الاصطناعي المحلي |
|
||||
| `:slim` | صورة خفيفة تستخدم خدمات خارجية للتضمينات واستخراج محتوى المستندات والصوت |
|
||||
| `:cuda` | Open WebUI مع تسريع CUDA |
|
||||
| `:ollama` | Open WebUI مرفقًا معه Ollama |
|
||||
| `:dev` | أحدث نسخة تطوير |
|
||||
|
||||
أضف هذه الخيارات إلى `docker run` قبل اسم الصورة حسب الحاجة:
|
||||
|
||||
| الخيار | الغرض |
|
||||
| --- | --- |
|
||||
| `-e OLLAMA_BASE_URL=http://your-ollama-server:11434` | الاتصال بـ Ollama على خادم آخر |
|
||||
| `-e OPENAI_API_KEY=your_secret_key` | تعيين مفتاح API الخاص بك لدى OpenAI |
|
||||
| `-e HF_HUB_OFFLINE=1` | تعطيل تنزيل نماذج Hugging Face للاستخدام دون اتصال |
|
||||
| `--gpus all` | تمكين الوصول إلى وحدة معالجة الرسوميات Nvidia مع `:cuda` أو `:ollama`؛ يتطلب Nvidia Container Toolkit |
|
||||
|
||||
راجع [دليل التثبيت باستخدام Docker](https://docs.openwebui.com/getting-started/quick-start/) للاطلاع على خطوات الإعداد وخيارات الضبط.
|
||||
|
||||
#### تطبيق سطح المكتب
|
||||
|
||||
[نزّل تطبيق سطح المكتب الأصلي](https://github.com/open-webui/desktop) لأنظمة macOS وWindows وLinux.
|
||||
|
||||
[اقرأ الوثائق →](https://docs.openwebui.com/getting-started/)
|
||||
|
||||
### المنظومة
|
||||
|
||||
- [Open Terminal](https://github.com/open-webui/open-terminal) / [Terminals (Enterprise)](https://github.com/open-webui/terminals): طبقة التنفيذ التي تجعل Open WebUI بيئة متكاملة للوكلاء، مع تنسيق مؤسسي لمساحات عمل منفصلة لكل مستخدم.
|
||||
- [Knowledge Base Sync (oikb)](https://github.com/open-webui/oikb): اعكس المجلدات والمستودعات وحاويات التخزين ومواقع الويكي في قواعد معرفة Open WebUI باستخدام المزامنة التزايدية.
|
||||
- [Open WebUI Computer](https://github.com/open-webui/computer): حاسوبك في أي متصفح: الملفات والمحرر والطرفية وGit ووكلاء الذكاء الاصطناعي الاختياريون، جميعها تعمل على جهازك الفعلي.
|
||||
|
||||
راجع [وثائق المنظومة](https://docs.openwebui.com/ecosystem/) لمزيد من التفاصيل.
|
||||
|
||||
### استكشاف الأخطاء والتحديثات
|
||||
|
||||
راجع [دليل استكشاف الأخطاء](https://docs.openwebui.com/troubleshooting/) لحل مشكلات الاتصال، و[دليل التحديث](https://docs.openwebui.com/getting-started/updating) لتحديث تثبيتك.
|
||||
|
||||
### الوثائق
|
||||
|
||||
راجع [الوثائق](https://docs.openwebui.com/) للإعداد والاستخدام، و[خارطة الطريق](https://docs.openwebui.com/roadmap/) للاطلاع على الأعمال المخطط لها.
|
||||
|
||||
لإعداد Docker Compose أو Kubernetes أو غيرهما، راجع [وثائق التثبيت](https://docs.openwebui.com/getting-started/).
|
||||
|
||||
### الدعم
|
||||
|
||||
[افتح بلاغًا](https://github.com/open-webui/open-webui/issues) أو [ابدأ نقاشًا](https://github.com/open-webui/open-webui/discussions).
|
||||
|
||||
تجدنا على [Reddit](https://www.reddit.com/r/OpenWebUI/) و[X](https://x.com/OpenWebUI) و[Discord](https://discord.gg/5rJgQTnV4s).
|
||||
|
||||
### الأمان
|
||||
|
||||
أبلغ عن الثغرات بسرية عبر [GitHub Security Advisories](https://github.com/open-webui/open-webui/security). تُقبل البلاغات الأمنية عبر GitHub فقط.
|
||||
|
||||
### سجل النجوم
|
||||
|
||||
<a href="https://star-history.com/#open-webui/open-webui&Date">
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=open-webui/open-webui&type=Date&theme=dark" />
|
||||
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=open-webui/open-webui&type=Date" />
|
||||
<img alt="مخطط سجل النجوم" src="https://api.star-history.com/svg?repos=open-webui/open-webui&type=Date" />
|
||||
</picture>
|
||||
</a>
|
||||
|
||||
#### الترخيص
|
||||
|
||||
يتضمن كودًا يخضع لترخيص Open WebUI License الذي يشترط الحفاظ على هوية Open WebUI التجارية، ومساهمات سابقة تخضع لتراخيصها الأصلية. راجع [LICENSE](./LICENSE) و[LICENSE_HISTORY](./LICENSE_HISTORY) للاطلاع على الشروط والسجل.
|
||||
|
||||
[المؤسسات](https://docs.openwebui.com/enterprise) · [الوظائف](https://careers.openwebui.com/) · [الرعاية](https://github.com/sponsors/open-webui)
|
||||
|
||||
أنشأه [Timothy Jaeryang Baek](https://github.com/tjbck).
|
||||
132
README.bn.md
Normal file
132
README.bn.md
Normal file
|
|
@ -0,0 +1,132 @@
|
|||
<h2>Open WebUI</h2>
|
||||
|
||||
<p>Open WebUI হলো <a href="https://docs.openwebui.com/"><strong>AI-এর একটি আপন ঠিকানা</strong></a>: একটি সম্প্রসারণযোগ্য, সহজে ব্যবহারযোগ্য ও নিজে হোস্ট করা যায় এমন প্ল্যাটফর্ম, যা সম্পূর্ণ অফলাইনে চলার জন্য তৈরি। Ollama দিয়ে স্থানীয় মডেল সংযুক্ত করুন, অথবা স্থানীয় ও ক্লাউড মডেলের জন্য OpenAI-সামঞ্জস্যপূর্ণ API ব্যবহার করুন।</p>
|
||||
|
||||
[English](README.md) |
|
||||
[简体中文](README.zh.md) |
|
||||
[繁體中文](README.zht.md) |
|
||||
[한국어](README.ko.md) |
|
||||
[Deutsch](README.de.md) |
|
||||
[Español](README.es.md) |
|
||||
[Français](README.fr.md) |
|
||||
[Italiano](README.it.md) |
|
||||
[Dansk](README.da.md) |
|
||||
[日本語](README.ja.md) |
|
||||
[Polski](README.pl.md) |
|
||||
[Русский](README.ru.md) |
|
||||
[Bosanski](README.bs.md) |
|
||||
[العربية](README.ar.md) |
|
||||
[Norsk](README.no.md) |
|
||||
[Português (Brasil)](README.br.md) |
|
||||
[ไทย](README.th.md) |
|
||||
[Türkçe](README.tr.md) |
|
||||
[Українська](README.uk.md) |
|
||||
[বাংলা](README.bn.md) |
|
||||
[Ελληνικά](README.gr.md) |
|
||||
[Tiếng Việt](README.vi.md)
|
||||
|
||||
[](https://docs.openwebui.com/)
|
||||
|
||||

|
||||

|
||||

|
||||

|
||||

|
||||

|
||||

|
||||
[](https://discord.gg/5rJgQTnV4s)
|
||||
[](https://github.com/sponsors/open-webui)
|
||||
|
||||
[Open WebUI ঘুরে দেখুন →](https://docs.openwebui.com/)
|
||||
|
||||
### ইনস্টলেশন
|
||||
|
||||
#### Python
|
||||
|
||||
Python 3.12 প্রয়োজন।
|
||||
|
||||
```bash
|
||||
pip install open-webui
|
||||
open-webui serve
|
||||
```
|
||||
|
||||
এরপর [http://localhost:8080](http://localhost:8080) খুলুন।
|
||||
|
||||
#### Docker
|
||||
|
||||
```bash
|
||||
docker run -d -p 3000:8080 --add-host=host.docker.internal:host-gateway -v open-webui:/app/backend/data --name open-webui --restart always ghcr.io/open-webui/open-webui:main
|
||||
```
|
||||
|
||||
এরপর [http://localhost:3000](http://localhost:3000) খুলুন।
|
||||
|
||||
| ইমেজ ট্যাগ | যা অন্তর্ভুক্ত আছে |
|
||||
| --- | --- |
|
||||
| `:main` | স্থানীয় AI-এর প্রয়োজনীয় ডিপেন্ডেন্সিসহ স্ট্যান্ডার্ড ইমেজ |
|
||||
| `:slim` | এম্বেডিং, ডকুমেন্ট থেকে তথ্য আহরণ ও ভয়েসের জন্য বাহ্যিক সেবা ব্যবহার করা হালকা ইমেজ |
|
||||
| `:cuda` | CUDA অ্যাক্সেলারেশনসহ Open WebUI |
|
||||
| `:ollama` | Ollama-সহ Open WebUI |
|
||||
| `:dev` | সর্বশেষ ডেভেলপমেন্ট বিল্ড |
|
||||
|
||||
প্রয়োজন অনুযায়ী `docker run` কমান্ডে ইমেজের নামের আগে এই অপশনগুলো যোগ করুন:
|
||||
|
||||
| অপশন | উদ্দেশ্য |
|
||||
| --- | --- |
|
||||
| `-e OLLAMA_BASE_URL=http://your-ollama-server:11434` | অন্য সার্ভারে থাকা Ollama-তে সংযোগ করা |
|
||||
| `-e OPENAI_API_KEY=your_secret_key` | আপনার OpenAI API কী সেট করা |
|
||||
| `-e HF_HUB_OFFLINE=1` | অফলাইনে ব্যবহারের জন্য Hugging Face মডেল ডাউনলোড বন্ধ করা |
|
||||
| `--gpus all` | `:cuda` বা `:ollama`-এর জন্য Nvidia GPU ব্যবহারের অনুমতি দেওয়া; Nvidia Container Toolkit প্রয়োজন |
|
||||
|
||||
সেটআপের নির্দেশনা ও কনফিগারেশন অপশনের জন্য [Docker ইনস্টলেশন নির্দেশিকা](https://docs.openwebui.com/getting-started/quick-start/) দেখুন।
|
||||
|
||||
#### ডেস্কটপ অ্যাপ
|
||||
|
||||
macOS, Windows ও Linux-এর জন্য [নেটিভ ডেস্কটপ অ্যাপ ডাউনলোড করুন](https://github.com/open-webui/desktop)।
|
||||
|
||||
[ডকুমেন্টেশন পড়ুন →](https://docs.openwebui.com/getting-started/)
|
||||
|
||||
### ইকোসিস্টেম
|
||||
|
||||
- [Open Terminal](https://github.com/open-webui/open-terminal) / [Terminals (Enterprise)](https://github.com/open-webui/terminals): Open WebUI-কে একটি পূর্ণাঙ্গ এজেন্ট পরিবেশে পরিণত করার এক্সিকিউশন স্তর, যেখানে প্রত্যেক ব্যবহারকারীর ওয়ার্কস্পেসের জন্য এন্টারপ্রাইজ অর্কেস্ট্রেশন রয়েছে।
|
||||
- [Knowledge Base Sync (oikb)](https://github.com/open-webui/oikb): ইনক্রিমেন্টাল সিঙ্কের মাধ্যমে ফোল্ডার, রিপোজিটরি, বাকেট ও উইকির প্রতিলিপি Open WebUI-এর নলেজ বেসে রাখুন।
|
||||
- [Open WebUI Computer](https://github.com/open-webui/computer): যেকোনো ব্রাউজারে আপনার কম্পিউটার: ফাইল, এডিটর, টার্মিনাল, Git ও ঐচ্ছিক AI এজেন্ট—সবই আপনার আসল মেশিনে চলে।
|
||||
|
||||
বিস্তারিত জানতে [ইকোসিস্টেম ডকুমেন্টেশন](https://docs.openwebui.com/ecosystem/) দেখুন।
|
||||
|
||||
### সমস্যা সমাধান ও আপডেট
|
||||
|
||||
সংযোগের সমস্যার জন্য [সমস্যা সমাধানের নির্দেশিকা](https://docs.openwebui.com/troubleshooting/) এবং আপনার ইনস্টলেশন আপডেট করতে [আপডেট নির্দেশিকা](https://docs.openwebui.com/getting-started/updating) দেখুন।
|
||||
|
||||
### ডকুমেন্টেশন
|
||||
|
||||
কনফিগারেশন ও ব্যবহারের জন্য [ডকুমেন্টেশন](https://docs.openwebui.com/) এবং পরিকল্পিত কাজের জন্য [রোডম্যাপ](https://docs.openwebui.com/roadmap/) দেখুন।
|
||||
|
||||
Docker Compose, Kubernetes ও অন্যান্য সেটআপের জন্য [ইনস্টলেশন ডকুমেন্টেশন](https://docs.openwebui.com/getting-started/) দেখুন।
|
||||
|
||||
### সহায়তা
|
||||
|
||||
[একটি ইস্যু খুলুন](https://github.com/open-webui/open-webui/issues) বা [আলোচনা শুরু করুন](https://github.com/open-webui/open-webui/discussions)।
|
||||
|
||||
আমাদের পাবেন [Reddit](https://www.reddit.com/r/OpenWebUI/), [X](https://x.com/OpenWebUI) ও [Discord](https://discord.gg/5rJgQTnV4s)-এ।
|
||||
|
||||
### নিরাপত্তা
|
||||
|
||||
[GitHub Security Advisories](https://github.com/open-webui/open-webui/security)-এর মাধ্যমে গোপনে নিরাপত্তা দুর্বলতা জানান। নিরাপত্তাসংক্রান্ত রিপোর্ট কেবল GitHub-এর মাধ্যমেই গ্রহণ করা হয়।
|
||||
|
||||
### স্টারের ইতিহাস
|
||||
|
||||
<a href="https://star-history.com/#open-webui/open-webui&Date">
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=open-webui/open-webui&type=Date&theme=dark" />
|
||||
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=open-webui/open-webui&type=Date" />
|
||||
<img alt="স্টারের ইতিহাসের চার্ট" src="https://api.star-history.com/svg?repos=open-webui/open-webui&type=Date" />
|
||||
</picture>
|
||||
</a>
|
||||
|
||||
#### লাইসেন্স
|
||||
|
||||
এতে Open WebUI License-এর আওতাধীন কোড রয়েছে, যা Open WebUI ব্র্যান্ডিং অক্ষুণ্ণ রাখা বাধ্যতামূলক করে, এবং আগের অবদানগুলো তাদের নিজ নিজ মূল লাইসেন্সের আওতায় রয়েছে। শর্ত ও ইতিহাসের জন্য [LICENSE](./LICENSE) ও [LICENSE_HISTORY](./LICENSE_HISTORY) দেখুন।
|
||||
|
||||
[এন্টারপ্রাইজ](https://docs.openwebui.com/enterprise) · [ক্যারিয়ার](https://careers.openwebui.com/) · [স্পনসর করুন](https://github.com/sponsors/open-webui)
|
||||
|
||||
তৈরি করেছেন [Timothy Jaeryang Baek](https://github.com/tjbck)।
|
||||
132
README.br.md
Normal file
132
README.br.md
Normal file
|
|
@ -0,0 +1,132 @@
|
|||
<h2>Open WebUI</h2>
|
||||
|
||||
<p>Open WebUI é <a href="https://docs.openwebui.com/"><strong>um lar para a IA</strong></a>: uma plataforma auto-hospedada, extensível e fácil de usar, feita para funcionar totalmente offline. Conecte modelos locais pelo Ollama ou use APIs compatíveis com OpenAI para modelos locais e na nuvem.</p>
|
||||
|
||||
[English](README.md) |
|
||||
[简体中文](README.zh.md) |
|
||||
[繁體中文](README.zht.md) |
|
||||
[한국어](README.ko.md) |
|
||||
[Deutsch](README.de.md) |
|
||||
[Español](README.es.md) |
|
||||
[Français](README.fr.md) |
|
||||
[Italiano](README.it.md) |
|
||||
[Dansk](README.da.md) |
|
||||
[日本語](README.ja.md) |
|
||||
[Polski](README.pl.md) |
|
||||
[Русский](README.ru.md) |
|
||||
[Bosanski](README.bs.md) |
|
||||
[العربية](README.ar.md) |
|
||||
[Norsk](README.no.md) |
|
||||
[Português (Brasil)](README.br.md) |
|
||||
[ไทย](README.th.md) |
|
||||
[Türkçe](README.tr.md) |
|
||||
[Українська](README.uk.md) |
|
||||
[বাংলা](README.bn.md) |
|
||||
[Ελληνικά](README.gr.md) |
|
||||
[Tiếng Việt](README.vi.md)
|
||||
|
||||
[](https://docs.openwebui.com/)
|
||||
|
||||

|
||||

|
||||

|
||||

|
||||

|
||||

|
||||

|
||||
[](https://discord.gg/5rJgQTnV4s)
|
||||
[](https://github.com/sponsors/open-webui)
|
||||
|
||||
[Explore o Open WebUI →](https://docs.openwebui.com/)
|
||||
|
||||
### Instalação
|
||||
|
||||
#### Python
|
||||
|
||||
Requer Python 3.12.
|
||||
|
||||
```bash
|
||||
pip install open-webui
|
||||
open-webui serve
|
||||
```
|
||||
|
||||
Depois, abra [http://localhost:8080](http://localhost:8080).
|
||||
|
||||
#### Docker
|
||||
|
||||
```bash
|
||||
docker run -d -p 3000:8080 --add-host=host.docker.internal:host-gateway -v open-webui:/app/backend/data --name open-webui --restart always ghcr.io/open-webui/open-webui:main
|
||||
```
|
||||
|
||||
Depois, abra [http://localhost:3000](http://localhost:3000).
|
||||
|
||||
| Tag da imagem | Conteúdo |
|
||||
| --- | --- |
|
||||
| `:main` | Imagem padrão com dependências de IA local |
|
||||
| `:slim` | Imagem leve que usa serviços externos para embeddings, extração de documentos e voz |
|
||||
| `:cuda` | Open WebUI com aceleração CUDA |
|
||||
| `:ollama` | Open WebUI com Ollama incluído |
|
||||
| `:dev` | Build de desenvolvimento mais recente |
|
||||
|
||||
Adicione estas opções ao `docker run` antes do nome da imagem, conforme necessário:
|
||||
|
||||
| Opção | Finalidade |
|
||||
| --- | --- |
|
||||
| `-e OLLAMA_BASE_URL=http://your-ollama-server:11434` | Conectar ao Ollama em outro servidor |
|
||||
| `-e OPENAI_API_KEY=your_secret_key` | Definir sua chave de API da OpenAI |
|
||||
| `-e HF_HUB_OFFLINE=1` | Desativar downloads de modelos do Hugging Face para uso offline |
|
||||
| `--gpus all` | Habilitar acesso à GPU Nvidia para `:cuda` ou `:ollama`; requer o Nvidia Container Toolkit |
|
||||
|
||||
Consulte o [guia de instalação com Docker](https://docs.openwebui.com/getting-started/quick-start/) para instruções e opções de configuração.
|
||||
|
||||
#### Aplicativo para desktop
|
||||
|
||||
[Baixe o aplicativo nativo para desktop](https://github.com/open-webui/desktop) para macOS, Windows e Linux.
|
||||
|
||||
[Leia a documentação →](https://docs.openwebui.com/getting-started/)
|
||||
|
||||
### Ecossistema
|
||||
|
||||
- [Open Terminal](https://github.com/open-webui/open-terminal) / [Terminals (Enterprise)](https://github.com/open-webui/terminals): A camada de execução que transforma o Open WebUI em um ambiente completo para agentes, com orquestração empresarial de espaços de trabalho por usuário.
|
||||
- [Knowledge Base Sync (oikb)](https://github.com/open-webui/oikb): Espelhe pastas, repositórios, buckets e wikis nas bases de conhecimento do Open WebUI com sincronização incremental.
|
||||
- [Open WebUI Computer](https://github.com/open-webui/computer): Seu computador em qualquer navegador: arquivos, editor, terminal, Git e agentes de IA opcionais, executados na sua própria máquina.
|
||||
|
||||
Consulte a [documentação do ecossistema](https://docs.openwebui.com/ecosystem/) para mais detalhes.
|
||||
|
||||
### Solução de problemas e atualizações
|
||||
|
||||
Consulte o [guia de solução de problemas](https://docs.openwebui.com/troubleshooting/) para problemas de conexão e o [guia de atualização](https://docs.openwebui.com/getting-started/updating) para atualizar sua instalação.
|
||||
|
||||
### Documentação
|
||||
|
||||
Consulte a [documentação](https://docs.openwebui.com/) para configuração e uso, e o [roteiro](https://docs.openwebui.com/roadmap/) para o trabalho planejado.
|
||||
|
||||
Para Docker Compose, Kubernetes e outras formas de instalação, consulte a [documentação de instalação](https://docs.openwebui.com/getting-started/).
|
||||
|
||||
### Suporte
|
||||
|
||||
[Abra uma issue](https://github.com/open-webui/open-webui/issues) ou [inicie uma discussão](https://github.com/open-webui/open-webui/discussions).
|
||||
|
||||
Encontre-nos no [Reddit](https://www.reddit.com/r/OpenWebUI/), [X](https://x.com/OpenWebUI) e [Discord](https://discord.gg/5rJgQTnV4s).
|
||||
|
||||
### Segurança
|
||||
|
||||
Relate vulnerabilidades de forma privada pelo [GitHub Security Advisories](https://github.com/open-webui/open-webui/security). Relatos de segurança são aceitos somente pelo GitHub.
|
||||
|
||||
### Histórico de estrelas
|
||||
|
||||
<a href="https://star-history.com/#open-webui/open-webui&Date">
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=open-webui/open-webui&type=Date&theme=dark" />
|
||||
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=open-webui/open-webui&type=Date" />
|
||||
<img alt="Gráfico do histórico de estrelas" src="https://api.star-history.com/svg?repos=open-webui/open-webui&type=Date" />
|
||||
</picture>
|
||||
</a>
|
||||
|
||||
#### Licença
|
||||
|
||||
Inclui código sob a Open WebUI License, que exige preservar a marca Open WebUI, e contribuições anteriores sob suas licenças originais. Consulte [LICENSE](./LICENSE) e [LICENSE_HISTORY](./LICENSE_HISTORY) para os termos e o histórico.
|
||||
|
||||
[Empresas](https://docs.openwebui.com/enterprise) · [Carreiras](https://careers.openwebui.com/) · [Patrocine](https://github.com/sponsors/open-webui)
|
||||
|
||||
Criado por [Timothy Jaeryang Baek](https://github.com/tjbck).
|
||||
132
README.bs.md
Normal file
132
README.bs.md
Normal file
|
|
@ -0,0 +1,132 @@
|
|||
<h2>Open WebUI</h2>
|
||||
|
||||
<p>Open WebUI je <a href="https://docs.openwebui.com/"><strong>dom za AI</strong></a>: proširiva platforma jednostavna za korištenje, koju sami hostujete i koja može raditi potpuno offline. Povežite lokalne modele putem Ollame ili koristite API-je kompatibilne s OpenAI-jem za lokalne modele i modele u oblaku.</p>
|
||||
|
||||
[English](README.md) |
|
||||
[简体中文](README.zh.md) |
|
||||
[繁體中文](README.zht.md) |
|
||||
[한국어](README.ko.md) |
|
||||
[Deutsch](README.de.md) |
|
||||
[Español](README.es.md) |
|
||||
[Français](README.fr.md) |
|
||||
[Italiano](README.it.md) |
|
||||
[Dansk](README.da.md) |
|
||||
[日本語](README.ja.md) |
|
||||
[Polski](README.pl.md) |
|
||||
[Русский](README.ru.md) |
|
||||
[Bosanski](README.bs.md) |
|
||||
[العربية](README.ar.md) |
|
||||
[Norsk](README.no.md) |
|
||||
[Português (Brasil)](README.br.md) |
|
||||
[ไทย](README.th.md) |
|
||||
[Türkçe](README.tr.md) |
|
||||
[Українська](README.uk.md) |
|
||||
[বাংলা](README.bn.md) |
|
||||
[Ελληνικά](README.gr.md) |
|
||||
[Tiếng Việt](README.vi.md)
|
||||
|
||||
[](https://docs.openwebui.com/)
|
||||
|
||||

|
||||

|
||||

|
||||

|
||||

|
||||

|
||||

|
||||
[](https://discord.gg/5rJgQTnV4s)
|
||||
[](https://github.com/sponsors/open-webui)
|
||||
|
||||
[Istražite Open WebUI →](https://docs.openwebui.com/)
|
||||
|
||||
### Instalacija
|
||||
|
||||
#### Python
|
||||
|
||||
Potreban je Python 3.12.
|
||||
|
||||
```bash
|
||||
pip install open-webui
|
||||
open-webui serve
|
||||
```
|
||||
|
||||
Zatim otvorite [http://localhost:8080](http://localhost:8080).
|
||||
|
||||
#### Docker
|
||||
|
||||
```bash
|
||||
docker run -d -p 3000:8080 --add-host=host.docker.internal:host-gateway -v open-webui:/app/backend/data --name open-webui --restart always ghcr.io/open-webui/open-webui:main
|
||||
```
|
||||
|
||||
Zatim otvorite [http://localhost:3000](http://localhost:3000).
|
||||
|
||||
| Oznaka slike | Sadržaj |
|
||||
| --- | --- |
|
||||
| `:main` | Standardna slika sa zavisnostima za lokalni AI |
|
||||
| `:slim` | Lagana slika koja koristi vanjske servise za embeddinge, izdvajanje sadržaja dokumenata i govor |
|
||||
| `:cuda` | Open WebUI s CUDA ubrzanjem |
|
||||
| `:ollama` | Open WebUI s uključenom Ollamom |
|
||||
| `:dev` | Najnovija razvojna verzija |
|
||||
|
||||
Po potrebi dodajte ove opcije u `docker run` prije naziva slike:
|
||||
|
||||
| Opcija | Namjena |
|
||||
| --- | --- |
|
||||
| `-e OLLAMA_BASE_URL=http://your-ollama-server:11434` | Povezivanje s Ollamom na drugom serveru |
|
||||
| `-e OPENAI_API_KEY=your_secret_key` | Postavljanje OpenAI API ključa |
|
||||
| `-e HF_HUB_OFFLINE=1` | Isključivanje preuzimanja Hugging Face modela za rad offline |
|
||||
| `--gpus all` | Omogućavanje pristupa Nvidia GPU-u za `:cuda` ili `:ollama`; potreban je Nvidia Container Toolkit |
|
||||
|
||||
Upute i opcije konfiguracije nalaze se u [vodiču za instalaciju putem Dockera](https://docs.openwebui.com/getting-started/quick-start/).
|
||||
|
||||
#### Desktop aplikacija
|
||||
|
||||
[Preuzmite nativnu desktop aplikaciju](https://github.com/open-webui/desktop) za macOS, Windows i Linux.
|
||||
|
||||
[Pročitajte dokumentaciju →](https://docs.openwebui.com/getting-started/)
|
||||
|
||||
### Ekosistem
|
||||
|
||||
- [Open Terminal](https://github.com/open-webui/open-terminal) / [Terminals (Enterprise)](https://github.com/open-webui/terminals): Izvršni sloj koji pretvara Open WebUI u potpuno okruženje za agente, s poslovnom orkestracijom zasebnih radnih prostora za svakog korisnika.
|
||||
- [Knowledge Base Sync (oikb)](https://github.com/open-webui/oikb): Preslikajte foldere, repozitorije, spremnike i wikije u baze znanja Open WebUI-ja uz inkrementalnu sinhronizaciju.
|
||||
- [Open WebUI Computer](https://github.com/open-webui/computer): Vaš računar u bilo kojem pregledniku: datoteke, uređivač, terminal, Git i opcionalni AI agenti koji rade na vašem stvarnom računaru.
|
||||
|
||||
Detalje potražite u [dokumentaciji ekosistema](https://docs.openwebui.com/ecosystem/).
|
||||
|
||||
### Rješavanje problema i ažuriranja
|
||||
|
||||
Za probleme s povezivanjem pogledajte [vodič za rješavanje problema](https://docs.openwebui.com/troubleshooting/), a za ažuriranje instalacije [vodič za ažuriranje](https://docs.openwebui.com/getting-started/updating).
|
||||
|
||||
### Dokumentacija
|
||||
|
||||
Za konfiguraciju i korištenje pogledajte [dokumentaciju](https://docs.openwebui.com/), a za planirani rad [plan razvoja](https://docs.openwebui.com/roadmap/).
|
||||
|
||||
Za Docker Compose, Kubernetes i druge načine instalacije pogledajte [dokumentaciju za instalaciju](https://docs.openwebui.com/getting-started/).
|
||||
|
||||
### Podrška
|
||||
|
||||
[Otvorite prijavu](https://github.com/open-webui/open-webui/issues) ili [pokrenite raspravu](https://github.com/open-webui/open-webui/discussions).
|
||||
|
||||
Pronađite nas na [Redditu](https://www.reddit.com/r/OpenWebUI/), [X-u](https://x.com/OpenWebUI) i [Discordu](https://discord.gg/5rJgQTnV4s).
|
||||
|
||||
### Sigurnost
|
||||
|
||||
Ranjivosti prijavite privatno putem [GitHub Security Advisories](https://github.com/open-webui/open-webui/security). Sigurnosne prijave prihvatamo isključivo putem GitHuba.
|
||||
|
||||
### Historija zvjezdica
|
||||
|
||||
<a href="https://star-history.com/#open-webui/open-webui&Date">
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=open-webui/open-webui&type=Date&theme=dark" />
|
||||
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=open-webui/open-webui&type=Date" />
|
||||
<img alt="Grafikon historije zvjezdica" src="https://api.star-history.com/svg?repos=open-webui/open-webui&type=Date" />
|
||||
</picture>
|
||||
</a>
|
||||
|
||||
#### Licenca
|
||||
|
||||
Sadrži kod pod licencom Open WebUI License, koja zahtijeva očuvanje brenda Open WebUI, te ranije doprinose pod njihovim izvornim licencama. Uslove i historiju pogledajte u [LICENSE](./LICENSE) i [LICENSE_HISTORY](./LICENSE_HISTORY).
|
||||
|
||||
[Enterprise](https://docs.openwebui.com/enterprise) · [Karijere](https://careers.openwebui.com/) · [Sponzorišite](https://github.com/sponsors/open-webui)
|
||||
|
||||
Autor: [Timothy Jaeryang Baek](https://github.com/tjbck).
|
||||
132
README.da.md
Normal file
132
README.da.md
Normal file
|
|
@ -0,0 +1,132 @@
|
|||
<h2>Open WebUI</h2>
|
||||
|
||||
<p>Open WebUI er <a href="https://docs.openwebui.com/"><strong>et hjem til AI</strong></a>: en udvidelig og brugervenlig platform, som du selv hoster, og som er bygget til at køre helt offline. Tilslut lokale modeller via Ollama, eller brug OpenAI-kompatible API’er til lokale modeller og cloudmodeller.</p>
|
||||
|
||||
[English](README.md) |
|
||||
[简体中文](README.zh.md) |
|
||||
[繁體中文](README.zht.md) |
|
||||
[한국어](README.ko.md) |
|
||||
[Deutsch](README.de.md) |
|
||||
[Español](README.es.md) |
|
||||
[Français](README.fr.md) |
|
||||
[Italiano](README.it.md) |
|
||||
[Dansk](README.da.md) |
|
||||
[日本語](README.ja.md) |
|
||||
[Polski](README.pl.md) |
|
||||
[Русский](README.ru.md) |
|
||||
[Bosanski](README.bs.md) |
|
||||
[العربية](README.ar.md) |
|
||||
[Norsk](README.no.md) |
|
||||
[Português (Brasil)](README.br.md) |
|
||||
[ไทย](README.th.md) |
|
||||
[Türkçe](README.tr.md) |
|
||||
[Українська](README.uk.md) |
|
||||
[বাংলা](README.bn.md) |
|
||||
[Ελληνικά](README.gr.md) |
|
||||
[Tiếng Việt](README.vi.md)
|
||||
|
||||
[](https://docs.openwebui.com/)
|
||||
|
||||

|
||||

|
||||

|
||||

|
||||

|
||||

|
||||

|
||||
[](https://discord.gg/5rJgQTnV4s)
|
||||
[](https://github.com/sponsors/open-webui)
|
||||
|
||||
[Udforsk Open WebUI →](https://docs.openwebui.com/)
|
||||
|
||||
### Installation
|
||||
|
||||
#### Python
|
||||
|
||||
Kræver Python 3.12.
|
||||
|
||||
```bash
|
||||
pip install open-webui
|
||||
open-webui serve
|
||||
```
|
||||
|
||||
Åbn derefter [http://localhost:8080](http://localhost:8080).
|
||||
|
||||
#### Docker
|
||||
|
||||
```bash
|
||||
docker run -d -p 3000:8080 --add-host=host.docker.internal:host-gateway -v open-webui:/app/backend/data --name open-webui --restart always ghcr.io/open-webui/open-webui:main
|
||||
```
|
||||
|
||||
Åbn derefter [http://localhost:3000](http://localhost:3000).
|
||||
|
||||
| Image-tag | Indhold |
|
||||
| --- | --- |
|
||||
| `:main` | Standardimage med afhængigheder til lokal AI |
|
||||
| `:slim` | Letvægtsimage med eksterne tjenester til embeddings, dokumentudtræk og tale |
|
||||
| `:cuda` | Open WebUI med CUDA-acceleration |
|
||||
| `:ollama` | Open WebUI med Ollama inkluderet |
|
||||
| `:dev` | Nyeste udviklingsbuild |
|
||||
|
||||
Tilføj disse indstillinger til `docker run` før image-navnet efter behov:
|
||||
|
||||
| Indstilling | Formål |
|
||||
| --- | --- |
|
||||
| `-e OLLAMA_BASE_URL=http://your-ollama-server:11434` | Opret forbindelse til Ollama på en anden server |
|
||||
| `-e OPENAI_API_KEY=your_secret_key` | Angiv din OpenAI-API-nøgle |
|
||||
| `-e HF_HUB_OFFLINE=1` | Deaktiver download af Hugging Face-modeller til offlinebrug |
|
||||
| `--gpus all` | Aktiver Nvidia-GPU-adgang for `:cuda` eller `:ollama`; kræver Nvidia Container Toolkit |
|
||||
|
||||
Se [installationsvejledningen til Docker](https://docs.openwebui.com/getting-started/quick-start/) for opsætning og konfigurationsmuligheder.
|
||||
|
||||
#### Desktop-app
|
||||
|
||||
[Download den native desktop-app](https://github.com/open-webui/desktop) til macOS, Windows og Linux.
|
||||
|
||||
[Læs dokumentationen →](https://docs.openwebui.com/getting-started/)
|
||||
|
||||
### Økosystem
|
||||
|
||||
- [Open Terminal](https://github.com/open-webui/open-terminal) / [Terminals (Enterprise)](https://github.com/open-webui/terminals): Det eksekveringslag, der gør Open WebUI til et komplet agentmiljø, med enterprise-orkestrering af individuelle arbejdsområder til hver bruger.
|
||||
- [Knowledge Base Sync (oikb)](https://github.com/open-webui/oikb): Spejl mapper, repositories, buckets og wikier i Open WebUI Knowledge Bases med inkrementel synkronisering.
|
||||
- [Open WebUI Computer](https://github.com/open-webui/computer): Din computer i enhver browser: filer, editor, terminal, Git og valgfrie AI-agenter, som kører på din egen maskine.
|
||||
|
||||
Se [dokumentationen til økosystemet](https://docs.openwebui.com/ecosystem/) for flere oplysninger.
|
||||
|
||||
### Fejlfinding og opdateringer
|
||||
|
||||
Se [fejlfindingsvejledningen](https://docs.openwebui.com/troubleshooting/) ved forbindelsesproblemer og [opdateringsvejledningen](https://docs.openwebui.com/getting-started/updating) for at opdatere din installation.
|
||||
|
||||
### Dokumentation
|
||||
|
||||
Se [dokumentationen](https://docs.openwebui.com/) for konfiguration og brug samt [køreplanen](https://docs.openwebui.com/roadmap/) for planlagt arbejde.
|
||||
|
||||
For Docker Compose, Kubernetes og andre opsætninger, se [installationsdokumentationen](https://docs.openwebui.com/getting-started/).
|
||||
|
||||
### Hjælp
|
||||
|
||||
[Opret et issue](https://github.com/open-webui/open-webui/issues), eller [start en diskussion](https://github.com/open-webui/open-webui/discussions).
|
||||
|
||||
Find os på [Reddit](https://www.reddit.com/r/OpenWebUI/), [X](https://x.com/OpenWebUI) og [Discord](https://discord.gg/5rJgQTnV4s).
|
||||
|
||||
### Sikkerhed
|
||||
|
||||
Indberet sårbarheder fortroligt via [GitHub Security Advisories](https://github.com/open-webui/open-webui/security). Sikkerhedsrapporter modtages kun via GitHub.
|
||||
|
||||
### Stjernehistorik
|
||||
|
||||
<a href="https://star-history.com/#open-webui/open-webui&Date">
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=open-webui/open-webui&type=Date&theme=dark" />
|
||||
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=open-webui/open-webui&type=Date" />
|
||||
<img alt="Diagram over stjernehistorik" src="https://api.star-history.com/svg?repos=open-webui/open-webui&type=Date" />
|
||||
</picture>
|
||||
</a>
|
||||
|
||||
#### Licens
|
||||
|
||||
Indeholder kode under Open WebUI License, som kræver, at Open WebUI-brandingen bevares, samt tidligere bidrag under deres oprindelige licenser. Se [LICENSE](./LICENSE) og [LICENSE_HISTORY](./LICENSE_HISTORY) for vilkår og historik.
|
||||
|
||||
[Enterprise](https://docs.openwebui.com/enterprise) · [Karriere](https://careers.openwebui.com/) · [Støt projektet](https://github.com/sponsors/open-webui)
|
||||
|
||||
Skabt af [Timothy Jaeryang Baek](https://github.com/tjbck).
|
||||
132
README.de.md
Normal file
132
README.de.md
Normal file
|
|
@ -0,0 +1,132 @@
|
|||
<h2>Open WebUI</h2>
|
||||
|
||||
<p>Open WebUI ist <a href="https://docs.openwebui.com/"><strong>ein Zuhause für KI</strong></a>: eine erweiterbare, benutzerfreundliche Plattform zum Selbsthosten, die vollständig offline betrieben werden kann. Verbinde lokale Modelle über Ollama oder nutze OpenAI-kompatible APIs für lokale und cloudbasierte Modelle.</p>
|
||||
|
||||
[English](README.md) |
|
||||
[简体中文](README.zh.md) |
|
||||
[繁體中文](README.zht.md) |
|
||||
[한국어](README.ko.md) |
|
||||
[Deutsch](README.de.md) |
|
||||
[Español](README.es.md) |
|
||||
[Français](README.fr.md) |
|
||||
[Italiano](README.it.md) |
|
||||
[Dansk](README.da.md) |
|
||||
[日本語](README.ja.md) |
|
||||
[Polski](README.pl.md) |
|
||||
[Русский](README.ru.md) |
|
||||
[Bosanski](README.bs.md) |
|
||||
[العربية](README.ar.md) |
|
||||
[Norsk](README.no.md) |
|
||||
[Português (Brasil)](README.br.md) |
|
||||
[ไทย](README.th.md) |
|
||||
[Türkçe](README.tr.md) |
|
||||
[Українська](README.uk.md) |
|
||||
[বাংলা](README.bn.md) |
|
||||
[Ελληνικά](README.gr.md) |
|
||||
[Tiếng Việt](README.vi.md)
|
||||
|
||||
[](https://docs.openwebui.com/)
|
||||
|
||||

|
||||

|
||||

|
||||

|
||||

|
||||

|
||||

|
||||
[](https://discord.gg/5rJgQTnV4s)
|
||||
[](https://github.com/sponsors/open-webui)
|
||||
|
||||
[Open WebUI entdecken →](https://docs.openwebui.com/)
|
||||
|
||||
### Installation
|
||||
|
||||
#### Python
|
||||
|
||||
Erfordert Python 3.12.
|
||||
|
||||
```bash
|
||||
pip install open-webui
|
||||
open-webui serve
|
||||
```
|
||||
|
||||
Öffne anschließend [http://localhost:8080](http://localhost:8080).
|
||||
|
||||
#### Docker
|
||||
|
||||
```bash
|
||||
docker run -d -p 3000:8080 --add-host=host.docker.internal:host-gateway -v open-webui:/app/backend/data --name open-webui --restart always ghcr.io/open-webui/open-webui:main
|
||||
```
|
||||
|
||||
Öffne anschließend [http://localhost:3000](http://localhost:3000).
|
||||
|
||||
| Image-Tag | Inhalt |
|
||||
| --- | --- |
|
||||
| `:main` | Standard-Image mit Abhängigkeiten für lokale KI |
|
||||
| `:slim` | Schlankes Image mit externen Diensten für Embeddings, Dokumentenextraktion und Sprache |
|
||||
| `:cuda` | Open WebUI mit CUDA-Beschleunigung |
|
||||
| `:ollama` | Open WebUI mit integriertem Ollama |
|
||||
| `:dev` | Neuester Entwicklungsbuild |
|
||||
|
||||
Füge diese Optionen bei Bedarf vor dem Image-Namen zu `docker run` hinzu:
|
||||
|
||||
| Option | Zweck |
|
||||
| --- | --- |
|
||||
| `-e OLLAMA_BASE_URL=http://your-ollama-server:11434` | Verbindung zu Ollama auf einem anderen Server |
|
||||
| `-e OPENAI_API_KEY=your_secret_key` | OpenAI-API-Schlüssel festlegen |
|
||||
| `-e HF_HUB_OFFLINE=1` | Downloads von Hugging-Face-Modellen für den Offlinebetrieb deaktivieren |
|
||||
| `--gpus all` | Nvidia-GPU-Zugriff für `:cuda` oder `:ollama` aktivieren; erfordert das Nvidia Container Toolkit |
|
||||
|
||||
Einrichtung und Konfigurationsoptionen findest du in der [Docker-Installationsanleitung](https://docs.openwebui.com/getting-started/quick-start/).
|
||||
|
||||
#### Desktop-App
|
||||
|
||||
[Native Desktop-App herunterladen](https://github.com/open-webui/desktop) für macOS, Windows und Linux.
|
||||
|
||||
[Dokumentation lesen →](https://docs.openwebui.com/getting-started/)
|
||||
|
||||
### Ökosystem
|
||||
|
||||
- [Open Terminal](https://github.com/open-webui/open-terminal) / [Terminals (Enterprise)](https://github.com/open-webui/terminals): Die Ausführungsebene, die Open WebUI zu einer vollständigen Agentenumgebung macht, mit Enterprise-Orchestrierung für Arbeitsbereiche pro Benutzer.
|
||||
- [Knowledge Base Sync (oikb)](https://github.com/open-webui/oikb): Ordner, Repositories, Buckets und Wikis durch inkrementelle Synchronisierung in Open WebUI Knowledge Bases spiegeln.
|
||||
- [Open WebUI Computer](https://github.com/open-webui/computer): Dein Computer in jedem Browser: Dateien, Editor, Terminal, Git und optionale KI-Agenten auf deinem eigenen Rechner.
|
||||
|
||||
Weitere Informationen findest du in der [Ökosystem-Dokumentation](https://docs.openwebui.com/ecosystem/).
|
||||
|
||||
### Fehlerbehebung und Updates
|
||||
|
||||
Bei Verbindungsproblemen hilft die [Anleitung zur Fehlerbehebung](https://docs.openwebui.com/troubleshooting/); zum Aktualisieren deiner Installation gibt es die [Update-Anleitung](https://docs.openwebui.com/getting-started/updating).
|
||||
|
||||
### Dokumentation
|
||||
|
||||
Informationen zu Konfiguration und Nutzung findest du in der [Dokumentation](https://docs.openwebui.com/), geplante Arbeiten in der [Roadmap](https://docs.openwebui.com/roadmap/).
|
||||
|
||||
Für Docker Compose, Kubernetes und weitere Installationsarten siehe die [Installationsdokumentation](https://docs.openwebui.com/getting-started/).
|
||||
|
||||
### Hilfe
|
||||
|
||||
[Erstelle ein Issue](https://github.com/open-webui/open-webui/issues) oder [starte eine Diskussion](https://github.com/open-webui/open-webui/discussions).
|
||||
|
||||
Du findest uns auf [Reddit](https://www.reddit.com/r/OpenWebUI/), [X](https://x.com/OpenWebUI) und [Discord](https://discord.gg/5rJgQTnV4s).
|
||||
|
||||
### Sicherheit
|
||||
|
||||
Melde Sicherheitslücken vertraulich über [GitHub Security Advisories](https://github.com/open-webui/open-webui/security). Sicherheitsmeldungen werden ausschließlich über GitHub angenommen.
|
||||
|
||||
### GitHub-Sterne im Zeitverlauf
|
||||
|
||||
<a href="https://star-history.com/#open-webui/open-webui&Date">
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=open-webui/open-webui&type=Date&theme=dark" />
|
||||
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=open-webui/open-webui&type=Date" />
|
||||
<img alt="Diagramm der GitHub-Sterne" src="https://api.star-history.com/svg?repos=open-webui/open-webui&type=Date" />
|
||||
</picture>
|
||||
</a>
|
||||
|
||||
#### Lizenz
|
||||
|
||||
Enthält Code unter der Open WebUI License, die den Erhalt des Open-WebUI-Brandings vorschreibt, sowie frühere Beiträge unter ihren ursprünglichen Lizenzen. Bedingungen und Lizenzhistorie stehen in [LICENSE](./LICENSE) und [LICENSE_HISTORY](./LICENSE_HISTORY).
|
||||
|
||||
[Enterprise](https://docs.openwebui.com/enterprise) · [Karriere](https://careers.openwebui.com/) · [Unterstützen](https://github.com/sponsors/open-webui)
|
||||
|
||||
Erstellt von [Timothy Jaeryang Baek](https://github.com/tjbck).
|
||||
132
README.es.md
Normal file
132
README.es.md
Normal file
|
|
@ -0,0 +1,132 @@
|
|||
<h2>Open WebUI</h2>
|
||||
|
||||
<p>Open WebUI es <a href="https://docs.openwebui.com/"><strong>un hogar para la IA</strong></a>: una plataforma autoalojada, extensible y fácil de usar, diseñada para funcionar completamente sin conexión. Conecta modelos locales mediante Ollama o usa API compatibles con OpenAI para modelos locales y en la nube.</p>
|
||||
|
||||
[English](README.md) |
|
||||
[简体中文](README.zh.md) |
|
||||
[繁體中文](README.zht.md) |
|
||||
[한국어](README.ko.md) |
|
||||
[Deutsch](README.de.md) |
|
||||
[Español](README.es.md) |
|
||||
[Français](README.fr.md) |
|
||||
[Italiano](README.it.md) |
|
||||
[Dansk](README.da.md) |
|
||||
[日本語](README.ja.md) |
|
||||
[Polski](README.pl.md) |
|
||||
[Русский](README.ru.md) |
|
||||
[Bosanski](README.bs.md) |
|
||||
[العربية](README.ar.md) |
|
||||
[Norsk](README.no.md) |
|
||||
[Português (Brasil)](README.br.md) |
|
||||
[ไทย](README.th.md) |
|
||||
[Türkçe](README.tr.md) |
|
||||
[Українська](README.uk.md) |
|
||||
[বাংলা](README.bn.md) |
|
||||
[Ελληνικά](README.gr.md) |
|
||||
[Tiếng Việt](README.vi.md)
|
||||
|
||||
[](https://docs.openwebui.com/)
|
||||
|
||||

|
||||

|
||||

|
||||

|
||||

|
||||

|
||||

|
||||
[](https://discord.gg/5rJgQTnV4s)
|
||||
[](https://github.com/sponsors/open-webui)
|
||||
|
||||
[Explora Open WebUI →](https://docs.openwebui.com/)
|
||||
|
||||
### Instalación
|
||||
|
||||
#### Python
|
||||
|
||||
Requiere Python 3.12.
|
||||
|
||||
```bash
|
||||
pip install open-webui
|
||||
open-webui serve
|
||||
```
|
||||
|
||||
Después, abre [http://localhost:8080](http://localhost:8080).
|
||||
|
||||
#### Docker
|
||||
|
||||
```bash
|
||||
docker run -d -p 3000:8080 --add-host=host.docker.internal:host-gateway -v open-webui:/app/backend/data --name open-webui --restart always ghcr.io/open-webui/open-webui:main
|
||||
```
|
||||
|
||||
Después, abre [http://localhost:3000](http://localhost:3000).
|
||||
|
||||
| Etiqueta de imagen | Contenido |
|
||||
| --- | --- |
|
||||
| `:main` | Imagen estándar con dependencias de IA local |
|
||||
| `:slim` | Imagen ligera que usa servicios externos para embeddings, extracción de documentos y voz |
|
||||
| `:cuda` | Open WebUI con aceleración CUDA |
|
||||
| `:ollama` | Open WebUI con Ollama incluido |
|
||||
| `:dev` | Última compilación de desarrollo |
|
||||
|
||||
Añade estas opciones a `docker run` antes del nombre de la imagen según lo necesites:
|
||||
|
||||
| Opción | Función |
|
||||
| --- | --- |
|
||||
| `-e OLLAMA_BASE_URL=http://your-ollama-server:11434` | Conectarse a Ollama en otro servidor |
|
||||
| `-e OPENAI_API_KEY=your_secret_key` | Configurar tu clave de API de OpenAI |
|
||||
| `-e HF_HUB_OFFLINE=1` | Desactivar las descargas de modelos de Hugging Face para el uso sin conexión |
|
||||
| `--gpus all` | Habilitar el acceso a GPU Nvidia para `:cuda` o `:ollama`; requiere Nvidia Container Toolkit |
|
||||
|
||||
Consulta la [guía de instalación con Docker](https://docs.openwebui.com/getting-started/quick-start/) para ver las instrucciones y opciones de configuración.
|
||||
|
||||
#### Aplicación de escritorio
|
||||
|
||||
[Descarga la aplicación de escritorio nativa](https://github.com/open-webui/desktop) para macOS, Windows y Linux.
|
||||
|
||||
[Lee la documentación →](https://docs.openwebui.com/getting-started/)
|
||||
|
||||
### Ecosistema
|
||||
|
||||
- [Open Terminal](https://github.com/open-webui/open-terminal) / [Terminals (Enterprise)](https://github.com/open-webui/terminals): La capa de ejecución que convierte Open WebUI en un entorno completo para agentes, con orquestación empresarial de espacios de trabajo por usuario.
|
||||
- [Knowledge Base Sync (oikb)](https://github.com/open-webui/oikb): Replica carpetas, repositorios, buckets y wikis en las bases de conocimiento de Open WebUI mediante sincronización incremental.
|
||||
- [Open WebUI Computer](https://github.com/open-webui/computer): Tu ordenador en cualquier navegador: archivos, editor, terminal, Git y agentes de IA opcionales, ejecutándose en tu propia máquina.
|
||||
|
||||
Consulta la [documentación del ecosistema](https://docs.openwebui.com/ecosystem/) para más información.
|
||||
|
||||
### Resolución de problemas y actualizaciones
|
||||
|
||||
Consulta la [guía de resolución de problemas](https://docs.openwebui.com/troubleshooting/) para los problemas de conexión y la [guía de actualización](https://docs.openwebui.com/getting-started/updating) para actualizar tu instalación.
|
||||
|
||||
### Documentación
|
||||
|
||||
Consulta la [documentación](https://docs.openwebui.com/) para la configuración y el uso, y la [hoja de ruta](https://docs.openwebui.com/roadmap/) para el trabajo previsto.
|
||||
|
||||
Para Docker Compose, Kubernetes y otras instalaciones, consulta la [documentación de instalación](https://docs.openwebui.com/getting-started/).
|
||||
|
||||
### Ayuda
|
||||
|
||||
[Abre una incidencia](https://github.com/open-webui/open-webui/issues) o [inicia una discusión](https://github.com/open-webui/open-webui/discussions).
|
||||
|
||||
Encuéntranos en [Reddit](https://www.reddit.com/r/OpenWebUI/), [X](https://x.com/OpenWebUI) y [Discord](https://discord.gg/5rJgQTnV4s).
|
||||
|
||||
### Seguridad
|
||||
|
||||
Comunica vulnerabilidades de forma privada mediante [GitHub Security Advisories](https://github.com/open-webui/open-webui/security). Solo se aceptan informes de seguridad a través de GitHub.
|
||||
|
||||
### Historial de estrellas
|
||||
|
||||
<a href="https://star-history.com/#open-webui/open-webui&Date">
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=open-webui/open-webui&type=Date&theme=dark" />
|
||||
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=open-webui/open-webui&type=Date" />
|
||||
<img alt="Gráfico del historial de estrellas" src="https://api.star-history.com/svg?repos=open-webui/open-webui&type=Date" />
|
||||
</picture>
|
||||
</a>
|
||||
|
||||
#### Licencia
|
||||
|
||||
Incluye código bajo la Open WebUI License, que exige conservar la marca Open WebUI, y contribuciones anteriores bajo sus licencias originales. Consulta [LICENSE](./LICENSE) y [LICENSE_HISTORY](./LICENSE_HISTORY) para conocer las condiciones y el historial.
|
||||
|
||||
[Empresas](https://docs.openwebui.com/enterprise) · [Empleo](https://careers.openwebui.com/) · [Patrocinar](https://github.com/sponsors/open-webui)
|
||||
|
||||
Creado por [Timothy Jaeryang Baek](https://github.com/tjbck).
|
||||
132
README.fr.md
Normal file
132
README.fr.md
Normal file
|
|
@ -0,0 +1,132 @@
|
|||
<h2>Open WebUI</h2>
|
||||
|
||||
<p>Open WebUI est <a href="https://docs.openwebui.com/"><strong>un foyer pour l’IA</strong></a> : une plateforme auto-hébergée, extensible et facile à utiliser, conçue pour fonctionner entièrement hors ligne. Connectez des modèles locaux via Ollama ou utilisez des API compatibles avec OpenAI pour des modèles locaux et cloud.</p>
|
||||
|
||||
[English](README.md) |
|
||||
[简体中文](README.zh.md) |
|
||||
[繁體中文](README.zht.md) |
|
||||
[한국어](README.ko.md) |
|
||||
[Deutsch](README.de.md) |
|
||||
[Español](README.es.md) |
|
||||
[Français](README.fr.md) |
|
||||
[Italiano](README.it.md) |
|
||||
[Dansk](README.da.md) |
|
||||
[日本語](README.ja.md) |
|
||||
[Polski](README.pl.md) |
|
||||
[Русский](README.ru.md) |
|
||||
[Bosanski](README.bs.md) |
|
||||
[العربية](README.ar.md) |
|
||||
[Norsk](README.no.md) |
|
||||
[Português (Brasil)](README.br.md) |
|
||||
[ไทย](README.th.md) |
|
||||
[Türkçe](README.tr.md) |
|
||||
[Українська](README.uk.md) |
|
||||
[বাংলা](README.bn.md) |
|
||||
[Ελληνικά](README.gr.md) |
|
||||
[Tiếng Việt](README.vi.md)
|
||||
|
||||
[](https://docs.openwebui.com/)
|
||||
|
||||

|
||||

|
||||

|
||||

|
||||

|
||||

|
||||

|
||||
[](https://discord.gg/5rJgQTnV4s)
|
||||
[](https://github.com/sponsors/open-webui)
|
||||
|
||||
[Découvrir Open WebUI →](https://docs.openwebui.com/)
|
||||
|
||||
### Installation
|
||||
|
||||
#### Python
|
||||
|
||||
Nécessite Python 3.12.
|
||||
|
||||
```bash
|
||||
pip install open-webui
|
||||
open-webui serve
|
||||
```
|
||||
|
||||
Ouvrez ensuite [http://localhost:8080](http://localhost:8080).
|
||||
|
||||
#### Docker
|
||||
|
||||
```bash
|
||||
docker run -d -p 3000:8080 --add-host=host.docker.internal:host-gateway -v open-webui:/app/backend/data --name open-webui --restart always ghcr.io/open-webui/open-webui:main
|
||||
```
|
||||
|
||||
Ouvrez ensuite [http://localhost:3000](http://localhost:3000).
|
||||
|
||||
| Tag de l’image | Contenu |
|
||||
| --- | --- |
|
||||
| `:main` | Image standard avec les dépendances d’IA locales |
|
||||
| `:slim` | Image légère utilisant des services externes pour les embeddings, l’extraction de documents et la voix |
|
||||
| `:cuda` | Open WebUI avec accélération CUDA |
|
||||
| `:ollama` | Open WebUI avec Ollama intégré |
|
||||
| `:dev` | Dernière version de développement |
|
||||
|
||||
Ajoutez ces options à `docker run` avant le nom de l’image, selon vos besoins :
|
||||
|
||||
| Option | Fonction |
|
||||
| --- | --- |
|
||||
| `-e OLLAMA_BASE_URL=http://your-ollama-server:11434` | Se connecter à Ollama sur un autre serveur |
|
||||
| `-e OPENAI_API_KEY=your_secret_key` | Définir votre clé API OpenAI |
|
||||
| `-e HF_HUB_OFFLINE=1` | Désactiver le téléchargement des modèles Hugging Face pour une utilisation hors ligne |
|
||||
| `--gpus all` | Activer l’accès aux GPU Nvidia pour `:cuda` ou `:ollama` ; nécessite Nvidia Container Toolkit |
|
||||
|
||||
Consultez le [guide d’installation Docker](https://docs.openwebui.com/getting-started/quick-start/) pour les instructions et les options de configuration.
|
||||
|
||||
#### Application de bureau
|
||||
|
||||
[Téléchargez l’application de bureau native](https://github.com/open-webui/desktop) pour macOS, Windows et Linux.
|
||||
|
||||
[Lire la documentation →](https://docs.openwebui.com/getting-started/)
|
||||
|
||||
### Écosystème
|
||||
|
||||
- [Open Terminal](https://github.com/open-webui/open-terminal) / [Terminals (Enterprise)](https://github.com/open-webui/terminals): La couche d’exécution qui fait d’Open WebUI un environnement complet pour les agents, avec une orchestration d’entreprise des espaces de travail individuels.
|
||||
- [Knowledge Base Sync (oikb)](https://github.com/open-webui/oikb): Répliquez dossiers, dépôts, buckets et wikis dans les bases de connaissances Open WebUI grâce à la synchronisation incrémentale.
|
||||
- [Open WebUI Computer](https://github.com/open-webui/computer): Votre ordinateur dans n’importe quel navigateur : fichiers, éditeur, terminal, Git et agents IA facultatifs, exécutés sur votre propre machine.
|
||||
|
||||
Consultez la [documentation de l’écosystème](https://docs.openwebui.com/ecosystem/) pour en savoir plus.
|
||||
|
||||
### Dépannage et mises à jour
|
||||
|
||||
Consultez le [guide de dépannage](https://docs.openwebui.com/troubleshooting/) pour les problèmes de connexion et le [guide de mise à jour](https://docs.openwebui.com/getting-started/updating) pour actualiser votre installation.
|
||||
|
||||
### Documentation
|
||||
|
||||
Consultez la [documentation](https://docs.openwebui.com/) pour la configuration et l’utilisation, et la [feuille de route](https://docs.openwebui.com/roadmap/) pour les travaux prévus.
|
||||
|
||||
Pour Docker Compose, Kubernetes et les autres modes d’installation, consultez la [documentation d’installation](https://docs.openwebui.com/getting-started/).
|
||||
|
||||
### Assistance
|
||||
|
||||
[Ouvrez une issue](https://github.com/open-webui/open-webui/issues) ou [lancez une discussion](https://github.com/open-webui/open-webui/discussions).
|
||||
|
||||
Retrouvez-nous sur [Reddit](https://www.reddit.com/r/OpenWebUI/), [X](https://x.com/OpenWebUI) et [Discord](https://discord.gg/5rJgQTnV4s).
|
||||
|
||||
### Sécurité
|
||||
|
||||
Signalez les vulnérabilités de manière confidentielle via [GitHub Security Advisories](https://github.com/open-webui/open-webui/security). Les signalements de sécurité sont acceptés uniquement sur GitHub.
|
||||
|
||||
### Historique des étoiles
|
||||
|
||||
<a href="https://star-history.com/#open-webui/open-webui&Date">
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=open-webui/open-webui&type=Date&theme=dark" />
|
||||
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=open-webui/open-webui&type=Date" />
|
||||
<img alt="Graphique de l’historique des étoiles" src="https://api.star-history.com/svg?repos=open-webui/open-webui&type=Date" />
|
||||
</picture>
|
||||
</a>
|
||||
|
||||
#### Licence
|
||||
|
||||
Inclut du code sous Open WebUI License, qui impose de conserver l’identité de marque Open WebUI, ainsi que des contributions antérieures sous leurs licences d’origine. Consultez [LICENSE](./LICENSE) et [LICENSE_HISTORY](./LICENSE_HISTORY) pour les conditions et l’historique.
|
||||
|
||||
[Entreprise](https://docs.openwebui.com/enterprise) · [Carrières](https://careers.openwebui.com/) · [Soutenir](https://github.com/sponsors/open-webui)
|
||||
|
||||
Créé par [Timothy Jaeryang Baek](https://github.com/tjbck).
|
||||
132
README.gr.md
Normal file
132
README.gr.md
Normal file
|
|
@ -0,0 +1,132 @@
|
|||
<h2>Open WebUI</h2>
|
||||
|
||||
<p>Το Open WebUI είναι <a href="https://docs.openwebui.com/"><strong>ένα σπίτι για την τεχνητή νοημοσύνη</strong></a>: μια επεκτάσιμη, εύχρηστη πλατφόρμα που φιλοξενείτε εσείς, σχεδιασμένη να λειτουργεί πλήρως εκτός σύνδεσης. Συνδέστε τοπικά μοντέλα μέσω του Ollama ή χρησιμοποιήστε API συμβατά με το OpenAI για τοπικά μοντέλα και μοντέλα στο cloud.</p>
|
||||
|
||||
[English](README.md) |
|
||||
[简体中文](README.zh.md) |
|
||||
[繁體中文](README.zht.md) |
|
||||
[한국어](README.ko.md) |
|
||||
[Deutsch](README.de.md) |
|
||||
[Español](README.es.md) |
|
||||
[Français](README.fr.md) |
|
||||
[Italiano](README.it.md) |
|
||||
[Dansk](README.da.md) |
|
||||
[日本語](README.ja.md) |
|
||||
[Polski](README.pl.md) |
|
||||
[Русский](README.ru.md) |
|
||||
[Bosanski](README.bs.md) |
|
||||
[العربية](README.ar.md) |
|
||||
[Norsk](README.no.md) |
|
||||
[Português (Brasil)](README.br.md) |
|
||||
[ไทย](README.th.md) |
|
||||
[Türkçe](README.tr.md) |
|
||||
[Українська](README.uk.md) |
|
||||
[বাংলা](README.bn.md) |
|
||||
[Ελληνικά](README.gr.md) |
|
||||
[Tiếng Việt](README.vi.md)
|
||||
|
||||
[](https://docs.openwebui.com/)
|
||||
|
||||

|
||||

|
||||

|
||||

|
||||

|
||||

|
||||

|
||||
[](https://discord.gg/5rJgQTnV4s)
|
||||
[](https://github.com/sponsors/open-webui)
|
||||
|
||||
[Εξερευνήστε το Open WebUI →](https://docs.openwebui.com/)
|
||||
|
||||
### Εγκατάσταση
|
||||
|
||||
#### Python
|
||||
|
||||
Απαιτείται Python 3.12.
|
||||
|
||||
```bash
|
||||
pip install open-webui
|
||||
open-webui serve
|
||||
```
|
||||
|
||||
Στη συνέχεια, ανοίξτε το [http://localhost:8080](http://localhost:8080).
|
||||
|
||||
#### Docker
|
||||
|
||||
```bash
|
||||
docker run -d -p 3000:8080 --add-host=host.docker.internal:host-gateway -v open-webui:/app/backend/data --name open-webui --restart always ghcr.io/open-webui/open-webui:main
|
||||
```
|
||||
|
||||
Στη συνέχεια, ανοίξτε το [http://localhost:3000](http://localhost:3000).
|
||||
|
||||
| Ετικέτα εικόνας | Περιεχόμενο |
|
||||
| --- | --- |
|
||||
| `:main` | Τυπική εικόνα με εξαρτήσεις για τοπική AI |
|
||||
| `:slim` | Ελαφριά εικόνα που χρησιμοποιεί εξωτερικές υπηρεσίες για embeddings, εξαγωγή περιεχομένου εγγράφων και φωνή |
|
||||
| `:cuda` | Open WebUI με επιτάχυνση CUDA |
|
||||
| `:ollama` | Open WebUI με ενσωματωμένο Ollama |
|
||||
| `:dev` | Νεότερη έκδοση ανάπτυξης |
|
||||
|
||||
Προσθέστε αυτές τις επιλογές στο `docker run` πριν από το όνομα της εικόνας, ανάλογα με τις ανάγκες σας:
|
||||
|
||||
| Επιλογή | Σκοπός |
|
||||
| --- | --- |
|
||||
| `-e OLLAMA_BASE_URL=http://your-ollama-server:11434` | Σύνδεση με Ollama σε άλλον διακομιστή |
|
||||
| `-e OPENAI_API_KEY=your_secret_key` | Ορισμός του κλειδιού API OpenAI |
|
||||
| `-e HF_HUB_OFFLINE=1` | Απενεργοποίηση λήψεων μοντέλων Hugging Face για χρήση εκτός σύνδεσης |
|
||||
| `--gpus all` | Ενεργοποίηση πρόσβασης σε GPU Nvidia για `:cuda` ή `:ollama`· απαιτείται Nvidia Container Toolkit |
|
||||
|
||||
Δείτε τον [οδηγό εγκατάστασης με Docker](https://docs.openwebui.com/getting-started/quick-start/) για οδηγίες και επιλογές διαμόρφωσης.
|
||||
|
||||
#### Εφαρμογή υπολογιστή
|
||||
|
||||
[Κατεβάστε την εγγενή εφαρμογή υπολογιστή](https://github.com/open-webui/desktop) για macOS, Windows και Linux.
|
||||
|
||||
[Διαβάστε την τεκμηρίωση →](https://docs.openwebui.com/getting-started/)
|
||||
|
||||
### Οικοσύστημα
|
||||
|
||||
- [Open Terminal](https://github.com/open-webui/open-terminal) / [Terminals (Enterprise)](https://github.com/open-webui/terminals): Το επίπεδο εκτέλεσης που μετατρέπει το Open WebUI σε πλήρες περιβάλλον πρακτόρων, με εταιρική ενορχήστρωση χώρων εργασίας ανά χρήστη.
|
||||
- [Knowledge Base Sync (oikb)](https://github.com/open-webui/oikb): Αντικατοπτρίστε φακέλους, αποθετήρια, buckets και wiki στις βάσεις γνώσεων του Open WebUI με αυξητικό συγχρονισμό.
|
||||
- [Open WebUI Computer](https://github.com/open-webui/computer): Ο υπολογιστής σας σε οποιονδήποτε περιηγητή: αρχεία, επεξεργαστής, τερματικό, Git και προαιρετικοί πράκτορες AI, που εκτελούνται στο πραγματικό σας μηχάνημα.
|
||||
|
||||
Δείτε την [τεκμηρίωση του οικοσυστήματος](https://docs.openwebui.com/ecosystem/) για λεπτομέρειες.
|
||||
|
||||
### Αντιμετώπιση προβλημάτων και ενημερώσεις
|
||||
|
||||
Δείτε τον [οδηγό αντιμετώπισης προβλημάτων](https://docs.openwebui.com/troubleshooting/) για προβλήματα σύνδεσης και τον [οδηγό ενημέρωσης](https://docs.openwebui.com/getting-started/updating) για να ενημερώσετε την εγκατάστασή σας.
|
||||
|
||||
### Τεκμηρίωση
|
||||
|
||||
Δείτε την [τεκμηρίωση](https://docs.openwebui.com/) για τη διαμόρφωση και τη χρήση, και τον [οδικό χάρτη](https://docs.openwebui.com/roadmap/) για τις προγραμματισμένες εργασίες.
|
||||
|
||||
Για Docker Compose, Kubernetes και άλλες εγκαταστάσεις, δείτε την [τεκμηρίωση εγκατάστασης](https://docs.openwebui.com/getting-started/).
|
||||
|
||||
### Υποστήριξη
|
||||
|
||||
[Ανοίξτε ένα issue](https://github.com/open-webui/open-webui/issues) ή [ξεκινήστε μια συζήτηση](https://github.com/open-webui/open-webui/discussions).
|
||||
|
||||
Βρείτε μας στο [Reddit](https://www.reddit.com/r/OpenWebUI/), στο [X](https://x.com/OpenWebUI) και στο [Discord](https://discord.gg/5rJgQTnV4s).
|
||||
|
||||
### Ασφάλεια
|
||||
|
||||
Αναφέρετε ευπάθειες ιδιωτικά μέσω των [GitHub Security Advisories](https://github.com/open-webui/open-webui/security). Οι αναφορές ασφάλειας γίνονται δεκτές μόνο μέσω του GitHub.
|
||||
|
||||
### Ιστορικό αστεριών
|
||||
|
||||
<a href="https://star-history.com/#open-webui/open-webui&Date">
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=open-webui/open-webui&type=Date&theme=dark" />
|
||||
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=open-webui/open-webui&type=Date" />
|
||||
<img alt="Γράφημα ιστορικού αστεριών" src="https://api.star-history.com/svg?repos=open-webui/open-webui&type=Date" />
|
||||
</picture>
|
||||
</a>
|
||||
|
||||
#### Άδεια χρήσης
|
||||
|
||||
Περιλαμβάνει κώδικα υπό την Open WebUI License, η οποία απαιτεί τη διατήρηση της ταυτότητας του Open WebUI, καθώς και παλαιότερες συνεισφορές υπό τις αρχικές τους άδειες. Δείτε τα [LICENSE](./LICENSE) και [LICENSE_HISTORY](./LICENSE_HISTORY) για τους όρους και το ιστορικό.
|
||||
|
||||
[Επιχειρήσεις](https://docs.openwebui.com/enterprise) · [Καριέρα](https://careers.openwebui.com/) · [Χορηγία](https://github.com/sponsors/open-webui)
|
||||
|
||||
Δημιουργήθηκε από τον [Timothy Jaeryang Baek](https://github.com/tjbck).
|
||||
132
README.it.md
Normal file
132
README.it.md
Normal file
|
|
@ -0,0 +1,132 @@
|
|||
<h2>Open WebUI</h2>
|
||||
|
||||
<p>Open WebUI è <a href="https://docs.openwebui.com/"><strong>una casa per l’IA</strong></a>: una piattaforma self-hosted, estensibile e facile da usare, progettata per funzionare completamente offline. Collega modelli locali tramite Ollama oppure usa API compatibili con OpenAI per modelli locali e cloud.</p>
|
||||
|
||||
[English](README.md) |
|
||||
[简体中文](README.zh.md) |
|
||||
[繁體中文](README.zht.md) |
|
||||
[한국어](README.ko.md) |
|
||||
[Deutsch](README.de.md) |
|
||||
[Español](README.es.md) |
|
||||
[Français](README.fr.md) |
|
||||
[Italiano](README.it.md) |
|
||||
[Dansk](README.da.md) |
|
||||
[日本語](README.ja.md) |
|
||||
[Polski](README.pl.md) |
|
||||
[Русский](README.ru.md) |
|
||||
[Bosanski](README.bs.md) |
|
||||
[العربية](README.ar.md) |
|
||||
[Norsk](README.no.md) |
|
||||
[Português (Brasil)](README.br.md) |
|
||||
[ไทย](README.th.md) |
|
||||
[Türkçe](README.tr.md) |
|
||||
[Українська](README.uk.md) |
|
||||
[বাংলা](README.bn.md) |
|
||||
[Ελληνικά](README.gr.md) |
|
||||
[Tiếng Việt](README.vi.md)
|
||||
|
||||
[](https://docs.openwebui.com/)
|
||||
|
||||

|
||||

|
||||

|
||||

|
||||

|
||||

|
||||

|
||||
[](https://discord.gg/5rJgQTnV4s)
|
||||
[](https://github.com/sponsors/open-webui)
|
||||
|
||||
[Esplora Open WebUI →](https://docs.openwebui.com/)
|
||||
|
||||
### Installazione
|
||||
|
||||
#### Python
|
||||
|
||||
Richiede Python 3.12.
|
||||
|
||||
```bash
|
||||
pip install open-webui
|
||||
open-webui serve
|
||||
```
|
||||
|
||||
Poi apri [http://localhost:8080](http://localhost:8080).
|
||||
|
||||
#### Docker
|
||||
|
||||
```bash
|
||||
docker run -d -p 3000:8080 --add-host=host.docker.internal:host-gateway -v open-webui:/app/backend/data --name open-webui --restart always ghcr.io/open-webui/open-webui:main
|
||||
```
|
||||
|
||||
Poi apri [http://localhost:3000](http://localhost:3000).
|
||||
|
||||
| Tag dell’immagine | Contenuto |
|
||||
| --- | --- |
|
||||
| `:main` | Immagine standard con dipendenze per l’IA locale |
|
||||
| `:slim` | Immagine leggera che usa servizi esterni per embedding, estrazione dei documenti e voce |
|
||||
| `:cuda` | Open WebUI con accelerazione CUDA |
|
||||
| `:ollama` | Open WebUI con Ollama incluso |
|
||||
| `:dev` | Ultima build di sviluppo |
|
||||
|
||||
Aggiungi queste opzioni a `docker run` prima del nome dell’immagine, secondo necessità:
|
||||
|
||||
| Opzione | Scopo |
|
||||
| --- | --- |
|
||||
| `-e OLLAMA_BASE_URL=http://your-ollama-server:11434` | Collegarsi a Ollama su un altro server |
|
||||
| `-e OPENAI_API_KEY=your_secret_key` | Impostare la chiave API OpenAI |
|
||||
| `-e HF_HUB_OFFLINE=1` | Disabilitare i download dei modelli Hugging Face per l’uso offline |
|
||||
| `--gpus all` | Abilitare l’accesso alla GPU Nvidia per `:cuda` o `:ollama`; richiede Nvidia Container Toolkit |
|
||||
|
||||
Consulta la [guida all’installazione con Docker](https://docs.openwebui.com/getting-started/quick-start/) per le istruzioni e le opzioni di configurazione.
|
||||
|
||||
#### App desktop
|
||||
|
||||
[Scarica l’app desktop nativa](https://github.com/open-webui/desktop) per macOS, Windows e Linux.
|
||||
|
||||
[Leggi la documentazione →](https://docs.openwebui.com/getting-started/)
|
||||
|
||||
### Ecosistema
|
||||
|
||||
- [Open Terminal](https://github.com/open-webui/open-terminal) / [Terminals (Enterprise)](https://github.com/open-webui/terminals): Il livello di esecuzione che rende Open WebUI un ambiente completo per gli agenti, con orchestrazione enterprise degli spazi di lavoro per utente.
|
||||
- [Knowledge Base Sync (oikb)](https://github.com/open-webui/oikb): Replica cartelle, repository, bucket e wiki nelle basi di conoscenza di Open WebUI tramite sincronizzazione incrementale.
|
||||
- [Open WebUI Computer](https://github.com/open-webui/computer): Il tuo computer in qualsiasi browser: file, editor, terminale, Git e agenti IA facoltativi, in esecuzione sulla tua macchina.
|
||||
|
||||
Consulta la [documentazione dell’ecosistema](https://docs.openwebui.com/ecosystem/) per i dettagli.
|
||||
|
||||
### Risoluzione dei problemi e aggiornamenti
|
||||
|
||||
Consulta la [guida alla risoluzione dei problemi](https://docs.openwebui.com/troubleshooting/) per i problemi di connessione e la [guida agli aggiornamenti](https://docs.openwebui.com/getting-started/updating) per aggiornare l’installazione.
|
||||
|
||||
### Documentazione
|
||||
|
||||
Consulta la [documentazione](https://docs.openwebui.com/) per configurazione e utilizzo, e la [roadmap](https://docs.openwebui.com/roadmap/) per il lavoro previsto.
|
||||
|
||||
Per Docker Compose, Kubernetes e altre installazioni, consulta la [documentazione di installazione](https://docs.openwebui.com/getting-started/).
|
||||
|
||||
### Supporto
|
||||
|
||||
[Apri una segnalazione](https://github.com/open-webui/open-webui/issues) oppure [avvia una discussione](https://github.com/open-webui/open-webui/discussions).
|
||||
|
||||
Ci trovi su [Reddit](https://www.reddit.com/r/OpenWebUI/), [X](https://x.com/OpenWebUI) e [Discord](https://discord.gg/5rJgQTnV4s).
|
||||
|
||||
### Sicurezza
|
||||
|
||||
Segnala le vulnerabilità in privato tramite [GitHub Security Advisories](https://github.com/open-webui/open-webui/security). Le segnalazioni di sicurezza sono accettate solo tramite GitHub.
|
||||
|
||||
### Cronologia delle stelle
|
||||
|
||||
<a href="https://star-history.com/#open-webui/open-webui&Date">
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=open-webui/open-webui&type=Date&theme=dark" />
|
||||
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=open-webui/open-webui&type=Date" />
|
||||
<img alt="Grafico della cronologia delle stelle" src="https://api.star-history.com/svg?repos=open-webui/open-webui&type=Date" />
|
||||
</picture>
|
||||
</a>
|
||||
|
||||
#### Licenza
|
||||
|
||||
Include codice soggetto alla Open WebUI License, che richiede di mantenere il marchio Open WebUI, e contributi precedenti soggetti alle rispettive licenze originali. Consulta [LICENSE](./LICENSE) e [LICENSE_HISTORY](./LICENSE_HISTORY) per condizioni e cronologia.
|
||||
|
||||
[Enterprise](https://docs.openwebui.com/enterprise) · [Lavora con noi](https://careers.openwebui.com/) · [Sostieni](https://github.com/sponsors/open-webui)
|
||||
|
||||
Creato da [Timothy Jaeryang Baek](https://github.com/tjbck).
|
||||
132
README.ja.md
Normal file
132
README.ja.md
Normal file
|
|
@ -0,0 +1,132 @@
|
|||
<h2>Open WebUI</h2>
|
||||
|
||||
<p>Open WebUI は <a href="https://docs.openwebui.com/"><strong>AI のためのホーム</strong></a>です。拡張可能で使いやすく、完全オフラインでの動作に対応したセルフホスト型プラットフォームです。Ollama でローカルモデルに接続するほか、OpenAI 互換 API を通じてローカルやクラウドのモデルを利用できます。</p>
|
||||
|
||||
[English](README.md) |
|
||||
[简体中文](README.zh.md) |
|
||||
[繁體中文](README.zht.md) |
|
||||
[한국어](README.ko.md) |
|
||||
[Deutsch](README.de.md) |
|
||||
[Español](README.es.md) |
|
||||
[Français](README.fr.md) |
|
||||
[Italiano](README.it.md) |
|
||||
[Dansk](README.da.md) |
|
||||
[日本語](README.ja.md) |
|
||||
[Polski](README.pl.md) |
|
||||
[Русский](README.ru.md) |
|
||||
[Bosanski](README.bs.md) |
|
||||
[العربية](README.ar.md) |
|
||||
[Norsk](README.no.md) |
|
||||
[Português (Brasil)](README.br.md) |
|
||||
[ไทย](README.th.md) |
|
||||
[Türkçe](README.tr.md) |
|
||||
[Українська](README.uk.md) |
|
||||
[বাংলা](README.bn.md) |
|
||||
[Ελληνικά](README.gr.md) |
|
||||
[Tiếng Việt](README.vi.md)
|
||||
|
||||
[](https://docs.openwebui.com/)
|
||||
|
||||

|
||||

|
||||

|
||||

|
||||

|
||||

|
||||

|
||||
[](https://discord.gg/5rJgQTnV4s)
|
||||
[](https://github.com/sponsors/open-webui)
|
||||
|
||||
[Open WebUI をもっと知る →](https://docs.openwebui.com/)
|
||||
|
||||
### インストール
|
||||
|
||||
#### Python
|
||||
|
||||
Python 3.12 が必要です。
|
||||
|
||||
```bash
|
||||
pip install open-webui
|
||||
open-webui serve
|
||||
```
|
||||
|
||||
その後、[http://localhost:8080](http://localhost:8080) を開きます。
|
||||
|
||||
#### Docker
|
||||
|
||||
```bash
|
||||
docker run -d -p 3000:8080 --add-host=host.docker.internal:host-gateway -v open-webui:/app/backend/data --name open-webui --restart always ghcr.io/open-webui/open-webui:main
|
||||
```
|
||||
|
||||
その後、[http://localhost:3000](http://localhost:3000) を開きます。
|
||||
|
||||
| イメージタグ | 内容 |
|
||||
| --- | --- |
|
||||
| `:main` | ローカル AI 用の依存パッケージを含む標準イメージ |
|
||||
| `:slim` | 埋め込み、ドキュメント抽出、音声処理に外部サービスを使う軽量イメージ |
|
||||
| `:cuda` | CUDA アクセラレーション対応の Open WebUI |
|
||||
| `:ollama` | Ollama を同梱した Open WebUI |
|
||||
| `:dev` | 最新の開発ビルド |
|
||||
|
||||
必要に応じて、`docker run` のイメージ名の前に以下のオプションを追加してください。
|
||||
|
||||
| オプション | 用途 |
|
||||
| --- | --- |
|
||||
| `-e OLLAMA_BASE_URL=http://your-ollama-server:11434` | 別のサーバー上の Ollama に接続 |
|
||||
| `-e OPENAI_API_KEY=your_secret_key` | OpenAI API キーを設定 |
|
||||
| `-e HF_HUB_OFFLINE=1` | オフライン利用のため Hugging Face のモデルダウンロードを無効化 |
|
||||
| `--gpus all` | `:cuda` または `:ollama` で Nvidia GPU を利用。Nvidia Container Toolkit が必要 |
|
||||
|
||||
セットアップ手順と設定項目は [Docker インストールガイド](https://docs.openwebui.com/getting-started/quick-start/)をご覧ください。
|
||||
|
||||
#### デスクトップアプリ
|
||||
|
||||
macOS、Windows、Linux 向けの[ネイティブデスクトップアプリをダウンロード](https://github.com/open-webui/desktop)。
|
||||
|
||||
[ドキュメントを読む →](https://docs.openwebui.com/getting-started/)
|
||||
|
||||
### エコシステム
|
||||
|
||||
- [Open Terminal](https://github.com/open-webui/open-terminal) / [Terminals (Enterprise)](https://github.com/open-webui/terminals): Open WebUI を完全なエージェント実行基盤にするアクション層。ユーザーごとのワークスペースを管理するエンタープライズ向けオーケストレーションにも対応。
|
||||
- [Knowledge Base Sync (oikb)](https://github.com/open-webui/oikb): フォルダー、リポジトリ、バケット、Wiki を差分同期し、Open WebUI のナレッジベースに反映。
|
||||
- [Open WebUI Computer](https://github.com/open-webui/computer): 自分のコンピューターをどのブラウザーからでも。ファイル、エディター、ターミナル、Git、任意の AI エージェントが実際のマシン上で動作。
|
||||
|
||||
詳しくは[エコシステムのドキュメント](https://docs.openwebui.com/ecosystem/)をご覧ください。
|
||||
|
||||
### トラブルシューティングと更新
|
||||
|
||||
接続の問題は[トラブルシューティングガイド](https://docs.openwebui.com/troubleshooting/)、インストールの更新は[更新ガイド](https://docs.openwebui.com/getting-started/updating)をご覧ください。
|
||||
|
||||
### ドキュメント
|
||||
|
||||
設定と使い方は[ドキュメント](https://docs.openwebui.com/)、今後の予定は[ロードマップ](https://docs.openwebui.com/roadmap/)をご覧ください。
|
||||
|
||||
Docker Compose、Kubernetes、その他の構成については[インストールドキュメント](https://docs.openwebui.com/getting-started/)をご覧ください。
|
||||
|
||||
### サポート
|
||||
|
||||
[Issue を作成](https://github.com/open-webui/open-webui/issues)するか、[ディスカッションを開始](https://github.com/open-webui/open-webui/discussions)してください。
|
||||
|
||||
[Reddit](https://www.reddit.com/r/OpenWebUI/)、[X](https://x.com/OpenWebUI)、[Discord](https://discord.gg/5rJgQTnV4s)でも発信しています。
|
||||
|
||||
### セキュリティ
|
||||
|
||||
脆弱性は [GitHub Security Advisories](https://github.com/open-webui/open-webui/security) を通じて非公開で報告してください。セキュリティ報告は GitHub 経由でのみ受け付けています。
|
||||
|
||||
### スター数の推移
|
||||
|
||||
<a href="https://star-history.com/#open-webui/open-webui&Date">
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=open-webui/open-webui&type=Date&theme=dark" />
|
||||
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=open-webui/open-webui&type=Date" />
|
||||
<img alt="スター数の推移グラフ" src="https://api.star-history.com/svg?repos=open-webui/open-webui&type=Date" />
|
||||
</picture>
|
||||
</a>
|
||||
|
||||
#### ライセンス
|
||||
|
||||
Open WebUI のブランド表示の保持を求める Open WebUI License に基づくコードと、それぞれ元のライセンスが適用される過去の貢献が含まれています。条件と履歴は [LICENSE](./LICENSE) と [LICENSE_HISTORY](./LICENSE_HISTORY) をご覧ください。
|
||||
|
||||
[エンタープライズ](https://docs.openwebui.com/enterprise) · [採用情報](https://careers.openwebui.com/) · [スポンサー](https://github.com/sponsors/open-webui)
|
||||
|
||||
作成者:[Timothy Jaeryang Baek](https://github.com/tjbck)。
|
||||
132
README.ko.md
Normal file
132
README.ko.md
Normal file
|
|
@ -0,0 +1,132 @@
|
|||
<h2>Open WebUI</h2>
|
||||
|
||||
<p>Open WebUI는 <a href="https://docs.openwebui.com/"><strong>AI를 위한 집</strong></a>입니다. 확장하기 쉽고 사용하기 편리하며, 완전한 오프라인 실행을 지원하는 셀프 호스팅 플랫폼입니다. Ollama로 로컬 모델에 연결하거나 OpenAI 호환 API를 통해 로컬 및 클라우드 모델을 사용하세요.</p>
|
||||
|
||||
[English](README.md) |
|
||||
[简体中文](README.zh.md) |
|
||||
[繁體中文](README.zht.md) |
|
||||
[한국어](README.ko.md) |
|
||||
[Deutsch](README.de.md) |
|
||||
[Español](README.es.md) |
|
||||
[Français](README.fr.md) |
|
||||
[Italiano](README.it.md) |
|
||||
[Dansk](README.da.md) |
|
||||
[日本語](README.ja.md) |
|
||||
[Polski](README.pl.md) |
|
||||
[Русский](README.ru.md) |
|
||||
[Bosanski](README.bs.md) |
|
||||
[العربية](README.ar.md) |
|
||||
[Norsk](README.no.md) |
|
||||
[Português (Brasil)](README.br.md) |
|
||||
[ไทย](README.th.md) |
|
||||
[Türkçe](README.tr.md) |
|
||||
[Українська](README.uk.md) |
|
||||
[বাংলা](README.bn.md) |
|
||||
[Ελληνικά](README.gr.md) |
|
||||
[Tiếng Việt](README.vi.md)
|
||||
|
||||
[](https://docs.openwebui.com/)
|
||||
|
||||

|
||||

|
||||

|
||||

|
||||

|
||||

|
||||

|
||||
[](https://discord.gg/5rJgQTnV4s)
|
||||
[](https://github.com/sponsors/open-webui)
|
||||
|
||||
[Open WebUI 둘러보기 →](https://docs.openwebui.com/)
|
||||
|
||||
### 설치
|
||||
|
||||
#### Python
|
||||
|
||||
Python 3.12가 필요합니다.
|
||||
|
||||
```bash
|
||||
pip install open-webui
|
||||
open-webui serve
|
||||
```
|
||||
|
||||
그런 다음 [http://localhost:8080](http://localhost:8080)을 여세요.
|
||||
|
||||
#### Docker
|
||||
|
||||
```bash
|
||||
docker run -d -p 3000:8080 --add-host=host.docker.internal:host-gateway -v open-webui:/app/backend/data --name open-webui --restart always ghcr.io/open-webui/open-webui:main
|
||||
```
|
||||
|
||||
그런 다음 [http://localhost:3000](http://localhost:3000)을 여세요.
|
||||
|
||||
| 이미지 태그 | 구성 |
|
||||
| --- | --- |
|
||||
| `:main` | 로컬 AI 의존성이 포함된 표준 이미지 |
|
||||
| `:slim` | 임베딩, 문서 추출, 음성 처리에 외부 서비스를 사용하는 경량 이미지 |
|
||||
| `:cuda` | CUDA 가속을 지원하는 Open WebUI |
|
||||
| `:ollama` | Ollama가 포함된 Open WebUI |
|
||||
| `:dev` | 최신 개발 빌드 |
|
||||
|
||||
필요에 따라 `docker run`의 이미지 이름 앞에 다음 옵션을 추가하세요.
|
||||
|
||||
| 옵션 | 용도 |
|
||||
| --- | --- |
|
||||
| `-e OLLAMA_BASE_URL=http://your-ollama-server:11434` | 다른 서버의 Ollama에 연결 |
|
||||
| `-e OPENAI_API_KEY=your_secret_key` | OpenAI API 키 설정 |
|
||||
| `-e HF_HUB_OFFLINE=1` | 오프라인 사용을 위해 Hugging Face 모델 다운로드 비활성화 |
|
||||
| `--gpus all` | `:cuda` 또는 `:ollama`에서 Nvidia GPU 사용 활성화. Nvidia Container Toolkit 필요 |
|
||||
|
||||
설치 방법과 설정 옵션은 [Docker 설치 가이드](https://docs.openwebui.com/getting-started/quick-start/)를 참고하세요.
|
||||
|
||||
#### 데스크톱 앱
|
||||
|
||||
macOS, Windows, Linux용 [네이티브 데스크톱 앱을 다운로드하세요](https://github.com/open-webui/desktop).
|
||||
|
||||
[문서 읽기 →](https://docs.openwebui.com/getting-started/)
|
||||
|
||||
### 생태계
|
||||
|
||||
- [Open Terminal](https://github.com/open-webui/open-terminal) / [Terminals (Enterprise)](https://github.com/open-webui/terminals): Open WebUI를 완전한 에이전트 실행 환경으로 만드는 실행 계층으로, 사용자별 작업 공간을 위한 엔터프라이즈 오케스트레이션을 제공합니다.
|
||||
- [Knowledge Base Sync (oikb)](https://github.com/open-webui/oikb): 폴더, 저장소, 버킷, 위키를 증분 동기화하여 Open WebUI 지식 베이스에 반영합니다.
|
||||
- [Open WebUI Computer](https://github.com/open-webui/computer): 어떤 브라우저에서든 내 컴퓨터를 사용하세요. 파일, 편집기, 터미널, Git, 선택적으로 사용하는 AI 에이전트가 실제 내 컴퓨터에서 실행됩니다.
|
||||
|
||||
자세한 내용은 [생태계 문서](https://docs.openwebui.com/ecosystem/)를 참고하세요.
|
||||
|
||||
### 문제 해결 및 업데이트
|
||||
|
||||
연결 문제는 [문제 해결 가이드](https://docs.openwebui.com/troubleshooting/)를, 설치 업데이트는 [업데이트 가이드](https://docs.openwebui.com/getting-started/updating)를 참고하세요.
|
||||
|
||||
### 문서
|
||||
|
||||
설정과 사용법은 [문서](https://docs.openwebui.com/)를, 예정된 작업은 [로드맵](https://docs.openwebui.com/roadmap/)을 참고하세요.
|
||||
|
||||
Docker Compose, Kubernetes 및 기타 설치 방법은 [설치 문서](https://docs.openwebui.com/getting-started/)를 참고하세요.
|
||||
|
||||
### 지원
|
||||
|
||||
[이슈를 등록](https://github.com/open-webui/open-webui/issues)하거나 [토론을 시작](https://github.com/open-webui/open-webui/discussions)하세요.
|
||||
|
||||
[Reddit](https://www.reddit.com/r/OpenWebUI/), [X](https://x.com/OpenWebUI), [Discord](https://discord.gg/5rJgQTnV4s)에서도 만나보세요.
|
||||
|
||||
### 보안
|
||||
|
||||
취약점은 [GitHub Security Advisories](https://github.com/open-webui/open-webui/security)를 통해 비공개로 제보해 주세요. 보안 제보는 GitHub를 통해서만 접수합니다.
|
||||
|
||||
### 스타 기록
|
||||
|
||||
<a href="https://star-history.com/#open-webui/open-webui&Date">
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=open-webui/open-webui&type=Date&theme=dark" />
|
||||
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=open-webui/open-webui&type=Date" />
|
||||
<img alt="스타 기록 차트" src="https://api.star-history.com/svg?repos=open-webui/open-webui&type=Date" />
|
||||
</picture>
|
||||
</a>
|
||||
|
||||
#### 라이선스
|
||||
|
||||
Open WebUI 브랜드 유지를 요구하는 Open WebUI License가 적용된 코드와, 각각 원래 라이선스가 적용되는 이전 기여분을 포함합니다. 조건과 이력은 [LICENSE](./LICENSE)와 [LICENSE_HISTORY](./LICENSE_HISTORY)를 참고하세요.
|
||||
|
||||
[엔터프라이즈](https://docs.openwebui.com/enterprise) · [채용](https://careers.openwebui.com/) · [후원](https://github.com/sponsors/open-webui)
|
||||
|
||||
제작: [Timothy Jaeryang Baek](https://github.com/tjbck).
|
||||
309
README.md
309
README.md
|
|
@ -1,4 +1,31 @@
|
|||
# Open WebUI 👋
|
||||
<h2>Open WebUI</h2>
|
||||
|
||||
<p>Open WebUI is <a href="https://docs.openwebui.com/"><strong>a home for AI</strong></a>: an extensible, easy-to-use, self-hosted platform built to run entirely offline. Connect local models through Ollama or use OpenAI-compatible APIs for local and cloud models.</p>
|
||||
|
||||
[English](README.md) |
|
||||
[简体中文](README.zh.md) |
|
||||
[繁體中文](README.zht.md) |
|
||||
[한국어](README.ko.md) |
|
||||
[Deutsch](README.de.md) |
|
||||
[Español](README.es.md) |
|
||||
[Français](README.fr.md) |
|
||||
[Italiano](README.it.md) |
|
||||
[Dansk](README.da.md) |
|
||||
[日本語](README.ja.md) |
|
||||
[Polski](README.pl.md) |
|
||||
[Русский](README.ru.md) |
|
||||
[Bosanski](README.bs.md) |
|
||||
[العربية](README.ar.md) |
|
||||
[Norsk](README.no.md) |
|
||||
[Português (Brasil)](README.br.md) |
|
||||
[ไทย](README.th.md) |
|
||||
[Türkçe](README.tr.md) |
|
||||
[Українська](README.uk.md) |
|
||||
[বাংলা](README.bn.md) |
|
||||
[Ελληνικά](README.gr.md) |
|
||||
[Tiếng Việt](README.vi.md)
|
||||
|
||||
[](https://docs.openwebui.com/)
|
||||
|
||||

|
||||

|
||||
|
|
@ -8,247 +35,85 @@
|
|||

|
||||

|
||||
[](https://discord.gg/5rJgQTnV4s)
|
||||
[](https://github.com/sponsors/open-webui)
|
||||
[](https://github.com/sponsors/open-webui)
|
||||
|
||||
Open WebUI is **a home for AI**, a self-hosted AI platform that's **[extensible](https://docs.openwebui.com/features/extensibility/plugin/)**, **[feature-rich](https://docs.openwebui.com/features/)**, user-friendly, and built to run **[entirely offline](https://openwebui.com/sovereign-ai)**. With support for **Ollama** and **OpenAI-compatible APIs**, it gives you a powerful, provider-agnostic interface for both local and cloud-based models.
|
||||
[Explore Open WebUI →](https://docs.openwebui.com/)
|
||||
|
||||
Passionate about open-source AI? [Join our team →](https://careers.openwebui.com/)
|
||||
### Installation
|
||||
|
||||

|
||||
#### Python
|
||||
|
||||
> [!TIP]
|
||||
> **Looking for an [Enterprise Plan](https://docs.openwebui.com/enterprise)?** – **[Speak with Our Sales Team Today!](https://docs.openwebui.com/enterprise)**
|
||||
|
||||
For more information, be sure to check out our [Open WebUI Documentation](https://docs.openwebui.com/).
|
||||
|
||||
## Key Features of Open WebUI ⭐
|
||||
|
||||
- 🚀 **Effortless Setup**: Install seamlessly via pip, uv, Docker, or Kubernetes (kubectl, kustomize, or helm), with `:ollama` and `:cuda` tagged images available for container deployments.
|
||||
|
||||
- 🤝 **Broad Model & API Integration**: Connect any OpenAI-compatible API alongside local Ollama models. Point the API URL at **LMStudio, GroqCloud, Mistral, OpenRouter, vLLM, and more** to mix and match providers freely.
|
||||
|
||||
- 🔐 **Granular RBAC & User Groups**: Administrators define detailed roles, groups, and permissions, giving each user exactly the access they need. Secure by default, with tailored experiences per group.
|
||||
|
||||
- 🧩 **Plugin Support**: Extend Open WebUI with **Filters**, **Actions**, **Pipes**, **Tools**, and **Skills**. Connect external services through **MCP**, **MCPO**, and **OpenAPI tool servers**. Build custom integrations, rate limits, approval flows, data connections, and more.
|
||||
|
||||
- 🤖 **Models & Agents**: Wrap any base model with custom instructions, tools, and knowledge to build specialized agents. Supports dynamic variables, per-user/group access control, and community preset imports via [Open WebUI Community](https://openwebui.com/).
|
||||
|
||||
- ⚡ **Agentic Execution with [Open Terminal](https://github.com/open-webui/open-terminal)**: Give your agents a terminal and filesystem to carry out multi-step tasks. Let them analyze data, run scripts, fix errors, and produce files directly in chat. Scale to teams with **[Terminals (Enterprise)](https://github.com/open-webui/terminals)** for per-user isolated environments, resource limits, and automatic lifecycle management.
|
||||
|
||||
- 📝 **Notes**: A dedicated workspace for content outside conversations. Draft with a rich editor, use AI to rewrite selected text, and attach notes to any chat for full-context injection.
|
||||
|
||||
- 📢 **Channels**: Real-time shared spaces where your team and AI models collaborate in one timeline. Tag models to draft or critique, with threads, reactions, pins, and access control.
|
||||
|
||||
- 🧠 **Persistent Memory**: The AI remembers facts about you across conversations, carrying context from one chat to the next.
|
||||
|
||||
- ✅ **Live Workflow & Message Flow**: Watch the AI build and work through checklists in real time. Queue messages while the AI is still responding; they send automatically when it's ready.
|
||||
|
||||
- 📅 **Calendar & AI Scheduling**: Built-in personal and shared calendars with month/week/day views, recurring events, color coding, attendees, and reminders. Models manage your schedule conversationally through native function calling.
|
||||
|
||||
- ⏱️ **Automations**: Schedule prompts to run on recurring schedules, with runs surfaced on your calendar and each completed run linking back to the chat it produced.
|
||||
|
||||
- 📱 **Responsive Design & PWA**: Seamless experience across desktop, laptop, and mobile, with a Progressive Web App for native app-like feel and offline access on localhost.
|
||||
|
||||
- ✒️🔢 **Full Markdown and LaTeX Support**: Comprehensive Markdown and LaTeX capabilities for enriched interaction.
|
||||
|
||||
- 🎤📹 **Hands-Free Voice/Video Call**: Integrated voice and video calls with multiple Speech-to-Text providers (Local Whisper, OpenAI, Deepgram, Azure) and Text-to-Speech engines (Azure, ElevenLabs, OpenAI, Transformers, WebAPI).
|
||||
|
||||
- 💾 **Persistent Artifact Storage**: Built-in key-value storage API for artifacts, enabling journals, trackers, leaderboards, and collaborative tools with personal and shared data scopes.
|
||||
|
||||
- 📚 **Local RAG Integration**: Retrieval Augmented Generation backed by 9 vector databases and multiple content-extraction engines (Tika, Docling, Document Intelligence, Mistral OCR, PaddleOCR-vl, external loaders). Supports hybrid search (BM25 + vector) with reranking and full-context mode. Load documents into chat or pull them from your library with the `#` command.
|
||||
|
||||
- 🔍 **Web Search for RAG**: Search the web through dozens of providers including `SearXNG`, `Google PSE`, `Brave Search`, `Kagi`, `Mojeek`, `Tavily`, `Perplexity`, `Firecrawl`, `serpstack`, `serper`, `Serply`, `DuckDuckGo`, `SearchApi`, `SerpApi`, `Bing`, `Jina`, `Exa`, `Sougou`, `Azure AI Search`, and `Ollama Cloud`, injecting results directly into the conversation.
|
||||
|
||||
- 🌐 **Web Browsing Capability**: Pull websites into chat with the `#` command followed by a URL, or let the model fetch them on its own when needed.
|
||||
|
||||
- 🎨 **Image Generation & Editing**: Create and edit images with multiple engines including OpenAI DALL·E, Gemini, ComfyUI (local), and AUTOMATIC1111 (local), supporting both generation and prompt-based editing.
|
||||
|
||||
- ⚙️ **Multi-Model Conversations**: Engage several models at once, harnessing their individual strengths in parallel for the best possible responses.
|
||||
|
||||
- 📊 **Usage Analytics & Model Evaluation**: Admin dashboards track message volume, token consumption, and cost across users and models. Evaluate models with a built-in arena, A/B testing, and ELO-based leaderboards.
|
||||
|
||||
- 🗄️ **Flexible Database & Storage**: Choose SQLite (with optional encryption) or PostgreSQL, and store files locally or on S3, Google Cloud Storage, or Azure Blob Storage.
|
||||
|
||||
- 🧬 **Advanced Vector Database Support**: Pick from 9 vector databases: ChromaDB, PGVector, Qdrant, Milvus, Elasticsearch, OpenSearch, Pinecone, S3Vector, and Oracle 23ai.
|
||||
|
||||
- 🪪 **Enterprise Authentication & Provisioning**: Full LDAP/Active Directory integration, SSO via trusted headers and OAuth providers, and SCIM 2.0 automated provisioning for identity providers like Okta, Azure AD, and Google Workspace.
|
||||
|
||||
- ☁️ **Cloud-Native File Integration**: Native Google Drive and OneDrive/SharePoint file picking for seamless document import from enterprise cloud storage.
|
||||
|
||||
- 🔭 **Production Observability**: Built-in OpenTelemetry support for traces, metrics, and logs, plugging into your existing monitoring stack.
|
||||
|
||||
- ⚖️ **Horizontal Scalability**: Redis-backed session management and WebSocket support for multi-worker, multi-node deployments behind load balancers.
|
||||
|
||||
- 🌐🌍 **Multilingual Support**: Use Open WebUI in your preferred language with i18n support. We're actively seeking contributors to expand language coverage!
|
||||
|
||||
- 🌟 **Continuous Updates**: We're committed to improving Open WebUI with regular updates, fixes, and new features.
|
||||
|
||||
- 🛡️ **Transparent Security Process**: Security reports are triaged, fixed, and published as open advisories through a documented responsible-disclosure process. See our [Security Policy](https://github.com/open-webui/open-webui/security).
|
||||
|
||||
Want to learn more about Open WebUI's features? Check out our [Open WebUI documentation](https://docs.openwebui.com/features) for a comprehensive overview!
|
||||
|
||||
## The Open WebUI Ecosystem 🌐
|
||||
|
||||
Open WebUI is the core, surrounded by companion apps and infrastructure that extend what your AI can do, where it can reach, and how you run it:
|
||||
|
||||
- 💻 **Open WebUI Computer** ([open-webui/computer](https://github.com/open-webui/computer)): A standalone, mobile-first computer and coding agent that runs on the machine you own. Files, terminal, and git in a browser tab, reachable from your phone. Connect it into Open WebUI as a model, or reach it from Telegram, WhatsApp, and more.
|
||||
|
||||
- ⚡ **Open Terminal** and **Terminals (Enterprise)** ([open-webui/open-terminal](https://github.com/open-webui/open-terminal) & [open-webui/terminals](https://github.com/open-webui/terminals)): A self-hosted computing environment that plugs into Open WebUI, giving the AI a place to write code, run it, read output, fix errors, and iterate inside the chat. Terminals gives you per-user isolated containers with separate credentials, resource limits, and network rules. Automatic lifecycle management on Docker or Kubernetes.
|
||||
|
||||
- 🔄 **oikb** ([open-webui/oikb](https://github.com/open-webui/oikb)): Feed your Knowledge Bases from 45+ sources (GitHub, Confluence, ServiceNow, Salesforce, Jira, Slack, SharePoint, Notion, and more), keeping the tools your team already uses continuously in sync.
|
||||
|
||||
- 🖥️ **Native Desktop App** ([open-webui/desktop](https://github.com/open-webui/desktop)): Run Open WebUI as a native app on macOS, Windows, and Linux. System-wide Spotlight chat bar with screenshot capture, push-to-talk voice, and optional fully-local inference via a built-in llama.cpp engine.
|
||||
|
||||
Want to learn more? Check out our [Open WebUI documentation](https://docs.openwebui.com) for more details!
|
||||
|
||||
---
|
||||
|
||||
We are incredibly grateful for the generous support of our sponsors. Their contributions help us to maintain and improve our project, ensuring we can continue to deliver quality work to our community. Thank you!
|
||||
|
||||
## How to Install 🚀
|
||||
|
||||
### Installation via Python pip 🐍
|
||||
|
||||
Open WebUI can be installed using pip, the Python package installer. Before proceeding, ensure you're using **Python 3.12** to avoid compatibility issues.
|
||||
|
||||
1. **Install Open WebUI**:
|
||||
Open your terminal and run the following command to install Open WebUI:
|
||||
|
||||
```bash
|
||||
pip install open-webui
|
||||
```
|
||||
|
||||
2. **Running Open WebUI**:
|
||||
After installation, you can start Open WebUI by executing:
|
||||
|
||||
```bash
|
||||
open-webui serve
|
||||
```
|
||||
|
||||
This will start the Open WebUI server, which you can access at [http://localhost:8080](http://localhost:8080)
|
||||
|
||||
### Quick Start with Docker 🐳
|
||||
|
||||
> [!NOTE]
|
||||
> Please note that for certain Docker environments, additional configurations might be needed. If you encounter any connection issues, our detailed guide on [Open WebUI Documentation](https://docs.openwebui.com/) is ready to assist you.
|
||||
|
||||
> [!WARNING]
|
||||
> When using Docker to install Open WebUI, make sure to include the `-v open-webui:/app/backend/data` in your Docker command. This step is crucial as it ensures your database is properly mounted and prevents any loss of data.
|
||||
|
||||
> [!TIP]
|
||||
> If you wish to utilize Open WebUI with Ollama included or CUDA acceleration, we recommend utilizing our official images tagged with either `:cuda` or `:ollama`. To enable CUDA, you must install the [Nvidia CUDA container toolkit](https://docs.nvidia.com/dgx/nvidia-container-runtime-upgrade/) on your Linux/WSL system.
|
||||
|
||||
### Installation with Default Configuration
|
||||
|
||||
- **If Ollama is on your computer**, use this command:
|
||||
|
||||
```bash
|
||||
docker run -d -p 3000:8080 --add-host=host.docker.internal:host-gateway -v open-webui:/app/backend/data --name open-webui --restart always ghcr.io/open-webui/open-webui:main
|
||||
```
|
||||
|
||||
- **If Ollama is on a Different Server**, use this command:
|
||||
|
||||
To connect to Ollama on another server, change the `OLLAMA_BASE_URL` to the server's URL:
|
||||
|
||||
```bash
|
||||
docker run -d -p 3000:8080 -e OLLAMA_BASE_URL=https://example.com -v open-webui:/app/backend/data --name open-webui --restart always ghcr.io/open-webui/open-webui:main
|
||||
```
|
||||
|
||||
- **To run Open WebUI with Nvidia GPU support**, use this command:
|
||||
|
||||
```bash
|
||||
docker run -d -p 3000:8080 --gpus all --add-host=host.docker.internal:host-gateway -v open-webui:/app/backend/data --name open-webui --restart always ghcr.io/open-webui/open-webui:cuda
|
||||
```
|
||||
|
||||
### Installation for OpenAI API Usage Only
|
||||
|
||||
- **If you're only using OpenAI API**, use this command:
|
||||
|
||||
```bash
|
||||
docker run -d -p 3000:8080 -e OPENAI_API_KEY=your_secret_key -v open-webui:/app/backend/data --name open-webui --restart always ghcr.io/open-webui/open-webui:main
|
||||
```
|
||||
|
||||
### Installing Open WebUI with Bundled Ollama Support
|
||||
|
||||
This installation method uses a single container image that bundles Open WebUI with Ollama, allowing for a streamlined setup via a single command. Choose the appropriate command based on your hardware setup:
|
||||
|
||||
- **With GPU Support**:
|
||||
Utilize GPU resources by running the following command:
|
||||
|
||||
```bash
|
||||
docker run -d -p 3000:8080 --gpus=all -v ollama:/root/.ollama -v open-webui:/app/backend/data --name open-webui --restart always ghcr.io/open-webui/open-webui:ollama
|
||||
```
|
||||
|
||||
- **For CPU Only**:
|
||||
If you're not using a GPU, use this command instead:
|
||||
|
||||
```bash
|
||||
docker run -d -p 3000:8080 -v ollama:/root/.ollama -v open-webui:/app/backend/data --name open-webui --restart always ghcr.io/open-webui/open-webui:ollama
|
||||
```
|
||||
|
||||
Both commands facilitate a built-in, hassle-free installation of both Open WebUI and Ollama, ensuring that you can get everything up and running swiftly.
|
||||
|
||||
After installation, you can access Open WebUI at [http://localhost:3000](http://localhost:3000). Enjoy! 😄
|
||||
|
||||
### Other Installation Methods
|
||||
|
||||
We offer various installation alternatives, including non-Docker native installation methods, Docker Compose, Kustomize, and Helm. Visit our [Open WebUI Documentation](https://docs.openwebui.com/getting-started/) or join our [Discord community](https://discord.gg/5rJgQTnV4s) for comprehensive guidance.
|
||||
|
||||
### Troubleshooting
|
||||
|
||||
Encountering connection issues? Our [Open WebUI Documentation](https://docs.openwebui.com/troubleshooting/) has got you covered. For further assistance and to join our vibrant community, visit the [Open WebUI Discord](https://discord.gg/5rJgQTnV4s).
|
||||
|
||||
#### Open WebUI: Server Connection Error
|
||||
|
||||
If you're experiencing connection issues, it’s often due to the WebUI docker container not being able to reach the Ollama server at 127.0.0.1:11434 (host.docker.internal:11434) inside the container . Use the `--network=host` flag in your docker command to resolve this. Note that the port changes from 3000 to 8080, resulting in the link: `http://localhost:8080`.
|
||||
|
||||
**Example Docker Command**:
|
||||
Requires Python 3.12.
|
||||
|
||||
```bash
|
||||
docker run -d --network=host -v open-webui:/app/backend/data -e OLLAMA_BASE_URL=http://127.0.0.1:11434 --name open-webui --restart always ghcr.io/open-webui/open-webui:main
|
||||
pip install open-webui
|
||||
open-webui serve
|
||||
```
|
||||
|
||||
### Keeping Your Docker Installation Up-to-Date
|
||||
Then open [http://localhost:8080](http://localhost:8080).
|
||||
|
||||
Check our Updating Guide available in our [Open WebUI Documentation](https://docs.openwebui.com/getting-started/updating).
|
||||
|
||||
### Using the Dev Branch 🌙
|
||||
|
||||
> [!WARNING]
|
||||
> The `:dev` branch contains the latest unstable features and changes. Use it at your own risk as it may have bugs or incomplete features.
|
||||
|
||||
If you want to try out the latest bleeding-edge features and are okay with occasional instability, you can use the `:dev` tag like this:
|
||||
#### Docker
|
||||
|
||||
```bash
|
||||
docker run -d -p 3000:8080 -v open-webui:/app/backend/data --name open-webui --add-host=host.docker.internal:host-gateway --restart always ghcr.io/open-webui/open-webui:dev
|
||||
docker run -d -p 3000:8080 --add-host=host.docker.internal:host-gateway -v open-webui:/app/backend/data --name open-webui --restart always ghcr.io/open-webui/open-webui:main
|
||||
```
|
||||
|
||||
### Offline Mode
|
||||
Then open [http://localhost:3000](http://localhost:3000).
|
||||
|
||||
If you are running Open WebUI in an offline environment, you can set the `HF_HUB_OFFLINE` environment variable to `1` to prevent attempts to download models from the internet.
|
||||
| Image tag | Includes |
|
||||
| --- | --- |
|
||||
| `:main` | Standard image with local AI dependencies |
|
||||
| `:slim` | Lightweight image using external services for embeddings, document extraction, and voice |
|
||||
| `:cuda` | Open WebUI with CUDA acceleration |
|
||||
| `:ollama` | Open WebUI bundled with Ollama |
|
||||
| `:dev` | Latest development build |
|
||||
|
||||
```bash
|
||||
export HF_HUB_OFFLINE=1
|
||||
```
|
||||
Add these options to `docker run` before the image name as needed:
|
||||
|
||||
## What's Next? 🌟
|
||||
| Option | Purpose |
|
||||
| --- | --- |
|
||||
| `-e OLLAMA_BASE_URL=http://your-ollama-server:11434` | Connect to Ollama on another server |
|
||||
| `-e OPENAI_API_KEY=your_secret_key` | Set your OpenAI API key |
|
||||
| `-e HF_HUB_OFFLINE=1` | Disable Hugging Face model downloads for offline use |
|
||||
| `--gpus all` | Enable Nvidia GPU access for `:cuda` or `:ollama`; requires the Nvidia Container Toolkit |
|
||||
|
||||
Discover upcoming features on our roadmap in the [Open WebUI Documentation](https://docs.openwebui.com/roadmap/).
|
||||
See the [Docker installation guide](https://docs.openwebui.com/getting-started/quick-start/) for setup instructions and configuration options.
|
||||
|
||||
## License 📜
|
||||
#### Desktop App
|
||||
|
||||
This project contains code under multiple licenses. The current codebase includes components licensed under the Open WebUI License with an additional requirement to preserve the "Open WebUI" branding, as well as prior contributions under their respective original licenses. For a detailed record of license changes and the applicable terms for each section of the code, please refer to [LICENSE_HISTORY](./LICENSE_HISTORY). For complete and updated licensing details, please see the [LICENSE](./LICENSE) and [LICENSE_HISTORY](./LICENSE_HISTORY) files.
|
||||
[Download the native desktop app](https://github.com/open-webui/desktop) for macOS, Windows, and Linux.
|
||||
|
||||
## Support 💬
|
||||
[Read the docs →](https://docs.openwebui.com/getting-started/)
|
||||
|
||||
If you have any questions, suggestions, or need assistance, please open an issue or join our
|
||||
[Open WebUI Discord community](https://discord.gg/5rJgQTnV4s) to connect with us! 🤝
|
||||
### Ecosystem
|
||||
|
||||
## Security 🛡️
|
||||
- [Open Terminal](https://github.com/open-webui/open-terminal) / [Terminals (Enterprise)](https://github.com/open-webui/terminals): The action layer that turns Open WebUI into a full agent harness, with enterprise orchestration for per-user workspaces.
|
||||
- [Knowledge Base Sync (oikb)](https://github.com/open-webui/oikb): Mirror folders, repos, buckets, and wikis into Open WebUI Knowledge Bases with incremental sync.
|
||||
- [Open WebUI Computer](https://github.com/open-webui/computer): Your computer in any browser: files, editor, terminal, git, and optional AI agents, running on your real machine.
|
||||
|
||||
If you believe you've found a security vulnerability, or something that shouldn't be disclosed publicly, please [reach out confidentially through our responsible disclosure program on GitHub](https://github.com/open-webui/open-webui/security). We accept reports only through GitHub, not through any other platform. Thank you for helping us keep Open WebUI secure!
|
||||
See the [ecosystem documentation](https://docs.openwebui.com/ecosystem/) for details.
|
||||
|
||||
## Star History
|
||||
### Troubleshooting and Updates
|
||||
|
||||
See the [troubleshooting guide](https://docs.openwebui.com/troubleshooting/) for connection issues and the [updating guide](https://docs.openwebui.com/getting-started/updating) to update your installation.
|
||||
|
||||
### Documentation
|
||||
|
||||
See the [docs](https://docs.openwebui.com/) for configuration and usage, and the [roadmap](https://docs.openwebui.com/roadmap/) for planned work.
|
||||
|
||||
For Docker Compose, Kubernetes, and other setups, see the [installation docs](https://docs.openwebui.com/getting-started/).
|
||||
|
||||
### Support
|
||||
|
||||
[Open an issue](https://github.com/open-webui/open-webui/issues) or [start a discussion](https://github.com/open-webui/open-webui/discussions).
|
||||
|
||||
Find us on [Reddit](https://www.reddit.com/r/OpenWebUI/), [X](https://x.com/OpenWebUI), and [Discord](https://discord.gg/5rJgQTnV4s).
|
||||
|
||||
### Security
|
||||
|
||||
Report vulnerabilities privately through [GitHub security advisories](https://github.com/open-webui/open-webui/security). Security reports are accepted only through GitHub.
|
||||
|
||||
### Star History
|
||||
|
||||
<a href="https://star-history.com/#open-webui/open-webui&Date">
|
||||
<picture>
|
||||
|
|
@ -258,6 +123,10 @@ If you believe you've found a security vulnerability, or something that shouldn'
|
|||
</picture>
|
||||
</a>
|
||||
|
||||
---
|
||||
#### License
|
||||
|
||||
Created by [Timothy Jaeryang Baek](https://github.com/tjbck) - Let's make Open WebUI even more amazing together! 💪
|
||||
Includes code under the Open WebUI License, which requires preserving the Open WebUI branding, and prior contributions under their original licenses. See [LICENSE](./LICENSE) and [LICENSE_HISTORY](./LICENSE_HISTORY) for terms and history.
|
||||
|
||||
[Enterprise](https://docs.openwebui.com/enterprise) · [Careers](https://careers.openwebui.com/) · [Sponsor](https://github.com/sponsors/open-webui)
|
||||
|
||||
Created by [Timothy Jaeryang Baek](https://github.com/tjbck).
|
||||
|
|
|
|||
132
README.no.md
Normal file
132
README.no.md
Normal file
|
|
@ -0,0 +1,132 @@
|
|||
<h2>Open WebUI</h2>
|
||||
|
||||
<p>Open WebUI er <a href="https://docs.openwebui.com/"><strong>et hjem for KI</strong></a>: en utvidbar og brukervennlig plattform du drifter selv, bygget for å kjøre helt uten nettilgang. Koble til lokale modeller via Ollama, eller bruk OpenAI-kompatible API-er for lokale og skybaserte modeller.</p>
|
||||
|
||||
[English](README.md) |
|
||||
[简体中文](README.zh.md) |
|
||||
[繁體中文](README.zht.md) |
|
||||
[한국어](README.ko.md) |
|
||||
[Deutsch](README.de.md) |
|
||||
[Español](README.es.md) |
|
||||
[Français](README.fr.md) |
|
||||
[Italiano](README.it.md) |
|
||||
[Dansk](README.da.md) |
|
||||
[日本語](README.ja.md) |
|
||||
[Polski](README.pl.md) |
|
||||
[Русский](README.ru.md) |
|
||||
[Bosanski](README.bs.md) |
|
||||
[العربية](README.ar.md) |
|
||||
[Norsk](README.no.md) |
|
||||
[Português (Brasil)](README.br.md) |
|
||||
[ไทย](README.th.md) |
|
||||
[Türkçe](README.tr.md) |
|
||||
[Українська](README.uk.md) |
|
||||
[বাংলা](README.bn.md) |
|
||||
[Ελληνικά](README.gr.md) |
|
||||
[Tiếng Việt](README.vi.md)
|
||||
|
||||
[](https://docs.openwebui.com/)
|
||||
|
||||

|
||||

|
||||

|
||||

|
||||

|
||||

|
||||

|
||||
[](https://discord.gg/5rJgQTnV4s)
|
||||
[](https://github.com/sponsors/open-webui)
|
||||
|
||||
[Utforsk Open WebUI →](https://docs.openwebui.com/)
|
||||
|
||||
### Installasjon
|
||||
|
||||
#### Python
|
||||
|
||||
Krever Python 3.12.
|
||||
|
||||
```bash
|
||||
pip install open-webui
|
||||
open-webui serve
|
||||
```
|
||||
|
||||
Åpne deretter [http://localhost:8080](http://localhost:8080).
|
||||
|
||||
#### Docker
|
||||
|
||||
```bash
|
||||
docker run -d -p 3000:8080 --add-host=host.docker.internal:host-gateway -v open-webui:/app/backend/data --name open-webui --restart always ghcr.io/open-webui/open-webui:main
|
||||
```
|
||||
|
||||
Åpne deretter [http://localhost:3000](http://localhost:3000).
|
||||
|
||||
| Image-tagg | Innhold |
|
||||
| --- | --- |
|
||||
| `:main` | Standardimage med avhengigheter for lokal KI |
|
||||
| `:slim` | Lettvektsimage med eksterne tjenester for embeddings, dokumentuttrekk og tale |
|
||||
| `:cuda` | Open WebUI med CUDA-akselerasjon |
|
||||
| `:ollama` | Open WebUI med Ollama inkludert |
|
||||
| `:dev` | Nyeste utviklingsbygg |
|
||||
|
||||
Legg til disse valgene i `docker run` før image-navnet etter behov:
|
||||
|
||||
| Valg | Formål |
|
||||
| --- | --- |
|
||||
| `-e OLLAMA_BASE_URL=http://your-ollama-server:11434` | Koble til Ollama på en annen server |
|
||||
| `-e OPENAI_API_KEY=your_secret_key` | Angi OpenAI-API-nøkkelen din |
|
||||
| `-e HF_HUB_OFFLINE=1` | Deaktiver nedlasting av Hugging Face-modeller for bruk uten nettilgang |
|
||||
| `--gpus all` | Aktiver tilgang til Nvidia-GPU for `:cuda` eller `:ollama`; krever Nvidia Container Toolkit |
|
||||
|
||||
Se [installasjonsveiledningen for Docker](https://docs.openwebui.com/getting-started/quick-start/) for oppsett og konfigurasjonsvalg.
|
||||
|
||||
#### Skrivebordsapp
|
||||
|
||||
[Last ned den native skrivebordsappen](https://github.com/open-webui/desktop) for macOS, Windows og Linux.
|
||||
|
||||
[Les dokumentasjonen →](https://docs.openwebui.com/getting-started/)
|
||||
|
||||
### Økosystem
|
||||
|
||||
- [Open Terminal](https://github.com/open-webui/open-terminal) / [Terminals (Enterprise)](https://github.com/open-webui/terminals): Utførelseslaget som gjør Open WebUI til et komplett agentmiljø, med enterprise-orkestrering av egne arbeidsområder for hver bruker.
|
||||
- [Knowledge Base Sync (oikb)](https://github.com/open-webui/oikb): Speil mapper, kodearkiver, bøtter og wikier til Open WebUI Knowledge Bases med inkrementell synkronisering.
|
||||
- [Open WebUI Computer](https://github.com/open-webui/computer): Datamaskinen din i enhver nettleser: filer, editor, terminal, Git og valgfrie KI-agenter, som kjører på din egen maskin.
|
||||
|
||||
Se [økosystemets dokumentasjon](https://docs.openwebui.com/ecosystem/) for detaljer.
|
||||
|
||||
### Feilsøking og oppdateringer
|
||||
|
||||
Se [feilsøkingsveiledningen](https://docs.openwebui.com/troubleshooting/) ved tilkoblingsproblemer og [oppdateringsveiledningen](https://docs.openwebui.com/getting-started/updating) for å oppdatere installasjonen.
|
||||
|
||||
### Dokumentasjon
|
||||
|
||||
Se [dokumentasjonen](https://docs.openwebui.com/) for konfigurasjon og bruk, og [veikartet](https://docs.openwebui.com/roadmap/) for planlagt arbeid.
|
||||
|
||||
For Docker Compose, Kubernetes og andre oppsett, se [installasjonsdokumentasjonen](https://docs.openwebui.com/getting-started/).
|
||||
|
||||
### Hjelp
|
||||
|
||||
[Opprett en sak](https://github.com/open-webui/open-webui/issues) eller [start en diskusjon](https://github.com/open-webui/open-webui/discussions).
|
||||
|
||||
Du finner oss på [Reddit](https://www.reddit.com/r/OpenWebUI/), [X](https://x.com/OpenWebUI) og [Discord](https://discord.gg/5rJgQTnV4s).
|
||||
|
||||
### Sikkerhet
|
||||
|
||||
Rapporter sårbarheter privat via [GitHub Security Advisories](https://github.com/open-webui/open-webui/security). Sikkerhetsrapporter mottas kun via GitHub.
|
||||
|
||||
### Stjernehistorikk
|
||||
|
||||
<a href="https://star-history.com/#open-webui/open-webui&Date">
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=open-webui/open-webui&type=Date&theme=dark" />
|
||||
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=open-webui/open-webui&type=Date" />
|
||||
<img alt="Diagram over stjernehistorikk" src="https://api.star-history.com/svg?repos=open-webui/open-webui&type=Date" />
|
||||
</picture>
|
||||
</a>
|
||||
|
||||
#### Lisens
|
||||
|
||||
Inneholder kode under Open WebUI License, som krever at Open WebUI-merkevaren beholdes, samt tidligere bidrag under sine opprinnelige lisenser. Se [LICENSE](./LICENSE) og [LICENSE_HISTORY](./LICENSE_HISTORY) for vilkår og historikk.
|
||||
|
||||
[Enterprise](https://docs.openwebui.com/enterprise) · [Karriere](https://careers.openwebui.com/) · [Støtt prosjektet](https://github.com/sponsors/open-webui)
|
||||
|
||||
Laget av [Timothy Jaeryang Baek](https://github.com/tjbck).
|
||||
132
README.pl.md
Normal file
132
README.pl.md
Normal file
|
|
@ -0,0 +1,132 @@
|
|||
<h2>Open WebUI</h2>
|
||||
|
||||
<p>Open WebUI to <a href="https://docs.openwebui.com/"><strong>dom dla AI</strong></a>: rozszerzalna, łatwa w obsłudze platforma do samodzielnego hostowania, zaprojektowana do pracy całkowicie offline. Podłącz lokalne modele przez Ollama lub korzystaj z API zgodnych z OpenAI dla modeli lokalnych i chmurowych.</p>
|
||||
|
||||
[English](README.md) |
|
||||
[简体中文](README.zh.md) |
|
||||
[繁體中文](README.zht.md) |
|
||||
[한국어](README.ko.md) |
|
||||
[Deutsch](README.de.md) |
|
||||
[Español](README.es.md) |
|
||||
[Français](README.fr.md) |
|
||||
[Italiano](README.it.md) |
|
||||
[Dansk](README.da.md) |
|
||||
[日本語](README.ja.md) |
|
||||
[Polski](README.pl.md) |
|
||||
[Русский](README.ru.md) |
|
||||
[Bosanski](README.bs.md) |
|
||||
[العربية](README.ar.md) |
|
||||
[Norsk](README.no.md) |
|
||||
[Português (Brasil)](README.br.md) |
|
||||
[ไทย](README.th.md) |
|
||||
[Türkçe](README.tr.md) |
|
||||
[Українська](README.uk.md) |
|
||||
[বাংলা](README.bn.md) |
|
||||
[Ελληνικά](README.gr.md) |
|
||||
[Tiếng Việt](README.vi.md)
|
||||
|
||||
[](https://docs.openwebui.com/)
|
||||
|
||||

|
||||

|
||||

|
||||

|
||||

|
||||

|
||||

|
||||
[](https://discord.gg/5rJgQTnV4s)
|
||||
[](https://github.com/sponsors/open-webui)
|
||||
|
||||
[Poznaj Open WebUI →](https://docs.openwebui.com/)
|
||||
|
||||
### Instalacja
|
||||
|
||||
#### Python
|
||||
|
||||
Wymaga Pythona 3.12.
|
||||
|
||||
```bash
|
||||
pip install open-webui
|
||||
open-webui serve
|
||||
```
|
||||
|
||||
Następnie otwórz [http://localhost:8080](http://localhost:8080).
|
||||
|
||||
#### Docker
|
||||
|
||||
```bash
|
||||
docker run -d -p 3000:8080 --add-host=host.docker.internal:host-gateway -v open-webui:/app/backend/data --name open-webui --restart always ghcr.io/open-webui/open-webui:main
|
||||
```
|
||||
|
||||
Następnie otwórz [http://localhost:3000](http://localhost:3000).
|
||||
|
||||
| Tag obrazu | Zawartość |
|
||||
| --- | --- |
|
||||
| `:main` | Standardowy obraz z zależnościami dla lokalnej AI |
|
||||
| `:slim` | Lekki obraz korzystający z usług zewnętrznych do osadzeń, ekstrakcji dokumentów i obsługi głosu |
|
||||
| `:cuda` | Open WebUI z akceleracją CUDA |
|
||||
| `:ollama` | Open WebUI z dołączonym Ollama |
|
||||
| `:dev` | Najnowsza kompilacja rozwojowa |
|
||||
|
||||
W razie potrzeby dodaj te opcje do `docker run` przed nazwą obrazu:
|
||||
|
||||
| Opcja | Zastosowanie |
|
||||
| --- | --- |
|
||||
| `-e OLLAMA_BASE_URL=http://your-ollama-server:11434` | Połączenie z Ollama na innym serwerze |
|
||||
| `-e OPENAI_API_KEY=your_secret_key` | Ustawienie klucza API OpenAI |
|
||||
| `-e HF_HUB_OFFLINE=1` | Wyłączenie pobierania modeli Hugging Face do pracy offline |
|
||||
| `--gpus all` | Włączenie dostępu do GPU Nvidia dla `:cuda` lub `:ollama`; wymaga Nvidia Container Toolkit |
|
||||
|
||||
Instrukcje i opcje konfiguracji znajdziesz w [przewodniku instalacji przez Docker](https://docs.openwebui.com/getting-started/quick-start/).
|
||||
|
||||
#### Aplikacja desktopowa
|
||||
|
||||
[Pobierz natywną aplikację desktopową](https://github.com/open-webui/desktop) dla macOS, Windows i Linux.
|
||||
|
||||
[Przeczytaj dokumentację →](https://docs.openwebui.com/getting-started/)
|
||||
|
||||
### Ekosystem
|
||||
|
||||
- [Open Terminal](https://github.com/open-webui/open-terminal) / [Terminals (Enterprise)](https://github.com/open-webui/terminals): Warstwa wykonawcza, która zmienia Open WebUI w kompletne środowisko agentowe, z orkiestracją klasy enterprise dla osobnych przestrzeni roboczych użytkowników.
|
||||
- [Knowledge Base Sync (oikb)](https://github.com/open-webui/oikb): Synchronizuj przyrostowo foldery, repozytoria, zasobniki i wiki z bazami wiedzy Open WebUI.
|
||||
- [Open WebUI Computer](https://github.com/open-webui/computer): Twój komputer w dowolnej przeglądarce: pliki, edytor, terminal, Git i opcjonalni agenci AI, działający na twojej własnej maszynie.
|
||||
|
||||
Szczegóły znajdziesz w [dokumentacji ekosystemu](https://docs.openwebui.com/ecosystem/).
|
||||
|
||||
### Rozwiązywanie problemów i aktualizacje
|
||||
|
||||
W razie problemów z połączeniem skorzystaj z [poradnika rozwiązywania problemów](https://docs.openwebui.com/troubleshooting/), a aby zaktualizować instalację — z [poradnika aktualizacji](https://docs.openwebui.com/getting-started/updating).
|
||||
|
||||
### Dokumentacja
|
||||
|
||||
Informacje o konfiguracji i użytkowaniu znajdziesz w [dokumentacji](https://docs.openwebui.com/), a planowane prace w [planie rozwoju](https://docs.openwebui.com/roadmap/).
|
||||
|
||||
Informacje o Docker Compose, Kubernetes i innych sposobach instalacji znajdziesz w [dokumentacji instalacji](https://docs.openwebui.com/getting-started/).
|
||||
|
||||
### Pomoc
|
||||
|
||||
[Utwórz zgłoszenie](https://github.com/open-webui/open-webui/issues) lub [rozpocznij dyskusję](https://github.com/open-webui/open-webui/discussions).
|
||||
|
||||
Znajdziesz nas na [Reddicie](https://www.reddit.com/r/OpenWebUI/), [X](https://x.com/OpenWebUI) i [Discordzie](https://discord.gg/5rJgQTnV4s).
|
||||
|
||||
### Bezpieczeństwo
|
||||
|
||||
Zgłaszaj luki poufnie przez [GitHub Security Advisories](https://github.com/open-webui/open-webui/security). Zgłoszenia dotyczące bezpieczeństwa przyjmujemy wyłącznie przez GitHub.
|
||||
|
||||
### Historia gwiazdek
|
||||
|
||||
<a href="https://star-history.com/#open-webui/open-webui&Date">
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=open-webui/open-webui&type=Date&theme=dark" />
|
||||
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=open-webui/open-webui&type=Date" />
|
||||
<img alt="Wykres historii gwiazdek" src="https://api.star-history.com/svg?repos=open-webui/open-webui&type=Date" />
|
||||
</picture>
|
||||
</a>
|
||||
|
||||
#### Licencja
|
||||
|
||||
Zawiera kod na licencji Open WebUI License, która wymaga zachowania oznaczeń marki Open WebUI, oraz wcześniejsze wkłady na ich oryginalnych licencjach. Warunki i historię znajdziesz w [LICENSE](./LICENSE) i [LICENSE_HISTORY](./LICENSE_HISTORY).
|
||||
|
||||
[Enterprise](https://docs.openwebui.com/enterprise) · [Kariera](https://careers.openwebui.com/) · [Wesprzyj](https://github.com/sponsors/open-webui)
|
||||
|
||||
Autor: [Timothy Jaeryang Baek](https://github.com/tjbck).
|
||||
132
README.ru.md
Normal file
132
README.ru.md
Normal file
|
|
@ -0,0 +1,132 @@
|
|||
<h2>Open WebUI</h2>
|
||||
|
||||
<p>Open WebUI — это <a href="https://docs.openwebui.com/"><strong>дом для ИИ</strong></a>: расширяемая и удобная платформа для самостоятельного размещения, способная работать полностью офлайн. Подключайте локальные модели через Ollama или используйте совместимые с OpenAI API для локальных и облачных моделей.</p>
|
||||
|
||||
[English](README.md) |
|
||||
[简体中文](README.zh.md) |
|
||||
[繁體中文](README.zht.md) |
|
||||
[한국어](README.ko.md) |
|
||||
[Deutsch](README.de.md) |
|
||||
[Español](README.es.md) |
|
||||
[Français](README.fr.md) |
|
||||
[Italiano](README.it.md) |
|
||||
[Dansk](README.da.md) |
|
||||
[日本語](README.ja.md) |
|
||||
[Polski](README.pl.md) |
|
||||
[Русский](README.ru.md) |
|
||||
[Bosanski](README.bs.md) |
|
||||
[العربية](README.ar.md) |
|
||||
[Norsk](README.no.md) |
|
||||
[Português (Brasil)](README.br.md) |
|
||||
[ไทย](README.th.md) |
|
||||
[Türkçe](README.tr.md) |
|
||||
[Українська](README.uk.md) |
|
||||
[বাংলা](README.bn.md) |
|
||||
[Ελληνικά](README.gr.md) |
|
||||
[Tiếng Việt](README.vi.md)
|
||||
|
||||
[](https://docs.openwebui.com/)
|
||||
|
||||

|
||||

|
||||

|
||||

|
||||

|
||||

|
||||

|
||||
[](https://discord.gg/5rJgQTnV4s)
|
||||
[](https://github.com/sponsors/open-webui)
|
||||
|
||||
[Знакомство с Open WebUI →](https://docs.openwebui.com/)
|
||||
|
||||
### Установка
|
||||
|
||||
#### Python
|
||||
|
||||
Требуется Python 3.12.
|
||||
|
||||
```bash
|
||||
pip install open-webui
|
||||
open-webui serve
|
||||
```
|
||||
|
||||
Затем откройте [http://localhost:8080](http://localhost:8080).
|
||||
|
||||
#### Docker
|
||||
|
||||
```bash
|
||||
docker run -d -p 3000:8080 --add-host=host.docker.internal:host-gateway -v open-webui:/app/backend/data --name open-webui --restart always ghcr.io/open-webui/open-webui:main
|
||||
```
|
||||
|
||||
Затем откройте [http://localhost:3000](http://localhost:3000).
|
||||
|
||||
| Тег образа | Содержимое |
|
||||
| --- | --- |
|
||||
| `:main` | Стандартный образ с зависимостями для локального ИИ |
|
||||
| `:slim` | Облегчённый образ с внешними сервисами для эмбеддингов, извлечения данных из документов и обработки речи |
|
||||
| `:cuda` | Open WebUI с ускорением CUDA |
|
||||
| `:ollama` | Open WebUI со встроенным Ollama |
|
||||
| `:dev` | Последняя сборка для разработки |
|
||||
|
||||
При необходимости добавьте эти параметры в `docker run` перед именем образа:
|
||||
|
||||
| Параметр | Назначение |
|
||||
| --- | --- |
|
||||
| `-e OLLAMA_BASE_URL=http://your-ollama-server:11434` | Подключение к Ollama на другом сервере |
|
||||
| `-e OPENAI_API_KEY=your_secret_key` | Установка ключа API OpenAI |
|
||||
| `-e HF_HUB_OFFLINE=1` | Отключение загрузки моделей Hugging Face для работы офлайн |
|
||||
| `--gpus all` | Доступ к GPU Nvidia для `:cuda` или `:ollama`; требуется Nvidia Container Toolkit |
|
||||
|
||||
Инструкции и параметры настройки приведены в [руководстве по установке через Docker](https://docs.openwebui.com/getting-started/quick-start/).
|
||||
|
||||
#### Приложение для компьютера
|
||||
|
||||
[Скачайте нативное приложение](https://github.com/open-webui/desktop) для macOS, Windows и Linux.
|
||||
|
||||
[Читать документацию →](https://docs.openwebui.com/getting-started/)
|
||||
|
||||
### Экосистема
|
||||
|
||||
- [Open Terminal](https://github.com/open-webui/open-terminal) / [Terminals (Enterprise)](https://github.com/open-webui/terminals): Слой выполнения действий, который превращает Open WebUI в полноценную среду для агентов, с корпоративной оркестрацией отдельных рабочих пространств пользователей.
|
||||
- [Knowledge Base Sync (oikb)](https://github.com/open-webui/oikb): Зеркалирование папок, репозиториев, бакетов и вики в базы знаний Open WebUI с инкрементальной синхронизацией.
|
||||
- [Open WebUI Computer](https://github.com/open-webui/computer): Ваш компьютер в любом браузере: файлы, редактор, терминал, Git и необязательные ИИ-агенты, работающие на вашей реальной машине.
|
||||
|
||||
Подробнее — в [документации экосистемы](https://docs.openwebui.com/ecosystem/).
|
||||
|
||||
### Устранение неполадок и обновления
|
||||
|
||||
При проблемах с подключением обратитесь к [руководству по устранению неполадок](https://docs.openwebui.com/troubleshooting/), а для обновления установки — к [руководству по обновлению](https://docs.openwebui.com/getting-started/updating).
|
||||
|
||||
### Документация
|
||||
|
||||
Настройка и использование описаны в [документации](https://docs.openwebui.com/), а запланированные работы — в [дорожной карте](https://docs.openwebui.com/roadmap/).
|
||||
|
||||
Для Docker Compose, Kubernetes и других вариантов установки см. [документацию по установке](https://docs.openwebui.com/getting-started/).
|
||||
|
||||
### Поддержка
|
||||
|
||||
[Создайте issue](https://github.com/open-webui/open-webui/issues) или [начните обсуждение](https://github.com/open-webui/open-webui/discussions).
|
||||
|
||||
Мы есть на [Reddit](https://www.reddit.com/r/OpenWebUI/), [X](https://x.com/OpenWebUI) и [Discord](https://discord.gg/5rJgQTnV4s).
|
||||
|
||||
### Безопасность
|
||||
|
||||
Сообщайте об уязвимостях конфиденциально через [GitHub Security Advisories](https://github.com/open-webui/open-webui/security). Сообщения о безопасности принимаются только через GitHub.
|
||||
|
||||
### История звёзд
|
||||
|
||||
<a href="https://star-history.com/#open-webui/open-webui&Date">
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=open-webui/open-webui&type=Date&theme=dark" />
|
||||
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=open-webui/open-webui&type=Date" />
|
||||
<img alt="График истории звёзд" src="https://api.star-history.com/svg?repos=open-webui/open-webui&type=Date" />
|
||||
</picture>
|
||||
</a>
|
||||
|
||||
#### Лицензия
|
||||
|
||||
Включает код под Open WebUI License, которая требует сохранения брендинга Open WebUI, а также предыдущие вклады под их исходными лицензиями. Условия и история приведены в [LICENSE](./LICENSE) и [LICENSE_HISTORY](./LICENSE_HISTORY).
|
||||
|
||||
[Для организаций](https://docs.openwebui.com/enterprise) · [Карьера](https://careers.openwebui.com/) · [Поддержать проект](https://github.com/sponsors/open-webui)
|
||||
|
||||
Автор: [Timothy Jaeryang Baek](https://github.com/tjbck).
|
||||
132
README.th.md
Normal file
132
README.th.md
Normal file
|
|
@ -0,0 +1,132 @@
|
|||
<h2>Open WebUI</h2>
|
||||
|
||||
<p>Open WebUI คือ <a href="https://docs.openwebui.com/"><strong>บ้านสำหรับ AI</strong></a>: แพลตฟอร์มที่โฮสต์เองได้ ขยายความสามารถได้ ใช้งานง่าย และออกแบบให้ทำงานแบบออฟไลน์ได้ทั้งหมด เชื่อมต่อโมเดลภายในเครื่องผ่าน Ollama หรือใช้ API ที่เข้ากันได้กับ OpenAI สำหรับโมเดลภายในเครื่องและบนคลาวด์</p>
|
||||
|
||||
[English](README.md) |
|
||||
[简体中文](README.zh.md) |
|
||||
[繁體中文](README.zht.md) |
|
||||
[한국어](README.ko.md) |
|
||||
[Deutsch](README.de.md) |
|
||||
[Español](README.es.md) |
|
||||
[Français](README.fr.md) |
|
||||
[Italiano](README.it.md) |
|
||||
[Dansk](README.da.md) |
|
||||
[日本語](README.ja.md) |
|
||||
[Polski](README.pl.md) |
|
||||
[Русский](README.ru.md) |
|
||||
[Bosanski](README.bs.md) |
|
||||
[العربية](README.ar.md) |
|
||||
[Norsk](README.no.md) |
|
||||
[Português (Brasil)](README.br.md) |
|
||||
[ไทย](README.th.md) |
|
||||
[Türkçe](README.tr.md) |
|
||||
[Українська](README.uk.md) |
|
||||
[বাংলা](README.bn.md) |
|
||||
[Ελληνικά](README.gr.md) |
|
||||
[Tiếng Việt](README.vi.md)
|
||||
|
||||
[](https://docs.openwebui.com/)
|
||||
|
||||

|
||||

|
||||

|
||||

|
||||

|
||||

|
||||

|
||||
[](https://discord.gg/5rJgQTnV4s)
|
||||
[](https://github.com/sponsors/open-webui)
|
||||
|
||||
[สำรวจ Open WebUI →](https://docs.openwebui.com/)
|
||||
|
||||
### การติดตั้ง
|
||||
|
||||
#### Python
|
||||
|
||||
ต้องใช้ Python 3.12
|
||||
|
||||
```bash
|
||||
pip install open-webui
|
||||
open-webui serve
|
||||
```
|
||||
|
||||
จากนั้นเปิด [http://localhost:8080](http://localhost:8080)
|
||||
|
||||
#### Docker
|
||||
|
||||
```bash
|
||||
docker run -d -p 3000:8080 --add-host=host.docker.internal:host-gateway -v open-webui:/app/backend/data --name open-webui --restart always ghcr.io/open-webui/open-webui:main
|
||||
```
|
||||
|
||||
จากนั้นเปิด [http://localhost:3000](http://localhost:3000)
|
||||
|
||||
| แท็กอิมเมจ | สิ่งที่มีให้ |
|
||||
| --- | --- |
|
||||
| `:main` | อิมเมจมาตรฐานพร้อมแพ็กเกจที่จำเป็นสำหรับ AI ภายในเครื่อง |
|
||||
| `:slim` | อิมเมจขนาดเล็กที่ใช้บริการภายนอกสำหรับ embeddings การสกัดข้อมูลจากเอกสาร และเสียง |
|
||||
| `:cuda` | Open WebUI พร้อมการเร่งความเร็วด้วย CUDA |
|
||||
| `:ollama` | Open WebUI ที่รวม Ollama มาให้ |
|
||||
| `:dev` | บิลด์สำหรับการพัฒนาล่าสุด |
|
||||
|
||||
เพิ่มตัวเลือกเหล่านี้ใน `docker run` ก่อนชื่ออิมเมจได้ตามต้องการ:
|
||||
|
||||
| ตัวเลือก | จุดประสงค์ |
|
||||
| --- | --- |
|
||||
| `-e OLLAMA_BASE_URL=http://your-ollama-server:11434` | เชื่อมต่อกับ Ollama บนเซิร์ฟเวอร์อื่น |
|
||||
| `-e OPENAI_API_KEY=your_secret_key` | กำหนดคีย์ API ของ OpenAI |
|
||||
| `-e HF_HUB_OFFLINE=1` | ปิดการดาวน์โหลดโมเดลจาก Hugging Face สำหรับการใช้งานออฟไลน์ |
|
||||
| `--gpus all` | เปิดใช้ GPU Nvidia สำหรับ `:cuda` หรือ `:ollama` โดยต้องมี Nvidia Container Toolkit |
|
||||
|
||||
ดูขั้นตอนการติดตั้งและตัวเลือกการตั้งค่าใน[คู่มือการติดตั้งด้วย Docker](https://docs.openwebui.com/getting-started/quick-start/)
|
||||
|
||||
#### แอปเดสก์ท็อป
|
||||
|
||||
[ดาวน์โหลดแอปเดสก์ท็อปเนทีฟ](https://github.com/open-webui/desktop)สำหรับ macOS, Windows และ Linux
|
||||
|
||||
[อ่านเอกสาร →](https://docs.openwebui.com/getting-started/)
|
||||
|
||||
### ระบบนิเวศ
|
||||
|
||||
- [Open Terminal](https://github.com/open-webui/open-terminal) / [Terminals (Enterprise)](https://github.com/open-webui/terminals): ชั้นการทำงานที่ทำให้ Open WebUI เป็นสภาพแวดล้อมเอเจนต์ที่ครบถ้วน พร้อมระบบจัดการพื้นที่ทำงานแยกตามผู้ใช้ในระดับองค์กร
|
||||
- [Knowledge Base Sync (oikb)](https://github.com/open-webui/oikb): ทำสำเนาโฟลเดอร์ รีโพซิทอรี บักเก็ต และวิกิลงในฐานความรู้ Open WebUI ด้วยการซิงก์เฉพาะส่วนที่เปลี่ยนแปลง
|
||||
- [Open WebUI Computer](https://github.com/open-webui/computer): คอมพิวเตอร์ของคุณในทุกเบราว์เซอร์: ไฟล์ ตัวแก้ไข เทอร์มินัล Git และเอเจนต์ AI ที่เลือกใช้ได้ ทั้งหมดทำงานบนเครื่องจริงของคุณ
|
||||
|
||||
ดูรายละเอียดใน[เอกสารระบบนิเวศ](https://docs.openwebui.com/ecosystem/)
|
||||
|
||||
### การแก้ไขปัญหาและการอัปเดต
|
||||
|
||||
ดู[คู่มือแก้ไขปัญหา](https://docs.openwebui.com/troubleshooting/)สำหรับปัญหาการเชื่อมต่อ และ[คู่มืออัปเดต](https://docs.openwebui.com/getting-started/updating)เพื่ออัปเดตการติดตั้งของคุณ
|
||||
|
||||
### เอกสาร
|
||||
|
||||
ดู[เอกสาร](https://docs.openwebui.com/)สำหรับการตั้งค่าและการใช้งาน และ[แผนการพัฒนา](https://docs.openwebui.com/roadmap/)สำหรับงานที่วางแผนไว้
|
||||
|
||||
สำหรับ Docker Compose, Kubernetes และการติดตั้งแบบอื่น ๆ ดู[เอกสารการติดตั้ง](https://docs.openwebui.com/getting-started/)
|
||||
|
||||
### การช่วยเหลือ
|
||||
|
||||
[เปิด issue](https://github.com/open-webui/open-webui/issues) หรือ[เริ่มการสนทนา](https://github.com/open-webui/open-webui/discussions)
|
||||
|
||||
พบเราได้ที่ [Reddit](https://www.reddit.com/r/OpenWebUI/), [X](https://x.com/OpenWebUI) และ [Discord](https://discord.gg/5rJgQTnV4s)
|
||||
|
||||
### ความปลอดภัย
|
||||
|
||||
รายงานช่องโหว่แบบเป็นส่วนตัวผ่าน [GitHub Security Advisories](https://github.com/open-webui/open-webui/security) โดยรับรายงานด้านความปลอดภัยผ่าน GitHub เท่านั้น
|
||||
|
||||
### ประวัติจำนวนดาว
|
||||
|
||||
<a href="https://star-history.com/#open-webui/open-webui&Date">
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=open-webui/open-webui&type=Date&theme=dark" />
|
||||
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=open-webui/open-webui&type=Date" />
|
||||
<img alt="กราฟประวัติจำนวนดาว" src="https://api.star-history.com/svg?repos=open-webui/open-webui&type=Date" />
|
||||
</picture>
|
||||
</a>
|
||||
|
||||
#### สัญญาอนุญาต
|
||||
|
||||
มีโค้ดภายใต้ Open WebUI License ซึ่งกำหนดให้คงแบรนด์ Open WebUI ไว้ รวมถึงผลงานที่มีผู้ร่วมพัฒนาก่อนหน้านี้ภายใต้สัญญาอนุญาตเดิมของแต่ละส่วน ดูเงื่อนไขและประวัติได้ที่ [LICENSE](./LICENSE) และ [LICENSE_HISTORY](./LICENSE_HISTORY)
|
||||
|
||||
[องค์กร](https://docs.openwebui.com/enterprise) · [ร่วมงานกับเรา](https://careers.openwebui.com/) · [สนับสนุนโครงการ](https://github.com/sponsors/open-webui)
|
||||
|
||||
สร้างโดย [Timothy Jaeryang Baek](https://github.com/tjbck)
|
||||
132
README.tr.md
Normal file
132
README.tr.md
Normal file
|
|
@ -0,0 +1,132 @@
|
|||
<h2>Open WebUI</h2>
|
||||
|
||||
<p>Open WebUI, <a href="https://docs.openwebui.com/"><strong>yapay zekâ için bir yuva</strong></a>dır: tamamen çevrimdışı çalışmak üzere tasarlanmış, genişletilebilir, kullanımı kolay ve kendi sunucunuzda barındırabileceğiniz bir platform. Yerel modellere Ollama üzerinden bağlanın veya yerel ve bulut modelleri için OpenAI uyumlu API’leri kullanın.</p>
|
||||
|
||||
[English](README.md) |
|
||||
[简体中文](README.zh.md) |
|
||||
[繁體中文](README.zht.md) |
|
||||
[한국어](README.ko.md) |
|
||||
[Deutsch](README.de.md) |
|
||||
[Español](README.es.md) |
|
||||
[Français](README.fr.md) |
|
||||
[Italiano](README.it.md) |
|
||||
[Dansk](README.da.md) |
|
||||
[日本語](README.ja.md) |
|
||||
[Polski](README.pl.md) |
|
||||
[Русский](README.ru.md) |
|
||||
[Bosanski](README.bs.md) |
|
||||
[العربية](README.ar.md) |
|
||||
[Norsk](README.no.md) |
|
||||
[Português (Brasil)](README.br.md) |
|
||||
[ไทย](README.th.md) |
|
||||
[Türkçe](README.tr.md) |
|
||||
[Українська](README.uk.md) |
|
||||
[বাংলা](README.bn.md) |
|
||||
[Ελληνικά](README.gr.md) |
|
||||
[Tiếng Việt](README.vi.md)
|
||||
|
||||
[](https://docs.openwebui.com/)
|
||||
|
||||

|
||||

|
||||

|
||||

|
||||

|
||||

|
||||

|
||||
[](https://discord.gg/5rJgQTnV4s)
|
||||
[](https://github.com/sponsors/open-webui)
|
||||
|
||||
[Open WebUI’ı keşfedin →](https://docs.openwebui.com/)
|
||||
|
||||
### Kurulum
|
||||
|
||||
#### Python
|
||||
|
||||
Python 3.12 gerektirir.
|
||||
|
||||
```bash
|
||||
pip install open-webui
|
||||
open-webui serve
|
||||
```
|
||||
|
||||
Ardından [http://localhost:8080](http://localhost:8080) adresini açın.
|
||||
|
||||
#### Docker
|
||||
|
||||
```bash
|
||||
docker run -d -p 3000:8080 --add-host=host.docker.internal:host-gateway -v open-webui:/app/backend/data --name open-webui --restart always ghcr.io/open-webui/open-webui:main
|
||||
```
|
||||
|
||||
Ardından [http://localhost:3000](http://localhost:3000) adresini açın.
|
||||
|
||||
| İmaj etiketi | İçerik |
|
||||
| --- | --- |
|
||||
| `:main` | Yerel yapay zekâ bağımlılıklarını içeren standart imaj |
|
||||
| `:slim` | Gömme vektörleri, belge çıkarımı ve ses için harici hizmetler kullanan hafif imaj |
|
||||
| `:cuda` | CUDA hızlandırmalı Open WebUI |
|
||||
| `:ollama` | Ollama ile birlikte gelen Open WebUI |
|
||||
| `:dev` | En son geliştirme derlemesi |
|
||||
|
||||
Gerektiğinde bu seçenekleri `docker run` komutunda imaj adından önce ekleyin:
|
||||
|
||||
| Seçenek | Amaç |
|
||||
| --- | --- |
|
||||
| `-e OLLAMA_BASE_URL=http://your-ollama-server:11434` | Başka bir sunucudaki Ollama’ya bağlanma |
|
||||
| `-e OPENAI_API_KEY=your_secret_key` | OpenAI API anahtarınızı ayarlama |
|
||||
| `-e HF_HUB_OFFLINE=1` | Çevrimdışı kullanım için Hugging Face model indirmelerini devre dışı bırakma |
|
||||
| `--gpus all` | `:cuda` veya `:ollama` için Nvidia GPU erişimini etkinleştirme; Nvidia Container Toolkit gerektirir |
|
||||
|
||||
Kurulum adımları ve yapılandırma seçenekleri için [Docker kurulum kılavuzuna](https://docs.openwebui.com/getting-started/quick-start/) bakın.
|
||||
|
||||
#### Masaüstü uygulaması
|
||||
|
||||
macOS, Windows ve Linux için [yerel masaüstü uygulamasını indirin](https://github.com/open-webui/desktop).
|
||||
|
||||
[Belgeleri okuyun →](https://docs.openwebui.com/getting-started/)
|
||||
|
||||
### Ekosistem
|
||||
|
||||
- [Open Terminal](https://github.com/open-webui/open-terminal) / [Terminals (Enterprise)](https://github.com/open-webui/terminals): Open WebUI’ı eksiksiz bir ajan çalışma ortamına dönüştüren yürütme katmanı; kullanıcıya özel çalışma alanları için kurumsal orkestrasyon sunar.
|
||||
- [Knowledge Base Sync (oikb)](https://github.com/open-webui/oikb): Klasörleri, depoları, nesne depolama kovalarını ve vikileri artımlı eşitleme ile Open WebUI bilgi tabanlarına yansıtın.
|
||||
- [Open WebUI Computer](https://github.com/open-webui/computer): Bilgisayarınız her tarayıcıda: dosyalar, düzenleyici, terminal, Git ve isteğe bağlı yapay zekâ ajanları kendi gerçek makinenizde çalışır.
|
||||
|
||||
Ayrıntılar için [ekosistem belgelerine](https://docs.openwebui.com/ecosystem/) bakın.
|
||||
|
||||
### Sorun giderme ve güncellemeler
|
||||
|
||||
Bağlantı sorunları için [sorun giderme kılavuzuna](https://docs.openwebui.com/troubleshooting/), kurulumunuzu güncellemek için [güncelleme kılavuzuna](https://docs.openwebui.com/getting-started/updating) bakın.
|
||||
|
||||
### Belgeler
|
||||
|
||||
Yapılandırma ve kullanım için [belgelere](https://docs.openwebui.com/), planlanan çalışmalar için [yol haritasına](https://docs.openwebui.com/roadmap/) bakın.
|
||||
|
||||
Docker Compose, Kubernetes ve diğer kurulumlar için [kurulum belgelerine](https://docs.openwebui.com/getting-started/) bakın.
|
||||
|
||||
### Destek
|
||||
|
||||
[Bir issue açın](https://github.com/open-webui/open-webui/issues) veya [tartışma başlatın](https://github.com/open-webui/open-webui/discussions).
|
||||
|
||||
Bizi [Reddit](https://www.reddit.com/r/OpenWebUI/), [X](https://x.com/OpenWebUI) ve [Discord](https://discord.gg/5rJgQTnV4s) üzerinde bulabilirsiniz.
|
||||
|
||||
### Güvenlik
|
||||
|
||||
Güvenlik açıklarını [GitHub Security Advisories](https://github.com/open-webui/open-webui/security) üzerinden gizli olarak bildirin. Güvenlik bildirimleri yalnızca GitHub üzerinden kabul edilir.
|
||||
|
||||
### Yıldız geçmişi
|
||||
|
||||
<a href="https://star-history.com/#open-webui/open-webui&Date">
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=open-webui/open-webui&type=Date&theme=dark" />
|
||||
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=open-webui/open-webui&type=Date" />
|
||||
<img alt="Yıldız geçmişi grafiği" src="https://api.star-history.com/svg?repos=open-webui/open-webui&type=Date" />
|
||||
</picture>
|
||||
</a>
|
||||
|
||||
#### Lisans
|
||||
|
||||
Open WebUI markasının korunmasını gerektiren Open WebUI License kapsamındaki kodu ve kendi özgün lisanslarına tabi önceki katkıları içerir. Koşullar ve geçmiş için [LICENSE](./LICENSE) ve [LICENSE_HISTORY](./LICENSE_HISTORY) dosyalarına bakın.
|
||||
|
||||
[Kurumsal](https://docs.openwebui.com/enterprise) · [Kariyer](https://careers.openwebui.com/) · [Sponsor olun](https://github.com/sponsors/open-webui)
|
||||
|
||||
Geliştiren: [Timothy Jaeryang Baek](https://github.com/tjbck).
|
||||
132
README.uk.md
Normal file
132
README.uk.md
Normal file
|
|
@ -0,0 +1,132 @@
|
|||
<h2>Open WebUI</h2>
|
||||
|
||||
<p>Open WebUI — це <a href="https://docs.openwebui.com/"><strong>дім для ШІ</strong></a>: розширювана й зручна платформа для самостійного розгортання, здатна працювати повністю офлайн. Підключайте локальні моделі через Ollama або використовуйте сумісні з OpenAI API для локальних і хмарних моделей.</p>
|
||||
|
||||
[English](README.md) |
|
||||
[简体中文](README.zh.md) |
|
||||
[繁體中文](README.zht.md) |
|
||||
[한국어](README.ko.md) |
|
||||
[Deutsch](README.de.md) |
|
||||
[Español](README.es.md) |
|
||||
[Français](README.fr.md) |
|
||||
[Italiano](README.it.md) |
|
||||
[Dansk](README.da.md) |
|
||||
[日本語](README.ja.md) |
|
||||
[Polski](README.pl.md) |
|
||||
[Русский](README.ru.md) |
|
||||
[Bosanski](README.bs.md) |
|
||||
[العربية](README.ar.md) |
|
||||
[Norsk](README.no.md) |
|
||||
[Português (Brasil)](README.br.md) |
|
||||
[ไทย](README.th.md) |
|
||||
[Türkçe](README.tr.md) |
|
||||
[Українська](README.uk.md) |
|
||||
[বাংলা](README.bn.md) |
|
||||
[Ελληνικά](README.gr.md) |
|
||||
[Tiếng Việt](README.vi.md)
|
||||
|
||||
[](https://docs.openwebui.com/)
|
||||
|
||||

|
||||

|
||||

|
||||

|
||||

|
||||

|
||||

|
||||
[](https://discord.gg/5rJgQTnV4s)
|
||||
[](https://github.com/sponsors/open-webui)
|
||||
|
||||
[Дізнатися про Open WebUI →](https://docs.openwebui.com/)
|
||||
|
||||
### Встановлення
|
||||
|
||||
#### Python
|
||||
|
||||
Потрібен Python 3.12.
|
||||
|
||||
```bash
|
||||
pip install open-webui
|
||||
open-webui serve
|
||||
```
|
||||
|
||||
Потім відкрийте [http://localhost:8080](http://localhost:8080).
|
||||
|
||||
#### Docker
|
||||
|
||||
```bash
|
||||
docker run -d -p 3000:8080 --add-host=host.docker.internal:host-gateway -v open-webui:/app/backend/data --name open-webui --restart always ghcr.io/open-webui/open-webui:main
|
||||
```
|
||||
|
||||
Потім відкрийте [http://localhost:3000](http://localhost:3000).
|
||||
|
||||
| Тег образу | Вміст |
|
||||
| --- | --- |
|
||||
| `:main` | Стандартний образ із залежностями для локального ШІ |
|
||||
| `:slim` | Полегшений образ із зовнішніми сервісами для ембедингів, видобування даних із документів і обробки мовлення |
|
||||
| `:cuda` | Open WebUI з прискоренням CUDA |
|
||||
| `:ollama` | Open WebUI із вбудованим Ollama |
|
||||
| `:dev` | Найновіша збірка для розробки |
|
||||
|
||||
За потреби додайте ці параметри до `docker run` перед назвою образу:
|
||||
|
||||
| Параметр | Призначення |
|
||||
| --- | --- |
|
||||
| `-e OLLAMA_BASE_URL=http://your-ollama-server:11434` | Підключення до Ollama на іншому сервері |
|
||||
| `-e OPENAI_API_KEY=your_secret_key` | Встановлення ключа API OpenAI |
|
||||
| `-e HF_HUB_OFFLINE=1` | Вимкнення завантаження моделей Hugging Face для роботи офлайн |
|
||||
| `--gpus all` | Доступ до GPU Nvidia для `:cuda` або `:ollama`; потрібен Nvidia Container Toolkit |
|
||||
|
||||
Інструкції та параметри налаштування наведено в [посібнику зі встановлення через Docker](https://docs.openwebui.com/getting-started/quick-start/).
|
||||
|
||||
#### Настільний застосунок
|
||||
|
||||
[Завантажте нативний настільний застосунок](https://github.com/open-webui/desktop) для macOS, Windows і Linux.
|
||||
|
||||
[Читати документацію →](https://docs.openwebui.com/getting-started/)
|
||||
|
||||
### Екосистема
|
||||
|
||||
- [Open Terminal](https://github.com/open-webui/open-terminal) / [Terminals (Enterprise)](https://github.com/open-webui/terminals): Шар виконання дій, який перетворює Open WebUI на повноцінне середовище для агентів, із корпоративною оркестрацією окремих робочих просторів користувачів.
|
||||
- [Knowledge Base Sync (oikb)](https://github.com/open-webui/oikb): Дзеркальне копіювання папок, репозиторіїв, бакетів і вікі до баз знань Open WebUI з інкрементальною синхронізацією.
|
||||
- [Open WebUI Computer](https://github.com/open-webui/computer): Ваш комп’ютер у будь-якому браузері: файли, редактор, термінал, Git і необов’язкові ШІ-агенти, що працюють на вашій реальній машині.
|
||||
|
||||
Докладніше — у [документації екосистеми](https://docs.openwebui.com/ecosystem/).
|
||||
|
||||
### Усунення несправностей та оновлення
|
||||
|
||||
У разі проблем із підключенням дивіться [посібник з усунення несправностей](https://docs.openwebui.com/troubleshooting/), а для оновлення інсталяції — [посібник з оновлення](https://docs.openwebui.com/getting-started/updating).
|
||||
|
||||
### Документація
|
||||
|
||||
Налаштування й використання описано в [документації](https://docs.openwebui.com/), а заплановані роботи — у [дорожній карті](https://docs.openwebui.com/roadmap/).
|
||||
|
||||
Для Docker Compose, Kubernetes та інших способів встановлення дивіться [документацію зі встановлення](https://docs.openwebui.com/getting-started/).
|
||||
|
||||
### Підтримка
|
||||
|
||||
[Створіть issue](https://github.com/open-webui/open-webui/issues) або [розпочніть обговорення](https://github.com/open-webui/open-webui/discussions).
|
||||
|
||||
Знайдіть нас на [Reddit](https://www.reddit.com/r/OpenWebUI/), [X](https://x.com/OpenWebUI) і [Discord](https://discord.gg/5rJgQTnV4s).
|
||||
|
||||
### Безпека
|
||||
|
||||
Повідомляйте про вразливості конфіденційно через [GitHub Security Advisories](https://github.com/open-webui/open-webui/security). Повідомлення про безпеку приймаються лише через GitHub.
|
||||
|
||||
### Історія зірок
|
||||
|
||||
<a href="https://star-history.com/#open-webui/open-webui&Date">
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=open-webui/open-webui&type=Date&theme=dark" />
|
||||
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=open-webui/open-webui&type=Date" />
|
||||
<img alt="Графік історії зірок" src="https://api.star-history.com/svg?repos=open-webui/open-webui&type=Date" />
|
||||
</picture>
|
||||
</a>
|
||||
|
||||
#### Ліцензія
|
||||
|
||||
Містить код під Open WebUI License, яка вимагає збереження брендингу Open WebUI, а також попередні внески під їхніми початковими ліцензіями. Умови й історію наведено в [LICENSE](./LICENSE) та [LICENSE_HISTORY](./LICENSE_HISTORY).
|
||||
|
||||
[Для організацій](https://docs.openwebui.com/enterprise) · [Кар’єра](https://careers.openwebui.com/) · [Підтримати проєкт](https://github.com/sponsors/open-webui)
|
||||
|
||||
Автор: [Timothy Jaeryang Baek](https://github.com/tjbck).
|
||||
132
README.vi.md
Normal file
132
README.vi.md
Normal file
|
|
@ -0,0 +1,132 @@
|
|||
<h2>Open WebUI</h2>
|
||||
|
||||
<p>Open WebUI là <a href="https://docs.openwebui.com/"><strong>ngôi nhà dành cho AI</strong></a>: một nền tảng tự lưu trữ, dễ mở rộng, dễ sử dụng và được thiết kế để hoạt động hoàn toàn ngoại tuyến. Kết nối mô hình cục bộ qua Ollama hoặc dùng API tương thích với OpenAI cho các mô hình cục bộ và trên đám mây.</p>
|
||||
|
||||
[English](README.md) |
|
||||
[简体中文](README.zh.md) |
|
||||
[繁體中文](README.zht.md) |
|
||||
[한국어](README.ko.md) |
|
||||
[Deutsch](README.de.md) |
|
||||
[Español](README.es.md) |
|
||||
[Français](README.fr.md) |
|
||||
[Italiano](README.it.md) |
|
||||
[Dansk](README.da.md) |
|
||||
[日本語](README.ja.md) |
|
||||
[Polski](README.pl.md) |
|
||||
[Русский](README.ru.md) |
|
||||
[Bosanski](README.bs.md) |
|
||||
[العربية](README.ar.md) |
|
||||
[Norsk](README.no.md) |
|
||||
[Português (Brasil)](README.br.md) |
|
||||
[ไทย](README.th.md) |
|
||||
[Türkçe](README.tr.md) |
|
||||
[Українська](README.uk.md) |
|
||||
[বাংলা](README.bn.md) |
|
||||
[Ελληνικά](README.gr.md) |
|
||||
[Tiếng Việt](README.vi.md)
|
||||
|
||||
[](https://docs.openwebui.com/)
|
||||
|
||||

|
||||

|
||||

|
||||

|
||||

|
||||

|
||||

|
||||
[](https://discord.gg/5rJgQTnV4s)
|
||||
[](https://github.com/sponsors/open-webui)
|
||||
|
||||
[Khám phá Open WebUI →](https://docs.openwebui.com/)
|
||||
|
||||
### Cài đặt
|
||||
|
||||
#### Python
|
||||
|
||||
Yêu cầu Python 3.12.
|
||||
|
||||
```bash
|
||||
pip install open-webui
|
||||
open-webui serve
|
||||
```
|
||||
|
||||
Sau đó mở [http://localhost:8080](http://localhost:8080).
|
||||
|
||||
#### Docker
|
||||
|
||||
```bash
|
||||
docker run -d -p 3000:8080 --add-host=host.docker.internal:host-gateway -v open-webui:/app/backend/data --name open-webui --restart always ghcr.io/open-webui/open-webui:main
|
||||
```
|
||||
|
||||
Sau đó mở [http://localhost:3000](http://localhost:3000).
|
||||
|
||||
| Thẻ image | Nội dung |
|
||||
| --- | --- |
|
||||
| `:main` | Image tiêu chuẩn với các thư viện phụ thuộc cho AI cục bộ |
|
||||
| `:slim` | Image gọn nhẹ dùng dịch vụ bên ngoài cho embedding, trích xuất tài liệu và giọng nói |
|
||||
| `:cuda` | Open WebUI với tăng tốc CUDA |
|
||||
| `:ollama` | Open WebUI tích hợp sẵn Ollama |
|
||||
| `:dev` | Bản dựng phát triển mới nhất |
|
||||
|
||||
Thêm các tùy chọn sau vào `docker run` trước tên image khi cần:
|
||||
|
||||
| Tùy chọn | Mục đích |
|
||||
| --- | --- |
|
||||
| `-e OLLAMA_BASE_URL=http://your-ollama-server:11434` | Kết nối đến Ollama trên máy chủ khác |
|
||||
| `-e OPENAI_API_KEY=your_secret_key` | Thiết lập khóa API OpenAI |
|
||||
| `-e HF_HUB_OFFLINE=1` | Tắt tải mô hình Hugging Face để sử dụng ngoại tuyến |
|
||||
| `--gpus all` | Bật quyền truy cập GPU Nvidia cho `:cuda` hoặc `:ollama`; yêu cầu Nvidia Container Toolkit |
|
||||
|
||||
Xem [hướng dẫn cài đặt Docker](https://docs.openwebui.com/getting-started/quick-start/) để biết các bước thiết lập và tùy chọn cấu hình.
|
||||
|
||||
#### Ứng dụng máy tính
|
||||
|
||||
[Tải ứng dụng máy tính gốc](https://github.com/open-webui/desktop) cho macOS, Windows và Linux.
|
||||
|
||||
[Đọc tài liệu →](https://docs.openwebui.com/getting-started/)
|
||||
|
||||
### Hệ sinh thái
|
||||
|
||||
- [Open Terminal](https://github.com/open-webui/open-terminal) / [Terminals (Enterprise)](https://github.com/open-webui/terminals): Lớp thực thi biến Open WebUI thành môi trường tác tử hoàn chỉnh, với khả năng điều phối cấp doanh nghiệp cho không gian làm việc riêng của từng người dùng.
|
||||
- [Knowledge Base Sync (oikb)](https://github.com/open-webui/oikb): Đồng bộ các thư mục, kho mã, bucket và wiki vào cơ sở tri thức Open WebUI theo kiểu gia tăng.
|
||||
- [Open WebUI Computer](https://github.com/open-webui/computer): Máy tính của bạn trong bất kỳ trình duyệt nào: tệp, trình soạn thảo, terminal, Git và các tác tử AI tùy chọn đều chạy trên máy thật của bạn.
|
||||
|
||||
Xem [tài liệu hệ sinh thái](https://docs.openwebui.com/ecosystem/) để biết chi tiết.
|
||||
|
||||
### Khắc phục sự cố và cập nhật
|
||||
|
||||
Xem [hướng dẫn khắc phục sự cố](https://docs.openwebui.com/troubleshooting/) khi gặp vấn đề kết nối và [hướng dẫn cập nhật](https://docs.openwebui.com/getting-started/updating) để cập nhật bản cài đặt.
|
||||
|
||||
### Tài liệu
|
||||
|
||||
Xem [tài liệu](https://docs.openwebui.com/) để biết cách cấu hình và sử dụng, cùng [lộ trình](https://docs.openwebui.com/roadmap/) cho các công việc dự kiến.
|
||||
|
||||
Với Docker Compose, Kubernetes và các cách thiết lập khác, xem [tài liệu cài đặt](https://docs.openwebui.com/getting-started/).
|
||||
|
||||
### Hỗ trợ
|
||||
|
||||
[Tạo issue](https://github.com/open-webui/open-webui/issues) hoặc [bắt đầu thảo luận](https://github.com/open-webui/open-webui/discussions).
|
||||
|
||||
Tìm chúng tôi trên [Reddit](https://www.reddit.com/r/OpenWebUI/), [X](https://x.com/OpenWebUI) và [Discord](https://discord.gg/5rJgQTnV4s).
|
||||
|
||||
### Bảo mật
|
||||
|
||||
Báo cáo lỗ hổng một cách riêng tư qua [GitHub Security Advisories](https://github.com/open-webui/open-webui/security). Báo cáo bảo mật chỉ được tiếp nhận qua GitHub.
|
||||
|
||||
### Lịch sử sao
|
||||
|
||||
<a href="https://star-history.com/#open-webui/open-webui&Date">
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=open-webui/open-webui&type=Date&theme=dark" />
|
||||
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=open-webui/open-webui&type=Date" />
|
||||
<img alt="Biểu đồ lịch sử sao" src="https://api.star-history.com/svg?repos=open-webui/open-webui&type=Date" />
|
||||
</picture>
|
||||
</a>
|
||||
|
||||
#### Giấy phép
|
||||
|
||||
Bao gồm mã theo Open WebUI License, yêu cầu giữ nguyên thương hiệu Open WebUI, và các đóng góp trước đây theo giấy phép gốc tương ứng. Xem [LICENSE](./LICENSE) và [LICENSE_HISTORY](./LICENSE_HISTORY) để biết điều khoản và lịch sử.
|
||||
|
||||
[Doanh nghiệp](https://docs.openwebui.com/enterprise) · [Tuyển dụng](https://careers.openwebui.com/) · [Tài trợ](https://github.com/sponsors/open-webui)
|
||||
|
||||
Được tạo bởi [Timothy Jaeryang Baek](https://github.com/tjbck).
|
||||
132
README.zh.md
Normal file
132
README.zh.md
Normal file
|
|
@ -0,0 +1,132 @@
|
|||
<h2>Open WebUI</h2>
|
||||
|
||||
<p>Open WebUI 是 <a href="https://docs.openwebui.com/"><strong>AI 的家</strong></a>:一个可扩展、易于使用的自托管平台,支持完全离线运行。通过 Ollama 连接本地模型,或使用兼容 OpenAI 的 API 连接本地和云端模型。</p>
|
||||
|
||||
[English](README.md) |
|
||||
[简体中文](README.zh.md) |
|
||||
[繁體中文](README.zht.md) |
|
||||
[한국어](README.ko.md) |
|
||||
[Deutsch](README.de.md) |
|
||||
[Español](README.es.md) |
|
||||
[Français](README.fr.md) |
|
||||
[Italiano](README.it.md) |
|
||||
[Dansk](README.da.md) |
|
||||
[日本語](README.ja.md) |
|
||||
[Polski](README.pl.md) |
|
||||
[Русский](README.ru.md) |
|
||||
[Bosanski](README.bs.md) |
|
||||
[العربية](README.ar.md) |
|
||||
[Norsk](README.no.md) |
|
||||
[Português (Brasil)](README.br.md) |
|
||||
[ไทย](README.th.md) |
|
||||
[Türkçe](README.tr.md) |
|
||||
[Українська](README.uk.md) |
|
||||
[বাংলা](README.bn.md) |
|
||||
[Ελληνικά](README.gr.md) |
|
||||
[Tiếng Việt](README.vi.md)
|
||||
|
||||
[](https://docs.openwebui.com/)
|
||||
|
||||

|
||||

|
||||

|
||||

|
||||

|
||||

|
||||

|
||||
[](https://discord.gg/5rJgQTnV4s)
|
||||
[](https://github.com/sponsors/open-webui)
|
||||
|
||||
[探索 Open WebUI →](https://docs.openwebui.com/)
|
||||
|
||||
### 安装
|
||||
|
||||
#### Python
|
||||
|
||||
需要 Python 3.12。
|
||||
|
||||
```bash
|
||||
pip install open-webui
|
||||
open-webui serve
|
||||
```
|
||||
|
||||
然后打开 [http://localhost:8080](http://localhost:8080)。
|
||||
|
||||
#### Docker
|
||||
|
||||
```bash
|
||||
docker run -d -p 3000:8080 --add-host=host.docker.internal:host-gateway -v open-webui:/app/backend/data --name open-webui --restart always ghcr.io/open-webui/open-webui:main
|
||||
```
|
||||
|
||||
然后打开 [http://localhost:3000](http://localhost:3000)。
|
||||
|
||||
| 镜像标签 | 内容 |
|
||||
| --- | --- |
|
||||
| `:main` | 包含本地 AI 依赖的标准镜像 |
|
||||
| `:slim` | 轻量镜像,通过外部服务处理嵌入、文档提取和语音 |
|
||||
| `:cuda` | 支持 CUDA 加速的 Open WebUI |
|
||||
| `:ollama` | 内置 Ollama 的 Open WebUI |
|
||||
| `:dev` | 最新开发版本 |
|
||||
|
||||
根据需要,在 `docker run` 的镜像名称前添加以下选项:
|
||||
|
||||
| 选项 | 用途 |
|
||||
| --- | --- |
|
||||
| `-e OLLAMA_BASE_URL=http://your-ollama-server:11434` | 连接另一台服务器上的 Ollama |
|
||||
| `-e OPENAI_API_KEY=your_secret_key` | 设置 OpenAI API 密钥 |
|
||||
| `-e HF_HUB_OFFLINE=1` | 禁用 Hugging Face 模型下载,以便离线使用 |
|
||||
| `--gpus all` | 为 `:cuda` 或 `:ollama` 启用 Nvidia GPU 访问;需要 Nvidia Container Toolkit |
|
||||
|
||||
安装步骤和配置选项请参阅 [Docker 安装指南](https://docs.openwebui.com/getting-started/quick-start/)。
|
||||
|
||||
#### 桌面应用
|
||||
|
||||
[下载原生桌面应用](https://github.com/open-webui/desktop),支持 macOS、Windows 和 Linux。
|
||||
|
||||
[阅读文档 →](https://docs.openwebui.com/getting-started/)
|
||||
|
||||
### 生态系统
|
||||
|
||||
- [Open Terminal](https://github.com/open-webui/open-terminal) / [Terminals (Enterprise)](https://github.com/open-webui/terminals): 为 Open WebUI 提供执行能力,使其成为完整的智能体运行框架,并通过企业级编排为每位用户管理独立工作空间。
|
||||
- [Knowledge Base Sync (oikb)](https://github.com/open-webui/oikb): 通过增量同步,将文件夹、代码仓库、存储桶和 Wiki 镜像到 Open WebUI 知识库。
|
||||
- [Open WebUI Computer](https://github.com/open-webui/computer): 在任意浏览器中使用你的电脑:文件、编辑器、终端、Git 和可选的 AI 智能体,均在你的真实机器上运行。
|
||||
|
||||
详情请参阅[生态系统文档](https://docs.openwebui.com/ecosystem/)。
|
||||
|
||||
### 故障排查与更新
|
||||
|
||||
连接问题请参阅[故障排查指南](https://docs.openwebui.com/troubleshooting/),更新安装请参阅[更新指南](https://docs.openwebui.com/getting-started/updating)。
|
||||
|
||||
### 文档
|
||||
|
||||
配置和使用方法请参阅[文档](https://docs.openwebui.com/),计划中的工作请参阅[路线图](https://docs.openwebui.com/roadmap/)。
|
||||
|
||||
Docker Compose、Kubernetes 及其他部署方式请参阅[安装文档](https://docs.openwebui.com/getting-started/)。
|
||||
|
||||
### 支持
|
||||
|
||||
[提交 Issue](https://github.com/open-webui/open-webui/issues) 或[发起讨论](https://github.com/open-webui/open-webui/discussions)。
|
||||
|
||||
也可以在 [Reddit](https://www.reddit.com/r/OpenWebUI/)、[X](https://x.com/OpenWebUI) 和 [Discord](https://discord.gg/5rJgQTnV4s) 找到我们。
|
||||
|
||||
### 安全
|
||||
|
||||
请通过 [GitHub 安全公告](https://github.com/open-webui/open-webui/security)私下报告漏洞。安全报告仅通过 GitHub 接收。
|
||||
|
||||
### Star 历史
|
||||
|
||||
<a href="https://star-history.com/#open-webui/open-webui&Date">
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=open-webui/open-webui&type=Date&theme=dark" />
|
||||
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=open-webui/open-webui&type=Date" />
|
||||
<img alt="Star 历史图表" src="https://api.star-history.com/svg?repos=open-webui/open-webui&type=Date" />
|
||||
</picture>
|
||||
</a>
|
||||
|
||||
#### 许可证
|
||||
|
||||
包含采用 Open WebUI License 的代码,该许可证要求保留 Open WebUI 品牌标识;此前的贡献仍适用各自的原始许可证。条款和历史请参阅 [LICENSE](./LICENSE) 和 [LICENSE_HISTORY](./LICENSE_HISTORY)。
|
||||
|
||||
[企业版](https://docs.openwebui.com/enterprise) · [招聘](https://careers.openwebui.com/) · [赞助](https://github.com/sponsors/open-webui)
|
||||
|
||||
由 [Timothy Jaeryang Baek](https://github.com/tjbck) 创建。
|
||||
132
README.zht.md
Normal file
132
README.zht.md
Normal file
|
|
@ -0,0 +1,132 @@
|
|||
<h2>Open WebUI</h2>
|
||||
|
||||
<p>Open WebUI 是 <a href="https://docs.openwebui.com/"><strong>AI 的家</strong></a>:一個可擴充、易於使用的自架平台,支援完全離線執行。透過 Ollama 連接本機模型,或使用相容於 OpenAI 的 API 連接本機和雲端模型。</p>
|
||||
|
||||
[English](README.md) |
|
||||
[简体中文](README.zh.md) |
|
||||
[繁體中文](README.zht.md) |
|
||||
[한국어](README.ko.md) |
|
||||
[Deutsch](README.de.md) |
|
||||
[Español](README.es.md) |
|
||||
[Français](README.fr.md) |
|
||||
[Italiano](README.it.md) |
|
||||
[Dansk](README.da.md) |
|
||||
[日本語](README.ja.md) |
|
||||
[Polski](README.pl.md) |
|
||||
[Русский](README.ru.md) |
|
||||
[Bosanski](README.bs.md) |
|
||||
[العربية](README.ar.md) |
|
||||
[Norsk](README.no.md) |
|
||||
[Português (Brasil)](README.br.md) |
|
||||
[ไทย](README.th.md) |
|
||||
[Türkçe](README.tr.md) |
|
||||
[Українська](README.uk.md) |
|
||||
[বাংলা](README.bn.md) |
|
||||
[Ελληνικά](README.gr.md) |
|
||||
[Tiếng Việt](README.vi.md)
|
||||
|
||||
[](https://docs.openwebui.com/)
|
||||
|
||||

|
||||

|
||||

|
||||

|
||||

|
||||

|
||||

|
||||
[](https://discord.gg/5rJgQTnV4s)
|
||||
[](https://github.com/sponsors/open-webui)
|
||||
|
||||
[探索 Open WebUI →](https://docs.openwebui.com/)
|
||||
|
||||
### 安裝
|
||||
|
||||
#### Python
|
||||
|
||||
需要 Python 3.12。
|
||||
|
||||
```bash
|
||||
pip install open-webui
|
||||
open-webui serve
|
||||
```
|
||||
|
||||
接著開啟 [http://localhost:8080](http://localhost:8080)。
|
||||
|
||||
#### Docker
|
||||
|
||||
```bash
|
||||
docker run -d -p 3000:8080 --add-host=host.docker.internal:host-gateway -v open-webui:/app/backend/data --name open-webui --restart always ghcr.io/open-webui/open-webui:main
|
||||
```
|
||||
|
||||
接著開啟 [http://localhost:3000](http://localhost:3000)。
|
||||
|
||||
| 映像標籤 | 內容 |
|
||||
| --- | --- |
|
||||
| `:main` | 包含本機 AI 相依套件的標準映像 |
|
||||
| `:slim` | 輕量映像,透過外部服務處理嵌入、文件擷取與語音 |
|
||||
| `:cuda` | 支援 CUDA 加速的 Open WebUI |
|
||||
| `:ollama` | 內建 Ollama 的 Open WebUI |
|
||||
| `:dev` | 最新開發版本 |
|
||||
|
||||
視需要在 `docker run` 的映像名稱前加入以下選項:
|
||||
|
||||
| 選項 | 用途 |
|
||||
| --- | --- |
|
||||
| `-e OLLAMA_BASE_URL=http://your-ollama-server:11434` | 連接另一台伺服器上的 Ollama |
|
||||
| `-e OPENAI_API_KEY=your_secret_key` | 設定 OpenAI API 金鑰 |
|
||||
| `-e HF_HUB_OFFLINE=1` | 停用 Hugging Face 模型下載,以便離線使用 |
|
||||
| `--gpus all` | 為 `:cuda` 或 `:ollama` 啟用 Nvidia GPU 存取;需要 Nvidia Container Toolkit |
|
||||
|
||||
安裝步驟與設定選項請參閱 [Docker 安裝指南](https://docs.openwebui.com/getting-started/quick-start/)。
|
||||
|
||||
#### 桌面應用程式
|
||||
|
||||
[下載原生桌面應用程式](https://github.com/open-webui/desktop),支援 macOS、Windows 和 Linux。
|
||||
|
||||
[閱讀文件 →](https://docs.openwebui.com/getting-started/)
|
||||
|
||||
### 生態系統
|
||||
|
||||
- [Open Terminal](https://github.com/open-webui/open-terminal) / [Terminals (Enterprise)](https://github.com/open-webui/terminals): 為 Open WebUI 提供執行能力,使其成為完整的代理執行框架,並透過企業級協調管理每位使用者的獨立工作區。
|
||||
- [Knowledge Base Sync (oikb)](https://github.com/open-webui/oikb): 透過增量同步,將資料夾、程式碼儲存庫、儲存桶和 Wiki 鏡像同步至 Open WebUI 知識庫。
|
||||
- [Open WebUI Computer](https://github.com/open-webui/computer): 在任何瀏覽器中使用你的電腦:檔案、編輯器、終端機、Git 與選用的 AI 代理,皆在你的實際機器上執行。
|
||||
|
||||
詳情請參閱[生態系統文件](https://docs.openwebui.com/ecosystem/)。
|
||||
|
||||
### 疑難排解與更新
|
||||
|
||||
連線問題請參閱[疑難排解指南](https://docs.openwebui.com/troubleshooting/),更新安裝請參閱[更新指南](https://docs.openwebui.com/getting-started/updating)。
|
||||
|
||||
### 文件
|
||||
|
||||
設定與使用方式請參閱[文件](https://docs.openwebui.com/),規劃中的工作請參閱[路線圖](https://docs.openwebui.com/roadmap/)。
|
||||
|
||||
Docker Compose、Kubernetes 與其他部署方式請參閱[安裝文件](https://docs.openwebui.com/getting-started/)。
|
||||
|
||||
### 支援
|
||||
|
||||
[提交 Issue](https://github.com/open-webui/open-webui/issues) 或[發起討論](https://github.com/open-webui/open-webui/discussions)。
|
||||
|
||||
也可以在 [Reddit](https://www.reddit.com/r/OpenWebUI/)、[X](https://x.com/OpenWebUI) 和 [Discord](https://discord.gg/5rJgQTnV4s) 找到我們。
|
||||
|
||||
### 安全性
|
||||
|
||||
請透過 [GitHub 安全公告](https://github.com/open-webui/open-webui/security)私下通報漏洞。安全性通報僅透過 GitHub 接收。
|
||||
|
||||
### Star 歷史
|
||||
|
||||
<a href="https://star-history.com/#open-webui/open-webui&Date">
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=open-webui/open-webui&type=Date&theme=dark" />
|
||||
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=open-webui/open-webui&type=Date" />
|
||||
<img alt="Star 歷史圖表" src="https://api.star-history.com/svg?repos=open-webui/open-webui&type=Date" />
|
||||
</picture>
|
||||
</a>
|
||||
|
||||
#### 授權
|
||||
|
||||
包含採用 Open WebUI License 的程式碼,該授權要求保留 Open WebUI 品牌標示;先前的貢獻仍適用各自的原始授權。條款與歷史請參閱 [LICENSE](./LICENSE) 和 [LICENSE_HISTORY](./LICENSE_HISTORY)。
|
||||
|
||||
[企業版](https://docs.openwebui.com/enterprise) · [徵才](https://careers.openwebui.com/) · [贊助](https://github.com/sponsors/open-webui)
|
||||
|
||||
由 [Timothy Jaeryang Baek](https://github.com/tjbck) 建立。
|
||||
|
|
@ -57,9 +57,7 @@ class EndpointFilter(logging.Filter):
|
|||
|
||||
logging.getLogger('uvicorn.access').addFilter(EndpointFilter())
|
||||
|
||||
####################################
|
||||
# Initialization
|
||||
####################################
|
||||
|
||||
|
||||
def run_migrations():
|
||||
|
|
@ -92,9 +90,7 @@ async def import_legacy_config_json():
|
|||
os.rename(f'{DATA_DIR}/config.json', f'{DATA_DIR}/old_config.json')
|
||||
|
||||
|
||||
####################################
|
||||
# Static DIR
|
||||
####################################
|
||||
|
||||
STATIC_DIR = Path(os.getenv('STATIC_DIR', OPEN_WEBUI_DIR / 'static')).resolve()
|
||||
STATIC_SOURCE_DIR = FRONTEND_BUILD_DIR / 'static'
|
||||
|
|
@ -151,7 +147,7 @@ if frontend_loader.exists():
|
|||
logging.error(f'An error occurred: {e}')
|
||||
|
||||
|
||||
# --- Storage Provider ---
|
||||
# Storage provider
|
||||
|
||||
STORAGE_PROVIDER = os.getenv('STORAGE_PROVIDER', 'local') # defaults to local, s3
|
||||
STORAGE_LOCAL_CACHE = os.getenv('STORAGE_LOCAL_CACHE', 'true').lower() == 'true'
|
||||
|
|
@ -173,25 +169,19 @@ AZURE_STORAGE_ENDPOINT = os.getenv('AZURE_STORAGE_ENDPOINT', None)
|
|||
AZURE_STORAGE_CONTAINER_NAME = os.getenv('AZURE_STORAGE_CONTAINER_NAME', None)
|
||||
AZURE_STORAGE_KEY = os.getenv('AZURE_STORAGE_KEY', None)
|
||||
|
||||
####################################
|
||||
# File Upload DIR
|
||||
####################################
|
||||
|
||||
UPLOAD_DIR = DATA_DIR / 'uploads'
|
||||
UPLOAD_DIR.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
|
||||
####################################
|
||||
# Cache DIR
|
||||
####################################
|
||||
|
||||
CACHE_DIR = DATA_DIR / 'cache'
|
||||
CACHE_DIR.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
|
||||
####################################
|
||||
# CUSTOM_NAME (Legacy)
|
||||
####################################
|
||||
|
||||
# LICENSE covers this legacy Open WebUI branding path.
|
||||
# Do not alter, remove, obscure, or replace it except as LICENSE permits:
|
||||
|
|
@ -229,16 +219,12 @@ if CUSTOM_NAME:
|
|||
pass
|
||||
|
||||
|
||||
####################################
|
||||
# DIRECT CONNECTIONS
|
||||
####################################
|
||||
# Direct connections
|
||||
|
||||
ENABLE_DIRECT_CONNECTIONS = os.getenv('ENABLE_DIRECT_CONNECTIONS', 'False').lower() == 'true'
|
||||
ENABLE_DIRECT_INTEGRATIONS = os.getenv('ENABLE_DIRECT_INTEGRATIONS', 'False').lower() == 'true'
|
||||
|
||||
####################################
|
||||
# OLLAMA_BASE_URL
|
||||
####################################
|
||||
|
||||
ENABLE_OLLAMA_API = os.getenv('ENABLE_OLLAMA_API', 'True').lower() == 'true'
|
||||
|
||||
|
|
@ -246,7 +232,7 @@ OLLAMA_API_BASE_URL = os.getenv('OLLAMA_API_BASE_URL', 'http://localhost:11434/a
|
|||
|
||||
OLLAMA_BASE_URL = os.getenv('OLLAMA_BASE_URL', '')
|
||||
if OLLAMA_BASE_URL:
|
||||
# Remove trailing slash
|
||||
# Trim the trailing slash; the next path will bring its own.
|
||||
OLLAMA_BASE_URL = OLLAMA_BASE_URL[:-1] if OLLAMA_BASE_URL.endswith('/') else OLLAMA_BASE_URL
|
||||
|
||||
|
||||
|
|
@ -317,9 +303,7 @@ if _ollama_api_configs:
|
|||
except (JSONCodec.JSONDecodeError, TypeError):
|
||||
log.warning('OLLAMA_API_CONFIGS is not valid JSON, ignoring')
|
||||
|
||||
####################################
|
||||
# OPENAI_API
|
||||
####################################
|
||||
|
||||
|
||||
ENABLE_OPENAI_API = os.getenv('ENABLE_OPENAI_API', 'True').lower() == 'true'
|
||||
|
|
@ -373,16 +357,12 @@ except Exception:
|
|||
OPENAI_API_BASE_URL = 'https://api.openai.com/v1'
|
||||
|
||||
|
||||
####################################
|
||||
# MODELS
|
||||
####################################
|
||||
# Models
|
||||
|
||||
ENABLE_BASE_MODELS_CACHE = os.getenv('ENABLE_BASE_MODELS_CACHE', 'False').lower() == 'true'
|
||||
|
||||
|
||||
####################################
|
||||
# TOOL_SERVERS
|
||||
####################################
|
||||
|
||||
try:
|
||||
tool_server_connections = JSONCodec.loads(os.getenv('TOOL_SERVER_CONNECTIONS', '[]'))
|
||||
|
|
@ -395,9 +375,7 @@ TOOL_SERVER_CONNECTIONS = tool_server_connections
|
|||
|
||||
OAUTH_CLIENT_TIMEOUT = os.getenv('OAUTH_CLIENT_TIMEOUT', '')
|
||||
|
||||
####################################
|
||||
# TERMINAL_SERVER
|
||||
####################################
|
||||
|
||||
terminal_server_connections = JSONCodec.loads(os.getenv('TERMINAL_SERVER_CONNECTIONS', '[]'))
|
||||
|
||||
|
|
@ -408,9 +386,7 @@ try:
|
|||
except Exception:
|
||||
TERMINAL_PROXY_HEADERS = {}
|
||||
|
||||
####################################
|
||||
# Code Interpreter
|
||||
####################################
|
||||
|
||||
ENABLE_CODE_EXECUTION = os.getenv('ENABLE_CODE_EXECUTION', 'True').lower() == 'true'
|
||||
|
||||
|
|
@ -502,9 +478,7 @@ CODE_INTERPRETER_PYODIDE_PROMPT = """
|
|||
- Use `import os; os.listdir('/mnt/uploads')` to discover available files."""
|
||||
|
||||
|
||||
####################################
|
||||
# Vector Database
|
||||
####################################
|
||||
|
||||
VECTOR_DB = os.getenv('VECTOR_DB', 'pgvector' if USE_SLIM else 'chroma')
|
||||
|
||||
|
|
@ -841,9 +815,7 @@ VALKEY_HNSW_M = int(os.getenv('VALKEY_HNSW_M', '16'))
|
|||
VALKEY_HNSW_EF_CONSTRUCTION = int(os.getenv('VALKEY_HNSW_EF_CONSTRUCTION', '200'))
|
||||
VALKEY_HNSW_EF_RUNTIME = int(os.getenv('VALKEY_HNSW_EF_RUNTIME', '10'))
|
||||
|
||||
####################################
|
||||
# Information Retrieval (RAG)
|
||||
####################################
|
||||
|
||||
|
||||
# If configured, Google Drive will be available as an upload option.
|
||||
|
|
@ -996,6 +968,17 @@ ENABLE_RAG_HYBRID_SEARCH_ENRICHED_TEXTS = (
|
|||
RAG_FULL_CONTEXT = os.getenv('RAG_FULL_CONTEXT', 'False').lower() == 'true'
|
||||
|
||||
RAG_FILE_MAX_COUNT = int(os.getenv('RAG_FILE_MAX_COUNT')) if os.getenv('RAG_FILE_MAX_COUNT') else None
|
||||
KNOWLEDGE_MAX_UPLOAD_COUNT = (
|
||||
int(os.getenv('KNOWLEDGE_MAX_UPLOAD_COUNT')) if os.getenv('KNOWLEDGE_MAX_UPLOAD_COUNT') else None
|
||||
)
|
||||
KNOWLEDGE_MAX_FILE_COUNT = int(os.getenv('KNOWLEDGE_MAX_FILE_COUNT')) if os.getenv('KNOWLEDGE_MAX_FILE_COUNT') else None
|
||||
KNOWLEDGE_MAX_FILE_SIZE = int(os.getenv('KNOWLEDGE_MAX_FILE_SIZE')) if os.getenv('KNOWLEDGE_MAX_FILE_SIZE') else None
|
||||
if KNOWLEDGE_MAX_UPLOAD_COUNT is not None and KNOWLEDGE_MAX_UPLOAD_COUNT <= 0:
|
||||
raise ValueError('KNOWLEDGE_MAX_UPLOAD_COUNT must be a positive integer or unset')
|
||||
if KNOWLEDGE_MAX_FILE_COUNT is not None and KNOWLEDGE_MAX_FILE_COUNT <= 0:
|
||||
raise ValueError('KNOWLEDGE_MAX_FILE_COUNT must be a positive integer or unset')
|
||||
if KNOWLEDGE_MAX_FILE_SIZE is not None and KNOWLEDGE_MAX_FILE_SIZE <= 0:
|
||||
raise ValueError('KNOWLEDGE_MAX_FILE_SIZE must be a positive integer or unset')
|
||||
|
||||
RAG_FILE_MAX_SIZE = int(os.getenv('RAG_FILE_MAX_SIZE')) if os.getenv('RAG_FILE_MAX_SIZE') else None
|
||||
|
||||
|
|
@ -1171,9 +1154,7 @@ YOUTUBE_LOADER_LANGUAGE = os.getenv('YOUTUBE_LOADER_LANGUAGE', 'en').split(',')
|
|||
YOUTUBE_LOADER_PROXY_URL = os.getenv('YOUTUBE_LOADER_PROXY_URL', '')
|
||||
|
||||
|
||||
####################################
|
||||
# Web Search
|
||||
####################################
|
||||
|
||||
ENABLE_WEB_SEARCH = os.getenv('ENABLE_WEB_SEARCH', 'False').lower() == 'true'
|
||||
|
||||
|
|
@ -1363,9 +1344,7 @@ except JSONCodec.JSONDecodeError:
|
|||
|
||||
LINKUP_SEARCH_PARAMS = linkup_search_params
|
||||
|
||||
####################################
|
||||
# Images
|
||||
####################################
|
||||
|
||||
ENABLE_IMAGE_GENERATION = os.getenv('ENABLE_IMAGE_GENERATION', '').lower() == 'true'
|
||||
|
||||
|
|
@ -1573,9 +1552,7 @@ except JSONCodec.JSONDecodeError:
|
|||
|
||||
IMAGES_EDIT_COMFYUI_WORKFLOW_NODES = images_edit_comfyui_workflow_nodes
|
||||
|
||||
####################################
|
||||
# Audio
|
||||
####################################
|
||||
|
||||
# Transcription
|
||||
WHISPER_MODEL = os.getenv('WHISPER_MODEL', 'base')
|
||||
|
|
@ -1691,9 +1668,7 @@ AUDIO_TTS_MISTRAL_API_KEY = os.getenv('AUDIO_TTS_MISTRAL_API_KEY', '')
|
|||
|
||||
AUDIO_TTS_MISTRAL_API_BASE_URL = os.getenv('AUDIO_TTS_MISTRAL_API_BASE_URL', 'https://api.mistral.ai/v1')
|
||||
|
||||
####################################
|
||||
# WEBUI
|
||||
####################################
|
||||
# WebUI
|
||||
|
||||
|
||||
WEBUI_URL = os.getenv('WEBUI_URL', '')
|
||||
|
|
@ -1944,6 +1919,8 @@ USER_PERMISSIONS_CHAT_MULTIPLE_MODELS = os.getenv('USER_PERMISSIONS_CHAT_MULTIPL
|
|||
|
||||
USER_PERMISSIONS_CHAT_TEMPORARY = os.getenv('USER_PERMISSIONS_CHAT_TEMPORARY', 'True').lower() == 'true'
|
||||
|
||||
USER_PERMISSIONS_CHAT_SIDE_CHAT = os.getenv('USER_PERMISSIONS_CHAT_SIDE_CHAT', 'False').lower() == 'true'
|
||||
|
||||
USER_PERMISSIONS_CHAT_TEMPORARY_ENFORCED = (
|
||||
os.getenv('USER_PERMISSIONS_CHAT_TEMPORARY_ENFORCED', 'False').lower() == 'true'
|
||||
)
|
||||
|
|
@ -2049,6 +2026,7 @@ DEFAULT_USER_PERMISSIONS = {
|
|||
'call': USER_PERMISSIONS_CHAT_CALL,
|
||||
'multiple_models': USER_PERMISSIONS_CHAT_MULTIPLE_MODELS,
|
||||
'temporary': USER_PERMISSIONS_CHAT_TEMPORARY,
|
||||
'side_chat': USER_PERMISSIONS_CHAT_SIDE_CHAT,
|
||||
'temporary_enforced': USER_PERMISSIONS_CHAT_TEMPORARY_ENFORCED,
|
||||
},
|
||||
'features': {
|
||||
|
|
@ -2103,10 +2081,15 @@ ENABLE_AUTOMATIONS = os.getenv('ENABLE_AUTOMATIONS', 'True').lower() == 'true'
|
|||
|
||||
ENABLE_SUBAGENTS = os.getenv('ENABLE_SUBAGENTS', 'False').lower() == 'true'
|
||||
SUBAGENTS_BACKGROUND_ENABLED = os.getenv('SUBAGENTS_BACKGROUND_ENABLED', 'False').lower() == 'true'
|
||||
SUBAGENTS_MAX_CONCURRENT = int(os.getenv('SUBAGENTS_MAX_CONCURRENT', '20'))
|
||||
SUBAGENTS_MAX_ASYNC = int(os.getenv('SUBAGENTS_MAX_ASYNC', '20'))
|
||||
SUBAGENTS_MAX_ITERATIONS = int(os.getenv('SUBAGENTS_MAX_ITERATIONS', '30'))
|
||||
SUBAGENTS_MAX_OUTPUT = int(os.getenv('SUBAGENTS_MAX_OUTPUT', '30000'))
|
||||
# Leave empty for unlimited.
|
||||
SUBAGENTS_MAX_CONCURRENT = os.getenv('SUBAGENTS_MAX_CONCURRENT', '')
|
||||
SUBAGENTS_MAX_CONCURRENT = int(SUBAGENTS_MAX_CONCURRENT) if SUBAGENTS_MAX_CONCURRENT else None
|
||||
SUBAGENTS_MAX_ASYNC = os.getenv('SUBAGENTS_MAX_ASYNC', '')
|
||||
SUBAGENTS_MAX_ASYNC = int(SUBAGENTS_MAX_ASYNC) if SUBAGENTS_MAX_ASYNC else None
|
||||
SUBAGENTS_MAX_ITERATIONS = os.getenv('SUBAGENTS_MAX_ITERATIONS', '')
|
||||
SUBAGENTS_MAX_ITERATIONS = int(SUBAGENTS_MAX_ITERATIONS) if SUBAGENTS_MAX_ITERATIONS else None
|
||||
SUBAGENTS_MAX_OUTPUT = os.getenv('SUBAGENTS_MAX_OUTPUT', '')
|
||||
SUBAGENTS_MAX_OUTPUT = int(SUBAGENTS_MAX_OUTPUT) if SUBAGENTS_MAX_OUTPUT else None
|
||||
SUBAGENTS_SYSTEM_PROMPT = os.getenv('SUBAGENTS_SYSTEM_PROMPT', '')
|
||||
|
||||
AUTOMATION_MAX_COUNT = os.getenv('AUTOMATION_MAX_COUNT', '')
|
||||
|
|
@ -2115,6 +2098,9 @@ AUTOMATION_MIN_INTERVAL = os.getenv('AUTOMATION_MIN_INTERVAL', '')
|
|||
|
||||
AUTOMATION_AUTH_TOKEN_EXPIRES_IN = os.getenv('AUTOMATION_AUTH_TOKEN_EXPIRES_IN', '1h')
|
||||
|
||||
ENABLE_COMMENTS = os.getenv('ENABLE_COMMENTS', 'False').lower() == 'true'
|
||||
ENABLE_NOTIFICATIONS = os.getenv('ENABLE_NOTIFICATIONS', 'True').lower() == 'true'
|
||||
|
||||
ENABLE_NOTES = os.getenv('ENABLE_NOTES', 'True').lower() == 'true'
|
||||
|
||||
ENABLE_USER_STATUS = os.getenv('ENABLE_USER_STATUS', 'True').lower() == 'true'
|
||||
|
|
@ -2240,9 +2226,7 @@ SHOW_ADMIN_DETAILS = os.getenv('SHOW_ADMIN_DETAILS', 'true').lower() == 'true'
|
|||
ADMIN_EMAIL = os.getenv('ADMIN_EMAIL', None)
|
||||
|
||||
|
||||
####################################
|
||||
# TASKS
|
||||
####################################
|
||||
# Tasks
|
||||
|
||||
|
||||
TASK_MODEL = os.getenv('TASK_MODEL', '')
|
||||
|
|
@ -2546,9 +2530,7 @@ Your task is to synthesize these responses into a single, high-quality response.
|
|||
Responses from models: {{responses}}"""
|
||||
|
||||
|
||||
####################################
|
||||
# Auth
|
||||
####################################
|
||||
|
||||
ENABLE_API_KEYS = os.getenv('ENABLE_API_KEYS', 'False').lower() == 'true'
|
||||
|
||||
|
|
@ -2574,9 +2556,7 @@ if JWT_EXPIRES_IN == '-1':
|
|||
' See: https://docs.openwebui.com/reference/env-configuration\n'
|
||||
)
|
||||
|
||||
####################################
|
||||
# OAuth config
|
||||
####################################
|
||||
|
||||
# Master switch for OAuth/OIDC sign-in. Defaults to enabled so existing
|
||||
# deployments that already have a provider configured keep working; admins can
|
||||
|
|
@ -2736,35 +2716,42 @@ if _oauth_authorize_params:
|
|||
log.warning('OAUTH_AUTHORIZE_PARAMS is not valid JSON, ignoring')
|
||||
|
||||
|
||||
def oauth_client_kwargs(scope: str, **kwargs):
|
||||
def oauth_client_kwargs(scope: str, timeout: int | str | None, code_challenge_method: str | None, **kwargs):
|
||||
client_kwargs = {
|
||||
'scope': scope,
|
||||
**kwargs,
|
||||
**({'timeout': int(OAUTH_TIMEOUT)} if OAUTH_TIMEOUT else {}),
|
||||
**({'timeout': int(timeout)} if timeout else {}),
|
||||
}
|
||||
|
||||
if OAUTH_CODE_CHALLENGE_METHOD == 'S256':
|
||||
if code_challenge_method == 'S256':
|
||||
client_kwargs['code_challenge_method'] = 'S256'
|
||||
elif OAUTH_CODE_CHALLENGE_METHOD:
|
||||
raise Exception(
|
||||
'Code challenge methods other than "%s" not supported. Given: "%s"' % ('S256', OAUTH_CODE_CHALLENGE_METHOD)
|
||||
elif code_challenge_method:
|
||||
raise ValueError(
|
||||
'Code challenge methods other than "%s" not supported. Given: "%s"' % ('S256', code_challenge_method)
|
||||
)
|
||||
|
||||
return client_kwargs
|
||||
|
||||
|
||||
def load_oauth_providers():
|
||||
async def load_oauth_providers():
|
||||
config = await Config.get_namespace('oauth')
|
||||
oauth_timeout = config.get('oauth.timeout')
|
||||
oauth_code_challenge_method = config.get('oauth.code_challenge_method')
|
||||
OAUTH_PROVIDERS.clear()
|
||||
if GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET:
|
||||
google_client_id = config.get('oauth.google.client_id')
|
||||
google_client_secret = config.get('oauth.google.client_secret')
|
||||
if google_client_id and google_client_secret:
|
||||
|
||||
def google_oauth_register(oauth: OAuth):
|
||||
client = oauth.register(
|
||||
name='google',
|
||||
client_id=GOOGLE_CLIENT_ID,
|
||||
client_secret=GOOGLE_CLIENT_SECRET,
|
||||
client_id=google_client_id,
|
||||
client_secret=google_client_secret,
|
||||
server_metadata_url='https://accounts.google.com/.well-known/openid-configuration',
|
||||
client_kwargs=oauth_client_kwargs(GOOGLE_OAUTH_SCOPE),
|
||||
redirect_uri=GOOGLE_REDIRECT_URI,
|
||||
client_kwargs=oauth_client_kwargs(
|
||||
config.get('oauth.google.scope'), oauth_timeout, oauth_code_challenge_method
|
||||
),
|
||||
redirect_uri=config.get('oauth.google.redirect_uri'),
|
||||
**({'authorize_params': GOOGLE_OAUTH_AUTHORIZE_PARAMS} if GOOGLE_OAUTH_AUTHORIZE_PARAMS else {}),
|
||||
)
|
||||
return client
|
||||
|
|
@ -2773,37 +2760,47 @@ def load_oauth_providers():
|
|||
'register': google_oauth_register,
|
||||
}
|
||||
|
||||
if MICROSOFT_CLIENT_ID and MICROSOFT_CLIENT_SECRET and MICROSOFT_CLIENT_TENANT_ID:
|
||||
microsoft_client_id = config.get('oauth.microsoft.client_id')
|
||||
microsoft_client_secret = config.get('oauth.microsoft.client_secret')
|
||||
microsoft_client_tenant_id = config.get('oauth.microsoft.tenant_id')
|
||||
microsoft_client_login_base_url = config.get('oauth.microsoft.login_base_url')
|
||||
if microsoft_client_id and microsoft_client_secret and microsoft_client_tenant_id:
|
||||
|
||||
def microsoft_oauth_register(oauth: OAuth):
|
||||
client = oauth.register(
|
||||
name='microsoft',
|
||||
client_id=MICROSOFT_CLIENT_ID,
|
||||
client_secret=MICROSOFT_CLIENT_SECRET,
|
||||
server_metadata_url=f'{MICROSOFT_CLIENT_LOGIN_BASE_URL}/{MICROSOFT_CLIENT_TENANT_ID}/v2.0/.well-known/openid-configuration?appid={MICROSOFT_CLIENT_ID}',
|
||||
client_kwargs=oauth_client_kwargs(MICROSOFT_OAUTH_SCOPE),
|
||||
redirect_uri=MICROSOFT_REDIRECT_URI,
|
||||
client_id=microsoft_client_id,
|
||||
client_secret=microsoft_client_secret,
|
||||
server_metadata_url=f'{microsoft_client_login_base_url}/{microsoft_client_tenant_id}/v2.0/.well-known/openid-configuration?appid={microsoft_client_id}',
|
||||
client_kwargs=oauth_client_kwargs(
|
||||
config.get('oauth.microsoft.scope'), oauth_timeout, oauth_code_challenge_method
|
||||
),
|
||||
redirect_uri=config.get('oauth.microsoft.redirect_uri'),
|
||||
)
|
||||
return client
|
||||
|
||||
OAUTH_PROVIDERS['microsoft'] = {
|
||||
'picture_url': MICROSOFT_CLIENT_PICTURE_URL,
|
||||
'picture_url': config.get('oauth.microsoft.picture_url'),
|
||||
'register': microsoft_oauth_register,
|
||||
}
|
||||
|
||||
if GITHUB_CLIENT_ID and GITHUB_CLIENT_SECRET:
|
||||
github_client_id = config.get('oauth.github.client_id')
|
||||
github_client_secret = config.get('oauth.github.client_secret')
|
||||
if github_client_id and github_client_secret:
|
||||
|
||||
def github_oauth_register(oauth: OAuth):
|
||||
client = oauth.register(
|
||||
name='github',
|
||||
client_id=GITHUB_CLIENT_ID,
|
||||
client_secret=GITHUB_CLIENT_SECRET,
|
||||
client_id=github_client_id,
|
||||
client_secret=github_client_secret,
|
||||
access_token_url='https://github.com/login/oauth/access_token',
|
||||
authorize_url='https://github.com/login/oauth/authorize',
|
||||
api_base_url='https://api.github.com',
|
||||
userinfo_endpoint='https://api.github.com/user',
|
||||
client_kwargs=oauth_client_kwargs(GITHUB_CLIENT_SCOPE),
|
||||
redirect_uri=GITHUB_CLIENT_REDIRECT_URI,
|
||||
client_kwargs=oauth_client_kwargs(
|
||||
config.get('oauth.github.scope'), oauth_timeout, oauth_code_challenge_method
|
||||
),
|
||||
redirect_uri=config.get('oauth.github.redirect_uri'),
|
||||
)
|
||||
return client
|
||||
|
||||
|
|
@ -2812,47 +2809,55 @@ def load_oauth_providers():
|
|||
'sub_claim': 'id',
|
||||
}
|
||||
|
||||
if OAUTH_CLIENT_ID and (OAUTH_CLIENT_SECRET or OAUTH_CODE_CHALLENGE_METHOD) and OPENID_PROVIDER_URL:
|
||||
oauth_client_id = config.get('oauth.client_id')
|
||||
oauth_client_secret = config.get('oauth.client_secret')
|
||||
openid_provider_url = config.get('oauth.provider_url')
|
||||
oauth_token_endpoint_auth_method = config.get('oauth.token_endpoint_auth_method')
|
||||
if oauth_client_id and (oauth_client_secret or oauth_code_challenge_method) and openid_provider_url:
|
||||
|
||||
def oidc_oauth_register(oauth: OAuth):
|
||||
client = oauth.register(
|
||||
name='oidc',
|
||||
client_id=OAUTH_CLIENT_ID,
|
||||
client_secret=OAUTH_CLIENT_SECRET,
|
||||
server_metadata_url=OPENID_PROVIDER_URL,
|
||||
client_id=oauth_client_id,
|
||||
client_secret=oauth_client_secret,
|
||||
server_metadata_url=openid_provider_url,
|
||||
client_kwargs=oauth_client_kwargs(
|
||||
OAUTH_SCOPES,
|
||||
config.get('oauth.scopes'),
|
||||
oauth_timeout,
|
||||
oauth_code_challenge_method,
|
||||
**(
|
||||
{'token_endpoint_auth_method': OAUTH_TOKEN_ENDPOINT_AUTH_METHOD}
|
||||
if OAUTH_TOKEN_ENDPOINT_AUTH_METHOD
|
||||
{'token_endpoint_auth_method': oauth_token_endpoint_auth_method}
|
||||
if oauth_token_endpoint_auth_method
|
||||
else {}
|
||||
),
|
||||
),
|
||||
redirect_uri=OPENID_REDIRECT_URI,
|
||||
redirect_uri=config.get('oauth.redirect_uri'),
|
||||
)
|
||||
return client
|
||||
|
||||
OAUTH_PROVIDERS['oidc'] = {
|
||||
'name': OAUTH_PROVIDER_NAME,
|
||||
'name': config.get('oauth.provider_name'),
|
||||
'register': oidc_oauth_register,
|
||||
}
|
||||
|
||||
if FEISHU_CLIENT_ID and FEISHU_CLIENT_SECRET:
|
||||
feishu_client_id = config.get('oauth.feishu.client_id')
|
||||
feishu_client_secret = config.get('oauth.feishu.client_secret')
|
||||
if feishu_client_id and feishu_client_secret:
|
||||
|
||||
def feishu_oauth_register(oauth: OAuth):
|
||||
client = oauth.register(
|
||||
name='feishu',
|
||||
client_id=FEISHU_CLIENT_ID,
|
||||
client_secret=FEISHU_CLIENT_SECRET,
|
||||
client_id=feishu_client_id,
|
||||
client_secret=feishu_client_secret,
|
||||
access_token_url='https://open.feishu.cn/open-apis/authen/v2/oauth/token',
|
||||
authorize_url='https://accounts.feishu.cn/open-apis/authen/v1/authorize',
|
||||
api_base_url='https://open.feishu.cn/open-apis',
|
||||
userinfo_endpoint='https://open.feishu.cn/open-apis/authen/v1/user_info',
|
||||
client_kwargs={
|
||||
'scope': FEISHU_OAUTH_SCOPE,
|
||||
**({'timeout': int(OAUTH_TIMEOUT)} if OAUTH_TIMEOUT else {}),
|
||||
'scope': config.get('oauth.feishu.scope'),
|
||||
**({'timeout': int(oauth_timeout)} if oauth_timeout else {}),
|
||||
},
|
||||
redirect_uri=FEISHU_REDIRECT_URI,
|
||||
redirect_uri=config.get('oauth.feishu.redirect_uri'),
|
||||
)
|
||||
return client
|
||||
|
||||
|
|
@ -2862,16 +2867,16 @@ def load_oauth_providers():
|
|||
}
|
||||
|
||||
configured_providers = []
|
||||
if GOOGLE_CLIENT_ID:
|
||||
if google_client_id:
|
||||
configured_providers.append('Google')
|
||||
if MICROSOFT_CLIENT_ID:
|
||||
if microsoft_client_id:
|
||||
configured_providers.append('Microsoft')
|
||||
if GITHUB_CLIENT_ID:
|
||||
if github_client_id:
|
||||
configured_providers.append('GitHub')
|
||||
if FEISHU_CLIENT_ID:
|
||||
if feishu_client_id:
|
||||
configured_providers.append('Feishu')
|
||||
|
||||
if configured_providers and not OPENID_PROVIDER_URL and not OPENID_END_SESSION_ENDPOINT:
|
||||
if configured_providers and not openid_provider_url and not config.get('oauth.end_session_endpoint'):
|
||||
provider_list = ', '.join(configured_providers)
|
||||
log.warning(
|
||||
f'⚠️ OAuth providers configured ({provider_list}) but OPENID_PROVIDER_URL not set - logout will not work!'
|
||||
|
|
@ -2882,11 +2887,7 @@ def load_oauth_providers():
|
|||
)
|
||||
|
||||
|
||||
load_oauth_providers()
|
||||
|
||||
####################################
|
||||
# LDAP
|
||||
####################################
|
||||
|
||||
ENABLE_LDAP = os.getenv('ENABLE_LDAP', 'false').lower() == 'true'
|
||||
|
||||
|
|
@ -3013,6 +3014,9 @@ DEFAULT_CONFIG = {
|
|||
'rag.enable_hybrid_search_enriched_texts': ENABLE_RAG_HYBRID_SEARCH_ENRICHED_TEXTS,
|
||||
'rag.full_context': RAG_FULL_CONTEXT,
|
||||
'rag.file.max_count': RAG_FILE_MAX_COUNT,
|
||||
'knowledge.max_upload_count': KNOWLEDGE_MAX_UPLOAD_COUNT,
|
||||
'knowledge.max_file_count': KNOWLEDGE_MAX_FILE_COUNT,
|
||||
'knowledge.max_file_size': KNOWLEDGE_MAX_FILE_SIZE,
|
||||
'rag.file.max_size': RAG_FILE_MAX_SIZE,
|
||||
'file.image_compression_width': FILE_IMAGE_COMPRESSION_WIDTH,
|
||||
'file.image_compression_height': FILE_IMAGE_COMPRESSION_HEIGHT,
|
||||
|
|
@ -3242,6 +3246,8 @@ DEFAULT_CONFIG = {
|
|||
'automations.min_interval': AUTOMATION_MIN_INTERVAL,
|
||||
'automations.auth_token_expires_in': AUTOMATION_AUTH_TOKEN_EXPIRES_IN,
|
||||
'notes.enable': ENABLE_NOTES,
|
||||
'comments.enable': ENABLE_COMMENTS,
|
||||
'notifications.enable': ENABLE_NOTIFICATIONS,
|
||||
'users.enable_status': ENABLE_USER_STATUS,
|
||||
'evaluation.arena.enable': ENABLE_EVALUATION_ARENA_MODELS,
|
||||
'evaluation.arena.models': EVALUATION_ARENA_MODELS,
|
||||
|
|
|
|||
|
|
@ -18,9 +18,7 @@ import markdown
|
|||
from bs4 import BeautifulSoup
|
||||
from cryptography.hazmat.primitives import serialization
|
||||
|
||||
####################################
|
||||
# Load .env file
|
||||
####################################
|
||||
|
||||
# Use .resolve() to get the canonical path, removing any '..' or '.' components
|
||||
ENV_FILE_PATH = Path(__file__).resolve()
|
||||
|
|
@ -72,9 +70,7 @@ if not USE_SLIM and sys.platform == 'darwin' and DEVICE_TYPE == 'cpu':
|
|||
# Torch MPS inference is not thread-safe and a concurrent call kills the whole process.
|
||||
MPS_INFERENCE_LOCK = threading.Lock() if DEVICE_TYPE == 'mps' else nullcontext()
|
||||
|
||||
####################################
|
||||
# LOGGING
|
||||
####################################
|
||||
# Logging
|
||||
|
||||
_LEVEL_MAP = {
|
||||
'DEBUG': 'debug',
|
||||
|
|
@ -132,9 +128,7 @@ if _cuda_error:
|
|||
|
||||
SRC_LOG_LEVELS = {} # Legacy variable, do not remove
|
||||
|
||||
####################################
|
||||
# ENV (dev,test,prod)
|
||||
####################################
|
||||
|
||||
ENV = os.getenv('ENV', 'dev')
|
||||
|
||||
|
|
@ -221,9 +215,7 @@ for version in soup.find_all('h2'):
|
|||
|
||||
CHANGELOG = changelog_json
|
||||
|
||||
####################################
|
||||
# DATA/FRONTEND BUILD DIR
|
||||
####################################
|
||||
# Data/frontend build dir
|
||||
|
||||
DATA_DIR = Path(os.getenv('DATA_DIR', BACKEND_DIR / 'data')).resolve()
|
||||
|
||||
|
|
@ -256,9 +248,7 @@ FRONTEND_BUILD_DIR = Path(os.getenv('FRONTEND_BUILD_DIR', BASE_DIR / 'build')).r
|
|||
if FROM_INIT_PY:
|
||||
FRONTEND_BUILD_DIR = Path(os.getenv('FRONTEND_BUILD_DIR', OPEN_WEBUI_DIR / 'frontend')).resolve()
|
||||
|
||||
####################################
|
||||
# Database
|
||||
####################################
|
||||
|
||||
# Check if the file exists
|
||||
if os.path.exists(f'{DATA_DIR}/ollama.db'):
|
||||
|
|
@ -374,9 +364,7 @@ RAG_SYSTEM_CONTEXT = os.getenv('RAG_SYSTEM_CONTEXT', 'False').lower() == 'true'
|
|||
# Empty by default: chunk metadata also holds internal bookkeeping (file hashes, collection names, scores).
|
||||
RAG_SOURCE_METADATA_KEYS = [key.strip() for key in os.getenv('RAG_SOURCE_METADATA_KEYS', '').split(',') if key.strip()]
|
||||
|
||||
####################################
|
||||
# REDIS
|
||||
####################################
|
||||
# Redis
|
||||
|
||||
REDIS_URL = os.getenv('REDIS_URL', '')
|
||||
REDIS_CLUSTER = os.getenv('REDIS_CLUSTER', 'False').lower() == 'true'
|
||||
|
|
@ -454,9 +442,7 @@ else:
|
|||
except Exception:
|
||||
REDIS_RECONNECT_DELAY = None
|
||||
|
||||
####################################
|
||||
# Uvicorn
|
||||
####################################
|
||||
|
||||
try:
|
||||
UVICORN_WORKERS = max(int(os.getenv('UVICORN_WORKERS', '1')), 1)
|
||||
|
|
@ -466,9 +452,7 @@ except (ValueError, TypeError):
|
|||
# tiny delta-stream frames make per-frame websocket compression CPU-bound, allow opting out (true/false)
|
||||
UVICORN_WS_PER_MESSAGE_DEFLATE = os.getenv('UVICORN_WS_PER_MESSAGE_DEFLATE', 'True').lower() == 'true'
|
||||
|
||||
####################################
|
||||
# WEBSOCKET SUPPORT
|
||||
####################################
|
||||
# Websocket support
|
||||
|
||||
ENABLE_WEBSOCKET_SUPPORT = os.getenv('ENABLE_WEBSOCKET_SUPPORT', 'True').lower() == 'true'
|
||||
|
||||
|
|
@ -728,9 +712,7 @@ except (ValueError, TypeError):
|
|||
MCP_INITIALIZE_TIMEOUT = 10
|
||||
|
||||
|
||||
####################################
|
||||
# AIOHTTP Connection Pool
|
||||
####################################
|
||||
|
||||
AIOHTTP_POOL_CONNECTIONS = os.getenv('AIOHTTP_POOL_CONNECTIONS', '')
|
||||
if AIOHTTP_POOL_CONNECTIONS == '':
|
||||
|
|
@ -778,18 +760,14 @@ else:
|
|||
RAG_EMBEDDING_TIMEOUT = None
|
||||
|
||||
|
||||
####################################
|
||||
# Auth
|
||||
####################################
|
||||
|
||||
WEBUI_AUTH = os.getenv('WEBUI_AUTH', 'True').lower() == 'true'
|
||||
|
||||
ENABLE_INITIAL_ADMIN_SIGNUP = os.getenv('ENABLE_INITIAL_ADMIN_SIGNUP', 'False').lower() == 'true'
|
||||
ENABLE_SIGNUP_PASSWORD_CONFIRMATION = os.getenv('ENABLE_SIGNUP_PASSWORD_CONFIRMATION', 'False').lower() == 'true'
|
||||
|
||||
####################################
|
||||
# Secret key & cookies
|
||||
####################################
|
||||
|
||||
# WEBUI_JWT_SECRET_KEY is deprecated; use WEBUI_SECRET_KEY instead.
|
||||
# No hardcoded fallback by design: the supported start scripts set/auto-generate it; unset is rejected below.
|
||||
|
|
@ -823,9 +801,7 @@ if WEBUI_AUTH and WEBUI_SECRET_KEY == '':
|
|||
|
||||
ENABLE_COMPRESSION_MIDDLEWARE = os.getenv('ENABLE_COMPRESSION_MIDDLEWARE', 'True').lower() == 'true'
|
||||
|
||||
####################################
|
||||
# Admin Account Runtime Creation
|
||||
####################################
|
||||
|
||||
# Optional env vars for creating an admin account on startup
|
||||
# Useful for headless/automated deployments
|
||||
|
|
@ -907,9 +883,7 @@ ENABLE_OPENAI_API_PASSTHROUGH = os.getenv('ENABLE_OPENAI_API_PASSTHROUGH', 'Fals
|
|||
|
||||
WEBUI_AUTH_SIGNOUT_REDIRECT_URL = os.getenv('WEBUI_AUTH_SIGNOUT_REDIRECT_URL', None)
|
||||
|
||||
####################################
|
||||
# OAUTH Configuration
|
||||
####################################
|
||||
ENABLE_OAUTH_EMAIL_FALLBACK = os.getenv('ENABLE_OAUTH_EMAIL_FALLBACK', 'False').lower() == 'true'
|
||||
|
||||
ENABLE_OAUTH_ID_TOKEN_COOKIE = os.getenv('ENABLE_OAUTH_ID_TOKEN_COOKIE', 'True').lower() == 'true'
|
||||
|
|
@ -944,9 +918,7 @@ OAUTH_TOKEN_EXCHANGE_TRUSTED_CLIENT_IDS = [
|
|||
# Requires Redis for JWT revocation.
|
||||
ENABLE_OAUTH_BACKCHANNEL_LOGOUT = os.getenv('ENABLE_OAUTH_BACKCHANNEL_LOGOUT', 'False').lower() == 'true'
|
||||
|
||||
####################################
|
||||
# SCIM Configuration
|
||||
####################################
|
||||
|
||||
ENABLE_SCIM = os.getenv('ENABLE_SCIM', os.getenv('SCIM_ENABLED', 'False')).lower() == 'true'
|
||||
SCIM_TOKEN = os.getenv('SCIM_TOKEN', '')
|
||||
|
|
@ -959,9 +931,7 @@ if ENABLE_SCIM and not SCIM_AUTH_PROVIDER:
|
|||
'to enable externalId storage.'
|
||||
)
|
||||
|
||||
####################################
|
||||
# LICENSE_KEY
|
||||
####################################
|
||||
|
||||
LICENSE_KEY = os.getenv('LICENSE_KEY', '')
|
||||
|
||||
|
|
@ -984,9 +954,7 @@ if LICENSE_PUBLIC_KEY:
|
|||
)
|
||||
|
||||
|
||||
####################################
|
||||
# WEBUI Identity
|
||||
####################################
|
||||
|
||||
# LICENSE covers this Open WebUI branding surface, including name, logo,
|
||||
# visual, textual, symbolic identifiers, metadata, and surrounding UI.
|
||||
|
|
@ -1004,9 +972,7 @@ WEBUI_FAVICON_URL = 'https://openwebui.com/favicon.png'
|
|||
WEBUI_BUILD_HASH = os.getenv('WEBUI_BUILD_HASH', 'dev-build')
|
||||
TRUSTED_SIGNATURE_KEY = os.getenv('TRUSTED_SIGNATURE_KEY', '')
|
||||
|
||||
####################################
|
||||
# Feature flags
|
||||
####################################
|
||||
|
||||
SAFE_MODE = os.getenv('SAFE_MODE', 'False').lower() == 'true'
|
||||
ENABLE_EASTER_EGGS = os.getenv('ENABLE_EASTER_EGGS', 'True').lower() == 'true'
|
||||
|
|
@ -1028,9 +994,7 @@ PROFILE_IMAGE_ALLOWED_MIME_TYPES = frozenset(
|
|||
_profile_image_max_data_uri_size = os.getenv('PROFILE_IMAGE_MAX_DATA_URI_SIZE', '').strip()
|
||||
PROFILE_IMAGE_MAX_DATA_URI_SIZE = int(_profile_image_max_data_uri_size) if _profile_image_max_data_uri_size else None
|
||||
|
||||
####################################
|
||||
# Forward Headers
|
||||
####################################
|
||||
|
||||
ENABLE_FORWARD_USER_INFO_HEADERS = os.getenv('ENABLE_FORWARD_USER_INFO_HEADERS', 'False').lower() == 'true'
|
||||
|
||||
|
|
@ -1053,9 +1017,7 @@ try:
|
|||
except ValueError:
|
||||
FORWARD_USER_INFO_HEADER_JWT_EXPIRES_SECONDS = 300
|
||||
|
||||
####################################
|
||||
# Progressive Web App
|
||||
####################################
|
||||
|
||||
# LICENSE covers this install-time Open WebUI branding surface, including
|
||||
# names, logos, manifests, metadata, and surrounding UI.
|
||||
|
|
@ -1063,18 +1025,14 @@ except ValueError:
|
|||
# https://docs.openwebui.com/license.
|
||||
EXTERNAL_PWA_MANIFEST_URL = os.getenv('EXTERNAL_PWA_MANIFEST_URL', None)
|
||||
|
||||
####################################
|
||||
# GROUP DEFAULTS
|
||||
####################################
|
||||
# Group defaults
|
||||
|
||||
# Controls the default "Who can share to this group" setting for new groups.
|
||||
# Env var values: "true" (anyone), "false" (no one), "members" (only group members).
|
||||
_default_group_share = os.getenv('DEFAULT_GROUP_SHARE_PERMISSION', 'members').strip().lower()
|
||||
DEFAULT_GROUP_SHARE_PERMISSION = 'members' if _default_group_share == 'members' else _default_group_share == 'true'
|
||||
|
||||
####################################
|
||||
# MODELS
|
||||
####################################
|
||||
# Models
|
||||
|
||||
ENABLE_CUSTOM_MODEL_FALLBACK = os.getenv('ENABLE_CUSTOM_MODEL_FALLBACK', 'False').lower() == 'true'
|
||||
|
||||
|
|
@ -1088,9 +1046,7 @@ else:
|
|||
MODELS_CACHE_TTL = 1
|
||||
|
||||
|
||||
####################################
|
||||
# CHAT
|
||||
####################################
|
||||
# Chat
|
||||
|
||||
ENABLE_CHAT_RESPONSE_BASE64_IMAGE_URL_CONVERSION = (
|
||||
os.getenv('ENABLE_CHAT_RESPONSE_BASE64_IMAGE_URL_CONVERSION', 'False').lower() == 'true'
|
||||
|
|
@ -1128,16 +1084,16 @@ else:
|
|||
# The old CHAT_RESPONSE_MAX_TOOL_CALL_RETRIES name is accepted as a fallback.
|
||||
CHAT_RESPONSE_MAX_TOOL_CALL_ITERATIONS = os.getenv(
|
||||
'CHAT_RESPONSE_MAX_TOOL_CALL_ITERATIONS',
|
||||
os.getenv('CHAT_RESPONSE_MAX_TOOL_CALL_RETRIES', '256'),
|
||||
os.getenv('CHAT_RESPONSE_MAX_TOOL_CALL_RETRIES', '1024'),
|
||||
)
|
||||
|
||||
if CHAT_RESPONSE_MAX_TOOL_CALL_ITERATIONS == '':
|
||||
CHAT_RESPONSE_MAX_TOOL_CALL_ITERATIONS = 256
|
||||
CHAT_RESPONSE_MAX_TOOL_CALL_ITERATIONS = 1024
|
||||
else:
|
||||
try:
|
||||
CHAT_RESPONSE_MAX_TOOL_CALL_ITERATIONS = int(CHAT_RESPONSE_MAX_TOOL_CALL_ITERATIONS)
|
||||
except Exception:
|
||||
CHAT_RESPONSE_MAX_TOOL_CALL_ITERATIONS = 256
|
||||
CHAT_RESPONSE_MAX_TOOL_CALL_ITERATIONS = 1024
|
||||
|
||||
# -1 means unlimited (no cap).
|
||||
if CHAT_RESPONSE_MAX_TOOL_CALL_ITERATIONS == -1:
|
||||
|
|
@ -1162,9 +1118,7 @@ else:
|
|||
CHAT_STREAM_RESPONSE_CHUNK_MAX_BUFFER_SIZE = None
|
||||
|
||||
|
||||
####################################
|
||||
# SENTENCE TRANSFORMERS
|
||||
####################################
|
||||
# Sentence transformers
|
||||
|
||||
|
||||
SENTENCE_TRANSFORMERS_BACKEND = os.getenv('SENTENCE_TRANSFORMERS_BACKEND', '')
|
||||
|
|
@ -1203,9 +1157,7 @@ SENTENCE_TRANSFORMERS_CROSS_ENCODER_SIGMOID_ACTIVATION_FUNCTION = (
|
|||
os.getenv('SENTENCE_TRANSFORMERS_CROSS_ENCODER_SIGMOID_ACTIVATION_FUNCTION', 'True').lower() == 'true'
|
||||
)
|
||||
|
||||
####################################
|
||||
# KNOWLEDGE TOOLS
|
||||
####################################
|
||||
# Knowledge tools
|
||||
|
||||
|
||||
def _int_env(name: str, default: int) -> int:
|
||||
|
|
@ -1225,9 +1177,7 @@ KNOWLEDGE_GREP_MAX_MATCHES = _int_env('KNOWLEDGE_GREP_MAX_MATCHES', 50)
|
|||
VIEW_FILE_MAX_CHARS = _int_env('VIEW_FILE_MAX_CHARS', 100_000)
|
||||
VIEW_FILE_DEFAULT_MAX_CHARS = _int_env('VIEW_FILE_DEFAULT_MAX_CHARS', 10_000)
|
||||
|
||||
####################################
|
||||
# TOOLS/FUNCTIONS PIP OPTIONS
|
||||
####################################
|
||||
# Tools/functions pip options
|
||||
|
||||
ENABLE_PLUGINS = os.getenv('ENABLE_PLUGINS', 'True').lower() == 'true'
|
||||
# Deployment controls: the master switch always overrides all feature switches.
|
||||
|
|
@ -1243,9 +1193,7 @@ PIP_OPTIONS = os.getenv('PIP_OPTIONS', '').split()
|
|||
PIP_PACKAGE_INDEX_OPTIONS = os.getenv('PIP_PACKAGE_INDEX_OPTIONS', '').split()
|
||||
|
||||
|
||||
####################################
|
||||
# OFFLINE_MODE
|
||||
####################################
|
||||
|
||||
ENABLE_VERSION_UPDATE_CHECK = os.getenv('ENABLE_VERSION_UPDATE_CHECK', 'true').lower() == 'true'
|
||||
OFFLINE_MODE = os.getenv('OFFLINE_MODE', 'false').lower() == 'true'
|
||||
|
|
@ -1254,15 +1202,11 @@ if OFFLINE_MODE:
|
|||
os.environ['HF_HUB_OFFLINE'] = '1'
|
||||
ENABLE_VERSION_UPDATE_CHECK = False
|
||||
|
||||
####################################
|
||||
# Pyodide file persistence
|
||||
####################################
|
||||
|
||||
ENABLE_PYODIDE_FILE_PERSISTENCE = os.getenv('ENABLE_PYODIDE_FILE_PERSISTENCE', 'false').lower() == 'true'
|
||||
|
||||
####################################
|
||||
# Audit logging
|
||||
####################################
|
||||
|
||||
|
||||
ENABLE_AUDIT_STDOUT = os.getenv('ENABLE_AUDIT_STDOUT', 'False').lower() == 'true'
|
||||
|
|
@ -1306,9 +1250,7 @@ AUDIT_INCLUDED_PATHS = [
|
|||
ENABLE_AUDIT_GET_REQUESTS = os.getenv('ENABLE_AUDIT_GET_REQUESTS', 'False').lower() == 'true'
|
||||
|
||||
|
||||
####################################
|
||||
# OPENTELEMETRY
|
||||
####################################
|
||||
# OpenTelemetry
|
||||
|
||||
ENABLE_OTEL = os.getenv('ENABLE_OTEL', 'False').lower() == 'true'
|
||||
ENABLE_OTEL_TRACES = os.getenv('ENABLE_OTEL_TRACES', 'False').lower() == 'true'
|
||||
|
|
|
|||
|
|
@ -5,9 +5,9 @@ import inspect
|
|||
import logging
|
||||
import time
|
||||
import uuid
|
||||
from types import SimpleNamespace
|
||||
from typing import Any
|
||||
|
||||
from fastapi import Request
|
||||
from pydantic import BaseModel, ConfigDict, Field, model_validator
|
||||
|
||||
from open_webui.env import ENABLE_FUNCTIONS, VERSION
|
||||
|
|
@ -43,6 +43,13 @@ class EventDefinition(BaseModel):
|
|||
class EventDefinitions(BaseModel):
|
||||
model_config = ConfigDict(frozen=True)
|
||||
|
||||
COMMENT_CREATED: EventDefinition = EventDefinition(
|
||||
name='comment.created', description='A resource comment or reply was created.', message='Comment created'
|
||||
)
|
||||
COMMENT_UPDATED: EventDefinition = EventDefinition(
|
||||
name='comment.updated', description='A resource comment was edited.', message='Comment updated'
|
||||
)
|
||||
|
||||
SYSTEM_STARTUP_STARTED: EventDefinition = EventDefinition(
|
||||
name='system.startup.started', description='Application startup began.', message='Startup started'
|
||||
)
|
||||
|
|
@ -540,6 +547,12 @@ class EventDefinitions(BaseModel):
|
|||
TOOL_UPDATED: EventDefinition = EventDefinition(
|
||||
name='tool.updated', description='A tool was updated.', message='Tool updated'
|
||||
)
|
||||
TOOL_ENABLED: EventDefinition = EventDefinition(
|
||||
name='tool.enabled', description='A tool was enabled.', message='Tool enabled'
|
||||
)
|
||||
TOOL_DISABLED: EventDefinition = EventDefinition(
|
||||
name='tool.disabled', description='A tool was disabled.', message='Tool disabled'
|
||||
)
|
||||
TOOL_DELETED: EventDefinition = EventDefinition(
|
||||
name='tool.deleted', description='A tool was deleted.', message='Tool deleted'
|
||||
)
|
||||
|
|
@ -704,7 +717,6 @@ NOTIFICATION_EVENTS = (
|
|||
EVENTS.CHAT_FAILED.name,
|
||||
EVENTS.CHANNEL_MESSAGE.name,
|
||||
EVENTS.CALENDAR_ALERT.name,
|
||||
EVENTS.RETRIEVAL_CONTENT_PROCESS_FAILED.name,
|
||||
EVENTS.AUTOMATION_RUN_FAILED.name,
|
||||
)
|
||||
|
||||
|
|
@ -1027,7 +1039,7 @@ def event_name(event: EventDefinition | str) -> str:
|
|||
|
||||
|
||||
def build_event(
|
||||
request_or_app: Any,
|
||||
request: Request | None,
|
||||
event: EventDefinition | str,
|
||||
*,
|
||||
actor: Any | None = None,
|
||||
|
|
@ -1036,9 +1048,10 @@ def build_event(
|
|||
source: str = 'api',
|
||||
data: dict | None = None,
|
||||
message: str | None = None,
|
||||
event_id: str | None = None,
|
||||
) -> Event:
|
||||
event_name_value = event_name(event)
|
||||
app = getattr(request_or_app, 'app', request_or_app)
|
||||
app = request.app if request is not None else None
|
||||
parts = event_name_value.split('.')
|
||||
resource = '.'.join(parts[:-1])
|
||||
instance_id = getattr(getattr(app, 'state', None), 'instance_id', None)
|
||||
|
|
@ -1050,7 +1063,7 @@ def build_event(
|
|||
|
||||
return Event(
|
||||
schema=VERSION,
|
||||
id=str(uuid.uuid4()),
|
||||
id=event_id or str(uuid.uuid4()),
|
||||
event=event_name_value,
|
||||
resource=resource,
|
||||
operation=parts[-1],
|
||||
|
|
@ -1101,8 +1114,8 @@ def schedule_webhook_dispatch(app: Any, event: Event) -> None:
|
|||
|
||||
|
||||
class WebhookEventSink:
|
||||
async def handle_event(self, app: Any, event: Event, request: Any | None = None) -> None:
|
||||
schedule_webhook_dispatch(app, event)
|
||||
async def handle_event(self, request: Request, event: Event) -> None:
|
||||
schedule_webhook_dispatch(request.app, event)
|
||||
|
||||
|
||||
def schedule_notification_dispatch(app: Any, event: Event) -> None:
|
||||
|
|
@ -1115,13 +1128,13 @@ def schedule_notification_dispatch(app: Any, event: Event) -> None:
|
|||
|
||||
|
||||
class NotificationEventSink:
|
||||
async def handle_event(self, app: Any, event: Event, request: Any | None = None) -> None:
|
||||
async def handle_event(self, request: Request, event: Event) -> None:
|
||||
if event.event in NOTIFICATION_EVENTS:
|
||||
schedule_notification_dispatch(app, event)
|
||||
schedule_notification_dispatch(request.app, event)
|
||||
|
||||
|
||||
class SocketSessionEventSink:
|
||||
async def handle_event(self, app: Any, event: Event, request: Any | None = None) -> None:
|
||||
async def handle_event(self, request: Request, event: Event) -> None:
|
||||
from open_webui.socket.main import refresh_chat_access
|
||||
|
||||
if event.event in {
|
||||
|
|
@ -1156,7 +1169,7 @@ class SocketSessionEventSink:
|
|||
|
||||
|
||||
async def dispatch_event_functions(
|
||||
app: Any, event: Event, request: Any | None = None, extra_function_ids: list[str] | None = None
|
||||
request: Request, event: Event, extra_function_ids: list[str] | None = None
|
||||
) -> None:
|
||||
if not ENABLE_FUNCTIONS:
|
||||
return
|
||||
|
|
@ -1164,7 +1177,6 @@ async def dispatch_event_functions(
|
|||
from open_webui.models.functions import Functions
|
||||
from open_webui.utils.plugin import get_function_module_from_cache
|
||||
|
||||
context = request or SimpleNamespace(app=app)
|
||||
event_payload = event.model_dump()
|
||||
|
||||
try:
|
||||
|
|
@ -1181,7 +1193,7 @@ async def dispatch_event_functions(
|
|||
|
||||
for function in event_functions:
|
||||
try:
|
||||
function_module, _, _ = await get_function_module_from_cache(context, function.id, function=function)
|
||||
function_module, _, _ = await get_function_module_from_cache(request, function.id, function=function)
|
||||
handler = getattr(function_module, 'event', None)
|
||||
if not handler:
|
||||
continue
|
||||
|
|
@ -1198,7 +1210,7 @@ async def dispatch_event_functions(
|
|||
'__event__': event,
|
||||
'__event_id__': event.id,
|
||||
'__event_name__': event.event,
|
||||
'__app__': app,
|
||||
'__app__': request.app,
|
||||
'__request__': request,
|
||||
}
|
||||
params = {key: value for key, value in extra_params.items() if accepts_kwargs or key in sig.parameters}
|
||||
|
|
@ -1211,24 +1223,32 @@ async def dispatch_event_functions(
|
|||
log.exception('Event function failed for %s', function.id)
|
||||
|
||||
|
||||
def schedule_event_function_dispatch(app: Any, event: Event, request: Any | None = None) -> None:
|
||||
def schedule_event_function_dispatch(request: Request, event: Event) -> None:
|
||||
try:
|
||||
asyncio.create_task(dispatch_event_functions(app, event, request))
|
||||
asyncio.create_task(dispatch_event_functions(request, event))
|
||||
except RuntimeError:
|
||||
log.exception('Event functions could not be scheduled for %s', event.event)
|
||||
|
||||
|
||||
class EventFunctionSink:
|
||||
async def handle_event(self, app: Any, event: Event, request: Any | None = None) -> None:
|
||||
schedule_event_function_dispatch(app, event, request)
|
||||
async def handle_event(self, request: Request, event: Event) -> None:
|
||||
schedule_event_function_dispatch(request, event)
|
||||
|
||||
|
||||
EVENT_SINKS = [SocketSessionEventSink(), EventFunctionSink(), WebhookEventSink(), NotificationEventSink()]
|
||||
|
||||
|
||||
async def _dispatch_event(request, event_payload):
|
||||
for sink in EVENT_SINKS:
|
||||
try:
|
||||
await sink.handle_event(request, event_payload)
|
||||
except Exception:
|
||||
log.exception('Event sink failed for %s', event_payload.event)
|
||||
|
||||
|
||||
async def publish_event(
|
||||
request_or_app: Any,
|
||||
event: EventDefinition | str,
|
||||
request: Request,
|
||||
event: EventDefinition | str | Event,
|
||||
*,
|
||||
actor: Any | None = None,
|
||||
subject_id: Any | None = None,
|
||||
|
|
@ -1237,28 +1257,26 @@ async def publish_event(
|
|||
data: dict | None = None,
|
||||
message: str | None = None,
|
||||
) -> None:
|
||||
app = getattr(request_or_app, 'app', request_or_app)
|
||||
request = request_or_app if hasattr(request_or_app, 'app') else None
|
||||
event_payload = build_event(
|
||||
request_or_app,
|
||||
event,
|
||||
actor=actor,
|
||||
subject_id=subject_id,
|
||||
subject_type=subject_type,
|
||||
source=source,
|
||||
data=data,
|
||||
message=message,
|
||||
"""Deliver an event through the existing sinks. Call after committing source changes."""
|
||||
event_payload = (
|
||||
event
|
||||
if isinstance(event, Event)
|
||||
else build_event(
|
||||
request,
|
||||
event,
|
||||
actor=actor,
|
||||
subject_id=subject_id,
|
||||
subject_type=subject_type,
|
||||
source=source,
|
||||
data=data,
|
||||
message=message,
|
||||
)
|
||||
)
|
||||
|
||||
for sink in EVENT_SINKS:
|
||||
try:
|
||||
await sink.handle_event(app, event_payload, request=request)
|
||||
except Exception:
|
||||
log.exception('Event sink failed for %s', event_payload.event)
|
||||
await _dispatch_event(request, event_payload)
|
||||
|
||||
|
||||
async def publish_model_provider_request_failed(
|
||||
request_or_app: Any,
|
||||
request: Request,
|
||||
*,
|
||||
actor: Any | None,
|
||||
provider: str,
|
||||
|
|
@ -1319,7 +1337,7 @@ async def publish_model_provider_request_failed(
|
|||
data['upstream_message'] = error
|
||||
|
||||
await publish_event(
|
||||
request_or_app,
|
||||
request,
|
||||
EVENTS.MODEL_PROVIDER_REQUEST_FAILED,
|
||||
actor=actor,
|
||||
subject_id=requested_model,
|
||||
|
|
|
|||
|
|
@ -31,9 +31,9 @@ from open_webui.utils.access_control import check_model_access
|
|||
from open_webui.utils.json_codec import JSONCodec
|
||||
from open_webui.utils.misc import (
|
||||
add_or_update_system_message,
|
||||
chat_completion_chunk_template,
|
||||
chat_completion_message_template,
|
||||
get_last_user_message,
|
||||
openai_chat_chunk_message_template,
|
||||
openai_chat_completion_message_template,
|
||||
prepend_to_first_user_message_content,
|
||||
)
|
||||
from open_webui.utils.oauth import get_system_oauth_token
|
||||
|
|
@ -184,7 +184,7 @@ async def generate_function_chat_completion(request, form_data, user, models: di
|
|||
if line.startswith('data:'):
|
||||
return f'{line}\n\n'
|
||||
else:
|
||||
line = openai_chat_chunk_message_template(form_data['model'], line)
|
||||
line = chat_completion_chunk_template(form_data['model'], line)
|
||||
return f'data: {JSONCodec.dumps(line)}\n\n'
|
||||
|
||||
def get_pipe_id(form_data: dict) -> str:
|
||||
|
|
@ -304,7 +304,7 @@ async def generate_function_chat_completion(request, form_data, user, models: di
|
|||
return
|
||||
|
||||
if isinstance(res, str):
|
||||
message = openai_chat_chunk_message_template(form_data['model'], res)
|
||||
message = chat_completion_chunk_template(form_data['model'], res)
|
||||
yield f'data: {JSONCodec.dumps(message)}\n\n'
|
||||
|
||||
if isinstance(res, Iterator):
|
||||
|
|
@ -315,7 +315,7 @@ async def generate_function_chat_completion(request, form_data, user, models: di
|
|||
async for line in res:
|
||||
yield process_line(form_data, line)
|
||||
|
||||
finish_message = openai_chat_chunk_message_template(form_data['model'], '')
|
||||
finish_message = chat_completion_chunk_template(form_data['model'], '')
|
||||
finish_message['choices'][0]['finish_reason'] = 'stop'
|
||||
yield f'data: {JSONCodec.dumps(finish_message)}\n\n'
|
||||
yield 'data: [DONE]'
|
||||
|
|
@ -335,4 +335,4 @@ async def generate_function_chat_completion(request, form_data, user, models: di
|
|||
return res.model_dump()
|
||||
|
||||
message = await get_message_content(res)
|
||||
return openai_chat_completion_message_template(form_data['model'], message)
|
||||
return chat_completion_message_template(form_data['model'], message)
|
||||
|
|
|
|||
|
|
@ -43,17 +43,7 @@ from typing_extensions import Self
|
|||
log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
# ── SSL URL normalization (used by sync engine & Alembic migrations) ─
|
||||
#
|
||||
# psycopg2 (sync) needs ``sslmode=`` in the connection string (it does
|
||||
# not recognise the bare ``ssl=`` key that some ORMs emit). The helpers
|
||||
# below strip all SSL-related query params, normalise them, and
|
||||
# reattach them in the canonical libpq form.
|
||||
#
|
||||
# The **async** engine now uses psycopg (v3), which speaks libpq
|
||||
# natively, so it needs no translation at all — the DATABASE_URL is
|
||||
# passed through as-is.
|
||||
# ─────────────────────────────────────────────────────────────────────
|
||||
# Normalize SSL query parameters for sync psycopg2 and Alembic; async psycopg uses the URL unchanged.
|
||||
|
||||
|
||||
def _pop_first(params: dict[str, list[str]], key: str) -> str | None:
|
||||
|
|
@ -281,10 +271,8 @@ def _create_async_engine(*args, **kwargs):
|
|||
return create_async_engine(*args, **_json_codec_kwargs(kwargs))
|
||||
|
||||
|
||||
# ============================================================
|
||||
# SYNC ENGINE (used only for: startup migrations, config loading,
|
||||
# Sync engine (used only for: startup migrations, config loading,
|
||||
# Alembic, peewee migration, health checks)
|
||||
# ============================================================
|
||||
|
||||
# Handle SQLCipher URLs
|
||||
if SQLALCHEMY_DATABASE_URL.startswith('sqlite+sqlcipher://'):
|
||||
|
|
@ -443,9 +431,7 @@ def get_session():
|
|||
get_db = contextmanager(get_session)
|
||||
|
||||
|
||||
# ============================================================
|
||||
# ASYNC ENGINE (used for ALL runtime database operations)
|
||||
# ============================================================
|
||||
# Async engine (used for all runtime database operations)
|
||||
|
||||
# psycopg (v3) speaks libpq natively — the full DATABASE_URL is passed
|
||||
# through as-is. SSL params, ``options``, ``target_session_attrs``, etc.
|
||||
|
|
|
|||
|
|
@ -22,7 +22,6 @@ from fastapi import (
|
|||
applications,
|
||||
status,
|
||||
)
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.openapi.docs import get_swagger_ui_html
|
||||
from fastapi.responses import FileResponse, JSONResponse
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
|
|
@ -158,6 +157,7 @@ from open_webui.routers import (
|
|||
calendar,
|
||||
channels,
|
||||
chats,
|
||||
comments,
|
||||
configs,
|
||||
evaluations,
|
||||
files,
|
||||
|
|
@ -208,6 +208,7 @@ from open_webui.socket.main import (
|
|||
from open_webui.tasks import (
|
||||
cleanup_task,
|
||||
create_task,
|
||||
get_response_streams_by_chat_id,
|
||||
has_active_tasks,
|
||||
list_task_ids_by_item_id,
|
||||
list_tasks,
|
||||
|
|
@ -220,7 +221,7 @@ from open_webui.utils import logger
|
|||
from open_webui.utils.access_control import has_permission
|
||||
from open_webui.utils.access_control.folders import has_folder_write_access
|
||||
from open_webui.utils.actions import chat_action as chat_action_handler
|
||||
from open_webui.utils.asgi_middleware import AppHTTPMiddleware
|
||||
from open_webui.utils.asgi_middleware import AppHTTPMiddleware, BrowserCORSMiddleware
|
||||
from open_webui.utils.audit import AuditLevel, AuditLoggingMiddleware
|
||||
from open_webui.utils.auth import (
|
||||
create_admin_user,
|
||||
|
|
@ -232,7 +233,9 @@ from open_webui.utils.auth import (
|
|||
is_valid_token,
|
||||
)
|
||||
from open_webui.utils.chat import (
|
||||
register_temporary_chat_session,
|
||||
chat_completed as chat_completed_handler,
|
||||
get_temporary_chat,
|
||||
)
|
||||
from open_webui.utils.chat import (
|
||||
generate_chat_completion as chat_completion_handler,
|
||||
|
|
@ -386,12 +389,24 @@ async def lifespan(app: FastAPI):
|
|||
|
||||
await import_legacy_config_json()
|
||||
await seed_registered_defaults()
|
||||
await app.state.oauth_manager.initialize()
|
||||
from open_webui.utils.mfa import validate_mfa_configuration
|
||||
|
||||
await validate_mfa_configuration()
|
||||
await initialize_runtime_config(app)
|
||||
await migrate_legacy_webhook_config()
|
||||
await publish_event(app, EVENTS.SYSTEM_STARTUP_STARTED, source='system')
|
||||
request = Request(
|
||||
{
|
||||
'type': 'http',
|
||||
'method': 'GET',
|
||||
'path': '/internal',
|
||||
'query_string': b'',
|
||||
'headers': [],
|
||||
'scheme': 'http',
|
||||
'app': app,
|
||||
}
|
||||
)
|
||||
await publish_event(request, EVENTS.SYSTEM_STARTUP_STARTED, source='system')
|
||||
|
||||
license_task = None
|
||||
if LICENSE_KEY:
|
||||
|
|
@ -502,11 +517,11 @@ async def lifespan(app: FastAPI):
|
|||
log.warning(f'License data retrieval failed during startup: {e}')
|
||||
|
||||
app.state.startup_complete = True
|
||||
await publish_event(app, EVENTS.SYSTEM_STARTUP_COMPLETED, source='system')
|
||||
await publish_event(request, EVENTS.SYSTEM_STARTUP_COMPLETED, source='system')
|
||||
|
||||
yield
|
||||
|
||||
await publish_event(app, EVENTS.SYSTEM_SHUTDOWN_STARTED, source='system')
|
||||
await publish_event(request, EVENTS.SYSTEM_SHUTDOWN_STARTED, source='system')
|
||||
await app_connections.close()
|
||||
|
||||
# Shutdown: clean up shared resources
|
||||
|
|
@ -528,7 +543,7 @@ async def lifespan(app: FastAPI):
|
|||
app.state.periodic_session_pool_cleanup.cancel()
|
||||
app.state.scheduler_worker_loop.cancel()
|
||||
|
||||
await publish_event(app, EVENTS.SYSTEM_SHUTDOWN_COMPLETED, source='system')
|
||||
await publish_event(request, EVENTS.SYSTEM_SHUTDOWN_COMPLETED, source='system')
|
||||
|
||||
|
||||
# ENABLE_ORJSON: orjson for request-body parsing and JSONResponse bodies;
|
||||
|
|
@ -576,11 +591,7 @@ app.state.USER_COUNT = None
|
|||
app.state.EXTERNAL_PWA_MANIFEST_URL = EXTERNAL_PWA_MANIFEST_URL
|
||||
|
||||
|
||||
########################################
|
||||
#
|
||||
# OPENTELEMETRY
|
||||
#
|
||||
########################################
|
||||
# OpenTelemetry
|
||||
|
||||
if ENABLE_OTEL:
|
||||
from open_webui.utils.telemetry.setup import setup as setup_opentelemetry
|
||||
|
|
@ -588,69 +599,34 @@ if ENABLE_OTEL:
|
|||
setup_opentelemetry(app=app, db_engine=engine)
|
||||
|
||||
|
||||
########################################
|
||||
#
|
||||
# OLLAMA
|
||||
#
|
||||
########################################
|
||||
# Ollama
|
||||
|
||||
|
||||
app.state.OLLAMA_MODELS = {}
|
||||
|
||||
########################################
|
||||
#
|
||||
# OPENAI
|
||||
#
|
||||
########################################
|
||||
# OpenAI
|
||||
|
||||
|
||||
app.state.OPENAI_MODELS = {}
|
||||
|
||||
########################################
|
||||
#
|
||||
# TOOL SERVERS
|
||||
#
|
||||
########################################
|
||||
# Tool servers
|
||||
|
||||
app.state.TOOL_SERVERS = []
|
||||
|
||||
########################################
|
||||
#
|
||||
# TERMINAL SERVER
|
||||
#
|
||||
########################################
|
||||
# Terminal server
|
||||
|
||||
app.state.TERMINAL_SERVERS = []
|
||||
|
||||
########################################
|
||||
#
|
||||
# DIRECT CONNECTIONS
|
||||
#
|
||||
########################################
|
||||
|
||||
|
||||
########################################
|
||||
#
|
||||
# SCIM
|
||||
#
|
||||
########################################
|
||||
|
||||
app.state.ENABLE_SCIM = ENABLE_SCIM
|
||||
app.state.SCIM_TOKEN = SCIM_TOKEN
|
||||
|
||||
########################################
|
||||
#
|
||||
# MODELS
|
||||
#
|
||||
########################################
|
||||
# Models
|
||||
|
||||
app.state.BASE_MODELS = []
|
||||
|
||||
########################################
|
||||
#
|
||||
# WEBUI
|
||||
#
|
||||
########################################
|
||||
# WebUI
|
||||
|
||||
|
||||
async def initialize_runtime_config(app: FastAPI):
|
||||
|
|
@ -785,25 +761,7 @@ async def initialize_runtime_config(app: FastAPI):
|
|||
)
|
||||
|
||||
|
||||
########################################
|
||||
#
|
||||
# CODE EXECUTION
|
||||
#
|
||||
########################################
|
||||
|
||||
|
||||
########################################
|
||||
#
|
||||
# IMAGES
|
||||
#
|
||||
########################################
|
||||
|
||||
|
||||
########################################
|
||||
#
|
||||
# AUDIO
|
||||
#
|
||||
########################################
|
||||
# Audio
|
||||
|
||||
|
||||
app.state.faster_whisper_model = None
|
||||
|
|
@ -811,18 +769,7 @@ app.state.speech_synthesiser = None
|
|||
app.state.speech_speaker_embeddings_dataset = None
|
||||
|
||||
|
||||
########################################
|
||||
#
|
||||
# TASKS
|
||||
#
|
||||
########################################
|
||||
|
||||
|
||||
########################################
|
||||
#
|
||||
# WEBUI
|
||||
#
|
||||
########################################
|
||||
# WebUI
|
||||
|
||||
app.state.MODELS = MODELS
|
||||
|
||||
|
|
@ -850,19 +797,13 @@ if ENABLE_COMPRESSION_MIDDLEWARE:
|
|||
app.add_middleware(CompressMiddleware)
|
||||
|
||||
|
||||
# All HTTP middlewares below are pure-ASGI implementations. The previous
|
||||
# `BaseHTTPMiddleware` / `@app.middleware('http')` versions wrapped the
|
||||
# downstream app in an anyio task group whose cancel scope cancelled
|
||||
# in-flight DB calls (and any other awaits) on client disconnect /
|
||||
# response completion — which surfaced as noisy SQLAlchemy
|
||||
# `terminate_force_close` tracebacks under aiosqlite and as random
|
||||
# CancelledError storms across the request path. See
|
||||
# `open_webui.utils.asgi_middleware` for the rationale.
|
||||
# Use pure ASGI middleware to avoid BaseHTTPMiddleware cancellation of in-flight DB work.
|
||||
# See open_webui.utils.asgi_middleware for the disconnect and cleanup rationale.
|
||||
app.add_middleware(AppHTTPMiddleware)
|
||||
|
||||
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
BrowserCORSMiddleware,
|
||||
allow_origins=CORS_ALLOW_ORIGIN,
|
||||
allow_credentials=True,
|
||||
allow_methods=['*'],
|
||||
|
|
@ -894,6 +835,7 @@ app.include_router(users.router, prefix='/api/v1/users', tags=['users'])
|
|||
app.include_router(apps.router, prefix='/api/v1/apps', tags=['apps'])
|
||||
app.include_router(channels.router, prefix='/api/v1/channels', tags=['channels'])
|
||||
app.include_router(chats.router, prefix='/api/v1/chats', tags=['chats'])
|
||||
app.include_router(comments.router, prefix='/api/v1/comments', tags=['comments'])
|
||||
app.include_router(notes.router, prefix='/api/v1/notes', tags=['notes'])
|
||||
app.include_router(search.router, prefix='/api/v1/search', tags=['search'])
|
||||
|
||||
|
|
@ -923,11 +865,7 @@ if ENABLE_SCIM:
|
|||
app.include_router(scim.router, prefix='/api/v1/scim/v2', tags=['scim'])
|
||||
|
||||
|
||||
##################################
|
||||
#
|
||||
# Chat Endpoints
|
||||
#
|
||||
##################################
|
||||
|
||||
|
||||
@app.get('/api/models')
|
||||
|
|
@ -935,7 +873,7 @@ if ENABLE_SCIM:
|
|||
async def get_models(request: Request, refresh: bool = False, user=Depends(get_verified_user)):
|
||||
all_models = await get_all_models(request, refresh=refresh, user=user)
|
||||
|
||||
# Filter out filter pipelines
|
||||
# Keep filter pipelines off the model menu; they work backstage.
|
||||
models = [
|
||||
model for model in all_models if not ('pipeline' in model and model['pipeline'].get('type', None) == 'filter')
|
||||
]
|
||||
|
|
@ -952,7 +890,7 @@ async def get_models(request: Request, refresh: bool = False, user=Depends(get_v
|
|||
info = model.get('info') if isinstance(model.get('info'), dict) else {}
|
||||
meta = info.get('meta') if isinstance(info.get('meta'), dict) else {}
|
||||
|
||||
# Remove profile image URL to reduce payload size
|
||||
# Leave profile images out; this model list is traveling light.
|
||||
meta.pop('profile_image_url', None)
|
||||
|
||||
if 'tags' in meta:
|
||||
|
|
@ -964,7 +902,7 @@ async def get_models(request: Request, refresh: bool = False, user=Depends(get_v
|
|||
model_order_list = await Config.get('ui.model_order_list')
|
||||
if model_order_list:
|
||||
model_order_dict = {model_id: i for i, model_id in enumerate(model_order_list)}
|
||||
# Sort models by order list priority, with fallback for those not in the list
|
||||
# Configured models get the front seats; the rest line up by name.
|
||||
models.sort(
|
||||
key=lambda model: (
|
||||
model_order_dict.get(model.get('id', ''), float('inf')),
|
||||
|
|
@ -1009,7 +947,7 @@ async def unload_model(request: Request, form_data: ModelUnloadForm, user=Depend
|
|||
break
|
||||
model_id = model_info.base_model_id
|
||||
|
||||
# --- Ollama provider ---
|
||||
# Ollama provider
|
||||
if model_id in ollama_models:
|
||||
ollama_config = await Config.get_many('ollama.base_urls', 'ollama.api_configs')
|
||||
ollama_base_urls = ollama_config.get('ollama.base_urls') or []
|
||||
|
|
@ -1055,7 +993,7 @@ async def unload_model(request: Request, form_data: ModelUnloadForm, user=Depend
|
|||
)
|
||||
return {'status': True}
|
||||
|
||||
# --- OpenAI-compatible providers ---
|
||||
# OpenAI-compatible providers
|
||||
if model_id in openai_models:
|
||||
openai_config = await Config.get_many('openai.api_configs', 'openai.api_base_urls', 'openai.api_keys')
|
||||
openai_api_configs = openai_config.get('openai.api_configs') or {}
|
||||
|
|
@ -1102,9 +1040,7 @@ async def unload_model(request: Request, form_data: ModelUnloadForm, user=Depend
|
|||
raise HTTPException(status_code=404, detail=f'Model "{model_id}" not found')
|
||||
|
||||
|
||||
##################################
|
||||
# Embeddings
|
||||
##################################
|
||||
|
||||
|
||||
@app.post('/api/embeddings')
|
||||
|
|
@ -1364,6 +1300,18 @@ async def chat_completion(
|
|||
if is_new_chat:
|
||||
metadata['chat_id'] = str(uuid4())
|
||||
|
||||
if is_temporary_chat_id(metadata.get('chat_id')):
|
||||
session_id = metadata.get('session_id')
|
||||
if not isinstance(session_id, str) or not await register_temporary_chat_session(
|
||||
request.app.state.redis,
|
||||
metadata['chat_id'],
|
||||
user.id,
|
||||
session_id,
|
||||
get_user_id_from_session_pool(session_id),
|
||||
create=True,
|
||||
):
|
||||
raise HTTPException(status_code=404, detail='Temporary chat expired or unavailable')
|
||||
|
||||
initial_title_generation = None
|
||||
if is_new_chat and tasks and TASKS.TITLE_GENERATION in tasks:
|
||||
initial_title_generation = tasks.pop(TASKS.TITLE_GENERATION)
|
||||
|
|
@ -1963,18 +1911,14 @@ async def resolve_chat_message_tool_call(
|
|||
app.state.CHAT_COMPLETION_HANDLER = chat_completion
|
||||
|
||||
|
||||
##################################
|
||||
#
|
||||
# Anthropic Messages API Compatible Endpoint
|
||||
#
|
||||
##################################
|
||||
|
||||
|
||||
from open_webui.utils.anthropic import (
|
||||
convert_anthropic_to_openai_payload,
|
||||
convert_openai_to_anthropic_response,
|
||||
convert_anthropic_payload_to_chat_completions,
|
||||
convert_chat_completions_response_to_anthropic,
|
||||
convert_chat_completions_stream_to_anthropic,
|
||||
is_anthropic_messages_passthrough,
|
||||
openai_stream_to_anthropic_stream,
|
||||
)
|
||||
|
||||
|
||||
|
|
@ -2096,17 +2040,19 @@ async def generate_messages(
|
|||
return await passthrough_anthropic_messages(request, form_data, user)
|
||||
passthrough_params = api_config.get('passthrough_params') or []
|
||||
|
||||
# Convert Anthropic payload to OpenAI format
|
||||
openai_payload = convert_anthropic_to_openai_payload(form_data, passthrough_params)
|
||||
# Translate Anthropic into OpenAI before sending it through the house plumbing.
|
||||
openai_payload = convert_anthropic_payload_to_chat_completions(form_data, passthrough_params)
|
||||
|
||||
# Route through the existing chat_completion handler
|
||||
response = await chat_completion(request, openai_payload, user)
|
||||
|
||||
# Convert response back to Anthropic format
|
||||
# Translate back to Anthropic; the caller ordered that dialect.
|
||||
if isinstance(response, StreamingResponse):
|
||||
# Streaming response: wrap the generator to convert SSE format
|
||||
return StreamingResponse(
|
||||
openai_stream_to_anthropic_stream(response.body_iterator, model=requested_model, input_tokens=input_tokens),
|
||||
convert_chat_completions_stream_to_anthropic(
|
||||
response.body_iterator, model=requested_model, input_tokens=input_tokens
|
||||
),
|
||||
media_type='text/event-stream',
|
||||
headers={
|
||||
'Cache-Control': 'no-cache',
|
||||
|
|
@ -2114,7 +2060,9 @@ async def generate_messages(
|
|||
},
|
||||
)
|
||||
elif isinstance(response, dict):
|
||||
return convert_openai_to_anthropic_response(response, model=requested_model, input_tokens=input_tokens)
|
||||
return convert_chat_completions_response_to_anthropic(
|
||||
response, model=requested_model, input_tokens=input_tokens
|
||||
)
|
||||
else:
|
||||
# Passthrough for error responses (JSONResponse, PlainTextResponse, etc.)
|
||||
return response
|
||||
|
|
@ -2195,7 +2143,8 @@ async def list_tasks_endpoint(request: Request, user=Depends(get_admin_user)):
|
|||
async def list_tasks_by_chat_id_endpoint(request: Request, chat_id: str, user=Depends(get_verified_user)):
|
||||
socket_id = get_temporary_chat_session_id(chat_id)
|
||||
if socket_id:
|
||||
owner_id = get_user_id_from_session_pool(socket_id)
|
||||
owner = await get_temporary_chat(request.app.state.redis, chat_id)
|
||||
owner_id = owner['user_id'] if owner else get_user_id_from_session_pool(socket_id)
|
||||
if owner_id != user.id and not (user.role == 'admin' and ENABLE_ADMIN_CHAT_ACCESS):
|
||||
return {'task_ids': []}
|
||||
else:
|
||||
|
|
@ -2212,12 +2161,31 @@ async def list_tasks_by_chat_id_endpoint(request: Request, chat_id: str, user=De
|
|||
return {'task_ids': task_ids}
|
||||
|
||||
|
||||
@app.post('/api/tasks/chat/{chat_id:path}/resume')
|
||||
async def resume_temporary_chat(request: Request, chat_id: str, form_data: dict, user=Depends(get_verified_user)):
|
||||
session_id = form_data.get('session_id')
|
||||
if not isinstance(session_id, str) or not await register_temporary_chat_session(
|
||||
request.app.state.redis,
|
||||
chat_id,
|
||||
user.id,
|
||||
session_id,
|
||||
get_user_id_from_session_pool(session_id),
|
||||
create=True,
|
||||
):
|
||||
raise HTTPException(status_code=404, detail='Temporary chat expired or unavailable')
|
||||
return {
|
||||
'task_ids': await list_task_ids_by_item_id(request.app.state.redis, chat_id),
|
||||
'streams': await get_response_streams_by_chat_id(request.app.state.redis, chat_id),
|
||||
}
|
||||
|
||||
|
||||
@app.post('/api/tasks/chat/{chat_id:path}/stop')
|
||||
async def stop_tasks_by_chat_id_endpoint(request: Request, chat_id: str, user=Depends(get_verified_user)):
|
||||
socket_id = get_temporary_chat_session_id(chat_id)
|
||||
chat = None
|
||||
if socket_id:
|
||||
owner_id = get_user_id_from_session_pool(socket_id)
|
||||
owner = await get_temporary_chat(request.app.state.redis, chat_id)
|
||||
owner_id = owner['user_id'] if owner else get_user_id_from_session_pool(socket_id)
|
||||
if owner_id != user.id and not (user.role == 'admin' and ENABLE_ADMIN_CHAT_ACCESS):
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=ERROR_MESSAGES.NOT_FOUND)
|
||||
else:
|
||||
|
|
@ -2275,15 +2243,12 @@ async def stop_tasks_by_chat_id_endpoint(request: Request, chat_id: str, user=De
|
|||
if event_emitter:
|
||||
await event_emitter({'type': 'chat:completion', 'data': {'done': True, 'output': output}})
|
||||
await event_emitter({'type': 'chat:tasks:cancel'})
|
||||
await event_emitter({'type': 'chat:active', 'data': {'active': False}})
|
||||
|
||||
return result
|
||||
|
||||
|
||||
##################################
|
||||
#
|
||||
# Config Endpoints
|
||||
#
|
||||
##################################
|
||||
|
||||
|
||||
@app.get('/api/config')
|
||||
|
|
@ -2355,6 +2320,8 @@ async def get_app_config(request: Request):
|
|||
'calendar.enable',
|
||||
'automations.enable',
|
||||
'notes.enable',
|
||||
'comments.enable',
|
||||
'notifications.enable',
|
||||
'chat.context_compaction.enable',
|
||||
'chat.tool_permissions.enable',
|
||||
'web.search.enable',
|
||||
|
|
@ -2420,7 +2387,7 @@ async def get_app_config(request: Request):
|
|||
},
|
||||
'features': {
|
||||
'slim': USE_SLIM,
|
||||
# --- Public: required by login/signup page pre-auth ---
|
||||
# Public: required by login/signup page pre-auth
|
||||
'auth': WEBUI_AUTH,
|
||||
'auth_trusted_header': bool(WEBUI_AUTH_TRUSTED_EMAIL_HEADER),
|
||||
'enable_signup_password_confirmation': ENABLE_SIGNUP_PASSWORD_CONFIRMATION,
|
||||
|
|
@ -2433,7 +2400,7 @@ async def get_app_config(request: Request):
|
|||
if WEBSOCKET_HEARTBEAT_INTERVAL is not None
|
||||
else {}
|
||||
),
|
||||
# --- Authenticated: only consumed by logged-in frontend ---
|
||||
# Authenticated: only consumed by logged-in frontend
|
||||
**(
|
||||
{
|
||||
'enable_api_keys': config.get('auth.enable_api_keys'),
|
||||
|
|
@ -2462,6 +2429,8 @@ async def get_app_config(request: Request):
|
|||
'enable_calendar': config.get('calendar.enable'),
|
||||
'enable_automations': config.get('automations.enable'),
|
||||
'enable_notes': config.get('notes.enable'),
|
||||
'enable_comments': config.get('comments.enable'),
|
||||
'enable_notifications': config.get('notifications.enable'),
|
||||
'enable_context_compaction': config.get('chat.context_compaction.enable'),
|
||||
'enable_tool_permissions': config.get('chat.tool_permissions.enable'),
|
||||
'enable_web_search': config.get('web.search.enable'),
|
||||
|
|
@ -2617,7 +2586,7 @@ async def get_event_webhooks_api(user=Depends(get_admin_user)):
|
|||
|
||||
|
||||
@app.post('/api/events/webhooks')
|
||||
async def create_event_webhook(form_data: EventWebhookForm, user=Depends(get_admin_user)):
|
||||
async def create_event_webhook(request: Request, form_data: EventWebhookForm, user=Depends(get_admin_user)):
|
||||
try:
|
||||
webhook = await upsert_event_webhook(
|
||||
{
|
||||
|
|
@ -2632,7 +2601,7 @@ async def create_event_webhook(form_data: EventWebhookForm, user=Depends(get_adm
|
|||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))
|
||||
|
||||
await publish_event(
|
||||
app,
|
||||
request,
|
||||
EVENTS.CONFIG_WEBHOOK_UPDATED,
|
||||
actor=user,
|
||||
subject_id=webhook['id'],
|
||||
|
|
@ -2648,7 +2617,9 @@ async def create_event_webhook(form_data: EventWebhookForm, user=Depends(get_adm
|
|||
|
||||
|
||||
@app.put('/api/events/webhooks/{webhook_id}')
|
||||
async def update_event_webhook(webhook_id: str, form_data: EventWebhookUpdateForm, user=Depends(get_admin_user)):
|
||||
async def update_event_webhook(
|
||||
request: Request, webhook_id: str, form_data: EventWebhookUpdateForm, user=Depends(get_admin_user)
|
||||
):
|
||||
webhooks = await get_event_webhooks()
|
||||
existing = next((webhook for webhook in webhooks if webhook.get('id') == webhook_id), None)
|
||||
if not existing:
|
||||
|
|
@ -2666,7 +2637,7 @@ async def update_event_webhook(webhook_id: str, form_data: EventWebhookUpdateFor
|
|||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))
|
||||
|
||||
await publish_event(
|
||||
app,
|
||||
request,
|
||||
EVENTS.CONFIG_WEBHOOK_UPDATED,
|
||||
actor=user,
|
||||
subject_id=webhook_id,
|
||||
|
|
@ -2682,13 +2653,13 @@ async def update_event_webhook(webhook_id: str, form_data: EventWebhookUpdateFor
|
|||
|
||||
|
||||
@app.delete('/api/events/webhooks/{webhook_id}')
|
||||
async def delete_event_webhook_api(webhook_id: str, user=Depends(get_admin_user)):
|
||||
async def delete_event_webhook_api(request: Request, webhook_id: str, user=Depends(get_admin_user)):
|
||||
deleted = await delete_event_webhook(webhook_id)
|
||||
if not deleted:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail='Webhook not found')
|
||||
|
||||
await publish_event(
|
||||
app,
|
||||
request,
|
||||
EVENTS.CONFIG_WEBHOOK_UPDATED,
|
||||
actor=user,
|
||||
subject_id=webhook_id,
|
||||
|
|
@ -2758,7 +2729,7 @@ async def get_current_usage(user=Depends(get_verified_user)):
|
|||
raise HTTPException(status_code=500, detail='Internal Server Error')
|
||||
|
||||
|
||||
# --- OAuth Login & Callback ---
|
||||
# OAuth login & callback
|
||||
|
||||
|
||||
try:
|
||||
|
|
@ -2974,9 +2945,7 @@ async def oauth_login_callback(
|
|||
return await oauth_manager.handle_callback(request, provider, response, db=db)
|
||||
|
||||
|
||||
############################
|
||||
# OIDC Back-Channel Logout
|
||||
############################
|
||||
|
||||
|
||||
@app.post('/oauth/backchannel-logout')
|
||||
|
|
@ -3137,7 +3106,7 @@ async def check_db_health():
|
|||
return {'status': True}
|
||||
|
||||
|
||||
# --- static assets & files ---
|
||||
# Static assets & files
|
||||
# Windows registry entries can override these with text/plain, which breaks module and wasm loading
|
||||
mimetypes.add_type('text/javascript', '.js')
|
||||
mimetypes.add_type('text/javascript', '.mjs')
|
||||
|
|
|
|||
|
|
@ -14,6 +14,8 @@ from open_webui.models.auths import Auth
|
|||
from open_webui.models.calendar import Calendar, CalendarEvent, CalendarEventAttendee # noqa: F401
|
||||
from open_webui.models.chat_messages import ChatMessage # noqa: F401
|
||||
from open_webui.models.chats import Chat # noqa: F401
|
||||
from open_webui.models.comments import Comment, CommentReaction # noqa: F401
|
||||
from open_webui.models.notifications import Notification # noqa: F401
|
||||
from sqlalchemy import create_engine, engine_from_config, inspect, pool
|
||||
|
||||
alembic_config = alembic.context.config
|
||||
|
|
|
|||
|
|
@ -6,7 +6,7 @@ from alembic import op # noqa: E402 — alembic runtime context
|
|||
from sqlalchemy import inspect # metadata inspection
|
||||
|
||||
|
||||
# --- database helper functions ---
|
||||
# Database helper functions
|
||||
def get_existing_tables() -> set[str]:
|
||||
"""Return table names already present in the database."""
|
||||
conn = op.get_bind()
|
||||
|
|
|
|||
|
|
@ -22,7 +22,7 @@ def upgrade() -> None:
|
|||
inspector = sa.inspect(op.get_bind())
|
||||
existing_tables = set(inspector.get_table_names())
|
||||
|
||||
# ── Create oauth_session table (idempotent) ───────────────────────
|
||||
# Create oauth_session table (idempotent)
|
||||
if 'oauth_session' not in existing_tables:
|
||||
op.create_table(
|
||||
'oauth_session',
|
||||
|
|
|
|||
|
|
@ -0,0 +1,21 @@
|
|||
"""Add a persistent enabled state to tools.
|
||||
|
||||
Revision ID: 6f8c2a91d4e7
|
||||
Revises: c41f8d9e2a10
|
||||
"""
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
revision = '6f8c2a91d4e7'
|
||||
down_revision = 'c41f8d9e2a10'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
op.add_column('tool', sa.Column('is_active', sa.Boolean(), nullable=False, server_default=sa.true()))
|
||||
|
||||
|
||||
def downgrade():
|
||||
op.drop_column('tool', 'is_active')
|
||||
|
|
@ -178,7 +178,7 @@ _INITIAL_TABLES: list[tuple[str, list[sa.Column], list]] = [
|
|||
]
|
||||
|
||||
|
||||
# --- migration execution ---
|
||||
# Migration execution
|
||||
def upgrade() -> None: # deploy initial schema tables
|
||||
existing_tables = set(get_existing_tables())
|
||||
for name, columns, constraints in _INITIAL_TABLES:
|
||||
|
|
@ -186,7 +186,7 @@ def upgrade() -> None: # deploy initial schema tables
|
|||
op.create_table(name, *columns, *constraints)
|
||||
|
||||
|
||||
# --- rollback function ---
|
||||
# Rollback function
|
||||
def downgrade() -> None: # rollback initial schema tables
|
||||
for table_name, _, _ in reversed(_INITIAL_TABLES):
|
||||
op.drop_table(table_name)
|
||||
|
|
|
|||
|
|
@ -22,7 +22,7 @@ def upgrade():
|
|||
existing_tables = set(inspector.get_table_names())
|
||||
|
||||
if 'feedback' not in existing_tables:
|
||||
# ### Create feedback table ###
|
||||
# Create feedback table
|
||||
op.create_table(
|
||||
'feedback',
|
||||
sa.Column('id', sa.Text(), primary_key=True), # Unique identifier for each feedback (TEXT type)
|
||||
|
|
@ -42,5 +42,5 @@ def upgrade():
|
|||
|
||||
|
||||
def downgrade():
|
||||
# ### Drop feedback table ###
|
||||
# Drop feedback table
|
||||
op.drop_table('feedback')
|
||||
|
|
|
|||
|
|
@ -20,7 +20,7 @@ down_revision: Union[str, None] = '2f1211949ecc'
|
|||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
|
||||
# ── Ad-hoc table references for Core DML ─────────────────────────────────
|
||||
# Ad-hoc table references for Core DML
|
||||
# These are lightweight table() / column() references used only inside this
|
||||
# migration for SELECT / UPDATE / INSERT — they do NOT create or alter
|
||||
# anything on disk.
|
||||
|
|
@ -143,7 +143,7 @@ def upgrade() -> None:
|
|||
existing_tables = set(inspector.get_table_names())
|
||||
user_columns = {c['name'] for c in inspector.get_columns('user')}
|
||||
|
||||
# ── Add new columns (idempotent) ──────────────────────────────────
|
||||
# Add new columns (idempotent)
|
||||
for col_name, col_type in [
|
||||
('profile_banner_image_url', sa.Text()),
|
||||
('timezone', sa.String()),
|
||||
|
|
@ -164,7 +164,7 @@ def upgrade() -> None:
|
|||
if isinstance(user_col_types.get('settings'), sa.Text):
|
||||
_convert_column_to_json('user', 'settings')
|
||||
|
||||
# ── Create api_key table (idempotent) ─────────────────────────────
|
||||
# Create api_key table (idempotent)
|
||||
if 'api_key' not in existing_tables:
|
||||
op.create_table(
|
||||
'api_key',
|
||||
|
|
@ -178,7 +178,7 @@ def upgrade() -> None:
|
|||
sa.Column('updated_at', sa.BigInteger(), nullable=False),
|
||||
)
|
||||
|
||||
# ── Migrate oauth_sub → oauth JSON (only if old column still exists)
|
||||
# Migrate oauth_sub → OAuth JSON (only if old column still exists)
|
||||
if 'oauth_sub' in user_columns:
|
||||
rows = conn.execute(sa.select(_user.c.id, _user.c.oauth_sub).where(_user.c.oauth_sub.is_not(None))).fetchall()
|
||||
|
||||
|
|
@ -187,7 +187,7 @@ def upgrade() -> None:
|
|||
provider, sub = oauth_sub.split('@', 1) if '@' in oauth_sub else ('oidc', oauth_sub)
|
||||
conn.execute(sa.update(_user).where(_user.c.id == uid).values(oauth={provider: {'sub': sub}}))
|
||||
|
||||
# ── Migrate api_key column → api_key table (only if old column still exists)
|
||||
# Migrate api_key column → api_key table (only if old column still exists)
|
||||
if 'api_key' in user_columns:
|
||||
rows = conn.execute(sa.select(_user.c.id, _user.c.api_key).where(_user.c.api_key.is_not(None))).fetchall()
|
||||
now = int(time.time())
|
||||
|
|
@ -204,7 +204,7 @@ def upgrade() -> None:
|
|||
)
|
||||
)
|
||||
|
||||
# ── Drop legacy columns (idempotent) ──────────────────────────────
|
||||
# Drop legacy columns (idempotent)
|
||||
cols_to_drop = {'api_key', 'oauth_sub'} & user_columns
|
||||
if cols_to_drop:
|
||||
if conn.dialect.name == 'sqlite':
|
||||
|
|
@ -235,7 +235,7 @@ def downgrade() -> None:
|
|||
|
||||
op.drop_column('user', 'oauth')
|
||||
|
||||
# --- Restore api_key field ---
|
||||
# Restore api_key field
|
||||
op.add_column('user', sa.Column('api_key', sa.String(), nullable=True))
|
||||
|
||||
keys = conn.execute(sa.select(_api_key.c.user_id, _api_key.c.key)).fetchall()
|
||||
|
|
|
|||
|
|
@ -23,7 +23,7 @@ def upgrade():
|
|||
inspector = sa.inspect(conn)
|
||||
file_cols = {c['name'] for c in inspector.get_columns('file')}
|
||||
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
# Commands auto generated by alembic - please adjust!
|
||||
if 'hash' not in file_cols:
|
||||
op.add_column('file', sa.Column('hash', sa.Text(), nullable=True))
|
||||
if 'data' not in file_cols:
|
||||
|
|
@ -33,7 +33,7 @@ def upgrade():
|
|||
|
||||
|
||||
def downgrade():
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
# Commands auto generated by alembic - please adjust!
|
||||
op.drop_column('file', 'updated_at')
|
||||
op.drop_column('file', 'data')
|
||||
op.drop_column('file', 'hash')
|
||||
|
|
|
|||
|
|
@ -0,0 +1,50 @@
|
|||
"""Add resource comments and reactions.
|
||||
|
||||
Revision ID: c41f8d9e2a10
|
||||
Revises: 0bd252b206fb
|
||||
"""
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
revision = 'c41f8d9e2a10'
|
||||
down_revision = '0bd252b206fb'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
op.create_table(
|
||||
'comment',
|
||||
sa.Column('id', sa.Text(), primary_key=True),
|
||||
sa.Column('user_id', sa.Text(), nullable=True),
|
||||
sa.Column('resource_type', sa.Text(), nullable=False),
|
||||
sa.Column('resource_id', sa.Text(), nullable=False),
|
||||
sa.Column('parent_id', sa.Text(), nullable=True),
|
||||
sa.Column('reply_to_id', sa.Text(), nullable=True),
|
||||
sa.Column('content', sa.Text(), nullable=False),
|
||||
sa.Column('target_type', sa.Text(), nullable=True),
|
||||
sa.Column('target_id', sa.Text(), nullable=True),
|
||||
sa.Column('meta', sa.JSON(), nullable=True),
|
||||
sa.Column('created_at', sa.BigInteger(), nullable=False),
|
||||
sa.Column('updated_at', sa.BigInteger(), nullable=False),
|
||||
sa.Column('deleted_at', sa.BigInteger(), nullable=True),
|
||||
)
|
||||
op.create_index('ix_comment_resource', 'comment', ['resource_type', 'resource_id', 'parent_id', 'created_at', 'id'])
|
||||
op.create_index('ix_comment_parent', 'comment', ['parent_id', 'created_at', 'id'])
|
||||
op.create_index('ix_comment_target', 'comment', ['resource_type', 'resource_id', 'target_type', 'target_id'])
|
||||
op.create_table(
|
||||
'comment_reaction',
|
||||
sa.Column('id', sa.Text(), primary_key=True),
|
||||
sa.Column('user_id', sa.Text(), nullable=False),
|
||||
sa.Column('comment_id', sa.Text(), nullable=False),
|
||||
sa.Column('name', sa.Text(), nullable=False),
|
||||
sa.Column('created_at', sa.BigInteger(), nullable=False),
|
||||
sa.UniqueConstraint('comment_id', 'user_id', 'name', name='uq_comment_reaction'),
|
||||
)
|
||||
op.create_index('ix_comment_reaction_comment_id', 'comment_reaction', ['comment_id'])
|
||||
|
||||
|
||||
def downgrade():
|
||||
op.drop_table('comment_reaction')
|
||||
op.drop_table('comment')
|
||||
|
|
@ -0,0 +1,52 @@
|
|||
"""Add persistent general inbox notifications.
|
||||
|
||||
Revision ID: e42c8f710a36
|
||||
Revises: 6f8c2a91d4e7
|
||||
"""
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
revision = 'e42c8f710a36'
|
||||
down_revision = '6f8c2a91d4e7'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
op.create_table(
|
||||
'notification',
|
||||
sa.Column('id', sa.Text(), primary_key=True),
|
||||
sa.Column('user_id', sa.Text(), nullable=False),
|
||||
sa.Column('event_type', sa.Text(), nullable=False),
|
||||
sa.Column('event_key', sa.Text(), nullable=False),
|
||||
sa.Column('actor_type', sa.Text(), nullable=False),
|
||||
sa.Column('actor_id', sa.Text(), nullable=True),
|
||||
sa.Column('resource_type', sa.Text(), nullable=True),
|
||||
sa.Column('resource_id', sa.Text(), nullable=True),
|
||||
sa.Column('object_type', sa.Text(), nullable=True),
|
||||
sa.Column('object_id', sa.Text(), nullable=True),
|
||||
sa.Column('data', sa.JSON(), nullable=False),
|
||||
sa.Column('seen_at', sa.BigInteger(), nullable=True),
|
||||
sa.Column('read_at', sa.BigInteger(), nullable=True),
|
||||
sa.Column('created_at', sa.BigInteger(), nullable=False),
|
||||
sa.Column('updated_at', sa.BigInteger(), nullable=False),
|
||||
sa.UniqueConstraint('user_id', 'event_key', name='uq_notification_occurrence'),
|
||||
sa.CheckConstraint('(resource_type IS NULL) = (resource_id IS NULL)', name='ck_notification_resource'),
|
||||
sa.CheckConstraint('(object_type IS NULL) = (object_id IS NULL)', name='ck_notification_object'),
|
||||
sa.CheckConstraint("actor_type IN ('user', 'system')", name='ck_notification_actor'),
|
||||
)
|
||||
op.create_index('ix_notification_user_created', 'notification', ['user_id', 'created_at', 'id'])
|
||||
op.create_index(
|
||||
'ix_notification_unseen',
|
||||
'notification',
|
||||
['user_id', 'created_at', 'id'],
|
||||
sqlite_where=sa.text('seen_at IS NULL'),
|
||||
postgresql_where=sa.text('seen_at IS NULL'),
|
||||
)
|
||||
op.create_index('ix_notification_resource', 'notification', ['resource_type', 'resource_id'])
|
||||
op.create_index('ix_notification_object', 'notification', ['object_type', 'object_id'])
|
||||
|
||||
|
||||
def downgrade():
|
||||
op.drop_table('notification')
|
||||
|
|
@ -17,9 +17,7 @@ PRINCIPAL_TYPE_USER = 'user'
|
|||
WILDCARD_PRINCIPAL_ID = '*'
|
||||
|
||||
|
||||
####################
|
||||
# AccessGrant DB Schema
|
||||
####################
|
||||
|
||||
|
||||
class AccessGrant(Base):
|
||||
|
|
@ -75,9 +73,7 @@ class AccessGrantResponse(BaseModel):
|
|||
)
|
||||
|
||||
|
||||
####################
|
||||
# Conversion utilities
|
||||
####################
|
||||
|
||||
|
||||
def access_control_to_grants(
|
||||
|
|
@ -318,9 +314,7 @@ def grants_to_access_control(grants: list) -> Optional[dict]:
|
|||
return result
|
||||
|
||||
|
||||
####################
|
||||
# Table Operations
|
||||
####################
|
||||
|
||||
|
||||
class AccessGrantsTable:
|
||||
|
|
@ -582,47 +576,17 @@ class AccessGrantsTable:
|
|||
- There's a grant for any of the user's groups with the requested permission
|
||||
"""
|
||||
async with get_async_db_context(db) as db:
|
||||
# Build conditions for matching grants
|
||||
conditions = [
|
||||
# Public access
|
||||
and_(
|
||||
AccessGrant.principal_type == 'user',
|
||||
AccessGrant.principal_id == '*',
|
||||
),
|
||||
# Direct user access
|
||||
and_(
|
||||
AccessGrant.principal_type == 'user',
|
||||
AccessGrant.principal_id == user_id,
|
||||
),
|
||||
]
|
||||
|
||||
# Group access
|
||||
if user_group_ids is None:
|
||||
from open_webui.models.groups import Groups
|
||||
|
||||
user_groups = await Groups.get_groups_by_member_id(user_id, db=db, include_inherited=True)
|
||||
user_group_ids = {group.id for group in user_groups}
|
||||
|
||||
if user_group_ids:
|
||||
conditions.append(
|
||||
and_(
|
||||
AccessGrant.principal_type == 'group',
|
||||
AccessGrant.principal_id.in_(user_group_ids),
|
||||
)
|
||||
return bool(
|
||||
await db.scalar(
|
||||
select(self.has_grant_expression(user_id, resource_type, resource_id, permission, user_group_ids))
|
||||
)
|
||||
|
||||
result = await db.execute(
|
||||
select(AccessGrant)
|
||||
.filter(
|
||||
AccessGrant.resource_type == resource_type,
|
||||
AccessGrant.resource_id == resource_id,
|
||||
AccessGrant.permission == permission,
|
||||
or_(*conditions),
|
||||
)
|
||||
.limit(1)
|
||||
)
|
||||
grant = result.scalars().first()
|
||||
return grant is not None
|
||||
|
||||
async def get_accessible_resource_ids(
|
||||
self,
|
||||
|
|
@ -766,122 +730,55 @@ class AccessGrantsTable:
|
|||
user_ids = await self.get_user_ids_by_access_grants(access_grants, permission, db=db)
|
||||
return previous_user_ids - user_ids
|
||||
|
||||
def has_grant_expression(self, user_id, resource_type, resource_id, permission='read', user_group_ids=()):
|
||||
"""SQL grant check for one resource or a correlated resource column; ownership is separate."""
|
||||
return (
|
||||
select(AccessGrant.id)
|
||||
.where(
|
||||
AccessGrant.resource_type == resource_type,
|
||||
AccessGrant.resource_id == resource_id,
|
||||
AccessGrant.permission == permission,
|
||||
or_(
|
||||
and_(
|
||||
AccessGrant.principal_type == 'user',
|
||||
AccessGrant.principal_id.in_(['*', user_id] if user_id else ['*']),
|
||||
),
|
||||
and_(AccessGrant.principal_type == 'group', AccessGrant.principal_id.in_(user_group_ids or ())),
|
||||
),
|
||||
)
|
||||
.correlate_except(AccessGrant)
|
||||
.exists()
|
||||
)
|
||||
|
||||
def has_permission_filter(
|
||||
self,
|
||||
db,
|
||||
query,
|
||||
DocumentModel,
|
||||
filter: dict,
|
||||
resource_type: str,
|
||||
permission: str = 'read',
|
||||
*,
|
||||
db,
|
||||
):
|
||||
"""
|
||||
Apply access control filtering to a SQLAlchemy query by JOINing with access_grant.
|
||||
|
||||
This replaces the old JSON-column-based filtering with a proper relational JOIN.
|
||||
|
||||
Note: This method builds SQLAlchemy expressions and does NOT perform I/O itself,
|
||||
so it remains synchronous. The caller is responsible for executing the query
|
||||
asynchronously with `await db.execute(...)`.
|
||||
"""
|
||||
"""Apply owner-or-grant filtering without loading resources or duplicating rows."""
|
||||
if permission == 'read_only':
|
||||
return self._has_read_only_permission_filter(query, DocumentModel, filter, resource_type, db=db)
|
||||
group_ids = filter.get('group_ids', [])
|
||||
user_id = filter.get('user_id')
|
||||
|
||||
if permission == 'read_only':
|
||||
return self._has_read_only_permission_filter(db, query, DocumentModel, filter, resource_type)
|
||||
|
||||
# Build principal conditions
|
||||
principal_conditions = []
|
||||
|
||||
if group_ids or user_id:
|
||||
# Public access: user:* read
|
||||
principal_conditions.append(
|
||||
and_(
|
||||
AccessGrant.principal_type == 'user',
|
||||
AccessGrant.principal_id == '*',
|
||||
)
|
||||
)
|
||||
|
||||
if user_id:
|
||||
# Owner always has access
|
||||
principal_conditions.append(DocumentModel.user_id == user_id)
|
||||
|
||||
# Direct user grant
|
||||
principal_conditions.append(
|
||||
and_(
|
||||
AccessGrant.principal_type == 'user',
|
||||
AccessGrant.principal_id == user_id,
|
||||
)
|
||||
)
|
||||
|
||||
if group_ids:
|
||||
# Group grants
|
||||
principal_conditions.append(
|
||||
and_(
|
||||
AccessGrant.principal_type == 'group',
|
||||
AccessGrant.principal_id.in_(group_ids),
|
||||
)
|
||||
)
|
||||
|
||||
if not principal_conditions:
|
||||
if not group_ids and not user_id:
|
||||
return query
|
||||
|
||||
# LEFT JOIN access_grant and filter
|
||||
# We use a subquery approach to avoid duplicates from multiple matching grants
|
||||
from sqlalchemy import exists as sa_exists
|
||||
|
||||
grant_exists = (
|
||||
select(AccessGrant.id)
|
||||
.where(
|
||||
AccessGrant.resource_type == resource_type,
|
||||
AccessGrant.resource_id == DocumentModel.id,
|
||||
AccessGrant.permission == permission,
|
||||
or_(
|
||||
and_(
|
||||
AccessGrant.principal_type == 'user',
|
||||
AccessGrant.principal_id == '*',
|
||||
),
|
||||
*(
|
||||
[
|
||||
and_(
|
||||
AccessGrant.principal_type == 'user',
|
||||
AccessGrant.principal_id == user_id,
|
||||
)
|
||||
]
|
||||
if user_id
|
||||
else []
|
||||
),
|
||||
*(
|
||||
[
|
||||
and_(
|
||||
AccessGrant.principal_type == 'group',
|
||||
AccessGrant.principal_id.in_(group_ids),
|
||||
)
|
||||
]
|
||||
if group_ids
|
||||
else []
|
||||
),
|
||||
),
|
||||
)
|
||||
.correlate(DocumentModel)
|
||||
.exists()
|
||||
)
|
||||
|
||||
# Owner OR has a matching grant
|
||||
owner_or_grant = [grant_exists]
|
||||
allowed = self.has_grant_expression(user_id, resource_type, DocumentModel.id, permission, group_ids)
|
||||
if user_id:
|
||||
owner_or_grant.append(DocumentModel.user_id == user_id)
|
||||
|
||||
query = query.filter(or_(*owner_or_grant))
|
||||
return query
|
||||
allowed = or_(DocumentModel.user_id == user_id, allowed)
|
||||
return query.filter(allowed)
|
||||
|
||||
def _has_read_only_permission_filter(
|
||||
self,
|
||||
db,
|
||||
query,
|
||||
DocumentModel,
|
||||
filter: dict,
|
||||
resource_type: str,
|
||||
db,
|
||||
):
|
||||
"""
|
||||
Filter for items where user has read BUT NOT write access.
|
||||
|
|
@ -895,81 +792,8 @@ class AccessGrantsTable:
|
|||
group_ids = filter.get('group_ids', [])
|
||||
user_id = filter.get('user_id')
|
||||
|
||||
from sqlalchemy import exists as sa_exists
|
||||
|
||||
read_grant_exists = (
|
||||
select(AccessGrant.id)
|
||||
.where(
|
||||
AccessGrant.resource_type == resource_type,
|
||||
AccessGrant.resource_id == DocumentModel.id,
|
||||
AccessGrant.permission == 'read',
|
||||
or_(
|
||||
and_(
|
||||
AccessGrant.principal_type == 'user',
|
||||
AccessGrant.principal_id == '*',
|
||||
),
|
||||
*(
|
||||
[
|
||||
and_(
|
||||
AccessGrant.principal_type == 'user',
|
||||
AccessGrant.principal_id == user_id,
|
||||
)
|
||||
]
|
||||
if user_id
|
||||
else []
|
||||
),
|
||||
*(
|
||||
[
|
||||
and_(
|
||||
AccessGrant.principal_type == 'group',
|
||||
AccessGrant.principal_id.in_(group_ids),
|
||||
)
|
||||
]
|
||||
if group_ids
|
||||
else []
|
||||
),
|
||||
),
|
||||
)
|
||||
.correlate(DocumentModel)
|
||||
.exists()
|
||||
)
|
||||
|
||||
write_grant_exists = (
|
||||
select(AccessGrant.id)
|
||||
.where(
|
||||
AccessGrant.resource_type == resource_type,
|
||||
AccessGrant.resource_id == DocumentModel.id,
|
||||
AccessGrant.permission == 'write',
|
||||
or_(
|
||||
and_(
|
||||
AccessGrant.principal_type == 'user',
|
||||
AccessGrant.principal_id == '*',
|
||||
),
|
||||
*(
|
||||
[
|
||||
and_(
|
||||
AccessGrant.principal_type == 'user',
|
||||
AccessGrant.principal_id == user_id,
|
||||
)
|
||||
]
|
||||
if user_id
|
||||
else []
|
||||
),
|
||||
*(
|
||||
[
|
||||
and_(
|
||||
AccessGrant.principal_type == 'group',
|
||||
AccessGrant.principal_id.in_(group_ids),
|
||||
)
|
||||
]
|
||||
if group_ids
|
||||
else []
|
||||
),
|
||||
),
|
||||
)
|
||||
.correlate(DocumentModel)
|
||||
.exists()
|
||||
)
|
||||
read_grant_exists = self.has_grant_expression(user_id, resource_type, DocumentModel.id, 'read', group_ids)
|
||||
write_grant_exists = self.has_grant_expression(user_id, resource_type, DocumentModel.id, 'write', group_ids)
|
||||
|
||||
conditions = [read_grant_exists, ~write_grant_exists]
|
||||
|
||||
|
|
|
|||
|
|
@ -205,9 +205,7 @@ class AppInteractionForm(StrictModel):
|
|||
action_id: str = Field(min_length=1, max_length=100)
|
||||
|
||||
|
||||
####################
|
||||
# Forms
|
||||
####################
|
||||
|
||||
|
||||
class AppManifestForm(StrictModel):
|
||||
|
|
@ -244,9 +242,7 @@ class AppConnectionForm(StrictModel):
|
|||
api_key: SecretStr | None = Field(default=None, min_length=1, max_length=4096)
|
||||
|
||||
|
||||
####################
|
||||
# Responses
|
||||
####################
|
||||
|
||||
|
||||
class AppResponse(BaseModel):
|
||||
|
|
|
|||
|
|
@ -207,7 +207,7 @@ class AddUserForm(SignupForm):
|
|||
role: str | None = 'pending'
|
||||
|
||||
|
||||
# --- data-access layer ---
|
||||
# Data-access layer
|
||||
|
||||
|
||||
class AuthsTable:
|
||||
|
|
@ -393,7 +393,7 @@ class AuthsTable:
|
|||
await session.commit()
|
||||
await Users.update_user_by_id(user_id, {'email': email}, db=session)
|
||||
return True
|
||||
# --- password modification ---
|
||||
# Password modification
|
||||
|
||||
async def update_user_password_by_id(
|
||||
self,
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ import time
|
|||
from typing import Literal, Optional
|
||||
from uuid import uuid4
|
||||
|
||||
from open_webui.models.notifications import emit_changes
|
||||
from open_webui.internal.db import Base, get_async_db_context
|
||||
from open_webui.utils.misc import json_text_variants
|
||||
from pydantic import BaseModel, ConfigDict
|
||||
|
|
@ -12,9 +13,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
|
|||
log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
####################
|
||||
# Automation DB Schema
|
||||
####################
|
||||
|
||||
|
||||
class Automation(Base):
|
||||
|
|
@ -55,9 +54,7 @@ class AutomationRun(Base):
|
|||
)
|
||||
|
||||
|
||||
####################
|
||||
# Pydantic Models
|
||||
####################
|
||||
|
||||
|
||||
class AutomationTerminalConfig(BaseModel):
|
||||
|
|
@ -124,9 +121,7 @@ class AutomationListResponse(BaseModel):
|
|||
total: int
|
||||
|
||||
|
||||
####################
|
||||
# AutomationTable
|
||||
####################
|
||||
# Automation Table
|
||||
|
||||
|
||||
class AutomationTable:
|
||||
|
|
@ -291,8 +286,12 @@ class AutomationTable:
|
|||
row = await db.get(Automation, id)
|
||||
if not row:
|
||||
return False
|
||||
from open_webui.models.notifications import delete_notifications
|
||||
|
||||
recipients = await delete_notifications(resource_type='automation', resource_ids=[id], db=db)
|
||||
await db.delete(row)
|
||||
await db.commit()
|
||||
await emit_changes(recipients)
|
||||
return True
|
||||
|
||||
async def claim_due(self, now_ns: int, limit: int = 10, db: Optional[AsyncSession] = None) -> list[AutomationModel]:
|
||||
|
|
@ -349,9 +348,7 @@ class AutomationTable:
|
|||
return [AutomationModel.model_validate(r) for r in claimed]
|
||||
|
||||
|
||||
####################
|
||||
# AutomationRunTable
|
||||
####################
|
||||
# Automation Run Table
|
||||
|
||||
|
||||
class AutomationRunTable:
|
||||
|
|
@ -361,6 +358,9 @@ class AutomationRunTable:
|
|||
status: str,
|
||||
chat_id: Optional[str] = None,
|
||||
error: Optional[str] = None,
|
||||
*,
|
||||
request=None,
|
||||
event_actor=None,
|
||||
db: Optional[AsyncSession] = None,
|
||||
) -> AutomationRunModel:
|
||||
async with get_async_db_context(db) as db:
|
||||
|
|
@ -373,7 +373,37 @@ class AutomationRunTable:
|
|||
created_at=int(time.time_ns()),
|
||||
)
|
||||
db.add(row)
|
||||
await db.flush()
|
||||
event = None
|
||||
recipients = set()
|
||||
if status == 'error':
|
||||
from open_webui.events import EVENTS, build_event, publish_event
|
||||
from open_webui.utils.inbox import consume_event
|
||||
from open_webui.models.notifications import emit_changes
|
||||
|
||||
automation = await db.get(Automation, automation_id)
|
||||
if automation:
|
||||
event = build_event(
|
||||
request,
|
||||
EVENTS.AUTOMATION_RUN_FAILED,
|
||||
actor=event_actor,
|
||||
subject_id=automation_id,
|
||||
event_id=f'automation-run:{row.id}',
|
||||
data={
|
||||
'run_id': row.id,
|
||||
'name': automation.name,
|
||||
'error': error,
|
||||
'user_id': automation.user_id,
|
||||
'message': f'{automation.name}: {error}',
|
||||
**({'chat_id': chat_id} if chat_id else {}),
|
||||
},
|
||||
)
|
||||
recipients = await consume_event(event, db=db)
|
||||
await db.commit()
|
||||
if event is not None:
|
||||
await emit_changes(recipients)
|
||||
if request is not None:
|
||||
await publish_event(request, event)
|
||||
return AutomationRunModel.model_validate(row)
|
||||
|
||||
async def get_latest(self, automation_id: str, db: Optional[AsyncSession] = None) -> Optional[AutomationRunModel]:
|
||||
|
|
@ -434,8 +464,16 @@ class AutomationRunTable:
|
|||
|
||||
async def delete_by_automation(self, automation_id: str, db: Optional[AsyncSession] = None) -> int:
|
||||
async with get_async_db_context(db) as db:
|
||||
from open_webui.models.notifications import delete_notifications
|
||||
|
||||
recipients = await delete_notifications(
|
||||
object_type='automation_run',
|
||||
object_ids=select(AutomationRun.id).where(AutomationRun.automation_id == automation_id),
|
||||
db=db,
|
||||
)
|
||||
result = await db.execute(delete(AutomationRun).filter_by(automation_id=automation_id))
|
||||
await db.commit()
|
||||
await emit_changes(recipients)
|
||||
return result.rowcount
|
||||
|
||||
async def get_runs_by_user_range(
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ import time
|
|||
from typing import Optional
|
||||
from uuid import uuid4
|
||||
|
||||
from open_webui.models.notifications import emit_changes
|
||||
from open_webui.constants import ERROR_MESSAGES
|
||||
from open_webui.internal.db import Base, get_async_db_context
|
||||
from open_webui.models.access_grants import AccessGrantModel, AccessGrants
|
||||
|
|
@ -30,9 +31,7 @@ log = logging.getLogger(__name__)
|
|||
MIN_CALENDAR_RRULE_INTERVAL_SECONDS = 24 * 60 * 60
|
||||
|
||||
|
||||
####################
|
||||
# Calendar DB Schema
|
||||
####################
|
||||
|
||||
|
||||
class Calendar(Base):
|
||||
|
|
@ -97,9 +96,7 @@ class CalendarEventAttendee(Base):
|
|||
)
|
||||
|
||||
|
||||
####################
|
||||
# Pydantic Models
|
||||
####################
|
||||
|
||||
|
||||
class CalendarModel(BaseModel):
|
||||
|
|
@ -158,9 +155,7 @@ class CalendarEventAttendeeModel(BaseModel):
|
|||
updated_at: int
|
||||
|
||||
|
||||
####################
|
||||
# Forms
|
||||
####################
|
||||
|
||||
|
||||
class CalendarForm(BaseModel):
|
||||
|
|
@ -227,9 +222,7 @@ class RSVPForm(BaseModel):
|
|||
status: str # 'accepted' | 'declined' | 'tentative' | 'pending'
|
||||
|
||||
|
||||
####################
|
||||
# Response Models
|
||||
####################
|
||||
|
||||
|
||||
class CalendarEventUserResponse(CalendarEventModel):
|
||||
|
|
@ -241,9 +234,7 @@ class CalendarEventListResponse(BaseModel):
|
|||
total: int
|
||||
|
||||
|
||||
####################
|
||||
# Table Operations
|
||||
####################
|
||||
|
||||
|
||||
class CalendarTable:
|
||||
|
|
@ -408,8 +399,12 @@ class CalendarTable:
|
|||
await db.execute(delete(CalendarEvent).filter(CalendarEvent.calendar_id == id))
|
||||
|
||||
# Delete calendar
|
||||
from open_webui.models.notifications import delete_notifications
|
||||
|
||||
recipients = await delete_notifications(resource_type='calendar', resource_ids=[id], db=db)
|
||||
await db.execute(delete(Calendar).filter(Calendar.id == id))
|
||||
await db.commit()
|
||||
await emit_changes(recipients)
|
||||
|
||||
# Revoke access grants in a separate transaction to avoid
|
||||
# write-lock contention on SQLite when session sharing is off.
|
||||
|
|
@ -772,8 +767,12 @@ class CalendarEventTable:
|
|||
try:
|
||||
async with get_async_db_context(db) as db:
|
||||
await db.execute(delete(CalendarEventAttendee).filter(CalendarEventAttendee.event_id == id))
|
||||
from open_webui.models.notifications import delete_notifications
|
||||
|
||||
recipients = await delete_notifications(object_type='calendar_event', object_ids=[id], db=db)
|
||||
await db.execute(delete(CalendarEvent).filter(CalendarEvent.id == id))
|
||||
await db.commit()
|
||||
await emit_changes(recipients)
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ import time
|
|||
import uuid
|
||||
from typing import Optional
|
||||
|
||||
from open_webui.models.notifications import emit_changes
|
||||
from open_webui.internal.db import Base, JSONField, get_async_db_context
|
||||
from open_webui.models.access_grants import (
|
||||
AccessGrantModel,
|
||||
|
|
@ -33,9 +34,7 @@ from sqlalchemy import (
|
|||
from sqlalchemy.dialects.postgresql import JSONB
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
####################
|
||||
# Channel DB Schema
|
||||
####################
|
||||
|
||||
|
||||
class Channel(Base):
|
||||
|
|
@ -225,9 +224,7 @@ class ChannelWebhookModel(BaseModel):
|
|||
updated_at: int # timestamp in epoch (time_ns)
|
||||
|
||||
|
||||
####################
|
||||
# Forms
|
||||
####################
|
||||
|
||||
|
||||
class ChannelResponse(ChannelModel):
|
||||
|
|
@ -793,7 +790,7 @@ class ChannelTable:
|
|||
allowed_channels = []
|
||||
|
||||
for channel in channels:
|
||||
# --- Case A: group or dm => user must be an active member ---
|
||||
# Case a: group or dm => user must be an active member
|
||||
if channel.type in ['group', 'dm']:
|
||||
result = await db.execute(
|
||||
select(ChannelMember)
|
||||
|
|
@ -809,7 +806,7 @@ class ChannelTable:
|
|||
allowed_channels.append(await self._to_channel_model(channel, db=db))
|
||||
continue
|
||||
|
||||
# --- Case B: standard channel => rely on ACL permissions ---
|
||||
# Case b: standard channel => rely on acl permissions
|
||||
stmt = select(Channel).filter(Channel.id == channel.id)
|
||||
|
||||
stmt = self._has_permission(
|
||||
|
|
@ -963,13 +960,15 @@ class ChannelTable:
|
|||
async def delete_channel_by_id(self, id: str, db: Optional[AsyncSession] = None) -> bool:
|
||||
async with get_async_db_context(db) as db:
|
||||
await AccessGrants.revoke_all_access('channel', id, db=db)
|
||||
from open_webui.models.notifications import delete_notifications
|
||||
|
||||
recipients = await delete_notifications(resource_type='channel', resource_ids=[id], db=db)
|
||||
await db.execute(delete(Channel).filter(Channel.id == id))
|
||||
await db.commit()
|
||||
await emit_changes(recipients)
|
||||
return True
|
||||
|
||||
####################
|
||||
# Webhook Methods
|
||||
####################
|
||||
|
||||
async def insert_webhook(
|
||||
self,
|
||||
|
|
|
|||
|
|
@ -10,7 +10,7 @@ from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
|
|||
|
||||
from open_webui.internal.db import Base, get_async_db_context
|
||||
from open_webui.utils.response import normalize_usage
|
||||
from open_webui.utils.session_records import normalize_tool_output, recorded_timestamp
|
||||
from open_webui.utils.session_records import has_pending_tool_approval, normalize_tool_output, recorded_timestamp
|
||||
from pydantic import BaseModel, ConfigDict
|
||||
from sqlalchemy import (
|
||||
JSON,
|
||||
|
|
@ -32,9 +32,7 @@ from sqlalchemy import (
|
|||
)
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
####################
|
||||
# Helpers
|
||||
####################
|
||||
|
||||
|
||||
def _normalize_timestamp(timestamp: Optional[int]) -> float:
|
||||
|
|
@ -43,11 +41,11 @@ def _normalize_timestamp(timestamp: Optional[int]) -> float:
|
|||
if timestamp is None:
|
||||
return now
|
||||
|
||||
# Convert milliseconds to seconds if needed
|
||||
# Treat values above the seconds-range cutoff as milliseconds.
|
||||
if timestamp > 10_000_000_000:
|
||||
timestamp = timestamp / 1000
|
||||
|
||||
# Validate: must be after 2020 and not in the future (with 1 day tolerance)
|
||||
# Accept timestamps from 2020-01-01 through one day ahead of now, inclusive.
|
||||
min_valid = 1577836800 # 2020-01-01 00:00:00 UTC
|
||||
max_valid = now + 86400 # 1 day in the future (clock skew tolerance)
|
||||
|
||||
|
|
@ -157,9 +155,7 @@ def _extract_tool_names(value: Any) -> list[str]:
|
|||
return names
|
||||
|
||||
|
||||
####################
|
||||
# ChatMessage DB Schema
|
||||
####################
|
||||
|
||||
|
||||
class ChatMessage(Base):
|
||||
|
|
@ -210,9 +206,7 @@ class ChatMessage(Base):
|
|||
)
|
||||
|
||||
|
||||
####################
|
||||
# Pydantic Models
|
||||
####################
|
||||
|
||||
|
||||
class ChatMessageModel(BaseModel):
|
||||
|
|
@ -239,9 +233,7 @@ class ChatMessageModel(BaseModel):
|
|||
updated_at: int
|
||||
|
||||
|
||||
####################
|
||||
# Table Operations
|
||||
####################
|
||||
|
||||
|
||||
class ChatMessageTable:
|
||||
|
|
@ -364,6 +356,20 @@ class ChatMessageTable:
|
|||
message = await db.get(ChatMessage, id)
|
||||
return ChatMessageModel.model_validate(message) if message else None
|
||||
|
||||
async def get_chat_ids_with_pending_approval(
|
||||
self, chat_ids: list[str], db: AsyncSession | None = None
|
||||
) -> set[str]:
|
||||
if not chat_ids:
|
||||
return set()
|
||||
async with get_async_db_context(db) as db:
|
||||
result = await db.execute(
|
||||
select(ChatMessage.chat_id, ChatMessage.output)
|
||||
.where(ChatMessage.chat_id.in_(chat_ids))
|
||||
.where(ChatMessage.role == 'assistant')
|
||||
.where(ChatMessage.done.is_(False))
|
||||
)
|
||||
return {chat_id for chat_id, output in result.all() if has_pending_tool_approval(output)}
|
||||
|
||||
async def has_unfinished_assistant_by_chat_id(
|
||||
self,
|
||||
chat_id: str,
|
||||
|
|
|
|||
|
|
@ -11,7 +11,9 @@ import uuid
|
|||
from typing import Any, Literal
|
||||
|
||||
# local imports
|
||||
from open_webui.models.notifications import emit_changes
|
||||
from open_webui.env import ENABLE_ADMIN_CHAT_ACCESS
|
||||
from open_webui.models.comments import delete_resource_comments
|
||||
from open_webui.internal.db import Base, JSONField, get_async_db, get_async_db_context
|
||||
from open_webui.models.access_grants import AccessGrants
|
||||
from open_webui.models.automations import AutomationRun
|
||||
|
|
@ -295,9 +297,7 @@ class ChatFileModel(BaseModel):
|
|||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
|
||||
####################
|
||||
# Forms
|
||||
####################
|
||||
|
||||
|
||||
class ChatForm(BaseModel):
|
||||
|
|
@ -356,6 +356,7 @@ class ChatTitleIdResponse(BaseModel):
|
|||
last_read_at: int | None = None
|
||||
snippet: str | None = None
|
||||
active: bool = False
|
||||
pending_approval: bool = False
|
||||
archived: bool = False
|
||||
|
||||
|
||||
|
|
@ -2814,8 +2815,10 @@ class ChatTable:
|
|||
async with get_async_db_context(db) as session:
|
||||
await session.execute(update(AutomationRun).filter_by(chat_id=id).values(chat_id=None))
|
||||
await session.execute(delete(ChatMessage).filter_by(chat_id=id))
|
||||
recipients = await delete_resource_comments('chat', select(Chat.id).filter_by(id=id), db=session)
|
||||
await session.execute(delete(Chat).filter_by(id=id))
|
||||
await session.commit()
|
||||
await emit_changes(recipients)
|
||||
|
||||
return True and await self.delete_shared_chat_by_chat_id(id, db=session)
|
||||
except Exception:
|
||||
|
|
@ -2826,8 +2829,12 @@ class ChatTable:
|
|||
async with get_async_db_context(db) as session:
|
||||
await session.execute(update(AutomationRun).filter_by(chat_id=id).values(chat_id=None))
|
||||
await session.execute(delete(ChatMessage).filter_by(chat_id=id))
|
||||
recipients = await delete_resource_comments(
|
||||
'chat', select(Chat.id).filter_by(id=id, user_id=user_id), db=session
|
||||
)
|
||||
await session.execute(delete(Chat).filter_by(id=id, user_id=user_id))
|
||||
await session.commit()
|
||||
await emit_changes(recipients)
|
||||
|
||||
return True and await self.delete_shared_chat_by_chat_id(id, db=session)
|
||||
except Exception:
|
||||
|
|
@ -2847,8 +2854,12 @@ class ChatTable:
|
|||
await session.execute(
|
||||
delete(ChatMessage).filter(ChatMessage.chat_id.in_(select(Chat.id).filter_by(user_id=user_id)))
|
||||
)
|
||||
recipients = await delete_resource_comments(
|
||||
'chat', select(Chat.id).filter_by(user_id=user_id), db=session
|
||||
)
|
||||
await session.execute(delete(Chat).filter_by(user_id=user_id))
|
||||
await session.commit()
|
||||
await emit_changes(recipients)
|
||||
|
||||
return True
|
||||
except Exception:
|
||||
|
|
@ -2866,9 +2877,16 @@ class ChatTable:
|
|||
update(AutomationRun).filter(AutomationRun.chat_id.in_(chat_ids_stmt)).values(chat_id=None)
|
||||
)
|
||||
await session.execute(delete(ChatMessage).filter(ChatMessage.chat_id.in_(chat_ids_stmt)))
|
||||
recipients = await delete_resource_comments('chat', chat_ids_stmt, db=session)
|
||||
await session.execute(delete(SharedChatTable).filter(SharedChatTable.chat_id.in_(chat_ids_stmt)))
|
||||
recipients.update(
|
||||
await delete_resource_comments(
|
||||
'chat', select(Chat.id).filter_by(user_id=user_id, folder_id=folder_id), db=session
|
||||
)
|
||||
)
|
||||
await session.execute(delete(Chat).filter_by(user_id=user_id, folder_id=folder_id))
|
||||
await session.commit()
|
||||
await emit_changes(recipients)
|
||||
|
||||
return True
|
||||
except Exception:
|
||||
|
|
|
|||
160
backend/open_webui/models/comments.py
Normal file
160
backend/open_webui/models/comments.py
Normal file
|
|
@ -0,0 +1,160 @@
|
|||
"""Resource discussions. All operations use the caller's transaction."""
|
||||
|
||||
from typing import Literal
|
||||
from uuid import UUID
|
||||
|
||||
from open_webui.internal.db import Base
|
||||
from open_webui.models.users import User
|
||||
from pydantic import BaseModel, ConfigDict, Field, field_validator
|
||||
from sqlalchemy import JSON, BigInteger, Column, Index, Text, UniqueConstraint, case, delete, func, select, update
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
ResourceType = Literal['model', 'knowledge', 'prompt', 'skill', 'tool', 'note', 'chat']
|
||||
|
||||
|
||||
class Comment(Base):
|
||||
__tablename__ = 'comment'
|
||||
id = Column(Text, primary_key=True)
|
||||
user_id = Column(Text, nullable=True)
|
||||
resource_type = Column(Text, nullable=False)
|
||||
resource_id = Column(Text, nullable=False)
|
||||
parent_id = Column(Text, nullable=True)
|
||||
reply_to_id = Column(Text, nullable=True)
|
||||
content = Column(Text, nullable=False)
|
||||
target_type = Column(Text, nullable=True)
|
||||
target_id = Column(Text, nullable=True)
|
||||
meta = Column(JSON, nullable=True)
|
||||
created_at = Column(BigInteger, nullable=False)
|
||||
updated_at = Column(BigInteger, nullable=False)
|
||||
deleted_at = Column(BigInteger, nullable=True)
|
||||
__table_args__ = (
|
||||
Index('ix_comment_resource', 'resource_type', 'resource_id', 'parent_id', 'created_at', 'id'),
|
||||
Index('ix_comment_parent', 'parent_id', 'created_at', 'id'),
|
||||
Index('ix_comment_target', 'resource_type', 'resource_id', 'target_type', 'target_id'),
|
||||
)
|
||||
|
||||
|
||||
class CommentReaction(Base):
|
||||
__tablename__ = 'comment_reaction'
|
||||
id = Column(Text, primary_key=True)
|
||||
user_id = Column(Text, nullable=False)
|
||||
comment_id = Column(Text, nullable=False, index=True)
|
||||
name = Column(Text, nullable=False)
|
||||
created_at = Column(BigInteger, nullable=False)
|
||||
__table_args__ = (UniqueConstraint('comment_id', 'user_id', 'name', name='uq_comment_reaction'),)
|
||||
|
||||
|
||||
class CommentAnchor(BaseModel):
|
||||
model_config = ConfigDict(extra='forbid')
|
||||
quote: str = Field(min_length=1, max_length=10000)
|
||||
prefix: str = Field(default='', max_length=64)
|
||||
suffix: str = Field(default='', max_length=64)
|
||||
start: int = Field(ge=0)
|
||||
end: int = Field(ge=1)
|
||||
surface_id: str = Field(max_length=256)
|
||||
source: str = Field(pattern=r'^[0-9a-f]{64}$')
|
||||
content_hash: str = Field(pattern=r'^[0-9a-f]{64}$')
|
||||
|
||||
|
||||
class CommentContentForm(BaseModel):
|
||||
model_config = ConfigDict(extra='forbid')
|
||||
content: str = Field(min_length=1, max_length=20000)
|
||||
|
||||
@field_validator('content')
|
||||
@classmethod
|
||||
def nonempty(cls, value):
|
||||
if not value.strip():
|
||||
raise ValueError('Comment cannot be empty')
|
||||
return value
|
||||
|
||||
|
||||
class CommentForm(CommentContentForm):
|
||||
temp_id: UUID | None = None
|
||||
resource_type: ResourceType
|
||||
resource_id: str = Field(min_length=1, max_length=512)
|
||||
target_type: Literal['note_page', 'chat_message'] | None = None
|
||||
target_id: str | None = Field(default=None, max_length=256)
|
||||
anchor: CommentAnchor | None = None
|
||||
|
||||
|
||||
class CommentReplyForm(CommentContentForm):
|
||||
temp_id: UUID | None = None
|
||||
reply_to_id: str | None = None
|
||||
|
||||
|
||||
class CommentUpdateForm(CommentContentForm):
|
||||
etag: str = Field(pattern=r'^\d{1,20}$')
|
||||
|
||||
|
||||
async def comment_responses(db: AsyncSession, comments: list[Comment], user, owner_id: str) -> list[dict]:
|
||||
if not comments:
|
||||
return []
|
||||
ids = [c.id for c in comments]
|
||||
authors = {
|
||||
u.id: {'id': u.id, 'name': u.name, 'profile_image_url': u.profile_image_url}
|
||||
for u in (await db.scalars(select(User).where(User.id.in_({c.user_id for c in comments if c.user_id})))).all()
|
||||
}
|
||||
counts = {
|
||||
parent_id: (count, latest)
|
||||
for parent_id, count, latest in (
|
||||
await db.execute(
|
||||
select(Comment.parent_id, func.count(), func.max(Comment.created_at))
|
||||
.where(Comment.parent_id.in_(ids))
|
||||
.group_by(Comment.parent_id)
|
||||
)
|
||||
).all()
|
||||
}
|
||||
reactions = {}
|
||||
for comment_id, name, count, mine in (
|
||||
await db.execute(
|
||||
select(
|
||||
CommentReaction.comment_id,
|
||||
CommentReaction.name,
|
||||
func.count(),
|
||||
func.max(
|
||||
# CASE is portable across PostgreSQL and SQLite (boolean MAX isn't).
|
||||
case((CommentReaction.user_id == user.id, 1), else_=0)
|
||||
),
|
||||
)
|
||||
.where(CommentReaction.comment_id.in_(ids))
|
||||
.group_by(CommentReaction.comment_id, CommentReaction.name)
|
||||
)
|
||||
).all():
|
||||
reactions.setdefault(comment_id, []).append({'name': name, 'count': count, 'reacted': bool(mine)})
|
||||
return [
|
||||
{
|
||||
**{c.name: getattr(comment, c.name) for c in Comment.__table__.columns},
|
||||
'etag': str(comment.updated_at),
|
||||
'user': authors.get(comment.user_id),
|
||||
'reply_count': counts.get(comment.id, (0, None))[0],
|
||||
'latest_reply_at': counts.get(comment.id, (0, None))[1],
|
||||
'reactions': reactions.get(comment.id, []),
|
||||
'can_edit': not comment.deleted_at and comment.user_id == user.id,
|
||||
'can_delete': not comment.deleted_at
|
||||
and (comment.user_id == user.id or owner_id == user.id or user.role == 'admin'),
|
||||
}
|
||||
for comment in comments
|
||||
]
|
||||
|
||||
|
||||
async def delete_resource_comments(resource_type: str, resource_ids, db: AsyncSession):
|
||||
"""Lock resources before cleanup so concurrent comment creation cannot leave orphans."""
|
||||
from open_webui.utils.comments import resource_models
|
||||
|
||||
model = resource_models()[resource_type]
|
||||
ids = list((await db.scalars(select(model.id).where(model.id.in_(resource_ids)).with_for_update())).all())
|
||||
if not ids:
|
||||
return set()
|
||||
from open_webui.models.notifications import delete_notifications
|
||||
|
||||
recipients = await delete_notifications(resource_type=resource_type, resource_ids=ids, db=db)
|
||||
comment_ids = select(Comment.id).where(Comment.resource_type == resource_type, Comment.resource_id.in_(ids))
|
||||
await db.execute(delete(CommentReaction).where(CommentReaction.comment_id.in_(comment_ids)))
|
||||
await db.execute(delete(Comment).where(Comment.resource_type == resource_type, Comment.resource_id.in_(ids)))
|
||||
return recipients
|
||||
|
||||
|
||||
async def cleanup_comments_for_deleted_user(db: AsyncSession, user_id: str):
|
||||
"""Remove reactions and clear authorship, preserving comment text and threads."""
|
||||
await db.execute(delete(CommentReaction).where(CommentReaction.user_id == user_id))
|
||||
await db.execute(update(Comment).where(Comment.user_id == user_id).values(user_id=None))
|
||||
|
|
@ -98,7 +98,7 @@ def _json_value(value: Any) -> Any:
|
|||
return jsonable_encoder(value)
|
||||
|
||||
|
||||
# ── Model ────────────────────────────────────────────────────────────────────
|
||||
# Model
|
||||
|
||||
|
||||
class Config(Base):
|
||||
|
|
@ -114,7 +114,7 @@ class Config(Base):
|
|||
PERSISTENT_ENABLED: ClassVar[bool] = True
|
||||
OAUTH_PERSISTENT_ENABLED: ClassVar[bool] = False
|
||||
|
||||
# ── Class methods ────────────────────────────────────────
|
||||
# Class methods
|
||||
|
||||
@classmethod
|
||||
def configure(
|
||||
|
|
|
|||
|
|
@ -12,9 +12,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
|
|||
log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
####################
|
||||
# Feedback DB Schema
|
||||
####################
|
||||
|
||||
|
||||
class Feedback(Base):
|
||||
|
|
@ -44,9 +42,7 @@ class FeedbackModel(BaseModel):
|
|||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
|
||||
####################
|
||||
# Forms
|
||||
####################
|
||||
|
||||
|
||||
class FeedbackResponse(BaseModel):
|
||||
|
|
|
|||
|
|
@ -48,7 +48,7 @@ class FileModel(BaseModel):
|
|||
updated_at: int | None # timestamp in epoch
|
||||
|
||||
|
||||
# --- metadata structures ---
|
||||
# Metadata structures
|
||||
class FileMeta(BaseModel):
|
||||
name: str | None = None
|
||||
content_type: str | None = None
|
||||
|
|
|
|||
|
|
@ -12,11 +12,9 @@ from sqlalchemy.ext.asyncio import AsyncSession
|
|||
log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
####################
|
||||
# Folder DB Schema
|
||||
# Let every room in this house shelter someone who needs it,
|
||||
# and let no chamber stand empty while there is want.
|
||||
####################
|
||||
|
||||
|
||||
class Folder(Base):
|
||||
|
|
@ -78,9 +76,7 @@ class SharedFolderResponse(BaseModel):
|
|||
updated_at: int
|
||||
|
||||
|
||||
####################
|
||||
# Forms
|
||||
####################
|
||||
|
||||
|
||||
class FolderForm(BaseModel):
|
||||
|
|
|
|||
|
|
@ -59,7 +59,7 @@ class FunctionModel(BaseModel):
|
|||
model_config = ConfigDict(from_attributes=True) # allows ORM model binding
|
||||
|
||||
|
||||
# --- form / schema definitions ---
|
||||
# Form / schema definitions
|
||||
class FunctionWithValvesModel(BaseModel):
|
||||
version_id: str | None = None
|
||||
id: str
|
||||
|
|
@ -77,9 +77,7 @@ class FunctionWithValvesModel(BaseModel):
|
|||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
|
||||
####################
|
||||
# Forms
|
||||
####################
|
||||
|
||||
|
||||
class FunctionResponse(BaseModel):
|
||||
|
|
|
|||
|
|
@ -30,11 +30,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
|
|||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
####################
|
||||
# UserGroup DB Schema
|
||||
# Let none who belong to this house be turned away,
|
||||
# and let the covenant hold for every member.
|
||||
####################
|
||||
|
||||
|
||||
class Group(Base):
|
||||
|
|
@ -102,9 +98,7 @@ class GroupMemberModel(BaseModel):
|
|||
updated_at: Optional[int] = None # timestamp in epoch
|
||||
|
||||
|
||||
####################
|
||||
# Forms
|
||||
####################
|
||||
|
||||
|
||||
class GroupResponse(GroupModel):
|
||||
|
|
|
|||
|
|
@ -3,9 +3,12 @@ import time
|
|||
import uuid
|
||||
from typing import Optional
|
||||
|
||||
from open_webui.models.notifications import emit_changes
|
||||
from open_webui.config import RAG_FILE_CONTENT_SEARCH_MAX_CHARS
|
||||
from open_webui.models.comments import delete_resource_comments
|
||||
from open_webui.internal.db import Base, JSONField, get_async_db_context
|
||||
from open_webui.models.access_grants import AccessGrantModel, AccessGrants
|
||||
from open_webui.models.config import Config
|
||||
from open_webui.models.files import (
|
||||
File,
|
||||
FileMetadataResponse,
|
||||
|
|
@ -38,11 +41,9 @@ log = logging.getLogger(__name__)
|
|||
# Columns the knowledge base list may be ordered by; anything else falls back to the default.
|
||||
KNOWLEDGE_SORTABLE_FIELDS = {'name', 'created_at', 'updated_at'}
|
||||
|
||||
####################
|
||||
# Knowledge DB Schema
|
||||
# Let what was gathered here outlast the one who gathered it,
|
||||
# and still teach when the builder is gone.
|
||||
####################
|
||||
|
||||
|
||||
class Knowledge(Base):
|
||||
|
|
@ -146,9 +147,7 @@ class KnowledgeDirectoryForm(BaseModel):
|
|||
parent_id: Optional[str] = None
|
||||
|
||||
|
||||
####################
|
||||
# Forms
|
||||
####################
|
||||
class KnowledgeUserModel(KnowledgeModel):
|
||||
user: Optional[UserResponse] = None
|
||||
file_count: int | None = None
|
||||
|
|
@ -162,10 +161,16 @@ class KnowledgeUserResponse(KnowledgeUserModel):
|
|||
pass
|
||||
|
||||
|
||||
class KnowledgeMeta(BaseModel):
|
||||
max_file_count: int | None = Field(default=None, gt=0)
|
||||
max_file_size: int | None = Field(default=None, gt=0)
|
||||
|
||||
|
||||
class KnowledgeForm(BaseModel):
|
||||
name: str
|
||||
description: str
|
||||
access_grants: Optional[list[dict]] = None
|
||||
meta: KnowledgeMeta | None = None
|
||||
|
||||
|
||||
class FileUserResponse(FileModelResponse):
|
||||
|
|
@ -209,7 +214,8 @@ class KnowledgeTable:
|
|||
async with get_async_db_context(db) as db:
|
||||
knowledge = KnowledgeModel(
|
||||
**{
|
||||
**form_data.model_dump(exclude={'access_grants'}),
|
||||
**form_data.model_dump(exclude={'access_grants', 'meta'}),
|
||||
'meta': form_data.meta.model_dump() if form_data.meta else None,
|
||||
'id': str(uuid.uuid4()),
|
||||
'user_id': user_id,
|
||||
'created_at': int(time.time()),
|
||||
|
|
@ -544,12 +550,12 @@ class KnowledgeTable:
|
|||
.filter(KnowledgeFile.knowledge_id == knowledge_id)
|
||||
)
|
||||
|
||||
# Filter by directory_id (None = root level)
|
||||
# Omit directory_id to include all directories; supply it to restrict the listing.
|
||||
directory_id = filter.get('directory_id') if filter else None
|
||||
if directory_id:
|
||||
stmt = stmt.filter(KnowledgeFile.directory_id == directory_id)
|
||||
elif filter and 'directory_id' in filter:
|
||||
# Explicit None = root level only
|
||||
# A supplied but falsy directory_id selects root-level files only.
|
||||
stmt = stmt.filter(KnowledgeFile.directory_id.is_(None))
|
||||
|
||||
# Default sort: updated_at descending
|
||||
|
|
@ -671,6 +677,37 @@ class KnowledgeTable:
|
|||
except Exception:
|
||||
return []
|
||||
|
||||
async def get_file_limits(self, meta: dict | None) -> dict[str, int | None]:
|
||||
local = meta or {}
|
||||
counts = [
|
||||
int(value) for value in (await Config.get('knowledge.max_file_count'), local.get('max_file_count')) if value
|
||||
]
|
||||
sizes = [
|
||||
int(value) for value in (await Config.get('knowledge.max_file_size'), local.get('max_file_size')) if value
|
||||
]
|
||||
return {'max_file_count': min(counts, default=None), 'max_file_size': min(sizes, default=None)}
|
||||
|
||||
async def get_file_count_by_id(
|
||||
self,
|
||||
knowledge_id: str,
|
||||
include_pending: bool = False,
|
||||
exclude_file_ids: list[str] | None = None,
|
||||
db: Optional[AsyncSession] = None,
|
||||
) -> int:
|
||||
async with get_async_db_context(db) as db:
|
||||
linked = select(KnowledgeFile.file_id.label('file_id')).where(KnowledgeFile.knowledge_id == knowledge_id)
|
||||
if include_pending:
|
||||
pending = select(File.id.label('file_id')).where(
|
||||
File.meta['data']['knowledge_id'].as_string() == knowledge_id,
|
||||
File.data['status'].as_string().in_(['pending', 'processing']),
|
||||
)
|
||||
linked = linked.union(pending)
|
||||
files = linked.subquery()
|
||||
stmt = select(func.count()).select_from(files)
|
||||
if exclude_file_ids:
|
||||
stmt = stmt.where(files.c.file_id.notin_(exclude_file_ids))
|
||||
return (await db.execute(stmt)).scalar_one()
|
||||
|
||||
async def add_file_to_knowledge_by_id(
|
||||
self,
|
||||
knowledge_id: str,
|
||||
|
|
@ -679,7 +716,27 @@ class KnowledgeTable:
|
|||
directory_id: Optional[str] = None,
|
||||
db: Optional[AsyncSession] = None,
|
||||
) -> Optional[KnowledgeFileModel]:
|
||||
global_limit = await Config.get('knowledge.max_file_count')
|
||||
async with get_async_db_context(db) as db:
|
||||
# Read the local limit under the same write lock as count + insert.
|
||||
await db.execute(
|
||||
update(Knowledge).where(Knowledge.id == knowledge_id).values(updated_at=Knowledge.updated_at)
|
||||
)
|
||||
meta = await db.scalar(select(Knowledge.meta).where(Knowledge.id == knowledge_id))
|
||||
local_limit = (meta or {}).get('max_file_count')
|
||||
limit = min((int(value) for value in (global_limit, local_limit) if value), default=None)
|
||||
if limit is not None:
|
||||
existing = await db.scalar(select(KnowledgeFile).filter_by(knowledge_id=knowledge_id, file_id=file_id))
|
||||
if existing:
|
||||
await db.commit()
|
||||
# Preserve duplicate-insert semantics; callers must not release another request's slot.
|
||||
return None
|
||||
count = await db.scalar(
|
||||
select(func.count()).select_from(KnowledgeFile).where(KnowledgeFile.knowledge_id == knowledge_id)
|
||||
)
|
||||
if count >= int(limit):
|
||||
await db.rollback()
|
||||
raise ValueError(f'Knowledge base file limit exceeded ({limit} files maximum).')
|
||||
knowledge_file = KnowledgeFileModel(
|
||||
**{
|
||||
'id': str(uuid.uuid4()),
|
||||
|
|
@ -702,6 +759,7 @@ class KnowledgeTable:
|
|||
else:
|
||||
return None
|
||||
except Exception:
|
||||
await db.rollback()
|
||||
return None
|
||||
|
||||
async def has_file(self, knowledge_id: str, file_id: str, db: Optional[AsyncSession] = None) -> bool:
|
||||
|
|
@ -758,11 +816,15 @@ class KnowledgeTable:
|
|||
) -> Optional[KnowledgeModel]:
|
||||
try:
|
||||
async with get_async_db_context(db) as db:
|
||||
values = form_data.model_dump(exclude={'access_grants', 'meta'})
|
||||
if form_data.meta is not None:
|
||||
meta = await db.scalar(select(Knowledge.meta).where(Knowledge.id == id)) or {}
|
||||
values['meta'] = {**meta, **form_data.meta.model_dump(exclude_unset=True)}
|
||||
await db.execute(
|
||||
update(Knowledge)
|
||||
.filter_by(id=id)
|
||||
.values(
|
||||
**form_data.model_dump(exclude={'access_grants'}),
|
||||
**values,
|
||||
updated_at=int(time.time()),
|
||||
)
|
||||
)
|
||||
|
|
@ -795,8 +857,10 @@ class KnowledgeTable:
|
|||
try:
|
||||
async with get_async_db_context(db) as db:
|
||||
await AccessGrants.revoke_all_access('knowledge', id, db=db)
|
||||
recipients = await delete_resource_comments('knowledge', [id], db=db)
|
||||
await db.execute(delete(Knowledge).filter_by(id=id))
|
||||
await db.commit()
|
||||
await emit_changes(recipients)
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
|
|
@ -808,14 +872,16 @@ class KnowledgeTable:
|
|||
knowledge_ids = [row[0] for row in result.all()]
|
||||
for knowledge_id in knowledge_ids:
|
||||
await AccessGrants.revoke_all_access('knowledge', knowledge_id, db=db)
|
||||
recipients = await delete_resource_comments('knowledge', knowledge_ids, db=db)
|
||||
await db.execute(delete(Knowledge))
|
||||
await db.commit()
|
||||
await emit_changes(recipients)
|
||||
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
# ── Directory CRUD ────────────────────────────────────────────────
|
||||
# Directory CRUD
|
||||
|
||||
async def create_directory(
|
||||
self,
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ import time
|
|||
import uuid
|
||||
from typing import Optional
|
||||
|
||||
from open_webui.models.notifications import emit_changes
|
||||
from open_webui.internal.db import Base, JSONField, get_async_db_context
|
||||
from open_webui.models.channels import ChannelMember, Channels
|
||||
from open_webui.models.tags import Tag, TagModel, Tags
|
||||
|
|
@ -11,9 +12,7 @@ from sqlalchemy import JSON, BigInteger, Boolean, Column, String, Text, and_, de
|
|||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from sqlalchemy.sql import exists
|
||||
|
||||
####################
|
||||
# Message DB Schema
|
||||
####################
|
||||
|
||||
|
||||
class MessageReaction(Base):
|
||||
|
|
@ -88,9 +87,7 @@ class MessageModel(BaseModel):
|
|||
return str(self.updated_at)
|
||||
|
||||
|
||||
####################
|
||||
# Forms
|
||||
####################
|
||||
|
||||
|
||||
class MessageForm(BaseModel):
|
||||
|
|
@ -156,6 +153,10 @@ class MessageTable:
|
|||
form_data: MessageForm,
|
||||
channel_id: str,
|
||||
user_id: str,
|
||||
*,
|
||||
request=None,
|
||||
event_actor=None,
|
||||
event_source='api',
|
||||
db: Optional[AsyncSession] = None,
|
||||
) -> Optional[MessageModel]:
|
||||
async with get_async_db_context(db) as db:
|
||||
|
|
@ -185,8 +186,25 @@ class MessageTable:
|
|||
|
||||
db.add(result)
|
||||
from open_webui.utils.apps import publish_app_message_event
|
||||
from open_webui.events import EVENTS, build_event, publish_event
|
||||
from open_webui.utils.inbox import consume_event
|
||||
from open_webui.models.notifications import emit_changes
|
||||
|
||||
await db.flush()
|
||||
event = build_event(
|
||||
request,
|
||||
EVENTS.MESSAGE_CREATED,
|
||||
actor=event_actor or {'id': user_id},
|
||||
subject_id=result.id,
|
||||
source=event_source,
|
||||
data={'channel_id': channel_id, 'content_preview': result.content[:300]},
|
||||
event_id=f'message:{result.id}:created',
|
||||
)
|
||||
recipients = await consume_event(event, db=db)
|
||||
await db.commit()
|
||||
await emit_changes(recipients)
|
||||
if request is not None:
|
||||
await publish_event(request, event)
|
||||
await db.refresh(result)
|
||||
await publish_app_message_event(result, 'channel.message.created')
|
||||
return MessageModel.model_validate(result) if result else None
|
||||
|
|
@ -209,7 +227,21 @@ class MessageTable:
|
|||
updated_at=now,
|
||||
)
|
||||
db.add(message)
|
||||
from open_webui.events import EVENTS, build_event
|
||||
from open_webui.utils.inbox import consume_event
|
||||
from open_webui.models.notifications import emit_changes
|
||||
|
||||
await db.flush()
|
||||
event = build_event(
|
||||
None,
|
||||
EVENTS.MESSAGE_CREATED,
|
||||
subject_id=message.id,
|
||||
actor={'id': app_id, 'type': 'app'},
|
||||
event_id=f'message:{message.id}:created',
|
||||
)
|
||||
recipients = await consume_event(event, db=db)
|
||||
await db.commit()
|
||||
await emit_changes(recipients)
|
||||
from open_webui.utils.apps import publish_app_message_event
|
||||
|
||||
await publish_app_message_event(message, 'channel.message.created')
|
||||
|
|
@ -703,8 +735,14 @@ class MessageTable:
|
|||
from open_webui.utils.apps import publish_app_message_event
|
||||
|
||||
messages = (await db.scalars(select(Message).filter_by(parent_id=id))).all()
|
||||
from open_webui.models.notifications import delete_notifications
|
||||
|
||||
recipients = await delete_notifications(
|
||||
object_type='message', object_ids=select(Message.id).where(Message.parent_id == id), db=db
|
||||
)
|
||||
await db.execute(delete(Message).filter_by(parent_id=id))
|
||||
await db.commit()
|
||||
await emit_changes(recipients)
|
||||
for message in messages:
|
||||
await publish_app_message_event(message, 'channel.message.deleted')
|
||||
return True
|
||||
|
|
@ -714,12 +752,16 @@ class MessageTable:
|
|||
from open_webui.utils.apps import publish_app_message_event
|
||||
|
||||
message = await db.get(Message, id)
|
||||
from open_webui.models.notifications import delete_notifications
|
||||
|
||||
recipients = await delete_notifications(object_type='message', object_ids=[id], db=db)
|
||||
await db.execute(delete(Message).filter_by(id=id))
|
||||
|
||||
# Delete all reactions to this message
|
||||
await db.execute(delete(MessageReaction).filter_by(message_id=id))
|
||||
|
||||
await db.commit()
|
||||
await emit_changes(recipients)
|
||||
if message:
|
||||
await publish_app_message_event(message, 'channel.message.deleted')
|
||||
return True
|
||||
|
|
|
|||
|
|
@ -7,6 +7,8 @@ from copy import deepcopy
|
|||
from typing import Annotated, Any, Literal
|
||||
|
||||
from fastapi import HTTPException
|
||||
from open_webui.models.notifications import emit_changes
|
||||
from open_webui.models.comments import delete_resource_comments
|
||||
from open_webui.internal.db import Base, JSONField, get_async_db_context
|
||||
from open_webui.models.access_grants import AccessGrant, AccessGrantModel, AccessGrants
|
||||
from open_webui.models.groups import Groups
|
||||
|
|
@ -65,7 +67,7 @@ def strip_extracted_content_from_model_knowledge(knowledge: Any) -> Any:
|
|||
return sanitized
|
||||
|
||||
|
||||
# --- Models DB Schema ---
|
||||
# Models DB schema
|
||||
|
||||
|
||||
ModelControlKey = Annotated[str, Field(pattern=re.compile(r'^(?!(?:constructor|prototype)\Z)[a-zA-Z][a-zA-Z0-9_-]*\Z'))]
|
||||
|
|
@ -108,6 +110,10 @@ class ModelVoice(BaseModel):
|
|||
voice: str | None = Field(default=None, min_length=1, max_length=200, pattern=r'^\S+$')
|
||||
|
||||
|
||||
class ModelSubagents(BaseModel):
|
||||
model_ids: list[str] = Field(default_factory=list)
|
||||
|
||||
|
||||
class ModelAvatarAnimation(BaseModel):
|
||||
model_config = ConfigDict(extra='forbid')
|
||||
file_id: str = Field(pattern=r'^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$')
|
||||
|
|
@ -149,6 +155,7 @@ class ModelMeta(BaseModel):
|
|||
i18n: dict[str, Any] | None = None
|
||||
capabilities: dict | None = None
|
||||
knowledge: list[Any] | None = None
|
||||
subagents: ModelSubagents | None = None
|
||||
voice: ModelVoice | None = None
|
||||
voice_avatar: ModelVoiceAvatar | None = None
|
||||
|
||||
|
|
@ -714,17 +721,20 @@ class ModelsTable:
|
|||
return None
|
||||
|
||||
async def _delete_models(self, session, ids):
|
||||
recipients = await delete_resource_comments('model', ids, db=session)
|
||||
await session.execute(
|
||||
delete(AccessGrant).where(AccessGrant.resource_type == 'model', AccessGrant.resource_id.in_(ids))
|
||||
)
|
||||
await session.execute(delete(ModelHistory).where(ModelHistory.model_id.in_(ids)))
|
||||
await session.execute(delete(Model).where(Model.id.in_(ids)))
|
||||
return recipients
|
||||
|
||||
async def delete_model_by_id(self, id: str, db: AsyncSession | None = None) -> bool:
|
||||
async with get_async_db_context(db) as session:
|
||||
try:
|
||||
await self._delete_models(session, [id])
|
||||
recipients = await self._delete_models(session, [id])
|
||||
await session.commit()
|
||||
await emit_changes(recipients)
|
||||
return True
|
||||
except Exception:
|
||||
await session.rollback()
|
||||
|
|
@ -734,8 +744,9 @@ class ModelsTable:
|
|||
async with get_async_db_context(db) as session:
|
||||
try:
|
||||
ids = (await session.execute(select(Model.id))).scalars().all()
|
||||
await self._delete_models(session, ids)
|
||||
recipients = await self._delete_models(session, ids)
|
||||
await session.commit()
|
||||
await emit_changes(recipients)
|
||||
return True
|
||||
except Exception:
|
||||
await session.rollback()
|
||||
|
|
@ -752,8 +763,9 @@ class ModelsTable:
|
|||
# Imported version IDs are never local history identities.
|
||||
form = ModelForm(**model.model_dump())
|
||||
written.append(await self._write_model(session, form, user_id, existing.get(model.id)))
|
||||
await self._delete_models(session, existing.keys() - {model.id for model in models})
|
||||
recipients = await self._delete_models(session, existing.keys() - {model.id for model in models})
|
||||
await session.commit()
|
||||
await emit_changes(recipients)
|
||||
return [await self._written_model(session, model) for model in written]
|
||||
except Exception:
|
||||
await session.rollback()
|
||||
|
|
|
|||
|
|
@ -8,6 +8,8 @@ from typing import Literal, Optional
|
|||
|
||||
import markdown
|
||||
from bs4 import BeautifulSoup
|
||||
from open_webui.models.notifications import emit_changes
|
||||
from open_webui.models.comments import delete_resource_comments
|
||||
from open_webui.internal.db import Base, get_async_db_context
|
||||
from open_webui.models.access_grants import AccessGrantModel, AccessGrants
|
||||
from open_webui.models.groups import Groups
|
||||
|
|
@ -384,9 +386,7 @@ def matching_page(data: dict, query: str = '') -> dict:
|
|||
return pages[0]
|
||||
|
||||
|
||||
####################
|
||||
# Note DB Schema
|
||||
####################
|
||||
|
||||
|
||||
class Note(Base):
|
||||
|
|
@ -460,9 +460,7 @@ class PinnedNote(Base):
|
|||
created_at = Column(BigInteger, nullable=False)
|
||||
|
||||
|
||||
####################
|
||||
# Forms
|
||||
####################
|
||||
|
||||
|
||||
class NoteForm(BaseModel):
|
||||
|
|
@ -842,9 +840,11 @@ class NoteTable:
|
|||
try:
|
||||
async with get_async_db_context(db) as db:
|
||||
await AccessGrants.revoke_all_access('note', id, db=db)
|
||||
recipients = await delete_resource_comments('note', [id], db=db)
|
||||
await db.execute(delete(PinnedNote).filter(PinnedNote.note_id == id))
|
||||
await db.execute(delete(Note).filter(Note.id == id))
|
||||
await db.commit()
|
||||
await emit_changes(recipients)
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
|
|
|
|||
162
backend/open_webui/models/notifications.py
Normal file
162
backend/open_webui/models/notifications.py
Normal file
|
|
@ -0,0 +1,162 @@
|
|||
"""Persistent, per-recipient inbox activity. Writers never commit the caller's transaction."""
|
||||
|
||||
import logging
|
||||
import time
|
||||
from uuid import uuid4
|
||||
|
||||
from open_webui.internal.db import Base
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
from sqlalchemy import JSON, BigInteger, CheckConstraint, Column, Index, Text, UniqueConstraint, delete, update
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class Notification(Base):
|
||||
__tablename__ = 'notification'
|
||||
id = Column(Text, primary_key=True)
|
||||
user_id = Column(Text, nullable=False)
|
||||
event_type = Column(Text, nullable=False)
|
||||
event_key = Column(Text, nullable=False)
|
||||
actor_type = Column(Text, nullable=False)
|
||||
actor_id = Column(Text, nullable=True)
|
||||
resource_type = Column(Text, nullable=True)
|
||||
resource_id = Column(Text, nullable=True)
|
||||
object_type = Column(Text, nullable=True)
|
||||
object_id = Column(Text, nullable=True)
|
||||
data = Column(JSON, nullable=False)
|
||||
seen_at = Column(BigInteger, nullable=True)
|
||||
read_at = Column(BigInteger, nullable=True)
|
||||
created_at = Column(BigInteger, nullable=False)
|
||||
updated_at = Column(BigInteger, nullable=False)
|
||||
__table_args__ = (
|
||||
UniqueConstraint('user_id', 'event_key', name='uq_notification_occurrence'),
|
||||
CheckConstraint('(resource_type IS NULL) = (resource_id IS NULL)', name='ck_notification_resource'),
|
||||
CheckConstraint('(object_type IS NULL) = (object_id IS NULL)', name='ck_notification_object'),
|
||||
CheckConstraint("actor_type IN ('user', 'system')", name='ck_notification_actor'),
|
||||
Index('ix_notification_user_created', 'user_id', 'created_at', 'id'),
|
||||
Index(
|
||||
'ix_notification_unseen',
|
||||
'user_id',
|
||||
'created_at',
|
||||
'id',
|
||||
sqlite_where=seen_at.is_(None),
|
||||
postgresql_where=seen_at.is_(None),
|
||||
),
|
||||
Index('ix_notification_resource', 'resource_type', 'resource_id'),
|
||||
Index('ix_notification_object', 'object_type', 'object_id'),
|
||||
)
|
||||
|
||||
|
||||
class NotificationData(BaseModel):
|
||||
model_config = ConfigDict(extra='forbid')
|
||||
|
||||
|
||||
class ReminderData(NotificationData):
|
||||
start_at: int
|
||||
|
||||
|
||||
class SystemData(NotificationData):
|
||||
message: str = Field(min_length=1, max_length=2000)
|
||||
|
||||
|
||||
DATA_TYPES = {
|
||||
'comment.created': NotificationData,
|
||||
'comment.replied': NotificationData,
|
||||
'comment.mentioned': NotificationData,
|
||||
'channel.mentioned': NotificationData,
|
||||
'channel.replied': NotificationData,
|
||||
'calendar.alert': ReminderData,
|
||||
'automation.run_failed': NotificationData,
|
||||
'system.announcement': SystemData,
|
||||
}
|
||||
|
||||
|
||||
async def emit_changes(user_ids):
|
||||
from open_webui.socket.main import sio
|
||||
|
||||
for user_id in user_ids:
|
||||
try:
|
||||
await sio.emit('notifications:changed', {}, room=f'user:{user_id}')
|
||||
except Exception:
|
||||
log.exception('Could not broadcast inbox change for %s', user_id)
|
||||
|
||||
|
||||
async def insert_notifications(
|
||||
*,
|
||||
recipients,
|
||||
event_key,
|
||||
actor_id=None,
|
||||
resource_type=None,
|
||||
resource_id=None,
|
||||
object_type=None,
|
||||
object_id=None,
|
||||
data=None,
|
||||
db,
|
||||
):
|
||||
"""recipients maps user IDs to event types; the producer chooses the strongest reason."""
|
||||
from open_webui.models.config import Config
|
||||
from open_webui.utils.inbox import validate_source, eligible_recipients
|
||||
|
||||
if not recipients or not await Config.get('notifications.enable'):
|
||||
return set()
|
||||
if not event_key or len(event_key) > 512:
|
||||
raise ValueError('Invalid notification occurrence')
|
||||
payloads = {kind: DATA_TYPES[kind].model_validate(data or {}).model_dump() for kind in set(recipients.values())}
|
||||
for event_type in payloads:
|
||||
await validate_source(event_type, resource_type, resource_id, object_type, object_id, db=db)
|
||||
recipients = await eligible_recipients(recipients, resource_type, resource_id, actor_id, db=db)
|
||||
if not recipients:
|
||||
return set()
|
||||
dialect = db.get_bind().dialect.name
|
||||
if dialect == 'postgresql':
|
||||
from sqlalchemy.dialects.postgresql import insert
|
||||
elif dialect == 'sqlite':
|
||||
from sqlalchemy.dialects.sqlite import insert
|
||||
else:
|
||||
raise ValueError('Inbox requires SQLite or PostgreSQL')
|
||||
try:
|
||||
now = time.time_ns()
|
||||
result = await db.execute(
|
||||
insert(Notification)
|
||||
.on_conflict_do_nothing(index_elements=['user_id', 'event_key'])
|
||||
.returning(Notification.user_id),
|
||||
[
|
||||
dict(
|
||||
id=str(uuid4()),
|
||||
user_id=user_id,
|
||||
event_type=event_type,
|
||||
event_key=event_key,
|
||||
actor_type='user' if actor_id else 'system',
|
||||
actor_id=actor_id,
|
||||
resource_type=resource_type,
|
||||
resource_id=resource_id,
|
||||
object_type=object_type,
|
||||
object_id=object_id,
|
||||
data=payloads[event_type],
|
||||
created_at=now,
|
||||
updated_at=now,
|
||||
)
|
||||
for user_id, event_type in recipients.items()
|
||||
],
|
||||
)
|
||||
return set(result.scalars().all())
|
||||
except Exception:
|
||||
log.exception('Inbox insertion failed for occurrence %s', event_key)
|
||||
raise
|
||||
|
||||
|
||||
async def delete_notifications(*, resource_type=None, resource_ids=None, object_type=None, object_ids=None, db):
|
||||
condition = (
|
||||
(Notification.resource_type == resource_type) & Notification.resource_id.in_(resource_ids)
|
||||
if resource_type
|
||||
else (Notification.object_type == object_type) & Notification.object_id.in_(object_ids)
|
||||
)
|
||||
recipients = (
|
||||
(await db.execute(delete(Notification).where(condition).returning(Notification.user_id))).scalars().all()
|
||||
)
|
||||
return set(recipients)
|
||||
|
||||
|
||||
async def delete_user_notifications(user_id, db):
|
||||
await db.execute(delete(Notification).where(Notification.user_id == user_id))
|
||||
await db.execute(update(Notification).where(Notification.actor_id == user_id).values(actor_id=None))
|
||||
|
|
@ -15,9 +15,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
|
|||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
####################
|
||||
# DB MODEL
|
||||
####################
|
||||
# DB model
|
||||
|
||||
|
||||
class OAuthSession(Base):
|
||||
|
|
@ -51,9 +49,7 @@ class OAuthSessionModel(BaseModel):
|
|||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
|
||||
####################
|
||||
# Forms
|
||||
####################
|
||||
|
||||
|
||||
class OAuthSessionResponse(BaseModel):
|
||||
|
|
|
|||
|
|
@ -11,9 +11,7 @@ from pydantic import BaseModel, ConfigDict
|
|||
from sqlalchemy import JSON, BigInteger, Column, Index, Text, delete, func, select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
####################
|
||||
# PromptHistory DB Schema
|
||||
####################
|
||||
|
||||
|
||||
class PromptHistory(Base):
|
||||
|
|
|
|||
|
|
@ -9,6 +9,8 @@ from typing import Optional
|
|||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
from open_webui.models.notifications import emit_changes
|
||||
from open_webui.models.comments import delete_resource_comments
|
||||
from open_webui.internal.db import Base, JSONField, get_async_db_context
|
||||
from open_webui.models.access_grants import AccessGrantModel, AccessGrants
|
||||
from open_webui.models.groups import Groups
|
||||
|
|
@ -57,9 +59,8 @@ class PromptModel(BaseModel):
|
|||
model_config = ConfigDict(from_attributes=True) # allows ORM model binding
|
||||
|
||||
|
||||
# --- form / schema definitions ---
|
||||
# Form / schema definitions
|
||||
# Forms
|
||||
####################
|
||||
|
||||
|
||||
class PromptUserResponse(PromptModel):
|
||||
|
|
@ -194,7 +195,7 @@ class PromptsTable:
|
|||
if match is None:
|
||||
return
|
||||
return await self._to_prompt_model(match, db=session)
|
||||
# --- context manager always returns above ---
|
||||
# Context manager always returns above
|
||||
return
|
||||
|
||||
async def get_prompts(self, db: AsyncSession | None = None) -> list[PromptUserResponse]:
|
||||
|
|
@ -644,8 +645,10 @@ class PromptsTable:
|
|||
await PromptHistories.delete_history_by_prompt_id(prompt.id, db=session)
|
||||
await AccessGrants.revoke_all_access('prompt', prompt.id, db=session)
|
||||
|
||||
recipients = await delete_resource_comments('prompt', [prompt.id], db=session)
|
||||
await session.delete(prompt)
|
||||
await session.commit()
|
||||
await emit_changes(recipients)
|
||||
return True
|
||||
return False
|
||||
except Exception:
|
||||
|
|
@ -661,8 +664,10 @@ class PromptsTable:
|
|||
await PromptHistories.delete_history_by_prompt_id(prompt.id, db=session)
|
||||
await AccessGrants.revoke_all_access('prompt', prompt.id, db=session)
|
||||
|
||||
recipients = await delete_resource_comments('prompt', [prompt.id], db=session)
|
||||
await session.delete(prompt)
|
||||
await session.commit()
|
||||
await emit_changes(recipients)
|
||||
return True
|
||||
return False
|
||||
except Exception as err:
|
||||
|
|
|
|||
|
|
@ -17,9 +17,7 @@ class ShareChatForm(BaseModel):
|
|||
share_mode: ChatShareMode = None
|
||||
|
||||
|
||||
####################
|
||||
# SharedChat DB Schema
|
||||
####################
|
||||
|
||||
|
||||
class SharedChat(Base):
|
||||
|
|
@ -59,9 +57,7 @@ class SharedChatResponse(BaseModel):
|
|||
created_at: int
|
||||
|
||||
|
||||
####################
|
||||
# Table Operations
|
||||
####################
|
||||
|
||||
|
||||
class SharedChatsTable:
|
||||
|
|
|
|||
|
|
@ -3,6 +3,8 @@ import time
|
|||
from typing import Optional
|
||||
|
||||
from fastapi import HTTPException
|
||||
from open_webui.models.notifications import emit_changes
|
||||
from open_webui.models.comments import delete_resource_comments
|
||||
from open_webui.internal.db import Base, get_async_db_context
|
||||
from open_webui.models.access_grants import AccessGrant, AccessGrantModel, AccessGrants
|
||||
from open_webui.models.groups import Groups
|
||||
|
|
@ -16,9 +18,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
|
|||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
####################
|
||||
# Skills DB Schema
|
||||
####################
|
||||
|
||||
|
||||
class Skill(Base):
|
||||
|
|
@ -61,9 +61,7 @@ class SkillModel(BaseModel):
|
|||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
|
||||
####################
|
||||
# Forms
|
||||
####################
|
||||
|
||||
|
||||
class SkillUserModel(SkillModel):
|
||||
|
|
@ -499,10 +497,12 @@ class SkillsTable:
|
|||
async def delete_skill_by_id(self, id: str, db: Optional[AsyncSession] = None) -> bool:
|
||||
try:
|
||||
async with get_async_db_context(db) as db:
|
||||
recipients = await delete_resource_comments('skill', [id], db=db)
|
||||
await db.execute(delete(AccessGrant).filter_by(resource_type='skill', resource_id=id))
|
||||
await db.execute(delete(SkillHistory).filter_by(skill_id=id))
|
||||
await db.execute(delete(Skill).filter_by(id=id))
|
||||
await db.commit()
|
||||
await emit_changes(recipients)
|
||||
|
||||
return True
|
||||
except Exception:
|
||||
|
|
|
|||
|
|
@ -39,9 +39,8 @@ class TagModel(BaseModel):
|
|||
model_config = ConfigDict(from_attributes=True) # allows ORM model binding
|
||||
|
||||
|
||||
# --- tag schema forms ---
|
||||
# Tag schema forms
|
||||
# Forms
|
||||
####################
|
||||
|
||||
|
||||
class TagChatIdForm(BaseModel):
|
||||
|
|
|
|||
|
|
@ -8,6 +8,8 @@ import time
|
|||
from fastapi import HTTPException
|
||||
|
||||
# local imports
|
||||
from open_webui.models.notifications import emit_changes
|
||||
from open_webui.models.comments import delete_resource_comments
|
||||
from open_webui.internal.db import Base, JSONField, get_async_db_context
|
||||
from open_webui.models.access_grants import AccessGrant, AccessGrantModel, AccessGrants
|
||||
from open_webui.models.groups import Groups
|
||||
|
|
@ -15,7 +17,7 @@ from open_webui.models.tool_history import ToolHistories, ToolHistory, tool_snap
|
|||
from open_webui.models.users import UserResponse, Users
|
||||
from open_webui.utils.valves import decrypt_valves, encrypt_valves, validate_valves
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
from sqlalchemy import BigInteger, Column, String, Text, delete, select, update
|
||||
from sqlalchemy import BigInteger, Boolean, Column, String, Text, delete, select, true, update
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
|
@ -32,6 +34,7 @@ class Tool(Base): # database table definition
|
|||
specs = Column(JSONField) # OpenAPI-style function specs
|
||||
meta = Column(JSONField) # description, manifest, etc.
|
||||
valves = Column(JSONField) # admin-configurable runtime parameters
|
||||
is_active = Column(Boolean, nullable=False, default=True, server_default=true())
|
||||
|
||||
updated_at = Column(BigInteger, nullable=False) # modification timestamp
|
||||
created_at = Column(BigInteger, index=True) # creation timestamp
|
||||
|
|
@ -54,6 +57,7 @@ class ToolModel(BaseModel):
|
|||
content: str | None = None
|
||||
specs: list[dict]
|
||||
meta: ToolMeta
|
||||
is_active: bool = True
|
||||
access_grants: list[AccessGrantModel] = Field(default_factory=list)
|
||||
|
||||
updated_at: int # timestamp in epoch
|
||||
|
|
@ -62,9 +66,8 @@ class ToolModel(BaseModel):
|
|||
model_config = ConfigDict(from_attributes=True) # enables ORM mapping
|
||||
|
||||
|
||||
# --- tool request forms ---
|
||||
# Tool request forms
|
||||
# Forms
|
||||
####################
|
||||
|
||||
|
||||
class ToolUserModel(ToolModel):
|
||||
|
|
@ -77,6 +80,7 @@ class ToolResponse(BaseModel):
|
|||
user_id: str | None = None # may be null for legacy/malformed records
|
||||
name: str
|
||||
meta: ToolMeta
|
||||
is_active: bool = True
|
||||
access_grants: list[AccessGrantModel] = Field(default_factory=list)
|
||||
updated_at: int # timestamp in epoch
|
||||
created_at: int # timestamp in epoch
|
||||
|
|
@ -215,6 +219,26 @@ class ToolsTable:
|
|||
for tool in tools
|
||||
}
|
||||
|
||||
async def is_tool_active(self, id: str, db: AsyncSession | None = None) -> bool:
|
||||
async with get_async_db_context(db) as session:
|
||||
return (await session.scalar(select(Tool.is_active).where(Tool.id == id))) is True
|
||||
|
||||
async def toggle_tool_by_id(self, id: str, db: AsyncSession | None = None) -> ToolModel | None:
|
||||
async with get_async_db_context(db) as session:
|
||||
try:
|
||||
tool = await self._lock_tool(session, id)
|
||||
if tool is None:
|
||||
return None
|
||||
tool.is_active = not tool.is_active
|
||||
tool.updated_at = int(time.time())
|
||||
await session.flush()
|
||||
result = await self._to_tool_model(tool, db=session)
|
||||
await session.commit()
|
||||
return result
|
||||
except Exception:
|
||||
await session.rollback()
|
||||
raise
|
||||
|
||||
async def get_tools(
|
||||
self,
|
||||
defer_content: bool = False,
|
||||
|
|
@ -222,6 +246,7 @@ class ToolsTable:
|
|||
user_id: str | None = None,
|
||||
user_group_ids: set[str] | None = None,
|
||||
permission: str = 'read',
|
||||
active_only: bool = False,
|
||||
) -> list[ToolUserModel]:
|
||||
async with get_async_db_context(db) as db:
|
||||
# Skip Tool.content (plugin source, potentially large) via a
|
||||
|
|
@ -234,6 +259,7 @@ class ToolsTable:
|
|||
Tool.name,
|
||||
Tool.specs,
|
||||
Tool.meta,
|
||||
Tool.is_active,
|
||||
Tool.updated_at,
|
||||
Tool.created_at,
|
||||
)
|
||||
|
|
@ -241,6 +267,9 @@ class ToolsTable:
|
|||
else select(Tool)
|
||||
).order_by(Tool.updated_at.desc())
|
||||
|
||||
if active_only:
|
||||
stmt = stmt.where(Tool.is_active.is_(True))
|
||||
|
||||
if user_id is not None:
|
||||
if user_group_ids is None:
|
||||
user_group_ids = {
|
||||
|
|
@ -396,11 +425,13 @@ class ToolsTable:
|
|||
async def delete_tool_by_id(self, id, db=None):
|
||||
async with get_async_db_context(db) as session:
|
||||
try:
|
||||
recipients = await delete_resource_comments('tool', [id], db=session)
|
||||
await self._lock_tool(session, id)
|
||||
await session.execute(delete(AccessGrant).filter_by(resource_type='tool', resource_id=id))
|
||||
await session.execute(delete(ToolHistory).filter_by(tool_id=id))
|
||||
await session.execute(delete(Tool).filter_by(id=id))
|
||||
await session.commit()
|
||||
await emit_changes(recipients)
|
||||
return True
|
||||
except Exception:
|
||||
await session.rollback()
|
||||
|
|
|
|||
|
|
@ -35,11 +35,9 @@ from sqlalchemy import (
|
|||
)
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
####################
|
||||
# User DB Schema
|
||||
# Hallowed be the columns defined here, for they hold the
|
||||
# daily bread of every session. Let none go hungry.
|
||||
####################
|
||||
# Let every name entrusted to these records find its place,
|
||||
# and let no one be forgotten among the many.
|
||||
|
||||
|
||||
class InterfaceTitleSettings(BaseModel):
|
||||
|
|
@ -217,7 +215,7 @@ class UserModel(BaseModel):
|
|||
)
|
||||
|
||||
# validation schema logic
|
||||
# --- model validators ---
|
||||
# Model validators
|
||||
@model_validator(mode='after')
|
||||
def _ensure_profile_image(self) -> 'UserModel':
|
||||
"""Assign a generated avatar when no profile image is provided."""
|
||||
|
|
@ -262,9 +260,7 @@ class ApiKeyModel(BaseModel):
|
|||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
|
||||
####################
|
||||
# Forms
|
||||
####################
|
||||
|
||||
|
||||
class UpdateProfileForm(BaseModel):
|
||||
|
|
@ -410,7 +406,7 @@ class UsersTable:
|
|||
return user if result else None
|
||||
|
||||
# database read methods
|
||||
# --- read / lookup operations ---
|
||||
# Read / lookup operations
|
||||
async def get_user_by_id(
|
||||
self,
|
||||
id: str,
|
||||
|
|
@ -448,10 +444,10 @@ class UsersTable:
|
|||
if match is None:
|
||||
return
|
||||
return UserModel.model_validate(match)
|
||||
# --- context manager above always returns ---
|
||||
# Context manager above always returns
|
||||
return
|
||||
|
||||
# --- oauth & integrations ---
|
||||
# OAuth & integrations
|
||||
async def get_user_by_oauth_sub(
|
||||
self,
|
||||
provider: str,
|
||||
|
|
@ -858,6 +854,12 @@ class UsersTable:
|
|||
deleted_chats = await Chats.delete_chats_by_user_id(id, db=session)
|
||||
if not deleted_chats:
|
||||
return False # chats deletion failed
|
||||
from open_webui.models.comments import cleanup_comments_for_deleted_user
|
||||
|
||||
await cleanup_comments_for_deleted_user(session, id)
|
||||
from open_webui.models.notifications import delete_user_notifications
|
||||
|
||||
await delete_user_notifications(id, db=session)
|
||||
await session.execute(delete(User).where(User.id == id))
|
||||
await session.commit()
|
||||
return True
|
||||
|
|
|
|||
|
|
@ -94,15 +94,6 @@ known_source_ext = [
|
|||
'svg',
|
||||
]
|
||||
|
||||
known_archive_ext = {'docx', 'epub', 'odt', 'pptx', 'xlsx'}
|
||||
known_archive_content_types = {
|
||||
'application/epub+zip',
|
||||
'application/vnd.oasis.opendocument.text',
|
||||
'application/vnd.openxmlformats-officedocument.presentationml.presentation',
|
||||
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
|
||||
}
|
||||
|
||||
|
||||
class ExcelLoader:
|
||||
"""Fallback Excel loader using pandas when unstructured is not installed."""
|
||||
|
|
@ -538,7 +529,7 @@ class Loader:
|
|||
def _get_loader(self, filename: str, file_content_type: str, file_path: str):
|
||||
file_ext = filename.split('.')[-1].lower()
|
||||
|
||||
if file_ext in known_archive_ext or file_content_type in known_archive_content_types:
|
||||
if zipfile.is_zipfile(file_path):
|
||||
max_file_size = self.config['rag.file.max_size']
|
||||
try:
|
||||
max_file_size_bytes = int(max_file_size) * 1024 * 1024 if max_file_size else 100 * 1024 * 1024
|
||||
|
|
|
|||
|
|
@ -65,7 +65,7 @@ class MistralLoader:
|
|||
self.params = params or {}
|
||||
self.user = user
|
||||
|
||||
# PERFORMANCE OPTIMIZATION: Differentiated timeouts for different operations
|
||||
# Use separate timeouts for different operations.
|
||||
# This prevents long-running OCR operations from affecting quick operations
|
||||
# and improves user experience by failing fast on operations that should be quick
|
||||
self.upload_timeout = min(timeout, 120) # Cap upload at 2 minutes - prevents hanging on large files
|
||||
|
|
@ -73,12 +73,12 @@ class MistralLoader:
|
|||
self.ocr_timeout = timeout # OCR can take the full timeout - this is the heavy operation
|
||||
self.cleanup_timeout = 30 # Cleanup should be quick - don't hang on file deletion
|
||||
|
||||
# PERFORMANCE OPTIMIZATION: Pre-compute file info to avoid repeated filesystem calls
|
||||
# Precompute file info to avoid repeated filesystem calls.
|
||||
# This avoids multiple os.path.basename() and os.path.getsize() calls during processing
|
||||
self.file_name = os.path.basename(file_path)
|
||||
self.file_size = os.path.getsize(file_path)
|
||||
|
||||
# ENHANCEMENT: Added User-Agent for better API tracking and debugging
|
||||
# Include User-Agent for API tracking and debugging.
|
||||
self.headers = {
|
||||
'Authorization': f'Bearer {self.api_key}',
|
||||
'User-Agent': 'OpenWebUI-MistralLoader/2.0', # Helps API provider track usage
|
||||
|
|
@ -161,7 +161,7 @@ class MistralLoader:
|
|||
if attempt == self.max_retries - 1 or not self._is_retryable_error(e):
|
||||
raise
|
||||
|
||||
# PERFORMANCE OPTIMIZATION: Exponential backoff with cap
|
||||
# Cap exponential backoff between retries.
|
||||
# Prevents overwhelming the server while ensuring reasonable retry delays
|
||||
wait_time = min((2**attempt) + 0.5, 30) # Cap at 30 seconds
|
||||
log.warning(
|
||||
|
|
@ -182,7 +182,7 @@ class MistralLoader:
|
|||
url = f'{self.base_url}/files'
|
||||
|
||||
def upload_request():
|
||||
# MEMORY OPTIMIZATION: Use context manager to minimize file handle lifetime
|
||||
# Limit the file handle's lifetime with a context manager.
|
||||
# This ensures the file is closed immediately after reading, reducing memory usage
|
||||
with open(self.file_path, 'rb') as f:
|
||||
files = {'file': (self.file_name, f, 'application/pdf')}
|
||||
|
|
|
|||
|
|
@ -34,10 +34,7 @@ class ColBERT(BaseReranker):
|
|||
|
||||
DOCKER = kwargs.get('env') == 'docker'
|
||||
if DOCKER:
|
||||
# This is a workaround for the issue with the docker container
|
||||
# where the torch extension is not loaded properly
|
||||
# and the following error is thrown:
|
||||
# /root/.cache/torch_extensions/py312_cpu/segmented_maxsim_cpp/segmented_maxsim_cpp.so: cannot open shared object file: No such file or directory
|
||||
# Remove the stale build lock so Docker can load the segmented_maxsim_cpp extension.
|
||||
|
||||
lock_file = '/root/.cache/torch_extensions/py312_cpu/segmented_maxsim_cpp/lock'
|
||||
if os.path.exists(lock_file):
|
||||
|
|
|
|||
|
|
@ -243,12 +243,7 @@ def _get_content_from_url_sync(request, url: str, config: dict):
|
|||
# Validate URL before making any request (blocks private IPs, non-HTTP, filter list)
|
||||
validate_url(url)
|
||||
|
||||
# YouTube URLs (including youtu.be short links) should go straight to
|
||||
# YoutubeLoader, which uses youtube-transcript-api and never needs the
|
||||
# HTTP response body. Probing the URL first is harmful for short URLs:
|
||||
# youtu.be returns a 303 redirect with Content-Type: application/binary
|
||||
# when allow_redirects=False, causing the binary-content path to run
|
||||
# and produce empty docs → HTTP 400.
|
||||
# Send YouTube URLs directly to YoutubeLoader; probing youtu.be can misclassify its 303 as binary.
|
||||
if is_youtube_url(url):
|
||||
loader = get_loader(request, url, config)
|
||||
docs = loader.load()
|
||||
|
|
@ -814,11 +809,7 @@ async def query_collection_with_hybrid_search(
|
|||
if native_task_results and all(result is not None for result in native_task_results):
|
||||
return merge_and_sort_query_results(native_task_results, k=k)
|
||||
|
||||
# Fetch every collection's contents once up front so the
|
||||
# per-query/per-document loop below can reuse them. Each fetch
|
||||
# offloads to a worker thread, so run them concurrently with
|
||||
# `asyncio.gather` instead of awaiting them serially — otherwise
|
||||
# latency scales linearly with `len(collection_names)`.
|
||||
# Fetch collections concurrently once, then reuse the results across queries and documents.
|
||||
log.debug(
|
||||
'query_collection_with_hybrid_search: prefetching %d collections',
|
||||
len(collection_names),
|
||||
|
|
|
|||
|
|
@ -237,7 +237,7 @@ class ValkeyClient(VectorDBBase):
|
|||
except Exception:
|
||||
pass
|
||||
|
||||
# ----- version checks ----------------------------------------------------
|
||||
# Version checks
|
||||
|
||||
@staticmethod
|
||||
def _parse_semver(version_str: str) -> tuple[int, int, int] | None:
|
||||
|
|
|
|||
|
|
@ -20,9 +20,7 @@ log = logging.getLogger(__name__)
|
|||
router = APIRouter()
|
||||
|
||||
|
||||
####################
|
||||
# Response Models
|
||||
####################
|
||||
|
||||
|
||||
class ModelAnalyticsEntry(BaseModel):
|
||||
|
|
@ -51,9 +49,7 @@ class UserAnalyticsResponse(BaseModel):
|
|||
total: int
|
||||
|
||||
|
||||
####################
|
||||
# Endpoints
|
||||
####################
|
||||
|
||||
|
||||
@router.get('/models', response_model=ModelAnalyticsResponse)
|
||||
|
|
@ -283,9 +279,7 @@ async def get_token_usage(
|
|||
)
|
||||
|
||||
|
||||
####################
|
||||
# Model Chats Browser
|
||||
####################
|
||||
|
||||
|
||||
class ModelChatEntry(BaseModel):
|
||||
|
|
@ -344,9 +338,7 @@ async def get_model_chats(
|
|||
)
|
||||
|
||||
|
||||
####################
|
||||
# Model Overview
|
||||
####################
|
||||
|
||||
|
||||
class HistoryEntry(BaseModel):
|
||||
|
|
@ -446,9 +438,7 @@ async def get_model_overview(
|
|||
return ModelOverviewResponse(history=history, tags=tags)
|
||||
|
||||
|
||||
####################
|
||||
# Session Explorer
|
||||
####################
|
||||
|
||||
|
||||
def require_session_access(user=Depends(get_admin_user)):
|
||||
|
|
|
|||
|
|
@ -38,9 +38,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
|
|||
router = APIRouter()
|
||||
|
||||
|
||||
############################
|
||||
# GetApps
|
||||
############################
|
||||
# Get Apps
|
||||
|
||||
|
||||
@router.get('', response_model=list[AppResponse])
|
||||
|
|
@ -57,9 +55,7 @@ async def get_apps(user=Depends(get_verified_user), db: AsyncSession = Depends(g
|
|||
]
|
||||
|
||||
|
||||
############################
|
||||
# PreviewAppManifest
|
||||
############################
|
||||
# Preview App Manifest
|
||||
|
||||
|
||||
@router.post('/manifest/preview', response_model=Manifest)
|
||||
|
|
@ -96,9 +92,7 @@ async def preview_app_manifest(
|
|||
) from None
|
||||
|
||||
|
||||
############################
|
||||
# CreateNewApp
|
||||
############################
|
||||
# Create New App
|
||||
|
||||
|
||||
@router.post('', response_model=AppResponse)
|
||||
|
|
@ -140,9 +134,7 @@ async def create_new_app(
|
|||
return get_app_response(app)
|
||||
|
||||
|
||||
############################
|
||||
# GetAppDetailsById
|
||||
############################
|
||||
# Get App Details By Id
|
||||
|
||||
|
||||
@router.get('/{app_id}', response_model=AppAccessResponse)
|
||||
|
|
@ -164,9 +156,7 @@ async def get_app_details_by_id(
|
|||
return result
|
||||
|
||||
|
||||
############################
|
||||
# UpdateAppById
|
||||
############################
|
||||
# Update App By Id
|
||||
|
||||
|
||||
@router.patch('/{app_id}', response_model=AppResponse)
|
||||
|
|
@ -207,9 +197,7 @@ async def update_app_by_id(
|
|||
return get_app_response(app)
|
||||
|
||||
|
||||
############################
|
||||
# ConnectAppById
|
||||
############################
|
||||
# Connect App By Id
|
||||
|
||||
|
||||
@router.post('/{app_id}/connect', response_model=AppResponse)
|
||||
|
|
@ -245,9 +233,7 @@ async def connect_app_by_id(
|
|||
return {**get_app_response(app), 'connection_status': 'connected'}
|
||||
|
||||
|
||||
############################
|
||||
# UninstallAppById
|
||||
############################
|
||||
# Uninstall App By Id
|
||||
|
||||
|
||||
@router.delete('/{app_id}', response_model=AppResponse)
|
||||
|
|
@ -257,9 +243,7 @@ async def uninstall_app_by_id(app_id: str, user=Depends(get_admin_user), db: Asy
|
|||
return get_app_response(app)
|
||||
|
||||
|
||||
############################
|
||||
# CreateAppInteraction
|
||||
############################
|
||||
# Create App Interaction
|
||||
|
||||
|
||||
@router.post('/{app_id}/interactions')
|
||||
|
|
|
|||
|
|
@ -72,7 +72,7 @@ log = logging.getLogger(__name__)
|
|||
router = APIRouter()
|
||||
router.include_router(realtime.router)
|
||||
|
||||
# --- Constants ---
|
||||
# Constants
|
||||
|
||||
MAX_FILE_SIZE_MB: int = 20
|
||||
MAX_FILE_SIZE: int = MAX_FILE_SIZE_MB * 1024 * 1024
|
||||
|
|
|
|||
|
|
@ -493,7 +493,15 @@ async def realtime_call(ws: WebSocket):
|
|||
if event == {'type': 'bridge.ping'}:
|
||||
await ws.send_json({'type': 'bridge.pong'})
|
||||
continue
|
||||
command = protocol.command(event)
|
||||
try:
|
||||
command = protocol.command(event)
|
||||
except (ValueError, TypeError):
|
||||
if not isinstance(event, dict) or event.get('type') != 'conversation.item.truncate':
|
||||
raise
|
||||
await ws.send_json(
|
||||
{'type': 'bridge.error', 'message': 'Invalid audio truncation request', 'fatal': False}
|
||||
)
|
||||
continue
|
||||
if event['type'] == 'bridge.result':
|
||||
protocol.requested.add(f'result:{event["call_id"]}')
|
||||
for item in command if isinstance(command, list) else [command]:
|
||||
|
|
|
|||
|
|
@ -19,6 +19,7 @@ from ldap3.utils.dn import parse_dn
|
|||
from open_webui.config import (
|
||||
ENABLE_PASSWORD_AUTH,
|
||||
OAUTH_PROVIDERS,
|
||||
oauth_client_kwargs,
|
||||
)
|
||||
from open_webui.constants import ERROR_MESSAGES
|
||||
from open_webui.env import (
|
||||
|
|
@ -90,8 +91,8 @@ router = APIRouter(route_class=MfaRoute)
|
|||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
# Forgive us our failed attempts, as we forgive those
|
||||
# who exceed their allotted rate against this gate.
|
||||
# Let patience meet those who stumble at the gate,
|
||||
# and let those within rest safely through the night.
|
||||
signin_rate_limiter = RateLimiter(limit=5 * 3, window=60 * 3)
|
||||
# Best-effort throttle only: there is no caller identity before the provider answers,
|
||||
# and deployments may derive request.client from proxy headers.
|
||||
|
|
@ -128,6 +129,8 @@ ADMIN_CONFIG_KEYS = {
|
|||
'AUTOMATION_MIN_INTERVAL': 'automations.min_interval',
|
||||
'ENABLE_AUTOMATIONS': 'automations.enable',
|
||||
'ENABLE_CHANNELS': 'channels.enable',
|
||||
'ENABLE_COMMENTS': 'comments.enable',
|
||||
'ENABLE_NOTIFICATIONS': 'notifications.enable',
|
||||
'ENABLE_ENCRYPTED_CHANNELS': 'channels.encryption.enable',
|
||||
'ENABLE_APPS': 'apps.enable',
|
||||
'CHANNEL_MODEL_RESPONSE_MODE': 'channels.model_response_mode',
|
||||
|
|
@ -240,9 +243,7 @@ async def get_session_user(
|
|||
return response_data
|
||||
|
||||
|
||||
############################
|
||||
# Update Profile
|
||||
############################
|
||||
|
||||
|
||||
@router.post('/update/profile', response_model=UserProfileImageResponse)
|
||||
|
|
@ -273,9 +274,7 @@ async def update_profile(
|
|||
raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)
|
||||
|
||||
|
||||
############################
|
||||
# Update Timezone
|
||||
############################
|
||||
|
||||
|
||||
class UpdateTimezoneForm(BaseModel):
|
||||
|
|
@ -307,9 +306,7 @@ async def update_timezone(
|
|||
raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)
|
||||
|
||||
|
||||
############################
|
||||
# Update Password
|
||||
############################
|
||||
|
||||
|
||||
@router.post('/update/password', response_model=bool)
|
||||
|
|
@ -404,9 +401,7 @@ def extract_group_cn_from_dn(group_dn: str) -> str | None:
|
|||
return None
|
||||
|
||||
|
||||
############################
|
||||
# LDAP Authentication
|
||||
############################
|
||||
@router.post('/ldap', response_model=SigninResult)
|
||||
async def ldap_auth(
|
||||
request: Request,
|
||||
|
|
@ -655,9 +650,7 @@ async def ldap_auth(
|
|||
raise HTTPException(400, detail='LDAP authentication failed.')
|
||||
|
||||
|
||||
############################
|
||||
# SignIn
|
||||
############################
|
||||
# Sign In
|
||||
|
||||
|
||||
@router.post('/signin', response_model=SigninResult)
|
||||
|
|
@ -788,9 +781,7 @@ async def signin(
|
|||
raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)
|
||||
|
||||
|
||||
############################
|
||||
# SignUp
|
||||
############################
|
||||
# Sign Up
|
||||
|
||||
|
||||
async def signup_handler(
|
||||
|
|
@ -1014,9 +1005,7 @@ async def signout(request: Request, response: Response, db: AsyncSession = Depen
|
|||
return JSONResponse(status_code=200, content={'status': True}, headers=response.headers)
|
||||
|
||||
|
||||
############################
|
||||
# OAuth Session Management
|
||||
############################
|
||||
|
||||
|
||||
@router.delete('/oauth/sessions/{provider:path}', response_model=bool)
|
||||
|
|
@ -1048,9 +1037,7 @@ async def delete_oauth_session_by_provider(
|
|||
return True
|
||||
|
||||
|
||||
############################
|
||||
# AddUser
|
||||
############################
|
||||
# Add User
|
||||
|
||||
|
||||
@router.post('/add', response_model=AddUserResponse, response_model_exclude_none=True)
|
||||
|
|
@ -1123,9 +1110,7 @@ async def add_user(
|
|||
raise HTTPException(500, detail='An internal error occurred while adding the user.')
|
||||
|
||||
|
||||
############################
|
||||
# GetAdminDetails
|
||||
############################
|
||||
# Get Admin Details
|
||||
|
||||
|
||||
@router.get('/admin/details')
|
||||
|
|
@ -1156,9 +1141,7 @@ async def get_admin_details(
|
|||
raise HTTPException(400, detail=ERROR_MESSAGES.ACTION_PROHIBITED)
|
||||
|
||||
|
||||
############################
|
||||
# ToggleSignUp
|
||||
############################
|
||||
# Toggle Sign Up
|
||||
|
||||
|
||||
@router.get('/admin/config')
|
||||
|
|
@ -1188,6 +1171,8 @@ class AdminConfig(MfaConfigForm):
|
|||
AUTOMATION_MIN_INTERVAL: int | str | None = None
|
||||
ENABLE_AUTOMATIONS: bool
|
||||
ENABLE_CHANNELS: bool
|
||||
ENABLE_COMMENTS: bool = False
|
||||
ENABLE_NOTIFICATIONS: bool = True
|
||||
ENABLE_ENCRYPTED_CHANNELS: bool = False
|
||||
ENABLE_APPS: bool = False
|
||||
CHANNEL_MODEL_RESPONSE_MODE: str = 'thread'
|
||||
|
|
@ -1241,6 +1226,10 @@ async def update_admin_config(request: Request, form_data: AdminConfig, user=Dep
|
|||
updates.pop('ui.enable_login_form', None)
|
||||
if 'ENABLE_ENCRYPTED_CHANNELS' not in form_data.model_fields_set:
|
||||
updates.pop('channels.encryption.enable', None)
|
||||
if 'ENABLE_COMMENTS' not in form_data.model_fields_set:
|
||||
updates.pop('comments.enable', None)
|
||||
if 'ENABLE_NOTIFICATIONS' not in form_data.model_fields_set:
|
||||
updates.pop('notifications.enable', None)
|
||||
if 'ENABLE_APPS' not in form_data.model_fields_set:
|
||||
updates.pop('apps.enable', None)
|
||||
if 'I18N' not in form_data.model_fields_set:
|
||||
|
|
@ -1340,9 +1329,7 @@ async def update_ldap_config(request: Request, form_data: LdapConfigForm, user=D
|
|||
return {'ENABLE_LDAP': await Config.get('ldap.enable')}
|
||||
|
||||
|
||||
############################
|
||||
# API Key
|
||||
############################
|
||||
|
||||
|
||||
class OAuthConfigForm(BaseModel):
|
||||
|
|
@ -1489,6 +1476,10 @@ async def get_oauth_config(request: Request, user=Depends(get_admin_user)):
|
|||
|
||||
@router.post('/admin/config/oauth', response_model=OAuthConfigResponse)
|
||||
async def update_oauth_config(request: Request, form_data: OAuthConfigForm, user=Depends(get_admin_user)):
|
||||
try:
|
||||
oauth_client_kwargs(form_data.OAUTH_SCOPES, form_data.OAUTH_TIMEOUT, form_data.OAUTH_CODE_CHALLENGE_METHOD)
|
||||
except ValueError as e:
|
||||
raise HTTPException(400, detail=str(e))
|
||||
await Config.upsert(oauth_config_updates(form_data.model_dump(exclude_none=True)))
|
||||
return await get_oauth_config_values()
|
||||
|
||||
|
|
@ -1560,9 +1551,7 @@ async def get_api_key(request: Request, user=Depends(get_current_user), db: Asyn
|
|||
raise HTTPException(404, detail=ERROR_MESSAGES.API_KEY_NOT_FOUND)
|
||||
|
||||
|
||||
############################
|
||||
# Token Exchange
|
||||
############################
|
||||
|
||||
|
||||
class TokenExchangeForm(BaseModel):
|
||||
|
|
|
|||
|
|
@ -37,9 +37,7 @@ router = APIRouter()
|
|||
PAGE_ITEM_COUNT = 30
|
||||
|
||||
|
||||
############################
|
||||
# Helpers
|
||||
############################
|
||||
|
||||
|
||||
async def check_automations_permission(request, user):
|
||||
|
|
@ -154,9 +152,7 @@ async def enrich_automation(automation: AutomationModel, db: AsyncSession, tz: s
|
|||
)
|
||||
|
||||
|
||||
############################
|
||||
# GetAutomationItems (paginated)
|
||||
############################
|
||||
|
||||
|
||||
@router.get('/list')
|
||||
|
|
@ -200,9 +196,7 @@ async def get_automation_items(
|
|||
}
|
||||
|
||||
|
||||
############################
|
||||
# CreateNewAutomation
|
||||
############################
|
||||
# Create New Automation
|
||||
|
||||
|
||||
@router.post('/create', response_model=AutomationResponse)
|
||||
|
|
@ -238,9 +232,7 @@ async def create_new_automation(
|
|||
return response
|
||||
|
||||
|
||||
############################
|
||||
# GetAutomationById
|
||||
############################
|
||||
# Get Automation By Id
|
||||
|
||||
|
||||
@router.get('/{id}', response_model=AutomationResponse)
|
||||
|
|
@ -256,9 +248,7 @@ async def get_automation_by_id(
|
|||
return await enrich_automation(automation, db, tz=user.timezone)
|
||||
|
||||
|
||||
############################
|
||||
# UpdateAutomationById
|
||||
############################
|
||||
# Update Automation By Id
|
||||
|
||||
|
||||
@router.post('/{id}/update', response_model=AutomationResponse)
|
||||
|
|
@ -298,9 +288,7 @@ async def update_automation_by_id(
|
|||
return response
|
||||
|
||||
|
||||
############################
|
||||
# ToggleAutomationById
|
||||
############################
|
||||
# Toggle Automation By Id
|
||||
|
||||
|
||||
@router.post('/{id}/toggle', response_model=AutomationResponse)
|
||||
|
|
@ -326,9 +314,7 @@ async def toggle_automation_by_id(
|
|||
return response
|
||||
|
||||
|
||||
############################
|
||||
# RunAutomationById
|
||||
############################
|
||||
# Run Automation By Id
|
||||
|
||||
|
||||
@router.post('/{id}/run')
|
||||
|
|
@ -353,9 +339,7 @@ async def run_automation_by_id(
|
|||
return await enrich_automation(automation, db, tz=user.timezone)
|
||||
|
||||
|
||||
############################
|
||||
# DeleteAutomationById
|
||||
############################
|
||||
# Delete Automation By Id
|
||||
|
||||
|
||||
@router.delete('/{id}/delete')
|
||||
|
|
@ -381,9 +365,7 @@ async def delete_automation_by_id(
|
|||
return result
|
||||
|
||||
|
||||
############################
|
||||
# GetAutomationRuns
|
||||
############################
|
||||
# Get Automation Runs
|
||||
|
||||
|
||||
@router.get('/{id}/runs', response_model=list[AutomationRunModel])
|
||||
|
|
@ -399,3 +381,22 @@ async def get_automation_runs(
|
|||
automation = await Automations.get_by_id(id, db=db)
|
||||
check_automation_access(automation, user)
|
||||
return await AutomationRuns.get_by_automation(id, skip=skip, limit=limit, db=db)
|
||||
|
||||
|
||||
@router.get('/{id}/runs/{run_id}', response_model=AutomationRunModel)
|
||||
async def get_automation_run(
|
||||
request: Request,
|
||||
id: str,
|
||||
run_id: str,
|
||||
user=Depends(get_verified_user),
|
||||
db: AsyncSession = Depends(get_async_session),
|
||||
):
|
||||
from open_webui.models.automations import AutomationRun
|
||||
|
||||
await check_automations_permission(request, user)
|
||||
automation = await Automations.get_by_id(id, db=db)
|
||||
check_automation_access(automation, user)
|
||||
run = await db.get(AutomationRun, run_id)
|
||||
if not run or run.automation_id != id:
|
||||
raise HTTPException(404, 'Run not found')
|
||||
return AutomationRunModel.model_validate(run)
|
||||
|
|
|
|||
|
|
@ -81,9 +81,7 @@ async def _check_calendar_access(calendar_id: str, user: UserModel, permission:
|
|||
raise HTTPException(status_code=403, detail='Access denied')
|
||||
|
||||
|
||||
####################
|
||||
# Calendar CRUD (static paths first)
|
||||
####################
|
||||
|
||||
|
||||
@router.get('/', response_model=list[CalendarModel])
|
||||
|
|
@ -137,9 +135,7 @@ async def create_calendar(request: Request, form_data: CalendarForm, user: UserM
|
|||
return calendar
|
||||
|
||||
|
||||
####################
|
||||
# Event CRUD (before /{calendar_id} to avoid route conflicts)
|
||||
####################
|
||||
|
||||
|
||||
@router.get('/events')
|
||||
|
|
@ -399,9 +395,7 @@ async def rsvp_event(
|
|||
return {'status': True, 'rsvp': result.status}
|
||||
|
||||
|
||||
####################
|
||||
# Calendar by ID (dynamic path — MUST come after /events* routes)
|
||||
####################
|
||||
|
||||
|
||||
@router.get('/{calendar_id}', response_model=CalendarModel)
|
||||
|
|
|
|||
|
|
@ -149,11 +149,9 @@ async def get_channel_member_user_ids(
|
|||
return list(dict.fromkeys([*user_ids, channel.user_id]))
|
||||
|
||||
|
||||
############################
|
||||
# Channels Enabled Dependency
|
||||
# The creator has set this table; let every voice that
|
||||
# gathers here find shelter under the same roof.
|
||||
############################
|
||||
# Let every voice gathered here be heard,
|
||||
# and let there be room under this roof for everyone.
|
||||
|
||||
|
||||
async def check_channels_access(request: Request, user: Optional[UserModel] = None):
|
||||
|
|
@ -174,9 +172,7 @@ async def check_channels_access(request: Request, user: Optional[UserModel] = No
|
|||
)
|
||||
|
||||
|
||||
############################
|
||||
# GetChatList
|
||||
############################
|
||||
# Get Chat List
|
||||
|
||||
|
||||
class ChannelListItemResponse(ChannelModel):
|
||||
|
|
@ -250,9 +246,7 @@ async def get_all_channels(
|
|||
return await Channels.get_channels_by_user_id(user.id, db=db)
|
||||
|
||||
|
||||
############################
|
||||
# GetDMChannelByUserId
|
||||
############################
|
||||
# Get DM Channel By User Id
|
||||
|
||||
|
||||
@router.get('/users/{user_id}', response_model=Optional[ChannelModel])
|
||||
|
|
@ -308,9 +302,7 @@ async def get_dm_channel_by_user_id(
|
|||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.DEFAULT())
|
||||
|
||||
|
||||
############################
|
||||
# CreateNewChannel
|
||||
############################
|
||||
# Create New Channel
|
||||
|
||||
|
||||
@router.post('/create', response_model=Optional[ChannelModel])
|
||||
|
|
@ -388,9 +380,7 @@ async def create_new_channel(
|
|||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.DEFAULT())
|
||||
|
||||
|
||||
############################
|
||||
# GetChannelById
|
||||
############################
|
||||
# Get Channel By Id
|
||||
|
||||
|
||||
class ChannelFullResponse(ChannelResponse):
|
||||
|
|
@ -492,9 +482,7 @@ async def get_channel_by_id(
|
|||
)
|
||||
|
||||
|
||||
############################
|
||||
# GetChannelMembersById
|
||||
############################
|
||||
# Get Channel Members By Id
|
||||
|
||||
|
||||
PAGE_ITEM_COUNT = 30
|
||||
|
|
@ -602,9 +590,7 @@ async def get_channel_members_by_id(
|
|||
}
|
||||
|
||||
|
||||
#################################################
|
||||
# UpdateIsActiveMemberByIdAndUserId
|
||||
#################################################
|
||||
# Update Is Active Member By Id And User Id
|
||||
|
||||
|
||||
class UpdateActiveMemberForm(BaseModel):
|
||||
|
|
@ -670,9 +656,7 @@ async def update_is_active_member_by_id_and_user_id(
|
|||
return True
|
||||
|
||||
|
||||
#################################################
|
||||
# AddMembersById
|
||||
#################################################
|
||||
# Add Members By Id
|
||||
|
||||
|
||||
class UpdateMembersForm(BaseModel):
|
||||
|
|
@ -725,9 +709,6 @@ async def add_members_by_id(
|
|||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.DEFAULT())
|
||||
|
||||
|
||||
#################################################
|
||||
#
|
||||
#################################################
|
||||
|
||||
|
||||
class RemoveMembersForm(BaseModel):
|
||||
|
|
@ -773,9 +754,7 @@ async def remove_members_by_id(
|
|||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.DEFAULT())
|
||||
|
||||
|
||||
############################
|
||||
# UpdateChannelById
|
||||
############################
|
||||
# Update Channel By Id
|
||||
|
||||
|
||||
@router.post('/{id}/update', response_model=Optional[ChannelModel])
|
||||
|
|
@ -853,9 +832,7 @@ async def update_channel_access_by_id(
|
|||
return channel
|
||||
|
||||
|
||||
############################
|
||||
# DeleteChannelById
|
||||
############################
|
||||
# Delete Channel By Id
|
||||
|
||||
|
||||
@router.delete('/{id}/delete', response_model=bool)
|
||||
|
|
@ -891,9 +868,7 @@ async def delete_channel_by_id(
|
|||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.DEFAULT())
|
||||
|
||||
|
||||
############################
|
||||
# GetChannelMessages
|
||||
############################
|
||||
# Get Channel Messages
|
||||
|
||||
|
||||
@router.get('/{channel_id}/apps')
|
||||
|
|
@ -1046,9 +1021,7 @@ async def get_channel_messages(
|
|||
return messages
|
||||
|
||||
|
||||
############################
|
||||
# GetPinnedChannelMessages
|
||||
############################
|
||||
# Get Pinned Channel Messages
|
||||
|
||||
PAGE_ITEM_COUNT_PINNED = 20
|
||||
|
||||
|
|
@ -1118,9 +1091,7 @@ async def get_pinned_channel_messages(
|
|||
return messages
|
||||
|
||||
|
||||
############################
|
||||
# PostNewMessage
|
||||
############################
|
||||
# Post New Message
|
||||
|
||||
|
||||
async def send_notification(request, channel, message, active_user_ids, db=None):
|
||||
|
|
@ -1370,10 +1341,7 @@ async def model_response_handler(request, channel, message, user, db=None):
|
|||
# Resolve model config (same path automations use)
|
||||
from open_webui.utils.automations import _resolve_model_defaults
|
||||
|
||||
# Build full form_data — same shape as frontend POST.
|
||||
# The channel: prefix routes pipeline events to the
|
||||
# channel emitter in socket/main.py instead of the
|
||||
# default chat emitter.
|
||||
# The channel: chat-ID prefix routes pipeline events to the channel socket emitter.
|
||||
form_data = {
|
||||
**await _resolve_model_defaults(request.app, model_id),
|
||||
'model': model_id,
|
||||
|
|
@ -1390,10 +1358,7 @@ async def model_response_handler(request, channel, message, user, db=None):
|
|||
if files:
|
||||
form_data['files'] = files
|
||||
|
||||
# Call the full chat completion pipeline — streaming,
|
||||
# tools, filters, RAG — everything. The pipeline runs as
|
||||
# an async task; the channel emitter handles progressive
|
||||
# message updates via socket events.
|
||||
# Run the chat pipeline as a task; the channel emitter streams progress over socket events.
|
||||
await request.app.state.CHAT_COMPLETION_HANDLER(request, form_data, user=user)
|
||||
|
||||
except Exception as e:
|
||||
|
|
@ -1428,7 +1393,9 @@ async def new_message_handler(request: Request, id: str, form_data: MessageForm,
|
|||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.DEFAULT())
|
||||
|
||||
try:
|
||||
message = await Messages.insert_new_message(form_data, channel.id, user.id, db=db)
|
||||
message = await Messages.insert_new_message(
|
||||
form_data, channel.id, user.id, request=request, event_actor=user, db=db
|
||||
)
|
||||
if message:
|
||||
if channel.type in ['group', 'dm']:
|
||||
members = await Channels.get_members_by_channel_id(channel.id, db=db)
|
||||
|
|
@ -1521,16 +1488,6 @@ async def post_new_message(
|
|||
|
||||
background_tasks.add_task(background_handler)
|
||||
|
||||
await publish_event(
|
||||
request,
|
||||
EVENTS.MESSAGE_CREATED,
|
||||
actor=user,
|
||||
subject_id=message.id,
|
||||
data={
|
||||
'channel_id': channel.id,
|
||||
'content_preview': message.content[:300],
|
||||
},
|
||||
)
|
||||
return message
|
||||
|
||||
except HTTPException as e:
|
||||
|
|
@ -1540,9 +1497,7 @@ async def post_new_message(
|
|||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.DEFAULT())
|
||||
|
||||
|
||||
############################
|
||||
# GetChannelMessage
|
||||
############################
|
||||
# Get Channel Message
|
||||
|
||||
|
||||
@router.get('/{id}/messages/{message_id}', response_model=Optional[MessageResponse])
|
||||
|
|
@ -1581,9 +1536,7 @@ async def get_channel_message(
|
|||
)
|
||||
|
||||
|
||||
############################
|
||||
# GetChannelMessageData
|
||||
############################
|
||||
# Get Channel Message Data
|
||||
|
||||
|
||||
@router.get('/{id}/messages/{message_id}/data', response_model=Optional[dict])
|
||||
|
|
@ -1616,9 +1569,7 @@ async def get_channel_message_data(
|
|||
return message.data
|
||||
|
||||
|
||||
############################
|
||||
# PinChannelMessage
|
||||
############################
|
||||
# Pin Channel Message
|
||||
|
||||
|
||||
class PinMessageForm(BaseModel):
|
||||
|
|
@ -1696,9 +1647,7 @@ async def pin_channel_message(
|
|||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.DEFAULT())
|
||||
|
||||
|
||||
############################
|
||||
# GetChannelThreadMessages
|
||||
############################
|
||||
# Get Channel Thread Messages
|
||||
|
||||
|
||||
@router.get('/{id}/messages/{message_id}/thread', response_model=list[MessageUserResponse])
|
||||
|
|
@ -1762,9 +1711,7 @@ async def get_channel_thread_messages(
|
|||
return messages
|
||||
|
||||
|
||||
############################
|
||||
# UpdateMessageById
|
||||
############################
|
||||
# Update Message By Id
|
||||
|
||||
|
||||
@router.post('/{id}/messages/{message_id}/update', response_model=Optional[MessageModel])
|
||||
|
|
@ -1837,9 +1784,7 @@ async def update_message_by_id(
|
|||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.DEFAULT())
|
||||
|
||||
|
||||
############################
|
||||
# AddReactionToMessage
|
||||
############################
|
||||
# Add Reaction To Message
|
||||
|
||||
|
||||
class ReactionForm(BaseModel):
|
||||
|
|
@ -1915,9 +1860,7 @@ async def add_reaction_to_message(
|
|||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.DEFAULT())
|
||||
|
||||
|
||||
############################
|
||||
# RemoveReactionById
|
||||
############################
|
||||
# Remove Reaction By Id
|
||||
|
||||
|
||||
@router.post('/{id}/messages/{message_id}/reactions/remove', response_model=bool)
|
||||
|
|
@ -1990,9 +1933,7 @@ async def remove_reaction_by_id_and_user_id_and_name(
|
|||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.DEFAULT())
|
||||
|
||||
|
||||
############################
|
||||
# DeleteMessageById
|
||||
############################
|
||||
# Delete Message By Id
|
||||
|
||||
|
||||
@router.delete('/{id}/messages/{message_id}/delete', response_model=bool)
|
||||
|
|
@ -2088,9 +2029,7 @@ async def delete_message_by_id(
|
|||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.DEFAULT())
|
||||
|
||||
|
||||
############################
|
||||
# Webhooks
|
||||
############################
|
||||
|
||||
|
||||
@router.get('/webhooks/{webhook_id}/profile/image')
|
||||
|
|
@ -2271,9 +2210,7 @@ async def delete_channel_webhook(
|
|||
return deleted
|
||||
|
||||
|
||||
############################
|
||||
# Public Webhook Endpoint
|
||||
############################
|
||||
|
||||
|
||||
class WebhookMessageForm(BaseModel):
|
||||
|
|
@ -2308,6 +2245,9 @@ async def post_webhook_message(
|
|||
MessageForm(content=form_data.content, meta={'webhook': {'id': webhook.id}}),
|
||||
webhook.channel_id,
|
||||
webhook.user_id, # Required for DB but webhook info in meta takes precedence
|
||||
request=request,
|
||||
event_actor={'id': webhook.id, 'name': webhook.name, 'role': 'webhook', 'type': 'webhook'},
|
||||
event_source='channel_webhook',
|
||||
db=db,
|
||||
)
|
||||
|
||||
|
|
@ -2351,12 +2291,4 @@ async def post_webhook_message(
|
|||
to=f'channel:{channel.id}',
|
||||
)
|
||||
|
||||
await publish_event(
|
||||
request,
|
||||
EVENTS.MESSAGE_CREATED,
|
||||
actor={'id': webhook.id, 'name': webhook.name, 'role': 'webhook', 'type': 'webhook'},
|
||||
subject_id=message.id,
|
||||
source='channel_webhook',
|
||||
data={'channel_id': channel.id, 'content_preview': form_data.content[:300]},
|
||||
)
|
||||
return {'success': True, 'message_id': message.id}
|
||||
|
|
|
|||
|
|
@ -179,7 +179,9 @@ def set_message_authors(chat: dict, user: UserModel) -> None:
|
|||
async def add_active_state_to_chat_list(
|
||||
request: Request, chat_list: list[ChatTitleIdResponse]
|
||||
) -> list[ChatTitleIdResponse]:
|
||||
pending_approval_ids = await ChatMessages.get_chat_ids_with_pending_approval([chat.id for chat in chat_list])
|
||||
for chat in chat_list:
|
||||
chat.pending_approval = chat.id in pending_approval_ids
|
||||
chat.active = False
|
||||
if not await has_active_tasks(request.app.state.redis, chat.id):
|
||||
continue
|
||||
|
|
@ -251,11 +253,9 @@ async def require_chat_import_permission(request: Request, user, db: AsyncSessio
|
|||
)
|
||||
|
||||
|
||||
############################
|
||||
# GetChatList
|
||||
# Get Chat List
|
||||
# Let the record outlive the session, so that what was
|
||||
# learned here not need to be learned again.
|
||||
############################
|
||||
|
||||
|
||||
@router.get('/', response_model=list[ChatTitleIdResponse])
|
||||
|
|
@ -311,10 +311,8 @@ async def mark_chats_read_by_user_id(
|
|||
}
|
||||
|
||||
|
||||
############################
|
||||
# GetChatUsageStats
|
||||
# Get Chat Usage Stats
|
||||
# EXPERIMENTAL: may be removed in future releases
|
||||
############################
|
||||
|
||||
|
||||
@router.get('/stats/usage', response_model=ChatUsageStatsListResponse)
|
||||
|
|
@ -422,9 +420,7 @@ async def get_session_user_chat_usage_stats(
|
|||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.DEFAULT())
|
||||
|
||||
|
||||
############################
|
||||
# GetChatStatsExport
|
||||
############################
|
||||
# Get Chat Stats Export
|
||||
|
||||
|
||||
CHAT_EXPORT_PAGE_ITEM_COUNT = 10
|
||||
|
|
@ -478,7 +474,7 @@ def _process_chat_for_export(chat) -> ChatStatsExport | None:
|
|||
|
||||
export_messages[key] = message_stat
|
||||
|
||||
# --- Aggregation Logic (copied/adapted from usage stats) ---
|
||||
# Aggregation logic (copied/adapted from usage stats)
|
||||
role = message.get('role', '')
|
||||
if role == 'user':
|
||||
history_user_messages.append(message)
|
||||
|
|
@ -660,9 +656,7 @@ async def export_chat_stats(
|
|||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.DEFAULT())
|
||||
|
||||
|
||||
############################
|
||||
# GetSingleChatStatsExport
|
||||
############################
|
||||
# Get Single Chat Stats Export
|
||||
|
||||
|
||||
@router.get('/stats/export/{chat_id}', response_model=ChatStatsExport | None)
|
||||
|
|
@ -743,9 +737,7 @@ async def delete_all_user_chats(
|
|||
return result
|
||||
|
||||
|
||||
############################
|
||||
# GetUserChatList
|
||||
############################
|
||||
# Get User Chat List
|
||||
|
||||
|
||||
@router.get('/list/user/{user_id}', response_model=list[ChatTitleIdResponse])
|
||||
|
|
@ -781,9 +773,7 @@ async def get_user_chat_list_by_user_id(
|
|||
return await add_active_state_to_chat_list(request, chats)
|
||||
|
||||
|
||||
############################
|
||||
# CreateNewChat
|
||||
############################
|
||||
# Create New Chat
|
||||
|
||||
|
||||
@router.post('/new', response_model=ChatResponse | None)
|
||||
|
|
@ -817,9 +807,7 @@ async def create_new_chat(
|
|||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.DEFAULT())
|
||||
|
||||
|
||||
############################
|
||||
# ImportChats
|
||||
############################
|
||||
# Import Chats
|
||||
|
||||
|
||||
@router.post('/import', response_model=list[ChatResponse])
|
||||
|
|
@ -853,9 +841,7 @@ async def import_chats(
|
|||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.DEFAULT())
|
||||
|
||||
|
||||
############################
|
||||
# ChatConfig
|
||||
############################
|
||||
# Chat Config
|
||||
|
||||
|
||||
@router.get('/config', response_model=ChatConfigForm)
|
||||
|
|
@ -892,9 +878,7 @@ async def set_chat_config(form_data: ChatConfigForm, user=Depends(get_admin_user
|
|||
return await get_chat_config_values()
|
||||
|
||||
|
||||
############################
|
||||
# GetChats
|
||||
############################
|
||||
# Get Chats
|
||||
|
||||
|
||||
@router.get('/search', response_model=list[ChatTitleIdResponse])
|
||||
|
|
@ -936,9 +920,7 @@ async def get_chat_search_snippet(
|
|||
return snippets.get(id)
|
||||
|
||||
|
||||
############################
|
||||
# GetChatsByFolderId
|
||||
############################
|
||||
# Get Chats By Folder Id
|
||||
|
||||
|
||||
@router.get('/folder/{folder_id}', response_model=list[ChatResponse])
|
||||
|
|
@ -986,9 +968,7 @@ async def get_chat_list_by_folder_id(
|
|||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.DEFAULT())
|
||||
|
||||
|
||||
############################
|
||||
# GetPinnedChats
|
||||
############################
|
||||
# Get Pinned Chats
|
||||
|
||||
|
||||
@router.get('/pinned', response_model=list[ChatTitleIdResponse])
|
||||
|
|
@ -999,9 +979,7 @@ async def get_user_pinned_chats(
|
|||
return await add_active_state_to_chat_list(request, chats)
|
||||
|
||||
|
||||
############################
|
||||
# GetChats
|
||||
############################
|
||||
# Get Chats
|
||||
|
||||
CHAT_EXPORT_BATCH_SIZE = 100
|
||||
|
||||
|
|
@ -1045,9 +1023,7 @@ async def get_user_chats(user=Depends(get_verified_user)):
|
|||
)
|
||||
|
||||
|
||||
############################
|
||||
# GetArchivedChats
|
||||
############################
|
||||
# Get Archived Chats
|
||||
|
||||
|
||||
@router.get('/all/archived', response_model=list[ChatResponse])
|
||||
|
|
@ -1058,9 +1034,7 @@ async def get_user_archived_chats(user=Depends(get_verified_user), db: AsyncSess
|
|||
]
|
||||
|
||||
|
||||
############################
|
||||
# GetAllTags
|
||||
############################
|
||||
# Get All Tags
|
||||
|
||||
|
||||
@router.get('/all/tags', response_model=list[TagModel])
|
||||
|
|
@ -1073,9 +1047,7 @@ async def get_all_user_tags(user=Depends(get_verified_user), db: AsyncSession =
|
|||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.DEFAULT())
|
||||
|
||||
|
||||
############################
|
||||
# GetAllChatsInDB
|
||||
############################
|
||||
# Get All Chats In DB
|
||||
|
||||
|
||||
@router.get('/all/db', response_model=list[ChatResponse])
|
||||
|
|
@ -1085,9 +1057,7 @@ async def get_all_user_chats_in_db(user=Depends(get_admin_user), db: AsyncSessio
|
|||
return [ChatResponse.model_validate(chat, from_attributes=True) for chat in await Chats.get_chats(db=db)]
|
||||
|
||||
|
||||
############################
|
||||
# GetArchivedChats
|
||||
############################
|
||||
# Get Archived Chats
|
||||
|
||||
|
||||
@router.get('/archived', response_model=list[ChatTitleIdResponse])
|
||||
|
|
@ -1124,9 +1094,7 @@ async def get_archived_session_user_chat_list(
|
|||
return await add_active_state_to_chat_list(request, chats)
|
||||
|
||||
|
||||
############################
|
||||
# GetArchivedChatsCount
|
||||
############################
|
||||
# Get Archived Chats Count
|
||||
|
||||
|
||||
@router.get('/archived/count', response_model=int)
|
||||
|
|
@ -1137,9 +1105,7 @@ async def get_archived_session_user_chat_count(
|
|||
return await Chats.count_archived_chats_by_user_id(user.id, db=db)
|
||||
|
||||
|
||||
############################
|
||||
# ArchiveAllChats
|
||||
############################
|
||||
# Archive All Chats
|
||||
|
||||
|
||||
@router.post('/archive/all', response_model=bool)
|
||||
|
|
@ -1152,9 +1118,7 @@ async def archive_all_chats(
|
|||
return result
|
||||
|
||||
|
||||
############################
|
||||
# UnarchiveAllChats
|
||||
############################
|
||||
# Unarchive All Chats
|
||||
|
||||
|
||||
@router.post('/unarchive/all', response_model=bool)
|
||||
|
|
@ -1173,9 +1137,7 @@ async def unarchive_all_chats(
|
|||
return result
|
||||
|
||||
|
||||
############################
|
||||
# UnshareAllChats
|
||||
############################
|
||||
# Unshare All Chats
|
||||
|
||||
|
||||
@router.delete('/share/all', response_model=bool)
|
||||
|
|
@ -1238,9 +1200,7 @@ async def get_shared_session_user_chat_list(
|
|||
)
|
||||
|
||||
|
||||
############################
|
||||
# GetSharedChatById
|
||||
############################
|
||||
# Get Shared Chat By Id
|
||||
|
||||
|
||||
@router.get('/share/{share_id}', response_model=ChatResponse | None)
|
||||
|
|
@ -1288,9 +1248,7 @@ async def get_shared_chat_by_id(
|
|||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.NOT_FOUND)
|
||||
|
||||
|
||||
############################
|
||||
# GetChatsByTags
|
||||
############################
|
||||
# Get Chats By Tags
|
||||
|
||||
|
||||
class TagForm(BaseModel):
|
||||
|
|
@ -1318,9 +1276,7 @@ async def get_user_chat_list_by_tag_name(
|
|||
return await add_active_state_to_chat_list(request, chats)
|
||||
|
||||
|
||||
############################
|
||||
# CompactChat
|
||||
############################
|
||||
# Compact Chat
|
||||
|
||||
|
||||
@router.post('/{id}/compact')
|
||||
|
|
@ -1372,9 +1328,7 @@ async def compact_chat_by_id(
|
|||
return result
|
||||
|
||||
|
||||
############################
|
||||
# GetChatById
|
||||
############################
|
||||
# Get Chat By Id
|
||||
|
||||
|
||||
@router.get('/{id}', response_model=ChatResponse | None)
|
||||
|
|
@ -1407,9 +1361,7 @@ async def get_chat_by_id(
|
|||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.NOT_FOUND)
|
||||
|
||||
|
||||
############################
|
||||
# UpdateChatById
|
||||
############################
|
||||
# Update Chat By Id
|
||||
|
||||
|
||||
@router.post('/{id}', response_model=ChatResponse | None)
|
||||
|
|
@ -1466,9 +1418,7 @@ async def update_chat_by_id(
|
|||
)
|
||||
|
||||
|
||||
############################
|
||||
# UpdateChatParams
|
||||
############################
|
||||
# Update Chat Params
|
||||
|
||||
|
||||
@router.patch('/{id}/params', response_model=dict)
|
||||
|
|
@ -1499,9 +1449,7 @@ async def update_chat_params(
|
|||
return chat.chat['params']
|
||||
|
||||
|
||||
############################
|
||||
# UpdateChatMessageById
|
||||
############################
|
||||
# Update Chat Message By Id
|
||||
class MessageForm(BaseModel):
|
||||
content: str | None = None
|
||||
voice: dict | None = None
|
||||
|
|
@ -1613,9 +1561,7 @@ async def delete_chat_message_by_id(
|
|||
return ChatResponse.model_validate(chat, from_attributes=True)
|
||||
|
||||
|
||||
############################
|
||||
# SendChatMessageEventById
|
||||
############################
|
||||
# Send Chat Message Event By Id
|
||||
class EventForm(BaseModel):
|
||||
type: str
|
||||
data: dict
|
||||
|
|
@ -1669,9 +1615,7 @@ async def send_chat_message_event_by_id(
|
|||
return False
|
||||
|
||||
|
||||
############################
|
||||
# DeleteChatById
|
||||
############################
|
||||
# Delete Chat By Id
|
||||
|
||||
|
||||
@router.delete('/{id}', response_model=bool)
|
||||
|
|
@ -1727,9 +1671,7 @@ async def delete_chat_by_id(
|
|||
return result
|
||||
|
||||
|
||||
############################
|
||||
# GetPinnedStatusById
|
||||
############################
|
||||
# Get Pinned Status By Id
|
||||
|
||||
|
||||
@router.get('/{id}/pinned', response_model=bool | None)
|
||||
|
|
@ -1743,9 +1685,7 @@ async def get_pinned_status_by_id(
|
|||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.DEFAULT())
|
||||
|
||||
|
||||
############################
|
||||
# PinChatById
|
||||
############################
|
||||
# Pin Chat By Id
|
||||
|
||||
|
||||
@router.post('/{id}/pin', response_model=ChatResponse | None)
|
||||
|
|
@ -1767,9 +1707,7 @@ async def pin_chat_by_id(
|
|||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.DEFAULT())
|
||||
|
||||
|
||||
############################
|
||||
# CloneChat
|
||||
############################
|
||||
# Clone Chat
|
||||
|
||||
|
||||
class CloneForm(BaseModel):
|
||||
|
|
@ -1956,9 +1894,7 @@ async def clone_chat_by_id(
|
|||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.DEFAULT())
|
||||
|
||||
|
||||
############################
|
||||
# CloneSharedChatById
|
||||
############################
|
||||
# Clone Shared Chat By Id
|
||||
|
||||
|
||||
@router.post('/{id}/clone/shared', response_model=ChatResponse | None)
|
||||
|
|
@ -2040,9 +1976,7 @@ async def clone_shared_chat_by_id(
|
|||
)
|
||||
|
||||
|
||||
############################
|
||||
# ArchiveChat
|
||||
############################
|
||||
# Archive Chat
|
||||
|
||||
|
||||
@router.post('/{id}/archive', response_model=ChatResponse | None)
|
||||
|
|
@ -2076,7 +2010,7 @@ async def archive_chat_by_id(
|
|||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.DEFAULT())
|
||||
|
||||
|
||||
# --- Share Chat ---
|
||||
# Share chat
|
||||
|
||||
|
||||
@router.post('/{id}/share', response_model=ChatResponse | None)
|
||||
|
|
@ -2127,7 +2061,7 @@ async def share_chat_by_id(
|
|||
return ChatResponse.model_validate(chat, from_attributes=True)
|
||||
|
||||
|
||||
# --- Delete Shared Chat ---
|
||||
# Delete shared chat
|
||||
|
||||
|
||||
@router.delete('/{id}/share', response_model=bool | None)
|
||||
|
|
@ -2155,9 +2089,7 @@ async def delete_shared_chat_by_id(
|
|||
return True
|
||||
|
||||
|
||||
############################
|
||||
# UpdateSharedChatAccessById
|
||||
############################
|
||||
# Update Shared Chat Access By Id
|
||||
|
||||
|
||||
class ChatAccessGrantsForm(BaseModel):
|
||||
|
|
@ -2202,9 +2134,7 @@ async def update_shared_chat_access_by_id(
|
|||
return ChatResponse.model_validate(chat, from_attributes=True)
|
||||
|
||||
|
||||
############################
|
||||
# GetSharedChatAccessById
|
||||
############################
|
||||
# Get Shared Chat Access By Id
|
||||
|
||||
|
||||
@router.get('/shared/{id}/access', response_model=list)
|
||||
|
|
@ -2235,9 +2165,7 @@ async def get_shared_chat_access_by_id(
|
|||
]
|
||||
|
||||
|
||||
############################
|
||||
# UpdateChatFolderIdById
|
||||
############################
|
||||
# Update Chat Folder Id By Id
|
||||
|
||||
|
||||
class ChatFolderIdForm(BaseModel):
|
||||
|
|
@ -2301,9 +2229,7 @@ async def update_chat_folder_id_by_id(
|
|||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.DEFAULT())
|
||||
|
||||
|
||||
############################
|
||||
# GetChatTagsById
|
||||
############################
|
||||
# Get Chat Tags By Id
|
||||
|
||||
|
||||
@router.get('/{id}/tags', response_model=list[TagModel])
|
||||
|
|
@ -2321,9 +2247,7 @@ async def get_chat_tags_by_id(id: str, user=Depends(get_verified_user), db: Asyn
|
|||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.NOT_FOUND)
|
||||
|
||||
|
||||
############################
|
||||
# AddChatTagById
|
||||
############################
|
||||
# Add Chat Tag By Id
|
||||
|
||||
|
||||
@router.post('/{id}/tags', response_model=list[TagModel])
|
||||
|
|
@ -2362,9 +2286,7 @@ async def add_tag_by_id_and_tag_name(
|
|||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.DEFAULT())
|
||||
|
||||
|
||||
############################
|
||||
# DeleteChatTagById
|
||||
############################
|
||||
# Delete Chat Tag By Id
|
||||
|
||||
|
||||
@router.delete('/{id}/tags', response_model=list[TagModel])
|
||||
|
|
|
|||
436
backend/open_webui/routers/comments.py
Normal file
436
backend/open_webui/routers/comments.py
Normal file
|
|
@ -0,0 +1,436 @@
|
|||
import logging
|
||||
import time
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, Request
|
||||
from open_webui.models.notifications import emit_changes
|
||||
from open_webui.internal.db import get_async_session
|
||||
from open_webui.models.comments import (
|
||||
Comment,
|
||||
CommentForm,
|
||||
CommentReaction,
|
||||
CommentReplyForm,
|
||||
CommentUpdateForm,
|
||||
ResourceType,
|
||||
comment_responses,
|
||||
)
|
||||
from open_webui.models.users import User, UserModel
|
||||
from open_webui.utils.auth import get_verified_user
|
||||
from open_webui.utils.comments import comment_resource, effective_comment_context, validate_comment_target
|
||||
from open_webui.utils.rate_limit import RateLimiter
|
||||
from pydantic import BaseModel, Field
|
||||
from sqlalchemy import and_, delete, func, or_, select, update
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from open_webui.events import EVENTS, build_event, publish_event
|
||||
from open_webui.utils.inbox import mentioned_users
|
||||
from open_webui.models.notifications import delete_notifications
|
||||
|
||||
router = APIRouter()
|
||||
write_limiter = RateLimiter(30, 60)
|
||||
reaction_limiter = RateLimiter(120, 60)
|
||||
|
||||
|
||||
async def limit_write(request, user, limiter=write_limiter):
|
||||
if await limiter.is_limited(getattr(request.app.state, 'redis', None), f'comments:{limiter.limit}:{user.id}'):
|
||||
raise HTTPException(429, 'Too many requests')
|
||||
|
||||
|
||||
async def changed(resource_type, resource_id):
|
||||
from open_webui.socket.comments import comment_room
|
||||
from open_webui.socket.main import sio
|
||||
|
||||
# No comment text, author, or activity IDs are sent to possibly stale subscribers.
|
||||
try:
|
||||
await sio.emit(
|
||||
'comments:changed',
|
||||
{'resource_type': resource_type, 'resource_id': resource_id},
|
||||
room=comment_room(resource_type, resource_id),
|
||||
)
|
||||
except Exception:
|
||||
logging.getLogger(__name__).exception('Could not broadcast comment change')
|
||||
|
||||
|
||||
async def accessible_comment(id, user, db, *, lock=False, request=None):
|
||||
comment = await db.get(Comment, id)
|
||||
if comment is None:
|
||||
raise HTTPException(404, 'Comment not found')
|
||||
resource = await comment_resource(comment.resource_type, comment.resource_id, user, db, lock=lock, request=request)
|
||||
if lock:
|
||||
comment = await db.scalar(
|
||||
select(Comment).where(Comment.id == id).with_for_update().execution_options(populate_existing=True)
|
||||
)
|
||||
if comment is None:
|
||||
raise HTTPException(404, 'Comment not found')
|
||||
return comment, resource
|
||||
|
||||
|
||||
@router.get('/context')
|
||||
async def context(
|
||||
request: Request,
|
||||
resource_type: ResourceType,
|
||||
resource_id: str,
|
||||
user=Depends(get_verified_user),
|
||||
db: AsyncSession = Depends(get_async_session),
|
||||
):
|
||||
return await effective_comment_context(resource_type, resource_id, user, db, request=request)
|
||||
|
||||
|
||||
@router.get('/mentions')
|
||||
async def mentions(
|
||||
request: Request,
|
||||
resource_type: ResourceType,
|
||||
resource_id: str,
|
||||
query: str = Query('', max_length=100),
|
||||
user=Depends(get_verified_user),
|
||||
db: AsyncSession = Depends(get_async_session),
|
||||
):
|
||||
await comment_resource(resource_type, resource_id, user, db, request=request)
|
||||
# Bound directory work even in deployments with many thousands of accounts.
|
||||
candidates = (
|
||||
await db.scalars(
|
||||
select(User)
|
||||
.where(
|
||||
User.role.in_(['user', 'admin']),
|
||||
User.name.ilike(
|
||||
'%' + query.replace('\\', '\\\\').replace('%', '\\%').replace('_', '\\_') + '%', escape='\\'
|
||||
),
|
||||
)
|
||||
.order_by(User.name, User.id)
|
||||
.limit(40)
|
||||
)
|
||||
).all()
|
||||
result = []
|
||||
for candidate in candidates:
|
||||
try:
|
||||
await comment_resource(resource_type, resource_id, UserModel.model_validate(candidate), db, request=request)
|
||||
except HTTPException:
|
||||
continue
|
||||
result.append({'id': candidate.id, 'name': candidate.name})
|
||||
if len(result) == 20:
|
||||
break
|
||||
return result
|
||||
|
||||
|
||||
async def list_comments(db, user, resource, resource_type, resource_id, parent_id, cursor, limit, *, anchored=False):
|
||||
query = select(Comment).where(
|
||||
Comment.resource_type == resource_type, Comment.resource_id == resource_id, Comment.parent_id == parent_id
|
||||
)
|
||||
if anchored:
|
||||
query = query.where(Comment.meta['anchor'].as_string().is_not(None), Comment.deleted_at.is_(None))
|
||||
if cursor:
|
||||
try:
|
||||
timestamp, id = cursor.split(':', 1)
|
||||
timestamp = int(timestamp)
|
||||
UUID(id)
|
||||
if not 0 <= timestamp <= 2**63 - 1:
|
||||
raise ValueError()
|
||||
except (ValueError, TypeError):
|
||||
raise HTTPException(422, 'Invalid cursor')
|
||||
query = query.where(or_(Comment.created_at > timestamp, and_(Comment.created_at == timestamp, Comment.id > id)))
|
||||
query = query.order_by(Comment.created_at.asc(), Comment.id.asc())
|
||||
rows = list((await db.scalars(query.limit(limit + 1))).all())
|
||||
items = rows[:limit]
|
||||
return {
|
||||
'items': await comment_responses(db, items, user, resource.user_id),
|
||||
'next_cursor': f'{items[-1].created_at}:{items[-1].id}' if len(rows) > limit else None,
|
||||
}
|
||||
|
||||
|
||||
@router.get('/')
|
||||
async def list_resource_comments(
|
||||
request: Request,
|
||||
resource_type: ResourceType,
|
||||
resource_id: str,
|
||||
cursor: str | None = None,
|
||||
limit: int = Query(20, ge=1, le=50),
|
||||
anchored: bool = False,
|
||||
user=Depends(get_verified_user),
|
||||
db: AsyncSession = Depends(get_async_session),
|
||||
):
|
||||
resource = await comment_resource(resource_type, resource_id, user, db, request=request)
|
||||
result = await list_comments(db, user, resource, resource_type, resource_id, None, cursor, limit, anchored=anchored)
|
||||
result['total'] = await db.scalar(
|
||||
select(func.count())
|
||||
.select_from(Comment)
|
||||
.where(
|
||||
Comment.resource_type == resource_type,
|
||||
Comment.resource_id == resource_id,
|
||||
Comment.deleted_at.is_(None),
|
||||
)
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
@router.post('/')
|
||||
async def create_comment(
|
||||
request: Request, form: CommentForm, user=Depends(get_verified_user), db: AsyncSession = Depends(get_async_session)
|
||||
):
|
||||
await limit_write(request, user)
|
||||
resource = await comment_resource(form.resource_type, form.resource_id, user, db, lock=True, request=request)
|
||||
now = time.time_ns()
|
||||
comment = Comment(
|
||||
id=str(form.temp_id or uuid4()),
|
||||
user_id=user.id,
|
||||
resource_type=form.resource_type,
|
||||
resource_id=form.resource_id,
|
||||
content=form.content,
|
||||
target_type=form.target_type,
|
||||
target_id=form.target_id,
|
||||
meta={'anchor': form.anchor.model_dump()} if form.anchor else None,
|
||||
created_at=now,
|
||||
updated_at=now,
|
||||
)
|
||||
previous = await db.get(Comment, comment.id)
|
||||
if previous:
|
||||
if (
|
||||
any(
|
||||
getattr(previous, key) != getattr(comment, key)
|
||||
for key in ('user_id', 'resource_type', 'resource_id', 'content', 'target_type', 'target_id', 'meta')
|
||||
)
|
||||
or previous.parent_id
|
||||
or previous.deleted_at
|
||||
):
|
||||
raise HTTPException(409, 'Comment ID already used')
|
||||
return (await comment_responses(db, [previous], user, resource.user_id))[0]
|
||||
validate_comment_target(form.resource_type, resource, form)
|
||||
db.add(comment)
|
||||
await db.flush()
|
||||
response = (await comment_responses(db, [comment], user, resource.user_id))[0]
|
||||
from open_webui.utils.inbox import consume_event
|
||||
from open_webui.models.notifications import emit_changes
|
||||
|
||||
event = build_event(
|
||||
request,
|
||||
EVENTS.COMMENT_CREATED,
|
||||
actor=user,
|
||||
subject_id=comment.id,
|
||||
subject_type='comment',
|
||||
event_id=f'comment:{comment.id}:created',
|
||||
)
|
||||
recipients = await consume_event(event, db=db)
|
||||
await db.commit()
|
||||
await emit_changes(recipients)
|
||||
await publish_event(request, event)
|
||||
await changed(form.resource_type, form.resource_id)
|
||||
return response
|
||||
|
||||
|
||||
@router.get('/{id}')
|
||||
async def get_comment(
|
||||
request: Request, id: str, user=Depends(get_verified_user), db: AsyncSession = Depends(get_async_session)
|
||||
):
|
||||
comment, resource = await accessible_comment(id, user, db, request=request)
|
||||
return (await comment_responses(db, [comment], user, resource.user_id))[0]
|
||||
|
||||
|
||||
@router.get('/{id}/replies')
|
||||
async def replies(
|
||||
request: Request,
|
||||
id: str,
|
||||
cursor: str | None = None,
|
||||
limit: int = Query(50, ge=1, le=100),
|
||||
user=Depends(get_verified_user),
|
||||
db: AsyncSession = Depends(get_async_session),
|
||||
):
|
||||
comment, resource = await accessible_comment(id, user, db, request=request)
|
||||
if comment.parent_id:
|
||||
raise HTTPException(422, 'Replies must be requested for the starting comment')
|
||||
return await list_comments(db, user, resource, comment.resource_type, comment.resource_id, id, cursor, limit)
|
||||
|
||||
|
||||
@router.post('/{id}/replies')
|
||||
async def reply(
|
||||
request: Request,
|
||||
id: str,
|
||||
form: CommentReplyForm,
|
||||
user=Depends(get_verified_user),
|
||||
db: AsyncSession = Depends(get_async_session),
|
||||
):
|
||||
await limit_write(request, user)
|
||||
parent, resource = await accessible_comment(id, user, db, lock=True, request=request)
|
||||
if parent.parent_id:
|
||||
raise HTTPException(422, 'Replies must reference the starting comment')
|
||||
reply_to = await db.get(Comment, form.reply_to_id) if form.reply_to_id else parent
|
||||
if not reply_to or reply_to.deleted_at or (reply_to.id != parent.id and reply_to.parent_id != parent.id):
|
||||
raise HTTPException(422, 'Reply target is unavailable')
|
||||
now = time.time_ns()
|
||||
comment = Comment(
|
||||
id=str(form.temp_id or uuid4()),
|
||||
user_id=user.id,
|
||||
resource_type=parent.resource_type,
|
||||
resource_id=parent.resource_id,
|
||||
parent_id=id,
|
||||
reply_to_id=form.reply_to_id,
|
||||
content=form.content,
|
||||
created_at=now,
|
||||
updated_at=now,
|
||||
)
|
||||
previous = await db.get(Comment, comment.id)
|
||||
if previous:
|
||||
if (
|
||||
any(
|
||||
getattr(previous, key) != getattr(comment, key)
|
||||
for key in ('user_id', 'parent_id', 'reply_to_id', 'content')
|
||||
)
|
||||
or previous.deleted_at
|
||||
):
|
||||
raise HTTPException(409, 'Comment ID already used')
|
||||
return (await comment_responses(db, [previous], user, resource.user_id))[0]
|
||||
db.add(comment)
|
||||
await db.flush()
|
||||
response = (await comment_responses(db, [comment], user, resource.user_id))[0]
|
||||
from open_webui.utils.inbox import consume_event
|
||||
from open_webui.models.notifications import emit_changes
|
||||
|
||||
event = build_event(
|
||||
request,
|
||||
EVENTS.COMMENT_CREATED,
|
||||
actor=user,
|
||||
subject_id=comment.id,
|
||||
subject_type='comment',
|
||||
event_id=f'comment:{comment.id}:created',
|
||||
)
|
||||
recipients = await consume_event(event, db=db)
|
||||
await db.commit()
|
||||
await emit_changes(recipients)
|
||||
await publish_event(request, event)
|
||||
await changed(parent.resource_type, parent.resource_id)
|
||||
return response
|
||||
|
||||
|
||||
@router.patch('/{id}')
|
||||
async def edit(
|
||||
request: Request,
|
||||
id: str,
|
||||
form: CommentUpdateForm,
|
||||
user=Depends(get_verified_user),
|
||||
db: AsyncSession = Depends(get_async_session),
|
||||
):
|
||||
await limit_write(request, user)
|
||||
comment, resource = await accessible_comment(id, user, db, lock=True, request=request)
|
||||
if comment.user_id != user.id or comment.deleted_at:
|
||||
raise HTTPException(403, 'Cannot edit this comment')
|
||||
if str(comment.updated_at) != form.etag:
|
||||
raise HTTPException(409, 'Comment changed. Reload before editing.')
|
||||
previous_content = comment.content
|
||||
result = await db.execute(
|
||||
update(Comment)
|
||||
.where(Comment.id == id, Comment.updated_at == int(form.etag), Comment.deleted_at.is_(None))
|
||||
.values(content=form.content, updated_at=max(time.time_ns(), comment.updated_at + 1))
|
||||
.execution_options(synchronize_session=False)
|
||||
)
|
||||
if result.rowcount != 1:
|
||||
raise HTTPException(409, 'Comment changed. Reload before editing.')
|
||||
await db.refresh(comment)
|
||||
response = (await comment_responses(db, [comment], user, resource.user_id))[0]
|
||||
from open_webui.utils.inbox import consume_event
|
||||
from open_webui.models.notifications import emit_changes
|
||||
|
||||
event = build_event(
|
||||
request,
|
||||
EVENTS.COMMENT_UPDATED,
|
||||
actor=user,
|
||||
subject_id=comment.id,
|
||||
subject_type='comment',
|
||||
event_id=f'comment:{comment.id}:{comment.updated_at}',
|
||||
data={'previous_mentions': sorted(mentioned_users(previous_content))},
|
||||
)
|
||||
recipients = await consume_event(event, db=db)
|
||||
await db.commit()
|
||||
await emit_changes(recipients)
|
||||
await publish_event(request, event)
|
||||
await changed(comment.resource_type, comment.resource_id)
|
||||
return response
|
||||
|
||||
|
||||
@router.delete('/{id}')
|
||||
async def remove(
|
||||
request: Request,
|
||||
id: str,
|
||||
etag: str = Query(pattern=r'^\d{1,20}$'),
|
||||
user=Depends(get_verified_user),
|
||||
db: AsyncSession = Depends(get_async_session),
|
||||
):
|
||||
comment, resource = await accessible_comment(id, user, db, lock=True, request=request)
|
||||
if comment.user_id != user.id and resource.user_id != user.id and user.role != 'admin':
|
||||
raise HTTPException(403, 'Cannot delete this comment')
|
||||
if str(comment.updated_at) != etag:
|
||||
raise HTTPException(409, 'Comment changed. Reload before deleting.')
|
||||
await limit_write(request, user)
|
||||
kind, resource_id = comment.resource_type, comment.resource_id
|
||||
now = time.time_ns()
|
||||
result = await db.execute(
|
||||
update(Comment)
|
||||
.where(Comment.id == id, Comment.updated_at == int(etag), Comment.deleted_at.is_(None))
|
||||
.values(content='', user_id=None, meta=None, deleted_at=now, updated_at=now)
|
||||
.execution_options(synchronize_session=False)
|
||||
)
|
||||
if result.rowcount != 1:
|
||||
raise HTTPException(409, 'Comment changed. Reload before deleting.')
|
||||
await db.execute(delete(CommentReaction).where(CommentReaction.comment_id == id))
|
||||
recipients = await delete_notifications(object_type='comment', object_ids=[id], db=db)
|
||||
# Keep thread and quoted-reply references intact, without retaining deleted text.
|
||||
await db.commit()
|
||||
await emit_changes(recipients)
|
||||
await changed(kind, resource_id)
|
||||
return True
|
||||
|
||||
|
||||
class ReactionForm(BaseModel):
|
||||
name: str = Field(min_length=1, max_length=100)
|
||||
|
||||
|
||||
@router.put('/{id}/reactions')
|
||||
async def add_reaction(
|
||||
request: Request,
|
||||
id: str,
|
||||
form: ReactionForm,
|
||||
user=Depends(get_verified_user),
|
||||
db: AsyncSession = Depends(get_async_session),
|
||||
):
|
||||
await limit_write(request, user, reaction_limiter)
|
||||
comment, resource = await accessible_comment(id, user, db, lock=True, request=request)
|
||||
if comment.deleted_at:
|
||||
raise HTTPException(409, 'Comment was deleted')
|
||||
existing = await db.scalar(
|
||||
select(CommentReaction.id).where(
|
||||
CommentReaction.comment_id == id, CommentReaction.user_id == user.id, CommentReaction.name == form.name
|
||||
)
|
||||
)
|
||||
if not existing:
|
||||
try:
|
||||
async with db.begin_nested():
|
||||
db.add(
|
||||
CommentReaction(
|
||||
id=str(uuid4()), comment_id=id, user_id=user.id, name=form.name, created_at=time.time_ns()
|
||||
)
|
||||
)
|
||||
await db.flush()
|
||||
except IntegrityError:
|
||||
# A concurrent identical reaction is already the requested result.
|
||||
pass
|
||||
await db.commit()
|
||||
await changed(comment.resource_type, comment.resource_id)
|
||||
return True
|
||||
|
||||
|
||||
@router.delete('/{id}/reactions')
|
||||
async def remove_reaction(
|
||||
request: Request,
|
||||
id: str,
|
||||
name: str = Query(min_length=1, max_length=100),
|
||||
user=Depends(get_verified_user),
|
||||
db: AsyncSession = Depends(get_async_session),
|
||||
):
|
||||
await limit_write(request, user, reaction_limiter)
|
||||
comment, resource = await accessible_comment(id, user, db, lock=True, request=request)
|
||||
await db.execute(
|
||||
delete(CommentReaction).where(
|
||||
CommentReaction.comment_id == id, CommentReaction.user_id == user.id, CommentReaction.name == name
|
||||
)
|
||||
)
|
||||
await db.commit()
|
||||
await changed(comment.resource_type, comment.resource_id)
|
||||
return True
|
||||
|
|
@ -31,7 +31,7 @@ from open_webui.utils.tools import (
|
|||
set_terminal_servers,
|
||||
set_tool_servers,
|
||||
)
|
||||
from pydantic import BaseModel, ConfigDict, StrictBool
|
||||
from pydantic import BaseModel, ConfigDict, Field, StrictBool, field_validator
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
|
@ -86,11 +86,9 @@ def config_updates(data: dict, key_map: dict[str, str]) -> dict:
|
|||
return {key_map[field]: value for field, value in data.items() if field in key_map}
|
||||
|
||||
|
||||
############################
|
||||
# ImportConfig
|
||||
# Thy configuration come, thy settings be done,
|
||||
# in production as it is in development.
|
||||
############################
|
||||
# Import Config
|
||||
# Let what we prepare in quiet hold when the world grows loud,
|
||||
# and let those who depend on it find steadiness through change.
|
||||
|
||||
|
||||
class ImportConfigForm(BaseModel):
|
||||
|
|
@ -112,9 +110,7 @@ async def import_config(request: Request, form_data: ImportConfigForm, user=Depe
|
|||
return await Config.get_all()
|
||||
|
||||
|
||||
############################
|
||||
# ExportConfig
|
||||
############################
|
||||
# Export Config
|
||||
|
||||
|
||||
@router.get('/export', response_model=dict)
|
||||
|
|
@ -145,9 +141,7 @@ async def set_interface_visibility(request: Request, form_data: InterfaceVisibil
|
|||
return form_data
|
||||
|
||||
|
||||
############################
|
||||
# Connections Config
|
||||
############################
|
||||
|
||||
|
||||
class ConnectionsConfigForm(BaseModel):
|
||||
|
|
@ -232,9 +226,7 @@ async def register_oauth_client(
|
|||
)
|
||||
|
||||
|
||||
############################
|
||||
# ToolServers Config
|
||||
############################
|
||||
|
||||
|
||||
class ToolServerConnection(BaseModel):
|
||||
|
|
@ -718,9 +710,7 @@ async def verify_tool_servers_config(request: Request, form_data: ToolServerConn
|
|||
)
|
||||
|
||||
|
||||
############################
|
||||
# CodeInterpreterConfig
|
||||
############################
|
||||
# Code Interpreter Config
|
||||
class CodeInterpreterConfigForm(BaseModel):
|
||||
ENABLE_CODE_EXECUTION: bool
|
||||
CODE_EXECUTION_ENGINE: str
|
||||
|
|
@ -766,9 +756,7 @@ async def set_code_execution_config(
|
|||
return values
|
||||
|
||||
|
||||
############################
|
||||
# SetDefaultModels
|
||||
############################
|
||||
# Set Default Models
|
||||
class ModelsConfigForm(BaseModel):
|
||||
DEFAULT_MODELS: str | None
|
||||
DEFAULT_PINNED_MODELS: str | None
|
||||
|
|
@ -811,12 +799,28 @@ async def set_models_config(request: Request, form_data: ModelsConfigForm, user=
|
|||
class SubagentsConfigForm(BaseModel):
|
||||
ENABLE_SUBAGENTS: bool
|
||||
SUBAGENTS_BACKGROUND_ENABLED: bool
|
||||
SUBAGENTS_MAX_CONCURRENT: int
|
||||
SUBAGENTS_MAX_ASYNC: int
|
||||
SUBAGENTS_MAX_ITERATIONS: int
|
||||
SUBAGENTS_MAX_OUTPUT: int
|
||||
SUBAGENTS_MAX_CONCURRENT: int | None = Field(default=None, gt=0)
|
||||
SUBAGENTS_MAX_ASYNC: int | None = Field(default=None, gt=0)
|
||||
SUBAGENTS_MAX_ITERATIONS: int | None = Field(default=None, gt=0)
|
||||
SUBAGENTS_MAX_OUTPUT: int | None = Field(default=None, gt=0)
|
||||
SUBAGENTS_SYSTEM_PROMPT: str
|
||||
|
||||
@field_validator(
|
||||
'SUBAGENTS_MAX_CONCURRENT',
|
||||
'SUBAGENTS_MAX_ASYNC',
|
||||
'SUBAGENTS_MAX_ITERATIONS',
|
||||
'SUBAGENTS_MAX_OUTPUT',
|
||||
mode='before',
|
||||
)
|
||||
@classmethod
|
||||
def normalize_limit(cls, value):
|
||||
return None if value == '' else value
|
||||
|
||||
@field_validator('SUBAGENTS_MAX_CONCURRENT', 'SUBAGENTS_MAX_ASYNC', mode='before')
|
||||
@classmethod
|
||||
def normalize_legacy_unlimited(cls, value):
|
||||
return None if value == -1 else value
|
||||
|
||||
|
||||
@router.get('/subagents', response_model=SubagentsConfigForm)
|
||||
async def get_subagents_config(user=Depends(get_admin_user)):
|
||||
|
|
@ -878,9 +882,7 @@ async def set_default_suggestions(
|
|||
return {'suggestions': suggestions, 'i18n': suggestions_i18n}
|
||||
|
||||
|
||||
############################
|
||||
# SetBanners
|
||||
############################
|
||||
# Set Banners
|
||||
|
||||
|
||||
class SetBannersForm(BaseModel):
|
||||
|
|
|
|||
|
|
@ -41,27 +41,10 @@ async def get_config_values(key_map: dict[str, str]) -> dict:
|
|||
return {field: values[storage_key] for field, storage_key in key_map.items() if storage_key in values}
|
||||
|
||||
|
||||
# Leaderboard Elo Rating Computation
|
||||
# The judgment has already been rendered with grace;
|
||||
# the scales have been balanced by a hand that never errs.
|
||||
#
|
||||
# How it works:
|
||||
# 1. Each model starts with a rating of 1000
|
||||
# 2. When a user picks a winner between two models, ratings are adjusted:
|
||||
# - Winner gains points, loser loses points
|
||||
# - The amount depends on expected outcome (upset = bigger change)
|
||||
# 3. The Elo formula: new_rating = old_rating + K * (actual - expected)
|
||||
# - K=32 controls how much ratings can change per match
|
||||
# - expected = probability of winning based on current ratings
|
||||
#
|
||||
# Query-based re-ranking (optional):
|
||||
# When a user searches for a topic (e.g., "coding"), we want to show
|
||||
# which models perform best FOR THAT TOPIC. We do this by:
|
||||
# 1. Computing semantic similarity between the query and each feedback's tags
|
||||
# 2. Using that similarity as a weight in the Elo calculation
|
||||
# 3. Feedbacks about "coding" contribute more to the final ranking
|
||||
# 4. Feedbacks about unrelated topics (e.g., "cooking") contribute less
|
||||
# This gives topic-specific leaderboards without needing separate data.
|
||||
# Let the scales be fair even when our favorite loses,
|
||||
# and let a better score never go straight to our heads.
|
||||
|
||||
# Elo starts at 1000 with K=32; query similarity optionally weights each match.
|
||||
|
||||
import os
|
||||
|
||||
|
|
@ -277,9 +260,7 @@ async def get_model_history(
|
|||
return ModelHistoryResponse(model_id=model_id, history=history)
|
||||
|
||||
|
||||
############################
|
||||
# GetConfig
|
||||
############################
|
||||
# Get Config
|
||||
|
||||
|
||||
@router.get('/config')
|
||||
|
|
@ -287,9 +268,7 @@ async def get_config(request: Request, user=Depends(get_admin_user)):
|
|||
return await get_config_values(EVALUATION_CONFIG_KEYS)
|
||||
|
||||
|
||||
############################
|
||||
# UpdateConfig
|
||||
############################
|
||||
# Update Config
|
||||
|
||||
|
||||
class UpdateConfigForm(BaseModel):
|
||||
|
|
|
|||
|
|
@ -41,6 +41,7 @@ from open_webui.models.knowledge import Knowledges
|
|||
from open_webui.models.users import Users
|
||||
from open_webui.retrieval.vector.async_client import ASYNC_VECTOR_DB_CLIENT
|
||||
from open_webui.routers.audio import transcribe
|
||||
from open_webui.routers.knowledge import check_knowledge_upload_limits
|
||||
from open_webui.routers.retrieval import ProcessFileForm, index_file, process_file
|
||||
from open_webui.storage.provider import Storage
|
||||
from open_webui.utils.auth import get_admin_user, get_verified_user
|
||||
|
|
@ -56,11 +57,9 @@ router = APIRouter()
|
|||
from open_webui.utils.access_control.files import has_access_to_file
|
||||
from open_webui.utils.json_codec import JSONCodec
|
||||
|
||||
############################
|
||||
# Upload File
|
||||
# What was entrusted here was given in good faith. Let it
|
||||
# be returned the same way, whole and undiminished.
|
||||
############################
|
||||
|
||||
|
||||
def _is_text_file(file_path: str, chunk_size: int = 8192) -> bool:
|
||||
|
|
@ -136,6 +135,14 @@ async def process_uploaded_file(
|
|||
):
|
||||
async def _process_handler(db_session):
|
||||
try:
|
||||
if file_metadata.get('knowledge_id'):
|
||||
await check_knowledge_upload_limits(
|
||||
file_metadata['knowledge_id'],
|
||||
1,
|
||||
file_size=(file_item.meta or {}).get('size'),
|
||||
exclude_file_ids=[file_item.id],
|
||||
db=db_session,
|
||||
)
|
||||
await Files.update_file_data_by_id(file_item.id, {'status': 'processing'}, db=db_session)
|
||||
content_type = file.content_type
|
||||
|
||||
|
|
@ -174,10 +181,7 @@ async def process_uploaded_file(
|
|||
)
|
||||
):
|
||||
if content_type.startswith('video/'):
|
||||
# Videos are stored as-is for downstream multimodal
|
||||
# processing (Tools, vision models). Attempting text
|
||||
# extraction causes "Timeout reached while detecting
|
||||
# encoding" errors.
|
||||
# Keep videos for multimodal processing; text extraction can time out detecting their encoding.
|
||||
log.info('Video file detected (%s), skipping text extraction', content_type)
|
||||
else:
|
||||
raise Exception(f'File type {content_type} is not supported for processing')
|
||||
|
|
@ -229,12 +233,6 @@ async def process_uploaded_file(
|
|||
)
|
||||
directory_id = None
|
||||
|
||||
await index_file(
|
||||
request,
|
||||
ProcessFileForm(file_id=file_item.id, collection_name=knowledge_id),
|
||||
user=user,
|
||||
db=db_session,
|
||||
)
|
||||
knowledge_file = await Knowledges.add_file_to_knowledge_by_id(
|
||||
knowledge_id=knowledge_id,
|
||||
file_id=file_item.id,
|
||||
|
|
@ -244,6 +242,16 @@ async def process_uploaded_file(
|
|||
)
|
||||
if not knowledge_file:
|
||||
raise Exception(f'Failed to link file {file_item.id} to knowledge {knowledge_id}')
|
||||
try:
|
||||
await index_file(
|
||||
request,
|
||||
ProcessFileForm(file_id=file_item.id, collection_name=knowledge_id),
|
||||
user=user,
|
||||
db=db_session,
|
||||
)
|
||||
except Exception:
|
||||
await Knowledges.remove_file_from_knowledge_by_id(knowledge_id, file_item.id, db=db_session)
|
||||
raise
|
||||
log.info('Linked file %s to knowledge %s', file_item.id, knowledge_id)
|
||||
except Exception as e:
|
||||
log.warning(f'Failed to link file {file_item.id} to knowledge {knowledge_id}: {e}')
|
||||
|
|
@ -357,6 +365,19 @@ async def upload_file_handler(
|
|||
detail=ERROR_MESSAGES.DEFAULT(f'File type {file_extension} is not allowed'),
|
||||
)
|
||||
|
||||
knowledge_id = file_metadata.get('knowledge_id')
|
||||
if knowledge_id:
|
||||
knowledge = await Knowledges.get_knowledge_by_id(knowledge_id, db=db)
|
||||
if not knowledge or not (
|
||||
knowledge.user_id == user.id
|
||||
or user.role == 'admin'
|
||||
or await AccessGrants.has_access(
|
||||
user_id=user.id, resource_type='knowledge', resource_id=knowledge_id, permission='write', db=db
|
||||
)
|
||||
):
|
||||
raise HTTPException(403, ERROR_MESSAGES.ACCESS_PROHIBITED)
|
||||
await check_knowledge_upload_limits(knowledge_id, 1, batch=True, file_size=file.size, db=db)
|
||||
|
||||
# Prefer readable storage names for admins, but fall back if the filesystem rejects it.
|
||||
id = str(uuid.uuid4())
|
||||
name = filename
|
||||
|
|
@ -395,6 +416,13 @@ async def upload_file_handler(
|
|||
detail=ERROR_MESSAGES.FILE_TOO_LARGE(size=f'{max_size} MB'),
|
||||
)
|
||||
|
||||
if knowledge_id:
|
||||
try:
|
||||
await check_knowledge_upload_limits(knowledge_id, 0, file_size=len(contents), db=db)
|
||||
except HTTPException:
|
||||
await asyncio.to_thread(Storage.delete_file, file_path)
|
||||
raise
|
||||
|
||||
# SHA-256 of raw uploaded bytes for incremental sync diffing.
|
||||
# If the client pre-computed and sent file_hash, use that.
|
||||
file_hash = file_metadata.get('file_hash') or await asyncio.to_thread(
|
||||
|
|
@ -474,9 +502,7 @@ async def upload_file_handler(
|
|||
)
|
||||
|
||||
|
||||
############################
|
||||
# List Files
|
||||
############################
|
||||
|
||||
|
||||
PAGE_SIZE = 50
|
||||
|
|
@ -502,9 +528,7 @@ async def list_files(
|
|||
return result
|
||||
|
||||
|
||||
############################
|
||||
# Search Files
|
||||
############################
|
||||
|
||||
|
||||
async def _search_files(filename: str, content: bool, skip: int, limit: int, user_id: str | None, db: AsyncSession):
|
||||
|
|
@ -550,9 +574,7 @@ async def search_user_files(
|
|||
return await _search_files(filename, content, skip, limit, user.id, db)
|
||||
|
||||
|
||||
############################
|
||||
# Count Files
|
||||
############################
|
||||
|
||||
|
||||
@router.get('/count', response_model=int)
|
||||
|
|
@ -572,9 +594,7 @@ async def count_user_files(
|
|||
return await Files.count_files_by_user_id(user_id=user.id, db=db)
|
||||
|
||||
|
||||
############################
|
||||
# Delete All Files
|
||||
############################
|
||||
|
||||
|
||||
@router.delete('/all')
|
||||
|
|
@ -602,9 +622,7 @@ async def delete_all_files(
|
|||
)
|
||||
|
||||
|
||||
############################
|
||||
# Get File By Id
|
||||
############################
|
||||
|
||||
|
||||
@router.get('/{id}', response_model=Optional[FileModel])
|
||||
|
|
@ -632,10 +650,7 @@ async def get_file_process_status(
|
|||
stream: bool = Query(False),
|
||||
user=Depends(get_verified_user),
|
||||
):
|
||||
# NOTE: We intentionally do NOT use Depends(get_async_session) here.
|
||||
# Database operations manage their own short-lived sessions internally.
|
||||
# Holding a session here would keep a connection for the entire stream
|
||||
# (up to two hours) and exhaust the connection pool under concurrent load.
|
||||
# Let DB helpers own short-lived sessions so remote calls and streams do not hold pool connections.
|
||||
file = await Files.get_file_by_id(id)
|
||||
|
||||
if not file:
|
||||
|
|
@ -685,9 +700,7 @@ async def get_file_process_status(
|
|||
)
|
||||
|
||||
|
||||
############################
|
||||
# Get File Data Content By Id
|
||||
############################
|
||||
|
||||
|
||||
@router.get('/{id}/data/content')
|
||||
|
|
@ -711,9 +724,7 @@ async def get_file_data_content_by_id(
|
|||
)
|
||||
|
||||
|
||||
############################
|
||||
# Update File Data Content By Id
|
||||
############################
|
||||
|
||||
|
||||
class ContentForm(BaseModel):
|
||||
|
|
@ -805,9 +816,7 @@ async def update_file_data_content_by_id(
|
|||
)
|
||||
|
||||
|
||||
############################
|
||||
# Get File Content By Id
|
||||
############################
|
||||
|
||||
|
||||
@router.get('/{id}/content')
|
||||
|
|
@ -975,9 +984,7 @@ async def get_file_content_by_id(
|
|||
)
|
||||
|
||||
|
||||
############################
|
||||
# Rename File By Id
|
||||
############################
|
||||
|
||||
|
||||
class FileRenameForm(BaseModel):
|
||||
|
|
@ -1023,9 +1030,7 @@ async def rename_file_by_id(
|
|||
)
|
||||
|
||||
|
||||
############################
|
||||
# Delete File By Id
|
||||
############################
|
||||
|
||||
|
||||
@router.delete('/{id}')
|
||||
|
|
|
|||
|
|
@ -84,9 +84,7 @@ async def check_folders_permission(request: Request, user, db=None):
|
|||
)
|
||||
|
||||
|
||||
############################
|
||||
# Get Folders
|
||||
############################
|
||||
|
||||
|
||||
@router.get('/', response_model=list[FolderNameIdResponse])
|
||||
|
|
@ -142,9 +140,7 @@ async def get_folders(
|
|||
]
|
||||
|
||||
|
||||
############################
|
||||
# Create Folder
|
||||
############################
|
||||
|
||||
|
||||
@router.post('/')
|
||||
|
|
@ -234,9 +230,7 @@ async def create_folder(
|
|||
)
|
||||
|
||||
|
||||
############################
|
||||
# Get Shared Folders
|
||||
############################
|
||||
|
||||
|
||||
@router.get('/shared')
|
||||
|
|
@ -287,9 +281,7 @@ async def get_shared_folders(
|
|||
return results
|
||||
|
||||
|
||||
############################
|
||||
# Get Folders By Id
|
||||
############################
|
||||
|
||||
|
||||
class FolderResponse(FolderModel):
|
||||
|
|
@ -327,9 +319,7 @@ async def get_folder_by_id(
|
|||
)
|
||||
|
||||
|
||||
############################
|
||||
# Update Folder Name By Id
|
||||
############################
|
||||
|
||||
|
||||
@router.post('/{id}/update')
|
||||
|
|
@ -416,9 +406,7 @@ async def update_folder_name_by_id(
|
|||
)
|
||||
|
||||
|
||||
############################
|
||||
# Update Folder Parent Id By Id
|
||||
############################
|
||||
|
||||
|
||||
class FolderParentIdForm(BaseModel):
|
||||
|
|
@ -478,9 +466,7 @@ async def update_folder_parent_id_by_id(
|
|||
)
|
||||
|
||||
|
||||
############################
|
||||
# Update Folder Is Expanded By Id
|
||||
############################
|
||||
|
||||
|
||||
class FolderIsExpandedForm(BaseModel):
|
||||
|
|
@ -522,9 +508,7 @@ async def update_folder_is_expanded_by_id(
|
|||
)
|
||||
|
||||
|
||||
############################
|
||||
# Update Folder Access By Id
|
||||
############################
|
||||
|
||||
|
||||
class FolderAccessGrantsForm(BaseModel):
|
||||
|
|
@ -584,9 +568,7 @@ async def update_folder_access_by_id(
|
|||
}
|
||||
|
||||
|
||||
############################
|
||||
# Get Shared Folder Chats
|
||||
############################
|
||||
|
||||
|
||||
@router.get('/{id}/shared/chats')
|
||||
|
|
@ -637,6 +619,9 @@ async def get_shared_folder_chats(
|
|||
user_ids.update(uid for ids in participant_ids.values() for uid in ids)
|
||||
users = await Users.get_users_by_user_ids(list(user_ids), db=db) if user_ids else []
|
||||
names = {u.id: u.name for u in users}
|
||||
pending_approval_ids = await ChatMessages.get_chat_ids_with_pending_approval(
|
||||
[chat['id'] for chat in chats], db=db
|
||||
)
|
||||
for chat in chats:
|
||||
uid = chat['user_id']
|
||||
chat['owner_name'] = names.get(uid, 'Unknown')
|
||||
|
|
@ -650,6 +635,7 @@ async def get_shared_folder_chats(
|
|||
),
|
||||
)
|
||||
chat['active'] = False
|
||||
chat['pending_approval'] = chat['id'] in pending_approval_ids
|
||||
if chat['user_id'] != user.id:
|
||||
chat['last_read_at'] = chat['updated_at']
|
||||
if await has_active_tasks(request.app.state.redis, chat['id']):
|
||||
|
|
@ -702,9 +688,7 @@ async def mark_folder_chats_read_by_id(
|
|||
}
|
||||
|
||||
|
||||
############################
|
||||
# Delete Folder By Id
|
||||
############################
|
||||
|
||||
|
||||
@router.delete('/{id}')
|
||||
|
|
|
|||
|
|
@ -40,11 +40,9 @@ log = logging.getLogger(__name__)
|
|||
|
||||
router = APIRouter()
|
||||
|
||||
############################
|
||||
# GetFunctions
|
||||
# Our daily functions give us, and forgive us
|
||||
# our deprecated methods, as we refactor those who depend on us.
|
||||
############################
|
||||
# Get Functions
|
||||
# Let the work begun here be faithful to its promise,
|
||||
# and let it serve those who call upon it, quietly and well.
|
||||
|
||||
|
||||
@router.get('/', response_model=list[FunctionResponse])
|
||||
|
|
@ -63,9 +61,7 @@ async def get_function_list(user=Depends(get_admin_user), db: AsyncSession = Dep
|
|||
return await Functions.get_function_list(db=db)
|
||||
|
||||
|
||||
############################
|
||||
# ExportFunctions
|
||||
############################
|
||||
# Export Functions
|
||||
|
||||
|
||||
@router.get('/export', response_model=list[FunctionModel | FunctionWithValvesModel])
|
||||
|
|
@ -80,9 +76,7 @@ async def get_functions(
|
|||
return await Functions.get_functions(include_valves=include_valves, db=db)
|
||||
|
||||
|
||||
############################
|
||||
# LoadFunctionFromLink
|
||||
############################
|
||||
# Load Function From Link
|
||||
|
||||
|
||||
class LoadUrlForm(BaseModel):
|
||||
|
|
@ -153,9 +147,7 @@ async def load_function_from_url(request: Request, form_data: LoadUrlForm, user=
|
|||
)
|
||||
|
||||
|
||||
############################
|
||||
# SyncFunctions
|
||||
############################
|
||||
# Sync Functions
|
||||
|
||||
|
||||
class SyncFunctionsForm(BaseModel):
|
||||
|
|
@ -199,9 +191,7 @@ async def sync_functions(
|
|||
)
|
||||
|
||||
|
||||
############################
|
||||
# CreateNewFunction
|
||||
############################
|
||||
# Create New Function
|
||||
|
||||
|
||||
@router.post('/create', response_model=FunctionResponse | None)
|
||||
|
|
@ -267,9 +257,7 @@ async def create_new_function(
|
|||
)
|
||||
|
||||
|
||||
############################
|
||||
# GetFunctionById
|
||||
############################
|
||||
# Get Function By Id
|
||||
|
||||
|
||||
@router.get('/id/{id}', response_model=FunctionModel | None)
|
||||
|
|
@ -285,9 +273,7 @@ async def get_function_by_id(id: str, user=Depends(get_admin_user), db: AsyncSes
|
|||
)
|
||||
|
||||
|
||||
############################
|
||||
# ToggleFunctionById
|
||||
############################
|
||||
# Toggle Function By Id
|
||||
|
||||
|
||||
@router.post('/id/{id}/toggle', response_model=FunctionModel | None)
|
||||
|
|
@ -308,9 +294,8 @@ async def toggle_function_by_id(
|
|||
data={'type': function.type, 'name': function.name},
|
||||
)
|
||||
await dispatch_event_functions(
|
||||
request.app,
|
||||
request,
|
||||
lifecycle_event,
|
||||
request=request,
|
||||
extra_function_ids=[function.id] if not function.is_active else None,
|
||||
)
|
||||
schedule_webhook_dispatch(request.app, lifecycle_event)
|
||||
|
|
@ -339,9 +324,7 @@ async def toggle_function_by_id(
|
|||
)
|
||||
|
||||
|
||||
############################
|
||||
# ToggleGlobalById
|
||||
############################
|
||||
# Toggle Global By Id
|
||||
|
||||
|
||||
@router.post('/id/{id}/toggle/global', response_model=FunctionModel | None)
|
||||
|
|
@ -376,9 +359,7 @@ async def toggle_global_by_id(
|
|||
)
|
||||
|
||||
|
||||
############################
|
||||
# UpdateFunctionById
|
||||
############################
|
||||
# Update Function By Id
|
||||
|
||||
|
||||
@router.post('/id/{id}/update', response_model=FunctionModel | None)
|
||||
|
|
@ -434,9 +415,7 @@ async def _update_function(request, id, form_data, user, db, version_id=None):
|
|||
)
|
||||
|
||||
|
||||
############################
|
||||
# DeleteFunctionById
|
||||
############################
|
||||
# Delete Function By Id
|
||||
|
||||
|
||||
@router.delete('/id/{id}/delete', response_model=bool)
|
||||
|
|
@ -463,9 +442,7 @@ async def delete_function_by_id(
|
|||
return result
|
||||
|
||||
|
||||
############################
|
||||
# GetFunctionValves
|
||||
############################
|
||||
# Get Function Valves
|
||||
|
||||
|
||||
@router.get('/id/{id}/valves', response_model=dict | None)
|
||||
|
|
@ -489,9 +466,7 @@ async def get_function_valves_by_id(
|
|||
)
|
||||
|
||||
|
||||
############################
|
||||
# GetFunctionValvesSpec
|
||||
############################
|
||||
# Get Function Valves Spec
|
||||
|
||||
|
||||
@router.get('/id/{id}/valves/spec', response_model=dict | None)
|
||||
|
|
@ -519,9 +494,7 @@ async def get_function_valves_spec_by_id(
|
|||
)
|
||||
|
||||
|
||||
############################
|
||||
# UpdateFunctionValves
|
||||
############################
|
||||
# Update Function Valves
|
||||
|
||||
|
||||
@router.post('/id/{id}/valves/update', response_model=dict | None)
|
||||
|
|
@ -571,9 +544,7 @@ async def update_function_valves_by_id(
|
|||
)
|
||||
|
||||
|
||||
############################
|
||||
# FunctionUserValves
|
||||
############################
|
||||
# Function User Valves
|
||||
|
||||
|
||||
@router.get('/id/{id}/valves/user', response_model=dict | None)
|
||||
|
|
|
|||
|
|
@ -40,9 +40,7 @@ log = logging.getLogger(__name__)
|
|||
|
||||
router = APIRouter()
|
||||
|
||||
############################
|
||||
# GetFunctions
|
||||
############################
|
||||
# Get Functions
|
||||
|
||||
|
||||
@router.get('/', response_model=list[GroupResponse])
|
||||
|
|
@ -64,9 +62,7 @@ async def get_groups(
|
|||
return groups
|
||||
|
||||
|
||||
############################
|
||||
# CreateNewGroup
|
||||
############################
|
||||
# Create New Group
|
||||
|
||||
|
||||
@router.post('/create', response_model=Optional[GroupResponse])
|
||||
|
|
@ -107,9 +103,7 @@ async def create_new_group(
|
|||
)
|
||||
|
||||
|
||||
############################
|
||||
# GetGroupById
|
||||
############################
|
||||
# Get Group By Id
|
||||
|
||||
|
||||
@router.get('/id/{id}', response_model=Optional[GroupResponse])
|
||||
|
|
@ -142,9 +136,7 @@ async def get_group_info_by_id(id: str, user=Depends(get_verified_user), db: Asy
|
|||
)
|
||||
|
||||
|
||||
############################
|
||||
# ExportGroupById
|
||||
############################
|
||||
# Export Group By Id
|
||||
|
||||
|
||||
class GroupExportResponse(GroupResponse):
|
||||
|
|
@ -168,9 +160,7 @@ async def export_group_by_id(id: str, user=Depends(get_admin_user), db: AsyncSes
|
|||
)
|
||||
|
||||
|
||||
############################
|
||||
# GetUsersInGroupById
|
||||
############################
|
||||
# Get Users In Group By Id
|
||||
|
||||
|
||||
@router.post('/id/{id}/users', response_model=list[UserInfoResponse])
|
||||
|
|
@ -186,9 +176,7 @@ async def get_users_in_group(id: str, user=Depends(get_admin_user), db: AsyncSes
|
|||
)
|
||||
|
||||
|
||||
############################
|
||||
# UpdateGroupById
|
||||
############################
|
||||
# Update Group By Id
|
||||
|
||||
|
||||
@router.post('/id/{id}/update', response_model=Optional[GroupResponse])
|
||||
|
|
@ -231,9 +219,7 @@ async def update_group_by_id(
|
|||
)
|
||||
|
||||
|
||||
############################
|
||||
# AddUserToGroupByUserIdAndGroupId
|
||||
############################
|
||||
# Add User To Group By User Id And Group Id
|
||||
|
||||
|
||||
@router.post('/id/{id}/users/add', response_model=Optional[GroupResponse])
|
||||
|
|
@ -317,9 +303,7 @@ async def remove_users_from_group(
|
|||
)
|
||||
|
||||
|
||||
############################
|
||||
# DeleteGroupById
|
||||
############################
|
||||
# Delete Group By Id
|
||||
|
||||
|
||||
@router.delete('/id/{id}/delete', response_model=bool)
|
||||
|
|
@ -363,9 +347,7 @@ async def delete_group_by_id(
|
|||
)
|
||||
|
||||
|
||||
############################
|
||||
# PreviewGroupAccess
|
||||
############################
|
||||
# Preview Group Access
|
||||
|
||||
|
||||
@router.get('/id/{id}/preview')
|
||||
|
|
|
|||
|
|
@ -44,18 +44,16 @@ from open_webui.routers.retrieval import (
|
|||
from open_webui.storage.provider import Storage
|
||||
from open_webui.utils.access_control import filter_allowed_access_grants, has_permission, validate_access_grants
|
||||
from open_webui.utils.access_control.files import has_access_to_file
|
||||
from open_webui.utils.auth import get_admin_user, get_verified_user
|
||||
from open_webui.utils.auth import get_admin_user, get_verified_user, get_verified_user_by_id
|
||||
from open_webui.utils.json_codec import JSONCodec
|
||||
from pydantic import BaseModel
|
||||
from pydantic import BaseModel, Field
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
############################
|
||||
# getKnowledgeBases
|
||||
############################
|
||||
|
||||
PAGE_ITEM_COUNT = 30
|
||||
|
||||
|
|
@ -79,9 +77,7 @@ async def delete_file_resource(file: FileModel, db: AsyncSession) -> bool:
|
|||
return result
|
||||
|
||||
|
||||
############################
|
||||
# Knowledge Base Embedding
|
||||
############################
|
||||
|
||||
# Knowledge that sits unread serves no one. Let what is
|
||||
# stored here find the ones who need it.
|
||||
|
|
@ -311,9 +307,7 @@ async def search_knowledge_files(
|
|||
return await Knowledges.search_knowledge_files(filter=filter, skip=skip, limit=limit, db=db)
|
||||
|
||||
|
||||
############################
|
||||
# CreateNewKnowledge
|
||||
############################
|
||||
# Create New Knowledge
|
||||
|
||||
|
||||
@router.post('/create', response_model=KnowledgeResponse | None)
|
||||
|
|
@ -322,10 +316,7 @@ async def create_new_knowledge(
|
|||
form_data: KnowledgeForm,
|
||||
user=Depends(get_verified_user),
|
||||
):
|
||||
# NOTE: We intentionally do NOT use Depends(get_async_session) here.
|
||||
# Database operations (has_permission, filter_allowed_access_grants, insert_new_knowledge) manage their own sessions.
|
||||
# This prevents holding a connection during embed_knowledge_base_metadata()
|
||||
# which makes external embedding API calls (1-5+ seconds).
|
||||
# Let DB helpers own short-lived sessions so remote calls and streams do not hold pool connections.
|
||||
if user.role != 'admin' and not await has_permission(
|
||||
user.id, 'workspace.knowledge', await Config.get('user.permissions')
|
||||
):
|
||||
|
|
@ -367,9 +358,7 @@ async def create_new_knowledge(
|
|||
)
|
||||
|
||||
|
||||
############################
|
||||
# ReindexKnowledgeFiles
|
||||
############################
|
||||
# Reindex Knowledge Files
|
||||
|
||||
|
||||
@router.post('/reindex', response_model=bool)
|
||||
|
|
@ -462,9 +451,7 @@ async def reindex_knowledge_files(
|
|||
return True
|
||||
|
||||
|
||||
############################
|
||||
# ReindexKnowledgeBases
|
||||
############################
|
||||
# Reindex Knowledge Bases
|
||||
|
||||
|
||||
@router.post('/metadata/reindex', response_model=dict)
|
||||
|
|
@ -495,9 +482,7 @@ async def reindex_knowledge_base_metadata_embeddings(
|
|||
return {'total': len(knowledge_bases), 'success': success_count}
|
||||
|
||||
|
||||
############################
|
||||
# External Knowledge Sources
|
||||
############################
|
||||
|
||||
|
||||
class ExternalKnowledgeSourceForm(BaseModel):
|
||||
|
|
@ -1079,9 +1064,7 @@ async def update_external_knowledge_source(
|
|||
return updated
|
||||
|
||||
|
||||
############################
|
||||
# GetKnowledgeById
|
||||
############################
|
||||
# Get Knowledge By Id
|
||||
|
||||
|
||||
class KnowledgeFilesResponse(KnowledgeResponse):
|
||||
|
|
@ -1131,9 +1114,7 @@ async def get_knowledge_by_id(id: str, user=Depends(get_verified_user), db: Asyn
|
|||
)
|
||||
|
||||
|
||||
############################
|
||||
# UpdateKnowledgeById
|
||||
############################
|
||||
# Update Knowledge By Id
|
||||
|
||||
|
||||
@router.post('/{id}/update', response_model=KnowledgeFilesResponse | None)
|
||||
|
|
@ -1143,10 +1124,7 @@ async def update_knowledge_by_id(
|
|||
form_data: KnowledgeForm,
|
||||
user=Depends(get_verified_user),
|
||||
):
|
||||
# NOTE: We intentionally do NOT use Depends(get_async_session) here.
|
||||
# Database operations manage their own short-lived sessions internally.
|
||||
# This prevents holding a connection during embed_knowledge_base_metadata()
|
||||
# which makes external embedding API calls (1-5+ seconds).
|
||||
# Let DB helpers own short-lived sessions so remote calls and streams do not hold pool connections.
|
||||
knowledge = await Knowledges.get_knowledge_by_id(id=id)
|
||||
if not knowledge:
|
||||
raise HTTPException(
|
||||
|
|
@ -1169,6 +1147,12 @@ async def update_knowledge_by_id(
|
|||
detail=ERROR_MESSAGES.ACCESS_PROHIBITED,
|
||||
)
|
||||
|
||||
if form_data.meta is not None:
|
||||
if knowledge.user_id != user.id and user.role != 'admin':
|
||||
raise HTTPException(403, ERROR_MESSAGES.ACCESS_PROHIBITED)
|
||||
if is_external_knowledge(knowledge):
|
||||
external_knowledge_error()
|
||||
|
||||
knowledge = await Knowledges.update_knowledge_by_id(id=id, form_data=form_data)
|
||||
if knowledge:
|
||||
# Re-embed knowledge base for semantic search
|
||||
|
|
@ -1197,9 +1181,7 @@ async def update_knowledge_by_id(
|
|||
)
|
||||
|
||||
|
||||
############################
|
||||
# UpdateKnowledgeAccessById
|
||||
############################
|
||||
# Update Knowledge Access By Id
|
||||
|
||||
|
||||
class KnowledgeAccessGrantsForm(BaseModel):
|
||||
|
|
@ -1261,9 +1243,7 @@ async def update_knowledge_access_by_id(
|
|||
return response
|
||||
|
||||
|
||||
############################
|
||||
# GetPendingKnowledgeFiles
|
||||
############################
|
||||
# Get Pending Knowledge Files
|
||||
|
||||
|
||||
@router.get('/{id}/files/pending')
|
||||
|
|
@ -1283,10 +1263,7 @@ async def get_pending_knowledge_files(
|
|||
When ``stream=true``, returns an SSE stream that polls every 3 seconds
|
||||
and emits the current pending file list. Closes when no files remain.
|
||||
"""
|
||||
# NOTE: We intentionally do NOT use Depends(get_async_session) here.
|
||||
# Database operations manage their own short-lived sessions internally.
|
||||
# Holding a session here would keep a connection for the entire stream
|
||||
# (up to an hour) and exhaust the connection pool under concurrent load.
|
||||
# Let DB helpers own short-lived sessions so remote calls and streams do not hold pool connections.
|
||||
knowledge = await Knowledges.get_knowledge_by_id(id=id)
|
||||
if not knowledge:
|
||||
raise HTTPException(
|
||||
|
|
@ -1322,15 +1299,29 @@ async def get_pending_knowledge_files(
|
|||
break
|
||||
await asyncio.sleep(3)
|
||||
|
||||
# Access can be revoked while the stream is open.
|
||||
refreshed_user = await get_verified_user_by_id(user.id)
|
||||
if not refreshed_user:
|
||||
break
|
||||
if not (
|
||||
refreshed_user.role == 'admin'
|
||||
or knowledge.user_id == refreshed_user.id
|
||||
or await AccessGrants.has_access(
|
||||
user_id=refreshed_user.id,
|
||||
resource_type='knowledge',
|
||||
resource_id=knowledge_id,
|
||||
permission='read',
|
||||
)
|
||||
):
|
||||
break
|
||||
|
||||
return StreamingResponse(
|
||||
event_stream(id),
|
||||
media_type='text/event-stream',
|
||||
)
|
||||
|
||||
|
||||
############################
|
||||
# GetKnowledgeFilesById
|
||||
############################
|
||||
# Get Knowledge Files By Id
|
||||
|
||||
|
||||
@router.get('/{id}/files', response_model=KnowledgeFileListResponse)
|
||||
|
|
@ -1397,9 +1388,66 @@ async def get_knowledge_files_by_id(
|
|||
return await Knowledges.search_files_by_id(id, user.id, filter=filter, skip=skip, limit=limit, db=db)
|
||||
|
||||
|
||||
############################
|
||||
# AddFileToKnowledge
|
||||
############################
|
||||
# Add File To Knowledge
|
||||
|
||||
|
||||
async def check_knowledge_upload_limits(
|
||||
knowledge_id: str,
|
||||
count: int,
|
||||
*,
|
||||
batch: bool = False,
|
||||
file_size: int | None = None,
|
||||
exclude_file_ids: list[str] | None = None,
|
||||
db=None,
|
||||
) -> None:
|
||||
if batch:
|
||||
batch_limit = await Config.get('knowledge.max_upload_count')
|
||||
if batch_limit is not None and count > int(batch_limit):
|
||||
raise HTTPException(400, f'You can only upload a maximum of {batch_limit} file(s) per batch.')
|
||||
|
||||
knowledge = await Knowledges.get_knowledge_by_id(knowledge_id, db=db)
|
||||
if not knowledge:
|
||||
raise HTTPException(404, ERROR_MESSAGES.NOT_FOUND)
|
||||
limits = await Knowledges.get_file_limits(knowledge.meta)
|
||||
|
||||
if file_size is not None:
|
||||
for max_size in (await Config.get('rag.file.max_size'), limits['max_file_size']):
|
||||
if max_size and file_size > int(max_size) * 1024 * 1024:
|
||||
raise HTTPException(413, ERROR_MESSAGES.FILE_TOO_LARGE(size=f'{max_size} MB'))
|
||||
|
||||
limit = limits['max_file_count']
|
||||
if limit is not None and count > 0:
|
||||
current_count = await Knowledges.get_file_count_by_id(
|
||||
knowledge_id, include_pending=True, exclude_file_ids=exclude_file_ids, db=db
|
||||
)
|
||||
if current_count + count > int(limit):
|
||||
raise HTTPException(400, f'Knowledge base file limit exceeded ({limit} files maximum).')
|
||||
|
||||
|
||||
class KnowledgeUploadValidationForm(BaseModel):
|
||||
count: int = Field(ge=0)
|
||||
file_size: int | None = Field(default=None, ge=0)
|
||||
removed_file_ids: list[str] = Field(default_factory=list)
|
||||
|
||||
|
||||
@router.post('/{id}/files/validate')
|
||||
async def validate_knowledge_upload(
|
||||
id: str,
|
||||
form_data: KnowledgeUploadValidationForm,
|
||||
user=Depends(get_verified_user),
|
||||
db: AsyncSession = Depends(get_async_session),
|
||||
):
|
||||
await _verify_knowledge_write_access(id, user, db)
|
||||
# This is a preflight only. Actual additions recheck capacity without removal credits.
|
||||
await check_knowledge_upload_limits(
|
||||
id,
|
||||
form_data.count,
|
||||
batch=True,
|
||||
file_size=form_data.file_size,
|
||||
exclude_file_ids=form_data.removed_file_ids,
|
||||
db=db,
|
||||
)
|
||||
return {'status': True}
|
||||
|
||||
|
||||
class KnowledgeFileIdForm(BaseModel):
|
||||
|
|
@ -1462,24 +1510,34 @@ async def add_file_to_knowledge_by_id(
|
|||
detail=ERROR_MESSAGES.ACCESS_PROHIBITED,
|
||||
)
|
||||
|
||||
# Add content to the vector database
|
||||
already_linked = await Knowledges.has_file(knowledge_id=id, file_id=form_data.file_id, db=db)
|
||||
if not already_linked:
|
||||
await check_knowledge_upload_limits(
|
||||
id, 1, batch=True, file_size=(file.meta or {}).get('size', 0), exclude_file_ids=[form_data.file_id], db=db
|
||||
)
|
||||
|
||||
linked = None
|
||||
try:
|
||||
# Claim capacity atomically before indexing into the knowledge collection.
|
||||
if not already_linked:
|
||||
linked = await Knowledges.add_file_to_knowledge_by_id(
|
||||
knowledge_id=id,
|
||||
file_id=form_data.file_id,
|
||||
user_id=user.id,
|
||||
directory_id=form_data.directory_id,
|
||||
db=db,
|
||||
)
|
||||
if not linked:
|
||||
raise ValueError(f'Failed to link file {form_data.file_id} to knowledge {id}')
|
||||
await process_file(
|
||||
request,
|
||||
ProcessFileForm(file_id=form_data.file_id, collection_name=id),
|
||||
user=user,
|
||||
db=db,
|
||||
)
|
||||
|
||||
# Add file to knowledge base
|
||||
await Knowledges.add_file_to_knowledge_by_id(
|
||||
knowledge_id=id,
|
||||
file_id=form_data.file_id,
|
||||
user_id=user.id,
|
||||
directory_id=form_data.directory_id,
|
||||
db=db,
|
||||
)
|
||||
except Exception as e:
|
||||
if linked:
|
||||
await Knowledges.remove_file_from_knowledge_by_id(id, form_data.file_id, db=db)
|
||||
log.debug(e)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
|
|
@ -1590,9 +1648,7 @@ async def update_file_from_knowledge_by_id(
|
|||
)
|
||||
|
||||
|
||||
############################
|
||||
# RemoveFileFromKnowledge
|
||||
############################
|
||||
# Remove File From Knowledge
|
||||
|
||||
|
||||
@router.post('/{id}/file/remove', response_model=KnowledgeFilesResponse | None)
|
||||
|
|
@ -1679,9 +1735,7 @@ async def remove_file_from_knowledge_by_id(
|
|||
)
|
||||
|
||||
|
||||
############################
|
||||
# DeleteKnowledgeById
|
||||
############################
|
||||
# Delete Knowledge By Id
|
||||
|
||||
|
||||
@router.delete('/{id}/delete', response_model=bool)
|
||||
|
|
@ -1769,9 +1823,7 @@ async def delete_knowledge_by_id(
|
|||
return result
|
||||
|
||||
|
||||
############################
|
||||
# ResetKnowledgeById
|
||||
############################
|
||||
# Reset Knowledge By Id
|
||||
|
||||
|
||||
@router.post('/{id}/reset', response_model=KnowledgeResponse | None)
|
||||
|
|
@ -1831,9 +1883,7 @@ async def reset_knowledge_by_id(
|
|||
return knowledge
|
||||
|
||||
|
||||
############################
|
||||
# SyncKnowledgeDiff
|
||||
############################
|
||||
# Sync Knowledge Diff
|
||||
|
||||
|
||||
class FileManifestEntry(BaseModel):
|
||||
|
|
@ -1870,7 +1920,7 @@ async def sync_knowledge_diff(
|
|||
"""
|
||||
await _verify_knowledge_write_access(id, user, db)
|
||||
|
||||
# ── Index existing state ──
|
||||
# Index existing state
|
||||
existing_directories = await Knowledges.get_all_directories(id, db=db)
|
||||
|
||||
# Build directory path lookups
|
||||
|
|
@ -1911,7 +1961,7 @@ async def sync_knowledge_diff(
|
|||
'checksum': stored_checksum,
|
||||
}
|
||||
|
||||
# ── Diff files ──
|
||||
# Diff files
|
||||
added: list[dict] = []
|
||||
modified: list[dict] = []
|
||||
deleted: list[dict] = []
|
||||
|
|
@ -1943,7 +1993,19 @@ async def sync_knowledge_diff(
|
|||
if key not in manifest_keys:
|
||||
deleted.append({'file_id': file_info['file_id'], 'filename': key[1]})
|
||||
|
||||
# ── Diff directories ──
|
||||
changed_keys = {(entry['path'], entry['filename']) for entry in added + modified}
|
||||
await check_knowledge_upload_limits(
|
||||
id,
|
||||
len(added) + len(modified),
|
||||
file_size=max(
|
||||
(entry.size for entry in form_data.manifest if (entry.path, entry.filename) in changed_keys), default=0
|
||||
),
|
||||
batch=True,
|
||||
exclude_file_ids=[entry['file_id'] for entry in deleted] + [entry['stale_file_id'] for entry in modified],
|
||||
db=db,
|
||||
)
|
||||
|
||||
# Diff directories
|
||||
required_directory_paths: set[str] = set()
|
||||
for entry in form_data.manifest:
|
||||
if entry.path:
|
||||
|
|
@ -1967,9 +2029,7 @@ async def sync_knowledge_diff(
|
|||
)
|
||||
|
||||
|
||||
############################
|
||||
# SyncKnowledgeCleanup
|
||||
############################
|
||||
# Sync Knowledge Cleanup
|
||||
|
||||
|
||||
class SyncCleanupForm(BaseModel):
|
||||
|
|
@ -1990,7 +2050,7 @@ async def sync_knowledge_cleanup(
|
|||
"""
|
||||
await _verify_knowledge_write_access(id, user, db)
|
||||
|
||||
# ── Remove deleted files ──
|
||||
# Remove deleted files
|
||||
for file_id in form_data.file_ids:
|
||||
file = await Files.get_file_by_id(file_id, db=db)
|
||||
if not file:
|
||||
|
|
@ -2017,7 +2077,7 @@ async def sync_knowledge_cleanup(
|
|||
):
|
||||
await delete_file_resource(file, db)
|
||||
|
||||
# ── Remove orphaned directories (children before parents) ──
|
||||
# Remove orphaned directories (children before parents)
|
||||
for dir_id in reversed(form_data.dir_ids):
|
||||
# Only delete directories that belong to this knowledge base.
|
||||
directory = await Knowledges.get_directory_by_id(dir_id, db=db)
|
||||
|
|
@ -2028,9 +2088,7 @@ async def sync_knowledge_cleanup(
|
|||
return {'status': True}
|
||||
|
||||
|
||||
############################
|
||||
# AddFilesToKnowledge
|
||||
############################
|
||||
# Add Files To Knowledge
|
||||
|
||||
|
||||
@router.post('/{id}/files/batch/add', response_model=KnowledgeFilesResponse | None)
|
||||
|
|
@ -2069,6 +2127,10 @@ async def add_files_to_knowledge_batch(
|
|||
detail=ERROR_MESSAGES.ACCESS_PROHIBITED,
|
||||
)
|
||||
|
||||
batch_limit = await Config.get('knowledge.max_upload_count')
|
||||
if batch_limit is not None and len(form_data) > int(batch_limit):
|
||||
raise HTTPException(400, f'You can only upload a maximum of {batch_limit} file(s) per batch.')
|
||||
|
||||
for directory_id in {form.directory_id for form in form_data if form.directory_id}:
|
||||
await _verify_directory_in_knowledge(id, directory_id, db, detail='Target directory not found.')
|
||||
|
||||
|
|
@ -2112,8 +2174,29 @@ async def add_files_to_knowledge_batch(
|
|||
new_file_ids = {form.file_id for form in new_entries}
|
||||
files = [f for f in files if f.id in new_file_ids]
|
||||
|
||||
# Process files
|
||||
await check_knowledge_upload_limits(
|
||||
id,
|
||||
len(files),
|
||||
file_size=max(((file.meta or {}).get('size', 0) or 0 for file in files), default=0),
|
||||
exclude_file_ids=list(new_file_ids),
|
||||
db=db,
|
||||
)
|
||||
|
||||
# Claim slots before embedding; release them if processing fails.
|
||||
reserved_ids = []
|
||||
dir_map = {form.file_id: form.directory_id for form in new_entries}
|
||||
try:
|
||||
for file in files:
|
||||
linked = await Knowledges.add_file_to_knowledge_by_id(
|
||||
knowledge_id=id,
|
||||
file_id=file.id,
|
||||
user_id=user.id,
|
||||
directory_id=dir_map.get(file.id),
|
||||
db=db,
|
||||
)
|
||||
if not linked:
|
||||
raise ValueError(f'Failed to link file {file.id} to knowledge {id}')
|
||||
reserved_ids.append(file.id)
|
||||
result = await process_files_batch(
|
||||
request=request,
|
||||
form_data=BatchProcessFilesForm(files=files, collection_name=id),
|
||||
|
|
@ -2121,20 +2204,14 @@ async def add_files_to_knowledge_batch(
|
|||
db=db,
|
||||
)
|
||||
except Exception as e:
|
||||
for file_id in reserved_ids:
|
||||
await Knowledges.remove_file_from_knowledge_by_id(id, file_id, db=db)
|
||||
log.error(f'add_files_to_knowledge_batch: Exception occurred: {e}', exc_info=True)
|
||||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))
|
||||
|
||||
# Only add files that were successfully processed
|
||||
successful_file_ids = [r.file_id for r in result.results if r.status == 'completed']
|
||||
dir_map = {form.file_id: form.directory_id for form in new_entries}
|
||||
for file_id in successful_file_ids:
|
||||
await Knowledges.add_file_to_knowledge_by_id(
|
||||
knowledge_id=id,
|
||||
file_id=file_id,
|
||||
user_id=user.id,
|
||||
directory_id=dir_map.get(file_id),
|
||||
db=db,
|
||||
)
|
||||
for file_id in set(reserved_ids) - set(successful_file_ids):
|
||||
await Knowledges.remove_file_from_knowledge_by_id(id, file_id, db=db)
|
||||
|
||||
# If there were any errors, include them in the response
|
||||
if result.errors:
|
||||
|
|
@ -2154,9 +2231,7 @@ async def add_files_to_knowledge_batch(
|
|||
)
|
||||
|
||||
|
||||
############################
|
||||
# ExportKnowledgeById
|
||||
############################
|
||||
# Export Knowledge By Id
|
||||
|
||||
|
||||
@router.get('/{id}/export')
|
||||
|
|
@ -2202,9 +2277,7 @@ async def export_knowledge_by_id(id: str, user=Depends(get_admin_user), db: Asyn
|
|||
)
|
||||
|
||||
|
||||
############################
|
||||
# Directory endpoints
|
||||
############################
|
||||
|
||||
|
||||
class KnowledgeDirectoryCreateForm(BaseModel):
|
||||
|
|
|
|||
|
|
@ -45,11 +45,9 @@ async def check_memories_permission(user):
|
|||
)
|
||||
|
||||
|
||||
############################
|
||||
# GetMemories
|
||||
# Get Memories
|
||||
# Let what is remembered here spare someone the cost
|
||||
# of learning it twice.
|
||||
############################
|
||||
|
||||
|
||||
@router.get('/', response_model=list[MemoryModel])
|
||||
|
|
@ -63,9 +61,7 @@ async def get_memories(
|
|||
return await Memories.get_memories_by_user_id(user.id, db=db)
|
||||
|
||||
|
||||
############################
|
||||
# AddMemory
|
||||
############################
|
||||
# Add Memory
|
||||
|
||||
|
||||
class AddMemoryForm(BaseModel):
|
||||
|
|
@ -316,9 +312,7 @@ async def update_memories(
|
|||
return response
|
||||
|
||||
|
||||
############################
|
||||
# QueryMemory
|
||||
############################
|
||||
# Query Memory
|
||||
|
||||
|
||||
class QueryMemoryForm(BaseModel):
|
||||
|
|
@ -332,10 +326,7 @@ async def query_memory(
|
|||
form_data: QueryMemoryForm,
|
||||
user=Depends(get_verified_user),
|
||||
):
|
||||
# NOTE: We intentionally do NOT use Depends(get_async_session) here.
|
||||
# Database operations (get_memories_by_user_id) manage their own short-lived sessions.
|
||||
# This prevents holding a connection during EMBEDDING_FUNCTION()
|
||||
# which makes external embedding API calls (1-5+ seconds).
|
||||
# Let DB helpers own short-lived sessions so remote calls and streams do not hold pool connections.
|
||||
await check_memories_permission(user)
|
||||
|
||||
memories = await Memories.get_memories_by_user_id(user.id)
|
||||
|
|
@ -352,12 +343,7 @@ async def query_memory(
|
|||
limit=form_data.k,
|
||||
)
|
||||
|
||||
# Filter results by relevance threshold to avoid returning unrelated
|
||||
# memories. Vector similarity search always returns the top-K nearest
|
||||
# neighbours even when they are completely irrelevant; applying the
|
||||
# same RELEVANCE_THRESHOLD used by RAG ensures only genuinely matching
|
||||
# memories are surfaced (distances are normalised to 0→1, higher is
|
||||
# better).
|
||||
# Apply the RAG relevance threshold; top-K results can include unrelated memories.
|
||||
relevance_threshold = await Config.get('rag.relevance_threshold', 0.0)
|
||||
if results and relevance_threshold > 0.0 and results.distances and results.distances[0]:
|
||||
from open_webui.retrieval.vector.main import SearchResult
|
||||
|
|
@ -442,9 +428,7 @@ async def read_memory_path(
|
|||
}
|
||||
|
||||
|
||||
############################
|
||||
# ReindexMemoryVectorDB
|
||||
############################
|
||||
# Reindex Memory Vector DB
|
||||
@router.post('/reindex')
|
||||
async def reindex_memories_from_vector_db(
|
||||
request: Request,
|
||||
|
|
@ -506,9 +490,7 @@ async def reset_memory_from_vector_db(
|
|||
return True
|
||||
|
||||
|
||||
############################
|
||||
# DeleteMemoriesByUserId
|
||||
############################
|
||||
# Delete Memories By User Id
|
||||
|
||||
|
||||
@router.delete('/delete/user', response_model=bool)
|
||||
|
|
@ -538,9 +520,7 @@ async def delete_memory_by_user_id(
|
|||
return False
|
||||
|
||||
|
||||
############################
|
||||
# UpdateMemoryById
|
||||
############################
|
||||
# Update Memory By Id
|
||||
|
||||
|
||||
@router.post('/{memory_id}/update', response_model=MemoryModel | None)
|
||||
|
|
@ -550,10 +530,7 @@ async def update_memory_by_id(
|
|||
form_data: MemoryUpdateModel,
|
||||
user=Depends(get_verified_user),
|
||||
):
|
||||
# NOTE: We intentionally do NOT use Depends(get_async_session) here.
|
||||
# Database operations (update_memory_by_id_and_user_id) manage their own
|
||||
# short-lived sessions. This prevents holding a connection during
|
||||
# EMBEDDING_FUNCTION() which makes external API calls (1-5+ seconds).
|
||||
# Let DB helpers own short-lived sessions so remote calls and streams do not hold pool connections.
|
||||
await check_memories_permission(user)
|
||||
|
||||
content = clean_memory_content(form_data.content) if form_data.content is not None else None
|
||||
|
|
@ -602,9 +579,7 @@ async def update_memory_by_id(
|
|||
return memory
|
||||
|
||||
|
||||
############################
|
||||
# DeleteMemoryById
|
||||
############################
|
||||
# Delete Memory By Id
|
||||
|
||||
|
||||
@router.delete('/{memory_id}', response_model=bool)
|
||||
|
|
|
|||
|
|
@ -214,11 +214,7 @@ async def _verify_knowledge_file_access(
|
|||
)
|
||||
|
||||
|
||||
###########################
|
||||
# GetModels
|
||||
# Let each model here be judged by what it does and not
|
||||
# by what it claims. The house deserves honest servants.
|
||||
###########################
|
||||
# Get Models
|
||||
|
||||
|
||||
PAGE_ITEM_COUNT = 30
|
||||
|
|
@ -302,9 +298,7 @@ async def get_models(
|
|||
)
|
||||
|
||||
|
||||
###########################
|
||||
# GetBaseModels
|
||||
###########################
|
||||
# Get Base Models
|
||||
|
||||
|
||||
@router.get('/all', response_model=list[ModelResponse])
|
||||
|
|
@ -327,9 +321,7 @@ async def get_base_models(
|
|||
return await Models.get_base_models(tag=tag, db=db)
|
||||
|
||||
|
||||
###########################
|
||||
# GetModelTags
|
||||
###########################
|
||||
# Get Model Tags
|
||||
|
||||
|
||||
@router.get('/tags', response_model=list[str])
|
||||
|
|
@ -342,9 +334,7 @@ async def get_model_tags(user=Depends(get_verified_user), db: AsyncSession = Dep
|
|||
return sorted(tags)
|
||||
|
||||
|
||||
############################
|
||||
# CreateNewModel
|
||||
############################
|
||||
# Create New Model
|
||||
|
||||
|
||||
@router.post('/create', response_model=ModelModel | None)
|
||||
|
|
@ -436,9 +426,7 @@ async def create_new_model(
|
|||
return model_response(model)
|
||||
|
||||
|
||||
############################
|
||||
# ExportModels
|
||||
############################
|
||||
# Export Models
|
||||
|
||||
|
||||
class ModelExportResponse(ModelModel):
|
||||
|
|
@ -496,9 +484,7 @@ async def export_models(
|
|||
return exported
|
||||
|
||||
|
||||
############################
|
||||
# ImportModels
|
||||
############################
|
||||
# Import Models
|
||||
|
||||
|
||||
class ModelsImportForm(BaseModel):
|
||||
|
|
@ -737,9 +723,7 @@ async def import_models(
|
|||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
|
||||
############################
|
||||
# SyncModels
|
||||
############################
|
||||
# Sync Models
|
||||
|
||||
|
||||
class SyncModelsForm(BaseModel):
|
||||
|
|
@ -776,9 +760,7 @@ async def sync_models(
|
|||
return models
|
||||
|
||||
|
||||
###########################
|
||||
# GetModelById
|
||||
###########################
|
||||
# Get Model By Id
|
||||
|
||||
|
||||
class ModelIdForm(BaseModel):
|
||||
|
|
@ -835,9 +817,7 @@ async def get_model_by_id(id: str, user=Depends(get_verified_user), db: AsyncSes
|
|||
)
|
||||
|
||||
|
||||
###########################
|
||||
# GetModelById
|
||||
###########################
|
||||
# Get Model By Id
|
||||
|
||||
|
||||
async def authorized_model_history(id, user, db):
|
||||
|
|
@ -1084,9 +1064,7 @@ async def get_model_profile_image(
|
|||
)
|
||||
|
||||
|
||||
############################
|
||||
# ToggleModelById
|
||||
############################
|
||||
# Toggle Model By Id
|
||||
|
||||
|
||||
@router.post('/model/toggle', response_model=ModelResponse | None)
|
||||
|
|
@ -1135,9 +1113,7 @@ async def toggle_model_by_id(
|
|||
)
|
||||
|
||||
|
||||
############################
|
||||
# UpdateModelById
|
||||
############################
|
||||
# Update Model By Id
|
||||
|
||||
|
||||
@router.post('/model/update', response_model=ModelModel | None)
|
||||
|
|
@ -1212,9 +1188,7 @@ async def update_model_by_id(
|
|||
return model_response(model)
|
||||
|
||||
|
||||
############################
|
||||
# UpdateModelAccessById
|
||||
############################
|
||||
# Update Model Access By Id
|
||||
|
||||
|
||||
class ModelAccessGrantsForm(BaseModel):
|
||||
|
|
@ -1294,9 +1268,7 @@ async def update_model_access_by_id(
|
|||
return model_response(model)
|
||||
|
||||
|
||||
############################
|
||||
# DeleteModelById
|
||||
############################
|
||||
# Delete Model By Id
|
||||
|
||||
|
||||
@router.post('/model/delete', response_model=bool)
|
||||
|
|
|
|||
|
|
@ -95,9 +95,7 @@ async def leave_note_rooms_for_revoked_users(
|
|||
await leave_room_for_users(room, user_ids)
|
||||
|
||||
|
||||
############################
|
||||
# GetNotes
|
||||
############################
|
||||
# Get Notes
|
||||
|
||||
|
||||
class NoteItemResponse(BaseModel):
|
||||
|
|
@ -148,9 +146,7 @@ async def get_notes(
|
|||
]
|
||||
|
||||
|
||||
############################
|
||||
# GetPinnedNotes
|
||||
############################
|
||||
# Get Pinned Notes
|
||||
|
||||
|
||||
@router.get('/pinned', response_model=list[NoteItemResponse])
|
||||
|
|
@ -229,9 +225,7 @@ async def search_notes(
|
|||
return result
|
||||
|
||||
|
||||
############################
|
||||
# CreateNewNote
|
||||
############################
|
||||
# Create New Note
|
||||
|
||||
|
||||
@router.post('/create', response_model=Optional[NoteModel])
|
||||
|
|
@ -270,9 +264,7 @@ async def create_new_note(
|
|||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.DEFAULT())
|
||||
|
||||
|
||||
############################
|
||||
# GetNoteById
|
||||
############################
|
||||
# Get Note By Id
|
||||
|
||||
|
||||
class NoteResponse(NoteModel):
|
||||
|
|
@ -521,9 +513,7 @@ async def create_note_chat_by_id(
|
|||
return chat
|
||||
|
||||
|
||||
############################
|
||||
# UpdateNoteById
|
||||
############################
|
||||
# Update Note By Id
|
||||
|
||||
|
||||
@router.post('/{id}/update', response_model=Optional[NoteModel])
|
||||
|
|
@ -609,9 +599,7 @@ async def update_note_pages(
|
|||
return await update_note_by_id(request, id, NoteUpdateForm(page_operation=form_data), user, db)
|
||||
|
||||
|
||||
############################
|
||||
# UpdateNoteAccessById
|
||||
############################
|
||||
# Update Note Access By Id
|
||||
|
||||
|
||||
class NoteAccessGrantsForm(BaseModel):
|
||||
|
|
@ -667,9 +655,7 @@ async def update_note_access_by_id(
|
|||
return note
|
||||
|
||||
|
||||
############################
|
||||
# PinNoteById
|
||||
############################
|
||||
# Pin Note By Id
|
||||
|
||||
|
||||
@router.post('/{id}/pin', response_model=Optional[NoteModel])
|
||||
|
|
@ -710,9 +696,7 @@ async def pin_note_by_id(
|
|||
return note
|
||||
|
||||
|
||||
############################
|
||||
# DeleteNoteById
|
||||
############################
|
||||
# Delete Note By Id
|
||||
|
||||
|
||||
@router.delete('/{id}/delete', response_model=bool)
|
||||
|
|
|
|||
|
|
@ -1,8 +1,16 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
import logging
|
||||
import time
|
||||
from uuid import UUID
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request, status
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, Request, status
|
||||
from sqlalchemy import and_, func, or_, select, update
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from open_webui.internal.db import get_async_session
|
||||
from open_webui.models.notifications import Notification, emit_changes
|
||||
from open_webui.utils.inbox import hydrate, visible_clause
|
||||
from pydantic import BaseModel
|
||||
|
||||
from open_webui.constants import ERROR_MESSAGES
|
||||
|
|
@ -21,6 +29,121 @@ from open_webui.utils.notifications import (
|
|||
|
||||
router = APIRouter()
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
async def _check_notifications_enabled():
|
||||
if not await Config.get('notifications.enable'):
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=ERROR_MESSAGES.NOT_FOUND)
|
||||
|
||||
|
||||
async def inbox_page(user, cursor=None, limit=20, clause=None, *, db):
|
||||
started = time.monotonic()
|
||||
if clause is None:
|
||||
clause = await visible_clause(user, db=db)
|
||||
query = select(Notification).where(clause)
|
||||
if cursor:
|
||||
try:
|
||||
timestamp, id = cursor.split(':', 1)
|
||||
timestamp = int(timestamp)
|
||||
UUID(id)
|
||||
if not 0 <= timestamp <= 2**63 - 1:
|
||||
raise ValueError()
|
||||
except (ValueError, TypeError):
|
||||
raise HTTPException(422, 'Invalid inbox cursor')
|
||||
query = query.where(
|
||||
or_(Notification.created_at < timestamp, and_(Notification.created_at == timestamp, Notification.id < id))
|
||||
)
|
||||
rows = (
|
||||
await db.scalars(query.order_by(Notification.created_at.desc(), Notification.id.desc()).limit(limit + 1))
|
||||
).all()
|
||||
more = len(rows) > limit
|
||||
rows = rows[:limit]
|
||||
result = {
|
||||
'items': await hydrate(rows, db=db),
|
||||
'next_cursor': f'{rows[-1].created_at}:{rows[-1].id}' if more else None,
|
||||
}
|
||||
log.debug('Inbox page loaded in %.3fs', time.monotonic() - started)
|
||||
return result
|
||||
|
||||
|
||||
@router.get('/inbox')
|
||||
async def get_inbox(
|
||||
cursor: str | None = Query(None, max_length=100),
|
||||
limit: int = Query(20, ge=1, le=50),
|
||||
user=Depends(get_verified_user),
|
||||
db: AsyncSession = Depends(get_async_session),
|
||||
):
|
||||
await _check_notifications_enabled()
|
||||
return await inbox_page(user, cursor, limit, db=db)
|
||||
|
||||
|
||||
@router.get('/inbox/count')
|
||||
async def get_inbox_count(user=Depends(get_verified_user), db: AsyncSession = Depends(get_async_session)):
|
||||
await _check_notifications_enabled()
|
||||
started = time.monotonic()
|
||||
clause = await visible_clause(user, db=db)
|
||||
count = await db.scalar(
|
||||
select(func.count()).select_from(Notification).where(clause, Notification.seen_at.is_(None))
|
||||
)
|
||||
log.debug('Inbox count loaded in %.3fs', time.monotonic() - started)
|
||||
return {'count': count}
|
||||
|
||||
|
||||
@router.post('/inbox/open')
|
||||
async def open_inbox(user=Depends(get_verified_user), db: AsyncSession = Depends(get_async_session)):
|
||||
await _check_notifications_enabled()
|
||||
clause = await visible_clause(user, db=db)
|
||||
now = time.time_ns()
|
||||
# A single UPDATE acknowledges only rows visible to this statement. A late
|
||||
# commit with an older created_at must remain unseen (no timestamp watermark).
|
||||
result = await db.execute(
|
||||
update(Notification)
|
||||
.where(clause, Notification.seen_at.is_(None))
|
||||
.values(seen_at=now, updated_at=now)
|
||||
.returning(Notification.id)
|
||||
.execution_options(synchronize_session=False)
|
||||
)
|
||||
# SQLite reports rowcount=-1 for UPDATEs containing the recursive folder CTE.
|
||||
acknowledged = len(result.scalars().all())
|
||||
await db.commit()
|
||||
await emit_changes({user.id})
|
||||
page = await inbox_page(user, clause=clause, db=db)
|
||||
for item in page['items']:
|
||||
item['is_new'] = item['seen_at'] == str(now) or item['seen_at'] is None
|
||||
page.update(
|
||||
acknowledged_count=acknowledged,
|
||||
acknowledged_at=str(now),
|
||||
count=await db.scalar(
|
||||
select(func.count()).select_from(Notification).where(clause, Notification.seen_at.is_(None))
|
||||
),
|
||||
)
|
||||
return page
|
||||
|
||||
|
||||
@router.patch('/inbox/{id}')
|
||||
async def read_inbox_item(id: str, user=Depends(get_verified_user), db: AsyncSession = Depends(get_async_session)):
|
||||
await _check_notifications_enabled()
|
||||
clause = await visible_clause(user, db=db)
|
||||
now = time.time_ns()
|
||||
row = await db.scalar(
|
||||
update(Notification)
|
||||
.where(clause, Notification.id == id)
|
||||
.values(
|
||||
seen_at=func.coalesce(Notification.seen_at, now),
|
||||
read_at=func.coalesce(Notification.read_at, now),
|
||||
updated_at=now,
|
||||
)
|
||||
.returning(Notification)
|
||||
.execution_options(populate_existing=True)
|
||||
)
|
||||
if not row:
|
||||
raise HTTPException(404, 'Notification not found')
|
||||
response = (await hydrate([row], db=db))[0]
|
||||
await db.commit()
|
||||
await emit_changes({user.id})
|
||||
return response
|
||||
|
||||
|
||||
class NotificationTargetForm(BaseModel):
|
||||
id: str | None = None
|
||||
|
|
|
|||
|
|
@ -189,11 +189,7 @@ def get_api_key(idx, url, configs):
|
|||
return configs.get(str(idx), configs.get(base_url, {})).get('key', None) # Legacy support
|
||||
|
||||
|
||||
##########################################
|
||||
#
|
||||
# API routes
|
||||
#
|
||||
##########################################
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
|
@ -1138,10 +1134,7 @@ async def generate_chat_completion(
|
|||
if not await Config.get('ollama.enable'):
|
||||
raise HTTPException(status_code=503, detail=ERROR_MESSAGES.OLLAMA_API_DISABLED)
|
||||
|
||||
# NOTE: We intentionally do NOT use Depends(get_async_session) here.
|
||||
# Database operations (get_model_by_id, AccessGrants.has_access) manage their own short-lived sessions.
|
||||
# This prevents holding a connection during the entire LLM call (30-60+ seconds),
|
||||
# which would exhaust the connection pool under concurrent load.
|
||||
# Let DB helpers own short-lived sessions so remote calls and streams do not hold pool connections.
|
||||
|
||||
# bypass_filter and bypass_system_prompt are read from request.state to prevent
|
||||
# external clients from setting them via query parameter. Only internal
|
||||
|
|
@ -1254,10 +1247,7 @@ async def generate_openai_completion(
|
|||
user=Depends(get_verified_user), # noqa: B008
|
||||
):
|
||||
"""Forward a text completion request via the OpenAI-compatible proxy."""
|
||||
# NOTE: We intentionally do NOT use Depends(get_async_session) here.
|
||||
# Database operations (get_model_by_id, AccessGrants.has_access) manage their own short-lived sessions.
|
||||
# This prevents holding a connection during the entire LLM call (30-60+ seconds),
|
||||
# which would exhaust the connection pool under concurrent load.
|
||||
# Let DB helpers own short-lived sessions so remote calls and streams do not hold pool connections.
|
||||
metadata = form_data.pop('metadata', None)
|
||||
|
||||
try:
|
||||
|
|
@ -1359,10 +1349,7 @@ async def generate_openai_chat_completion(
|
|||
user=Depends(get_verified_user), # noqa: B008
|
||||
):
|
||||
"""Forward a chat completion request via the OpenAI-compatible proxy."""
|
||||
# NOTE: We intentionally do NOT use Depends(get_async_session) here.
|
||||
# Database operations (get_model_by_id, AccessGrants.has_access) manage their own short-lived sessions.
|
||||
# This prevents holding a connection during the entire LLM call (30-60+ seconds),
|
||||
# which would exhaust the connection pool under concurrent load.
|
||||
# Let DB helpers own short-lived sessions so remote calls and streams do not hold pool connections.
|
||||
metadata = form_data.pop('metadata', None)
|
||||
|
||||
try:
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ import asyncio
|
|||
import hashlib
|
||||
import logging
|
||||
import re
|
||||
import time
|
||||
from typing import Optional
|
||||
from urllib.parse import quote, urlparse
|
||||
|
||||
|
|
@ -48,6 +49,7 @@ from open_webui.utils.payload import (
|
|||
apply_model_params_to_body_openai,
|
||||
apply_system_prompt_to_body,
|
||||
)
|
||||
from open_webui.utils.response import convert_responses_usage_to_chat_completions, get_responses_finish_reason
|
||||
from open_webui.utils.session_pool import (
|
||||
cleanup_response,
|
||||
get_client_timeout,
|
||||
|
|
@ -60,13 +62,9 @@ from sqlalchemy.ext.asyncio import AsyncSession
|
|||
log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
##########################################
|
||||
#
|
||||
# Utility functions
|
||||
# Let the responses returned through this gate be worth
|
||||
# the question that summoned them.
|
||||
#
|
||||
##########################################
|
||||
|
||||
# Headers that become stale after aiohttp auto-decompresses the upstream
|
||||
# response body. Forwarding them verbatim causes desktop / programmatic
|
||||
|
|
@ -150,11 +148,7 @@ def openai_reasoning_model_handler(payload):
|
|||
return payload
|
||||
|
||||
|
||||
##########################################
|
||||
#
|
||||
# API routes
|
||||
#
|
||||
##########################################
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
|
@ -1363,12 +1357,15 @@ def convert_responses_result(response: dict) -> dict:
|
|||
output_items = response.get('output', [])
|
||||
|
||||
content = ''
|
||||
refusal = ''
|
||||
tool_calls = []
|
||||
for item in output_items:
|
||||
if item.get('type') == 'message':
|
||||
for part in item.get('content', []):
|
||||
if part.get('type') == 'output_text':
|
||||
content += part.get('text', '')
|
||||
elif part.get('type') == 'refusal':
|
||||
refusal += part.get('refusal', '')
|
||||
elif item.get('type') == 'function_call':
|
||||
arguments = item.get('arguments', '{}')
|
||||
if not isinstance(arguments, str):
|
||||
|
|
@ -1387,6 +1384,7 @@ def convert_responses_result(response: dict) -> dict:
|
|||
return {
|
||||
'id': response.get('id', ''),
|
||||
'object': 'chat.completion',
|
||||
'created': response.get('created_at') or int(time.time()),
|
||||
'model': response.get('model', ''),
|
||||
'choices': [
|
||||
{
|
||||
|
|
@ -1394,12 +1392,13 @@ def convert_responses_result(response: dict) -> dict:
|
|||
'message': {
|
||||
'role': 'assistant',
|
||||
'content': content,
|
||||
**({'refusal': refusal} if refusal else {}),
|
||||
**({'tool_calls': tool_calls} if tool_calls else {}),
|
||||
},
|
||||
'finish_reason': 'tool_calls' if tool_calls else 'stop',
|
||||
'finish_reason': get_responses_finish_reason(response, bool(tool_calls)),
|
||||
}
|
||||
],
|
||||
'usage': response.get('usage', {}),
|
||||
'usage': convert_responses_usage_to_chat_completions(response.get('usage')) or None,
|
||||
}
|
||||
|
||||
|
||||
|
|
@ -1412,10 +1411,7 @@ async def generate_chat_completion(
|
|||
if not await Config.get('openai.enable'):
|
||||
raise HTTPException(status_code=503, detail='OpenAI API is disabled')
|
||||
|
||||
# NOTE: We intentionally do NOT use Depends(get_async_session) here.
|
||||
# Database operations (get_model_by_id, AccessGrants.has_access) manage their own short-lived sessions.
|
||||
# This prevents holding a connection during the entire LLM call (30-60+ seconds),
|
||||
# which would exhaust the connection pool under concurrent load.
|
||||
# Let DB helpers own short-lived sessions so remote calls and streams do not hold pool connections.
|
||||
|
||||
# bypass_filter and bypass_system_prompt are read from request.state to prevent
|
||||
# external clients from setting them via query parameter. Only internal
|
||||
|
|
|
|||
|
|
@ -29,13 +29,9 @@ from starlette.responses import FileResponse
|
|||
log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
##################################
|
||||
#
|
||||
# Pipeline Middleware
|
||||
# Every hand this passes through can corrupt it or
|
||||
# improve it. Let each stage leave it better than it found.
|
||||
#
|
||||
##################################
|
||||
|
||||
|
||||
def get_sorted_filters(model_id, models):
|
||||
|
|
@ -192,11 +188,7 @@ async def process_pipeline_outlet_filter(request, payload, user, models):
|
|||
return payload
|
||||
|
||||
|
||||
##################################
|
||||
#
|
||||
# Pipelines Endpoints
|
||||
#
|
||||
##################################
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
|
|
|||
|
|
@ -44,11 +44,9 @@ router = APIRouter()
|
|||
PAGE_ITEM_COUNT = 30
|
||||
|
||||
|
||||
############################
|
||||
# GetPrompts
|
||||
# Get Prompts
|
||||
# The hardest part is knowing what to ask. Let the right
|
||||
# question already be here when it is needed.
|
||||
############################
|
||||
|
||||
|
||||
@router.get('/', response_model=list[PromptModel])
|
||||
|
|
@ -135,9 +133,7 @@ async def get_prompt_list(
|
|||
)
|
||||
|
||||
|
||||
############################
|
||||
# CreateNewPrompt
|
||||
############################
|
||||
# Create New Prompt
|
||||
|
||||
|
||||
@router.post('/create', response_model=PromptModel | None)
|
||||
|
|
@ -197,9 +193,7 @@ async def create_new_prompt(
|
|||
)
|
||||
|
||||
|
||||
############################
|
||||
# GetPromptById
|
||||
############################
|
||||
# Get Prompt By Id
|
||||
|
||||
|
||||
@router.get('/id/{prompt_id}', response_model=PromptAccessResponse | None)
|
||||
|
|
@ -241,9 +235,7 @@ async def get_prompt_by_id(
|
|||
)
|
||||
|
||||
|
||||
############################
|
||||
# UpdatePromptById
|
||||
############################
|
||||
# Update Prompt By Id
|
||||
|
||||
|
||||
@router.post('/id/{prompt_id}/update', response_model=PromptModel | None)
|
||||
|
|
@ -307,9 +299,7 @@ async def update_prompt_by_id(
|
|||
)
|
||||
|
||||
|
||||
############################
|
||||
# UpdatePromptMetadata
|
||||
############################
|
||||
# Update Prompt Metadata
|
||||
|
||||
|
||||
@router.post('/id/{prompt_id}/update/meta', response_model=PromptModel | None)
|
||||
|
|
@ -421,9 +411,7 @@ async def set_prompt_version(
|
|||
)
|
||||
|
||||
|
||||
############################
|
||||
# UpdatePromptAccessById
|
||||
############################
|
||||
# Update Prompt Access By Id
|
||||
|
||||
|
||||
class PromptAccessGrantsForm(BaseModel):
|
||||
|
|
@ -482,9 +470,7 @@ async def update_prompt_access_by_id(
|
|||
return updated_prompt
|
||||
|
||||
|
||||
############################
|
||||
# TogglePromptActiveById
|
||||
############################
|
||||
# Toggle Prompt Active By Id
|
||||
|
||||
|
||||
@router.post('/id/{prompt_id}/toggle', response_model=PromptModel | None)
|
||||
|
|
@ -535,9 +521,7 @@ async def toggle_prompt_active(
|
|||
)
|
||||
|
||||
|
||||
############################
|
||||
# DeletePromptById
|
||||
############################
|
||||
# Delete Prompt By Id
|
||||
|
||||
|
||||
@router.delete('/id/{prompt_id}/delete', response_model=bool)
|
||||
|
|
@ -583,9 +567,7 @@ async def delete_prompt_by_id(
|
|||
return result
|
||||
|
||||
|
||||
############################
|
||||
# Prompt History Endpoints
|
||||
############################
|
||||
|
||||
|
||||
@router.get('/id/{prompt_id}/history', response_model=list[PromptHistoryResponse])
|
||||
|
|
|
|||
|
|
@ -135,13 +135,9 @@ log = logging.getLogger(__name__)
|
|||
|
||||
TIKTOKEN_DISALLOWED_SPECIAL = ()
|
||||
|
||||
##########################################
|
||||
#
|
||||
# Utility functions
|
||||
# Give us this day our relevant chunks, and lead us
|
||||
# not into hallucination, but deliver us from noise.
|
||||
#
|
||||
##########################################
|
||||
# Let us find what is true among the many voices,
|
||||
# and let us not mistake the loudest answer for the wisest.
|
||||
|
||||
|
||||
def get_ef(
|
||||
|
|
@ -240,11 +236,7 @@ def get_rf(
|
|||
return rf
|
||||
|
||||
|
||||
##########################################
|
||||
#
|
||||
# API routes
|
||||
#
|
||||
##########################################
|
||||
|
||||
|
||||
RETRIEVAL_CONFIG_KEYS = {
|
||||
|
|
@ -305,6 +297,9 @@ RETRIEVAL_CONFIG_KEYS = {
|
|||
'FILE_IMAGE_COMPRESSION_HEIGHT': 'file.image_compression_height',
|
||||
'FILE_IMAGE_COMPRESSION_WIDTH': 'file.image_compression_width',
|
||||
'FILE_MAX_COUNT': 'rag.file.max_count',
|
||||
'KNOWLEDGE_MAX_UPLOAD_COUNT': 'knowledge.max_upload_count',
|
||||
'KNOWLEDGE_MAX_FILE_COUNT': 'knowledge.max_file_count',
|
||||
'KNOWLEDGE_MAX_FILE_SIZE': 'knowledge.max_file_size',
|
||||
'FILE_MAX_SIZE': 'rag.file.max_size',
|
||||
'FIRECRAWL_API_BASE_URL': 'web.loader.firecrawl_api_url',
|
||||
'FIRECRAWL_API_KEY': 'web.loader.firecrawl_api_key',
|
||||
|
|
@ -684,6 +679,9 @@ async def get_rag_config(request: Request, user=Depends(get_admin_user)):
|
|||
# File upload settings
|
||||
'FILE_MAX_SIZE': config['rag.file.max_size'],
|
||||
'FILE_MAX_COUNT': config['rag.file.max_count'],
|
||||
'KNOWLEDGE_MAX_UPLOAD_COUNT': config['knowledge.max_upload_count'],
|
||||
'KNOWLEDGE_MAX_FILE_COUNT': config['knowledge.max_file_count'],
|
||||
'KNOWLEDGE_MAX_FILE_SIZE': config['knowledge.max_file_size'],
|
||||
'FILE_IMAGE_COMPRESSION_WIDTH': config['file.image_compression_width'],
|
||||
'FILE_IMAGE_COMPRESSION_HEIGHT': config['file.image_compression_height'],
|
||||
'ALLOWED_FILE_EXTENSIONS': config['rag.file.allowed_extensions'],
|
||||
|
|
@ -935,6 +933,9 @@ class ConfigForm(BaseModel):
|
|||
# File upload settings
|
||||
FILE_MAX_SIZE: Union[int, str | None] = None
|
||||
FILE_MAX_COUNT: Union[int, str | None] = None
|
||||
KNOWLEDGE_MAX_UPLOAD_COUNT: Union[int, str | None] = None
|
||||
KNOWLEDGE_MAX_FILE_COUNT: Union[int, str | None] = None
|
||||
KNOWLEDGE_MAX_FILE_SIZE: Union[int, str | None] = None
|
||||
FILE_IMAGE_COMPRESSION_WIDTH: Union[int, str | None] = None
|
||||
FILE_IMAGE_COMPRESSION_HEIGHT: Union[int, str | None] = None
|
||||
ALLOWED_FILE_EXTENSIONS: list[str] | None = None
|
||||
|
|
@ -998,10 +999,35 @@ async def update_rag_config(request: Request, form_data: ConfigForm, user=Depend
|
|||
}
|
||||
if form_data.RAG_TOKENIZER_MODEL is not None:
|
||||
updates['rag.tokenizer_model'] = form_data.RAG_TOKENIZER_MODEL.strip()
|
||||
for field in ('FILE_MAX_SIZE', 'FILE_MAX_COUNT', 'FILE_IMAGE_COMPRESSION_WIDTH', 'FILE_IMAGE_COMPRESSION_HEIGHT'):
|
||||
for field in (
|
||||
'FILE_MAX_SIZE',
|
||||
'FILE_MAX_COUNT',
|
||||
'KNOWLEDGE_MAX_UPLOAD_COUNT',
|
||||
'KNOWLEDGE_MAX_FILE_COUNT',
|
||||
'KNOWLEDGE_MAX_FILE_SIZE',
|
||||
'FILE_IMAGE_COMPRESSION_WIDTH',
|
||||
'FILE_IMAGE_COMPRESSION_HEIGHT',
|
||||
):
|
||||
if getattr(form_data, field) == '':
|
||||
updates[RETRIEVAL_CONFIG_KEYS[field]] = None
|
||||
|
||||
for field, label in (
|
||||
('KNOWLEDGE_MAX_UPLOAD_COUNT', 'Knowledge batch upload limit'),
|
||||
('KNOWLEDGE_MAX_FILE_COUNT', 'Knowledge file count limit'),
|
||||
('KNOWLEDGE_MAX_FILE_SIZE', 'Knowledge file size limit'),
|
||||
):
|
||||
value = getattr(form_data, field)
|
||||
if field in form_data.model_fields_set and value is None:
|
||||
updates[RETRIEVAL_CONFIG_KEYS[field]] = None
|
||||
if value not in (None, ''):
|
||||
try:
|
||||
value = int(value)
|
||||
if value <= 0:
|
||||
raise ValueError
|
||||
except (TypeError, ValueError):
|
||||
raise HTTPException(400, f'{label} must be a positive integer.')
|
||||
updates[RETRIEVAL_CONFIG_KEYS[field]] = value
|
||||
|
||||
# Unload the previous internal reranker before applying its new settings.
|
||||
if config['rag.reranking_engine'] == '':
|
||||
request.app.state.rf = None
|
||||
|
|
@ -1116,6 +1142,9 @@ async def update_rag_config(request: Request, form_data: ConfigForm, user=Depend
|
|||
# File upload settings
|
||||
'FILE_MAX_SIZE': config['rag.file.max_size'],
|
||||
'FILE_MAX_COUNT': config['rag.file.max_count'],
|
||||
'KNOWLEDGE_MAX_UPLOAD_COUNT': config['knowledge.max_upload_count'],
|
||||
'KNOWLEDGE_MAX_FILE_COUNT': config['knowledge.max_file_count'],
|
||||
'KNOWLEDGE_MAX_FILE_SIZE': config['knowledge.max_file_size'],
|
||||
'FILE_IMAGE_COMPRESSION_WIDTH': config['file.image_compression_width'],
|
||||
'FILE_IMAGE_COMPRESSION_HEIGHT': config['file.image_compression_height'],
|
||||
'ALLOWED_FILE_EXTENSIONS': config['rag.file.allowed_extensions'],
|
||||
|
|
@ -1206,11 +1235,7 @@ async def update_rag_config(request: Request, form_data: ConfigForm, user=Depend
|
|||
}
|
||||
|
||||
|
||||
####################################
|
||||
#
|
||||
# Document process and retrieval
|
||||
#
|
||||
####################################
|
||||
|
||||
|
||||
def can_merge_chunks(a: Document, b: Document) -> bool:
|
||||
|
|
@ -2927,11 +2952,7 @@ async def query_collection_handler(
|
|||
)
|
||||
|
||||
|
||||
####################################
|
||||
#
|
||||
# Vector DB operations
|
||||
#
|
||||
####################################
|
||||
|
||||
|
||||
class DeleteForm(BaseModel):
|
||||
|
|
@ -2969,13 +2990,7 @@ async def delete_entries_from_collection(
|
|||
detail=ERROR_MESSAGES.DEFAULT('File has no hash; cannot delete vector entries by hash.'),
|
||||
)
|
||||
|
||||
# Pre-existing bug: this used `metadata=` which is not a
|
||||
# parameter on `VectorDBBase.delete` nor on any backend
|
||||
# implementation, so the call always raised TypeError that
|
||||
# was silently swallowed by the surrounding `except
|
||||
# Exception` and the endpoint reported `{'status': False}`
|
||||
# for every request. Use `filter` to actually do what the
|
||||
# endpoint name promises.
|
||||
# Vector deletion accepts filter, not metadata; passing the wrong keyword raises TypeError.
|
||||
await ASYNC_VECTOR_DB_CLIENT.delete(
|
||||
collection_name=form_data.collection_name,
|
||||
filter={'hash': hash},
|
||||
|
|
|
|||
|
|
@ -339,7 +339,7 @@ async def search_workspace( # noqa: C901 — keep permission scoping and source
|
|||
.exists()
|
||||
)
|
||||
stmt = AccessGrants.has_permission_filter(
|
||||
db, select(Note, pinned, note_shared), Note, {'user_id': user.id, 'group_ids': groups}, 'note', 'read'
|
||||
select(Note, pinned, note_shared), Note, {'user_id': user.id, 'group_ids': groups}, 'note', 'read', db=db
|
||||
)
|
||||
stmt = stmt.where(sharing_filter(Note.user_id))
|
||||
stmt = apply_match(
|
||||
|
|
|
|||
|
|
@ -48,9 +48,7 @@ PAGE_ITEM_COUNT = 30
|
|||
router = APIRouter()
|
||||
|
||||
|
||||
############################
|
||||
# GetSkills
|
||||
############################
|
||||
# Get Skills
|
||||
|
||||
|
||||
@router.get('/', response_model=list[SkillUserResponse])
|
||||
|
|
@ -72,9 +70,7 @@ async def get_skills(
|
|||
return skills
|
||||
|
||||
|
||||
############################
|
||||
# GetSkillList
|
||||
############################
|
||||
# Get Skill List
|
||||
|
||||
|
||||
@router.get('/list', response_model=SkillAccessListResponse)
|
||||
|
|
@ -134,9 +130,7 @@ async def get_skill_list(
|
|||
)
|
||||
|
||||
|
||||
############################
|
||||
# ExportSkills
|
||||
############################
|
||||
# Export Skills
|
||||
|
||||
|
||||
async def authorized_skill(id, user, permission='read', db=None):
|
||||
|
|
@ -211,9 +205,7 @@ async def export_skills(
|
|||
raise HTTPException(400, str(error))
|
||||
|
||||
|
||||
############################
|
||||
# CreateNewSkill
|
||||
############################
|
||||
# Create New Skill
|
||||
|
||||
|
||||
@router.post('/create', response_model=Optional[SkillResponse])
|
||||
|
|
@ -290,9 +282,7 @@ async def create_new_skill(
|
|||
)
|
||||
|
||||
|
||||
############################
|
||||
# GetSkillById
|
||||
############################
|
||||
# Get Skill By Id
|
||||
|
||||
|
||||
@router.get('/id/{id}', response_model=Optional[SkillDetailResponse])
|
||||
|
|
@ -337,9 +327,7 @@ async def get_skill_by_id(id: str, user=Depends(get_verified_user), db: AsyncSes
|
|||
)
|
||||
|
||||
|
||||
############################
|
||||
# UpdateSkillById
|
||||
############################
|
||||
# Update Skill By Id
|
||||
|
||||
|
||||
@router.post('/id/{id}/update', response_model=Optional[SkillModel])
|
||||
|
|
@ -403,9 +391,7 @@ async def update_skill_by_id(
|
|||
)
|
||||
|
||||
|
||||
############################
|
||||
# UpdateSkillAccessById
|
||||
############################
|
||||
# Update Skill Access By Id
|
||||
|
||||
|
||||
class SkillAccessGrantsForm(BaseModel):
|
||||
|
|
@ -464,9 +450,7 @@ async def update_skill_access_by_id(
|
|||
return skill
|
||||
|
||||
|
||||
############################
|
||||
# ToggleSkillById
|
||||
############################
|
||||
# Toggle Skill By Id
|
||||
|
||||
|
||||
@router.post('/id/{id}/toggle', response_model=Optional[SkillModel])
|
||||
|
|
@ -517,9 +501,7 @@ async def toggle_skill_by_id(
|
|||
)
|
||||
|
||||
|
||||
############################
|
||||
# DeleteSkillById
|
||||
############################
|
||||
# Delete Skill By Id
|
||||
|
||||
|
||||
@router.delete('/id/{id}/delete', response_model=bool)
|
||||
|
|
|
|||
|
|
@ -99,11 +99,7 @@ async def get_task_model_generation_config(default_model_id: str, models) -> tup
|
|||
)
|
||||
|
||||
|
||||
##################################
|
||||
#
|
||||
# Task Endpoints
|
||||
#
|
||||
##################################
|
||||
|
||||
|
||||
@router.get('/config')
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Reference in a new issue