mirror of
https://github.com/open-webui/open-webui.git
synced 2026-11-22 21:50:42 -05:00
518 files changed
+74667
-34731
No files matched your search
@@ -22,7 +22,6 @@ workflows:
|
||||
- 'actions/setup-node@v5.0.0'
|
||||
'.github/workflows/issue-label.yaml':
|
||||
- 'actions/github-script@v7.1.0'
|
||||
'.github/workflows/regression.yaml': []
|
||||
'.github/workflows/release-pypi.yml':
|
||||
- 'actions/checkout@v5.1.0'
|
||||
- 'actions/setup-node@v5.0.0'
|
||||
|
||||
@@ -1,9 +1,12 @@
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
# Backend CI — Python formatting checks via Ruff
|
||||
# Backend CI — Python formatting checks via Ruff and lock file check
|
||||
# Runs on pushes and PRs to main/dev when backend files change
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
name: Python CI
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main, dev]
|
||||
@@ -41,3 +44,24 @@ jobs:
|
||||
|
||||
- name: Detect logic errors
|
||||
run: ruff check --select=F --ignore=F401,F403,F405,F541,F811,F841 --output-format=github .
|
||||
|
||||
# ── Dockerfile lock files match the requirements files ───────────────────
|
||||
lock-check:
|
||||
name: Requirements locks up to date
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- uses: actions/checkout@v5.1.0
|
||||
|
||||
- uses: actions/setup-python@v6.3.0
|
||||
with:
|
||||
python-version: '3.12'
|
||||
|
||||
- name: Install uv
|
||||
run: pip install uv==0.12.10
|
||||
|
||||
- name: Regenerate locks
|
||||
run: backend/update-locks.sh
|
||||
|
||||
- name: Verify locks are up to date
|
||||
run: test -z "$(git status --porcelain -- backend)"
|
||||
File renamed without changes.
+159
@@ -5,6 +5,165 @@ All notable changes to this project will be documented in this file.
|
||||
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
|
||||
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
||||
|
||||
## [0.13.4] - 2026-11-17
|
||||
|
||||
### Added
|
||||
|
||||
- **Bring your own computer with Tether.** Tether turns your own computer into part of Open WebUI: models from Ollama, LM Studio or any OpenAI-compatible server, OpenAPI and MCP tool servers and Open Terminal servers that you add in the Tether app now show up just for you in the model selector, the Tools list of the + menu and the terminal menu of any Open WebUI you connect, from whatever device you open it on, and Open WebUI reaches them through Tether, so their addresses, commands and keys never leave your computer. This needs Tether 0.1.14 or later, or 0.1.16 for MCP servers, tool servers and terminals need "ENABLE_TOOL_SERVERS" turned on, and a Tether model whose ID matches a model already in Open WebUI stays hidden. Tether replaces Direct Connections. [#34397](https://github.com/open-webui/open-webui/issues/34397)
|
||||
- **Sandboxed agents on your own computer.** Tether 0.1.13 or later can lock the terminal on your computer into a sandbox, so models and coding agents work in your real files without reaching the rest of your machine: on macOS and supported Windows devices, Open Terminal and everything it launches, coding agents included, can only touch the one folder you pick, run offline unless you turn on Network access and accept no incoming connections, with no Docker, virtual machine or administrator setup needed. If the sandbox cannot be enforced, the terminal stays stopped instead of quietly running without it, and browser and desktop control stay off while it is on. Turn it on in Tether under Settings > Open Terminal > Sandbox.
|
||||
- **Local MCP servers through Tether.** Open WebUI can now use MCP servers that run as a local command over stdio, the way many MCP servers are distributed, by launching them on your computer through Tether 0.1.16 or later, with no proxy such as mcpo and no port to open. Add one in Tether under Settings > Integrations > Tools with its command, or connect an MCP server by its web address, and pick it from the Tools list of the + menu. Local commands run with your own account's access, outside Tether's workspace sandbox.
|
||||
- **A computer for every user.** With Terminals 0.4.0 or later connected, Open WebUI now hands out sandboxed computers on demand: anyone with Write access to the connection can create a terminal right from the terminal menu of the message input, pick whether everyone shares one machine or each user, chat or model gets its own, and set its image, CPU, memory, storage, network profile, environment variables, start directory and a setup script that, for example, clones a repository and installs its dependencies, without an administrator setting up each one. Terminals can be shared with users and groups and their instances started, stopped, restarted or deleted, a View files option opens any terminal's files without selecting it for the chat, System info shows how the setup script went, and those who manage a terminal can open the files and system info of other people's running instances. Start and Stop need Terminals 0.4.1 or later, the start directory and setup script need Open Terminal 0.17.7 or later in the terminal's image, and network profiles are the ones an administrator defined with "TERMINALS_NETWORK_PROFILES".
|
||||
- **Coding agents as chat models.** Coding agents now work much like any other model in the chat. Hermes, Antigravity, GitHub Copilot, Goose and Qwen Code join Codex, Claude Code, Cursor, Grok, OpenCode, Cline, Gemini CLI and Pi, and any other ACP agent added to Open Terminal with "OPEN_TERMINAL_ACP_AGENTS" works as well, once it is installed and signed in on the terminal. Auto for tool permissions now lets Codex, Claude Code and Grok approve routine actions themselves and pass on only what they escalate, and the reasoning effort in the advanced parameters now also applies to Claude Code, Pi and ACP agents that offer effort levels, such as OpenCode, which stop with an error when the chosen level is not offered for the model. Replies can now be regenerated and earlier messages edited, and a forked or cloned agent chat picks up where the original left off: Codex continues its own conversation from that point, other agents start over from the chat so far, and file changes the agent already made stay. Claude Code continues its own conversation too with the next Open Terminal release after 0.17.20 and until then asks you to update Open Terminal instead. The new agents and Auto for Claude Code and Grok need Open Terminal 0.17.19 or later, and effort for Claude Code, Pi and ACP agents needs 0.17.9 or later. [#34167](https://github.com/open-webui/open-webui/issues/34167)
|
||||
- **Pages open as tabs.** Notes, channels, the workspace, automations, the calendar, the playground, the home page and new chats from pinned models now open as tabs beside the current chat when you click or drag them from the sidebar, pick them in the user menu or follow a link to one of them in a chat message, and starting a new chat, also from a sidebar folder, keeps the open tabs.
|
||||
- **Queued messages steer replies.** A message you send to your own chat while a reply is still running now waits on the server, so it is kept when you leave the page, and the reply wraps up at its next step so your message is answered right away with what it has done so far.
|
||||
- **Instant first message.** The first message of a new chat now shows up right away while the chat is still being created, instead of only once it exists, unless files are still being uploaded with it.
|
||||
- **Full chat in side chats.** Side chats now run the same chat as the main view, so message buttons, sources, token usage, follow-up suggestions, slash commands, queued messages, chat variables, web search settings, tool events such as code execution and input requests, HTML and SVG previews, notifications while the window is in the background, unsent text after a page reload and answers from several models at once now work there too, and a side chat's tab now has the chat menu. [#34064](https://github.com/open-webui/open-webui/pull/34064), [#34165](https://github.com/open-webui/open-webui/pull/34165), [#34147](https://github.com/open-webui/open-webui/pull/34147), [#34031](https://github.com/open-webui/open-webui/issues/34031)
|
||||
- **Interactive visualizations.** Models can now draw interactive charts, diagrams, calculators and explainers right in the chat with the new Visualizations built-in tool, which is off by default and turned on per model under Builtin Tools, and administrators can rewrite its instructions under Admin Settings > Interface > Visualization Prompt or with "VISUALIZATION_PROMPT_TEMPLATE".
|
||||
- **Video generation.** Models can now generate videos with a built-in tool, also starting from an image in the chat, once an administrator turns on Video Generation under Admin Settings > Videos, adds connections to OpenAI, LiteLLM or OpenRouter, which offers models such as Veo and Kling, with a default video model, per-model defaults and access settings, and grants the Video Generation permission, which is off by default, after which users turn on Video in the + menu, can pick the model there and watch the result in the chat. [#13780](https://github.com/open-webui/open-webui/discussions/13780), [#13927](https://github.com/open-webui/open-webui/discussions/13927)
|
||||
- **Several image models.** Administrators can now add several image connections under Admin Settings > Images, each an OpenAI-compatible server such as LiteLLM, Gemini, ComfyUI or AUTOMATIC1111 with its own models, sizes, workflows and access, used for generating images, editing them or both, where OpenAI-compatible ones offer the same sign-in options and custom headers as model connections and list the image models of a LiteLLM server by themselves when no model IDs are entered, choose the default generation and edit models and give a model its own default image model in its settings, and users with more than one image model pick one from the Image entry in the + menu of the message input. [#10344](https://github.com/open-webui/open-webui/discussions/10344)
|
||||
- **Git panel becomes a GitHub workbench.** With Open Terminal 0.17.8 or later and the GitHub CLI signed in on the terminal, as included in the full, agents and cuda images, the Git panel now covers the whole GitHub loop: browse, search, create, edit, comment on, close and reopen the repository's issues, see each pull request's checks, review state, labels, activity and conflicts with a status filter and a choice of merge method, and search issues and pull requests across the whole repository instead of only the loaded list. Buttons such as Work on this, Fix, Address feedback and Resolve conflicts in chat hand the issue, review or conflict to the model as a ready-made request in the message input, and changed files can be picked with Ctrl or Shift click to discard several at once or all of them.
|
||||
- **Terminals follow your chats.** Each chat now saves its terminal and working folder and switches back to them when you reopen it, including a terminal you turned off, and administrators can pick a default terminal under Admin Settings > Models > Model Defaults that new chats start with for every model without a terminal of its own, so every chat can start with a computer attached. Chats from earlier versions open without a terminal unless they are coding agent chats.
|
||||
- **Folder chat board.** Folder pages now list their chats with a search through titles and messages and filters for status, tags, people, activity and last update, and can show them as a board with columns and rows by status, tag or activity such as unread, generating or waiting for approval, gives each chat there the sidebar's chat menu to rename, move, archive or delete it, and a folder's badge in the sidebar now also counts chats waiting for approval. [#33771](https://github.com/open-webui/open-webui/issues/33771)
|
||||
- **Chat statuses in folders.** Folders can now set up statuses for their chats under Edit statuses, with Backlog, To do, In progress, Waiting and Done offered as suggestions, chats then get a status from their menu on the folder page or by dragging them between board columns, people who can edit a shared folder can set the status of every chat in it, and each chat shows how long it has been in its status.
|
||||
- **Folder automations.** Folder pages now have an Automations section that lists the folder's automations with their state and last run and creates new ones there, chats made by an automation are marked with a clock, and automations can now post into shared folders their creator can edit, where everyone who can edit the folder can pause and run them and see their runs.
|
||||
- **Knowledge on folder pages.** Folder pages now have a Knowledge section that lists the knowledge bases, notes, chats and files new chats in the folder can use, where you can add, upload, drop, open and remove them.
|
||||
- **Colored chat tags.** Tags can now get a color on the folder page that applies wherever the tag is used, and the chat menu has a Tags submenu to find, add and create tags, and people who can edit a shared folder can tag every chat in it.
|
||||
- **Edit automations in place.** An automation's page now edits its name, instructions, status, schedule, model, terminal and destination right there with a Save button that appears once something changed, shows saved instructions collapsed behind Show more, lists its runs as activity below, and has Copy link and Duplicate in its More menu.
|
||||
- **Readable agent and terminal steps.** Steps of coding agents and the terminal tool calls of other models now show in the chat as what they did, a command with its output and its exit code when it failed, a diff of each edited file with its added and removed lines, or the files read, code and web searches, folders listed and pages fetched, and a group of steps is summarized as for example Ran 2 commands, Edited 1 file, Read 3 files. Diffs of files that other models edit through the terminal tools need Open Terminal 0.17.20 or later.
|
||||
- **Models can mention people.** With the Chat History built-in tool, models can now look up users by name or email and mention them in a reply, and each mentioned user who can see the chat gets an inbox notification that opens the chat at that reply.
|
||||
- **OpenAI-compatible vector stores.** External knowledge sources under Admin Settings > Integrations can now be OpenAI-compatible vector stores on OpenAI, Azure OpenAI or LiteLLM, searched on the server so no matching embedding model is needed, and you either pick one or more stores for a knowledge base or turn on 'List stores as knowledge bases' to show every store of the connection, or only chosen ones, as read-only knowledge bases that stay in sync with the endpoint and share the connection's access settings.
|
||||
- **Review settings before saving.** Admin settings pages now show next to Save how many settings changed since they were loaded or saved, and clicking that count or Save lists every change with its old and new value to confirm, with passwords and API keys kept hidden. [#34534](https://github.com/open-webui/open-webui/pull/34534), [#34532](https://github.com/open-webui/open-webui/discussions/34532)
|
||||
- **Smoother replies with code blocks.** Long replies with many code blocks no longer stall the tab a little longer with every new code block while they stream, so a reply with 300 code blocks that arrives at once now shows in 9 seconds instead of more than two minutes. [#34495](https://github.com/open-webui/open-webui/pull/34495), [#34492](https://github.com/open-webui/open-webui/issues/34492)
|
||||
- **Faster large PDF previews.** Long PDFs in the file preview now open in about a second and use far less memory, because only the pages near the screen are drawn and pages far away are released, so a 1500-page manual no longer takes over half a minute and a large scanned file no longer pushes the browser past many gigabytes. The browser's find (Ctrl+F) now only matches text on pages near the screen. [#34602](https://github.com/open-webui/open-webui/pull/34602), [#29576](https://github.com/open-webui/open-webui/issues/29576)
|
||||
- **Faster folder reopening.** Reopening a folder now shows its chats, details and coding agent models right away from what was already loaded and refreshes them in the background, sidebar folders keep their loaded chats when collapsed and expanded again, and folder chat lists update immediately when a chat is renamed, moved, archived or deleted.
|
||||
- **Faster model list with Redis.** With Redis, the model list now loads faster and Redis no longer keeps a copy of every model profile image, which helps most with large animated or imported images, and Functions and Tools now receive the model without its profile image. [#34595](https://github.com/open-webui/open-webui/pull/34595), [#34594](https://github.com/open-webui/open-webui/issues/34594)
|
||||
- **Faster profile pictures and knowledge exports.** Large profile pictures of users, models and channel webhooks and knowledge base exports are now sent in one piece, so a 2 MB picture loads in about 15 ms instead of a few hundred and a page full of large avatars no longer takes seconds, and exporting a knowledge base no longer holds up other users' requests on the same server process while the archive is packed. [#34598](https://github.com/open-webui/open-webui/pull/34598), [#34597](https://github.com/open-webui/open-webui/issues/34597), [#34600](https://github.com/open-webui/open-webui/pull/34600), [#34599](https://github.com/open-webui/open-webui/issues/34599)
|
||||
- **Shared chat terminals.** People who can reply to a chat shared with Allow replies can now work in that chat's terminal, as the share dialog now points out: with a Terminals template that gives each chat its own machine, and in coding agent chats, they work in the same machine and files as the owner, while with other terminals they use their own access to it. [#34103](https://github.com/open-webui/open-webui/issues/34103)
|
||||
- **Files tab upgrades.** With a terminal that reports file changes, the Files tab now updates by itself without a loading spinner when files in the folders it shows change, also through commands run outside the chat. Clicking the path above it lets you type a folder to go to, absolute or relative to the current one, with Tab completing folder names, or select and copy an open file's full path, Markdown files get an Outline button that lists their headings and jumps to the one you pick, and folders in the working directory menu of the message input have an Open folder button that opens them in a new Files tab. [#34494](https://github.com/open-webui/open-webui/pull/34494), [#34525](https://github.com/open-webui/open-webui/discussions/34525)
|
||||
- **Terminal tab upgrades.** Terminal tabs are now named after the title that the program running in them sets, or after the running program itself with Open Terminal 0.17.8 or later on macOS and Linux, and show an icon for well-known programs such as Claude Code, Codex, Python or Node.js. When no terminal is selected for the chat, the menu for opening a new tab still offers Files, new files, terminals, the browser, the desktop and voice notes, and picking one first asks you to choose a terminal from a searchable list.
|
||||
- **Grouped tools and skills.** The Tools and Skills lists in the + menu of the message input are now grouped by where each entry comes from, such as the workspace, tool servers or the terminal. [#34085](https://github.com/open-webui/open-webui/pull/34085)
|
||||
- **Reply progress on tabs.** The chat tab and side chat tabs now show a spinner while a reply is being written, so you can see from another tab when an answer is still coming.
|
||||
- **Rename from the tab.** Double-clicking the chat tab now renames the chat, also a chat someone else made in a folder you own, and on a folder page it renames the folder.
|
||||
- **Share folders from their menu.** The folder menu in the sidebar and on the folder page now has a Share option for administrators and for owners allowed to share folders.
|
||||
- **Sub-agent permission.** Administrators can now limit sub-agents to chosen users and groups with a Sub-agents switch under Features in the default and group permissions, or with "USER_PERMISSIONS_FEATURES_SUBAGENTS", and users without it get neither the sub-agent nor the timer tool. [#34040](https://github.com/open-webui/open-webui/pull/34040), [#34038](https://github.com/open-webui/open-webui/issues/34038)
|
||||
- **Lighter coding agent replies.** While a coding agent writes its reply, the chat is no longer saved in full about once a second, so long agent chats write several times less to the database for each reply. [#34062](https://github.com/open-webui/open-webui/issues/34062)
|
||||
- **Labels on failed tool calls.** Tool calls that failed now keep the short label the model gave them, also in a group of calls, where one failed call used to hide every label. [#34000](https://github.com/open-webui/open-webui/pull/34000), [#34529](https://github.com/open-webui/open-webui/discussions/34529)
|
||||
- **Drop files into skills.** Files and folders dragged onto a skill's files in the workspace now upload into the open folder, like the upload buttons do.
|
||||
- **Editable calendars.** Calendars can now be renamed and given another color after they are created, from a pencil next to each calendar in the Calendar sidebar. [#34136](https://github.com/open-webui/open-webui/pull/34136)
|
||||
- **Model names in analytics.** Admin analytics now name coding agent models by agent and model for replies made from now on, and the tooltips of the session timeline show model names instead of model IDs.
|
||||
- **Arena model management.** The view filter in Admin Settings > Models now has an Arena Models option that lists only the arena models, and each arena model in Admin Settings > Evaluations has a Clone button that opens a new arena model filled in from it. [#34137](https://github.com/open-webui/open-webui/pull/34137), [#34138](https://github.com/open-webui/open-webui/pull/34138)
|
||||
- **OAuth session removals logged.** Removing a stored OAuth session because of the "OAUTH_MAX_SESSIONS_PER_USER" limit, a sign-out sent by the identity provider or a reconnected MCP server now logs a warning naming the user, the session and the reason. [#34583](https://github.com/open-webui/open-webui/pull/34583), [#34580](https://github.com/open-webui/open-webui/issues/34580)
|
||||
- **Accessibility improvements.** A tab moved with Alt+Shift+Arrow keys now keeps the keyboard focus, so it can be moved several places in a row.
|
||||
- **General improvements.** Various improvements were implemented across the application to enhance performance, stability, and security.
|
||||
- **Translation updates.** Translations for Azerbaijani, Basque, Bengali, Bosnian, Bulgarian, Cebuano, Croatian, Czech, Danish, Dutch, Estonian, Faroese, Filipino, Galician, Georgian, German, Greek, Hebrew, Hindi, Hungarian, Indonesian, Irish, Italian, Japanese, Kabyle, Korean, Latvian, Lithuanian, Malay, Norwegian Bokmål, Persian, Polish, Portuguese (Brazil), Punjabi, Romanian, Russian, Serbian, Slovak, Slovenian, Spanish (Spain), Swedish, Tamil, Thai, Tibetan, Turkish, Turkmen, Ukrainian, Urdu, Uyghur and Vietnamese were enhanced and expanded.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Temporary chats leave no memories.** The background memory review now skips temporary chats, so facts from them are no longer saved as memories that show up in later chats. [#34263](https://github.com/open-webui/open-webui/pull/34263), [#34262](https://github.com/open-webui/open-webui/issues/34262)
|
||||
- **Whole numbers in parameters.** Whole-number fields in the advanced parameters, such as Context Length, Max Tokens and Seed, now reject a value with a decimal point, such as "32.767" typed for 32767, instead of saving it and running the model with a context of only a few tokens. [#34416](https://github.com/open-webui/open-webui/issues/34416)
|
||||
- **Busy servers with session sharing.** With "DATABASE_ENABLE_SESSION_SHARING" on, a burst of page loads no longer stalls for 30 seconds and fails with a "QueuePool limit" error, because chat lists and the inbox no longer open a second database connection for their extra reads. [#34185](https://github.com/open-webui/open-webui/pull/34185), [#34184](https://github.com/open-webui/open-webui/issues/34184)
|
||||
- **Uploads during knowledge syncs.** With a slow extraction engine, a large knowledge base sync no longer makes every other upload, chat attachments included, wait for an extraction before it is even saved, because files uploaded into knowledge bases now process at most half as many at a time as the server's worker threads ("THREAD_POOL_SIZE"), so other knowledge base uploads may wait their turn during a large sync. [#34379](https://github.com/open-webui/open-webui/pull/34379)
|
||||
- **Sign-in kept during provider outages.** A sign-in provider that is unreachable, rate limited or failing with a server error while a user's token is refreshed no longer deletes that user's stored sign-in, so tools and connections that use the sign-in token work again on the next call instead of only after signing out and back in. [#34585](https://github.com/open-webui/open-webui/pull/34585), [#34578](https://github.com/open-webui/open-webui/issues/34578)
|
||||
- **Chat keeps the newest turn.** A window that missed a turn, such as a laptop that just woke up, no longer moves the chat back to an older turn when it saves an edited message, so the newest reply stays in the conversation. [#34160](https://github.com/open-webui/open-webui/pull/34160), [#34126](https://github.com/open-webui/open-webui/issues/34126)
|
||||
- **Chats with looping history.** A chat whose saved messages loop back on themselves now opens and shows its messages instead of freezing the browser tab until it crashes. [#34481](https://github.com/open-webui/open-webui/pull/34481), [#34477](https://github.com/open-webui/open-webui/issues/34477)
|
||||
- **Summary kept through compaction.** A conversation compacted again between tool calls now keeps what its earlier summary held, and a chat compacted after such a compaction goes on from its newer summary instead of falling back to the older one and sending more than the model can take. [#34151](https://github.com/open-webui/open-webui/pull/34151), [#34141](https://github.com/open-webui/open-webui/issues/34141), [#34140](https://github.com/open-webui/open-webui/issues/34140)
|
||||
- **Steadier context compaction.** Compacting a chat by hand right after a failed reply now keeps the summary for the next message instead of losing it along with the failed reply, and automatic compaction now also counts a tool result that ended a reply, such as one too long for the model to answer, so the next message compacts the chat instead of sending it in full. [#34434](https://github.com/open-webui/open-webui/issues/34434)
|
||||
- **Fewer repeated context lists.** With native function calling, the list of available skills and the attached knowledge are no longer added to the chat again before every reply, only when they changed or after compaction, and recalled memories already in the chat are not sent again, so long chats use fewer tokens and need compaction later. [#34257](https://github.com/open-webui/open-webui/issues/34257)
|
||||
- **Tool call turns without text.** Replies in which a model called a tool without writing any text are now sent back to the model without an empty text, so proxies such as LiteLLM no longer turn them into a placeholder line that the model then starts copying into its answers. [#34265](https://github.com/open-webui/open-webui/pull/34265), [#34264](https://github.com/open-webui/open-webui/issues/34264)
|
||||
- **Final answers on vLLM.** When tool use stops, the request for a final answer no longer ends in a 400 error on vLLM, and Ollama models are kept from calling tools in it. [#34176](https://github.com/open-webui/open-webui/pull/34176), [#34169](https://github.com/open-webui/open-webui/issues/34169)
|
||||
- **Ollama proxy tool calls.** OpenAI-compatible clients that send back an assistant turn with only tool calls and no text no longer get a 400 "Field required" error from the Ollama OpenAI-compatible chat endpoint, so multi-turn tool calling works through it. [#34442](https://github.com/open-webui/open-webui/pull/34442), [#34441](https://github.com/open-webui/open-webui/issues/34441)
|
||||
- **Timed-out tool calls explained.** A terminal command or tool server call that runs past "AIOHTTP_CLIENT_TIMEOUT_TOOL_SERVER" now reaches the model as a timeout error instead of an empty one, so the model can tell you the call timed out. [#34119](https://github.com/open-webui/open-webui/pull/34119), [#34096](https://github.com/open-webui/open-webui/issues/34096)
|
||||
- **Tool calls in summaries.** Conversation summaries written with the plain summary prompt, as for models with a filter, now include the tool calls of earlier replies in saved chats. [#34139](https://github.com/open-webui/open-webui/issues/34139)
|
||||
- **MCP tools reconnect.** When an MCP server drops its connection during a reply, for example because it restarted, the next call to one of its tools now connects again instead of every later call in that reply failing with an "MCP client is not connected" error. [#34170](https://github.com/open-webui/open-webui/issues/34170)
|
||||
- **Large MCP tool lists.** MCP servers whose tool list or a single tool result is larger than 1 MB connect and answer again, also through Tether, instead of failing with "Failed to connect to MCP server". [#34421](https://github.com/open-webui/open-webui/pull/34421), [#34201](https://github.com/open-webui/open-webui/issues/34201)
|
||||
- **MCP sign-ins with rotating tokens.** Two tool calls that refresh the same MCP sign-in at the same time no longer delete the connection with providers that hand out a new refresh token on every refresh, because the refreshes now wait for each other, across workers when Redis is used. [#34582](https://github.com/open-webui/open-webui/issues/34582)
|
||||
- **MCP OAuth with HS256 tokens.** Connecting an MCP server over OAuth 2.1 now works when the server signs its ID token with the client secret, as Readwise does, instead of failing with "Algorithm 'HS256' requires 'oct' key". [#34593](https://github.com/open-webui/open-webui/pull/34593), [#34504](https://github.com/open-webui/open-webui/issues/34504)
|
||||
- **MCP OAuth with large headers.** Adding an MCP server with OAuth 2.1 and refreshing its tokens now work when its authorization server sends a very large response header, as monday.com does, instead of failing with "Connection error". [#34084](https://github.com/open-webui/open-webui/pull/34084), [#34078](https://github.com/open-webui/open-webui/issues/34078)
|
||||
- **Sign-in prompt for SSO tools.** When the single sign-on session whose token a tool server forwards has ended, those tools now show as needing a sign-in in the + menu and picking one takes you to sign in again, instead of the tools failing on every call with no hint. [#34579](https://github.com/open-webui/open-webui/issues/34579)
|
||||
- **OAuth sessions on other devices.** Signing in past "OAUTH_MAX_SESSIONS_PER_USER" now removes the stored provider sessions used least recently instead of the ones created first, so a device signed in early and still in use keeps its session, and signing out now removes that browser's stored session unless it is the person's only one for that provider. [#34586](https://github.com/open-webui/open-webui/pull/34586), [#34581](https://github.com/open-webui/open-webui/issues/34581)
|
||||
- **Quieter search logs.** Knowledge searches and several web search engines no longer write found file names or full search results to the server log at the default level, only with "GLOBAL_LOG_LEVEL" set to "DEBUG". [#34146](https://github.com/open-webui/open-webui/pull/34146), [#34129](https://github.com/open-webui/open-webui/issues/34129)
|
||||
- **Deleted accounts leave access lists.** Deleting an account now also removes it from the access lists of everything it was given access to, where it used to stay as a row showing only the deleted account's ID. [#34223](https://github.com/open-webui/open-webui/pull/34223), [#30023](https://github.com/open-webui/open-webui/discussions/30023)
|
||||
- **Local speech-to-text on pip installs.** Local speech-to-text in Open WebUI installed with pip now transcribes again instead of failing every recording with an error about "metadata_errors". [#34280](https://github.com/open-webui/open-webui/pull/34280), [#34278](https://github.com/open-webui/open-webui/issues/34278)
|
||||
- **OpenAI image generation defaults.** Generating images with OpenAI now works with the stock settings, because GPT image models get the auto size instead of the old 512x512 default they reject and Auto can be saved with the model field left empty, and a failed request now shows the provider's own error, such as "Invalid size".
|
||||
- **Fuller web page text.** With the Playwright web loader, the text of definition lists, of figures with their captions and of collapsible sections, open or closed, now reaches the model, so attached web pages and web search results no longer lose content such as the function and parameter descriptions on many documentation sites. [#34282](https://github.com/open-webui/open-webui/pull/34282), [#34281](https://github.com/open-webui/open-webui/issues/34281), [#34277](https://github.com/open-webui/open-webui/pull/34277), [#34272](https://github.com/open-webui/open-webui/issues/34272)
|
||||
- **Unreachable sites skipped sooner.** With SSL verification on, the Playwright, Tavily and Microsoft Web IQ web loaders now skip a site that never answers after 10 seconds instead of waiting about two minutes per link. [#34490](https://github.com/open-webui/open-webui/pull/34490), [#14241](https://github.com/open-webui/open-webui/discussions/14241)
|
||||
- **Web pages behind internal certificates.** With SSL verification on, the Playwright, Tavily and Microsoft Web IQ web loaders now load pages signed by an internal certificate authority set through "AIOHTTP_CLIENT_SSL_CERT_FILE" or "AIOHTTP_CLIENT_SESSION_SSL", and links that spell out a port or a username, instead of rejecting them. [#34482](https://github.com/open-webui/open-webui/pull/34482), [#34479](https://github.com/open-webui/open-webui/issues/34479), [#34462](https://github.com/open-webui/open-webui/issues/34462)
|
||||
- **No keyboard pop-up on phones.** On a phone, opening a chat, switching chats or starting a new chat no longer puts the cursor in the message input and brings up the on-screen keyboard over the conversation. [#34059](https://github.com/open-webui/open-webui/issues/34059)
|
||||
- **Smooth Firefox scrolling.** Scrolling up through a long chat in Firefox no longer throws the view back down, sometimes by several screens, while older messages load. [#33998](https://github.com/open-webui/open-webui/pull/33998), [#33994](https://github.com/open-webui/open-webui/issues/33994)
|
||||
- **Temporary chat choice kept.** With Temporary Chat by default turned on in the interface settings, a new chat switched to a normal chat now stays normal after a page reload.
|
||||
- **Permission changes reach open pages.** When an admin changes permissions, open pages now follow without a reload, so a new chat that is open becomes a temporary chat once Enforce Temporary Chat is turned on instead of failing on the first message, Compare in the model selector turns off and only the first selected model stays once Multiple Models in Chat is turned off, an open channel shows the permission notice in place of the channel once Channels is turned off, and turning off Folders removes Move from the chat menu and closes an open Create Folder window. [#34513](https://github.com/open-webui/open-webui/pull/34513), [#34512](https://github.com/open-webui/open-webui/issues/34512), [#34515](https://github.com/open-webui/open-webui/pull/34515), [#34514](https://github.com/open-webui/open-webui/issues/34514), [#34511](https://github.com/open-webui/open-webui/pull/34511), [#34510](https://github.com/open-webui/open-webui/issues/34510), [#34509](https://github.com/open-webui/open-webui/pull/34509), [#34508](https://github.com/open-webui/open-webui/issues/34508), [#34507](https://github.com/open-webui/open-webui/pull/34507), [#34506](https://github.com/open-webui/open-webui/issues/34506)
|
||||
- **Images reach coding agents.** Images attached to a message in a coding agent chat now reach the agent with the message instead of being dropped without a word. [#33993](https://github.com/open-webui/open-webui/pull/33993), [#33992](https://github.com/open-webui/open-webui/issues/33992), [#33991](https://github.com/open-webui/open-webui/discussions/33991)
|
||||
- **Coding agent chat titles.** Chats with a coding agent now get a generated title once the agent has replied, instead of keeping the default title. [#33971](https://github.com/open-webui/open-webui/pull/33971), [#33970](https://github.com/open-webui/open-webui/issues/33970)
|
||||
- **Agent model switches keep sessions.** Switching a coding agent chat to another model of the same agent now resumes the agent's existing session and working folder instead of starting a new session.
|
||||
- **Readable coding agent errors.** When the terminal refuses to start a coding agent, the reply now shows a short error instead of a technical dump containing the whole system prompt. [#34173](https://github.com/open-webui/open-webui/pull/34173), [#34172](https://github.com/open-webui/open-webui/issues/34172)
|
||||
- **Sub-agents with browser questions.** A sub-agent no longer hangs on "Executing Sub-agent" when a filter or tool asks the browser something, because the script, confirmation or form now appears in the tab that has the chat open. [#34045](https://github.com/open-webui/open-webui/pull/34045), [#34041](https://github.com/open-webui/open-webui/issues/34041)
|
||||
- **Sub-agent reports stay together.** Two background sub-agent reports that finish close together no longer split the chat into two branches that hide the first report and the reply to it. [#34542](https://github.com/open-webui/open-webui/pull/34542), [#34540](https://github.com/open-webui/open-webui/issues/34540)
|
||||
- **Shared chat changes saved.** Someone replying in a chat shared with Allow replies can now change its model, terminal and working folder, and the choice is saved to the chat instead of being dropped when it is reopened.
|
||||
- **Terminal choice kept in folders.** In a new chat inside a folder with a default terminal, a terminal you pick or turn off now stays that way when the model changes, instead of going back to the folder default, and a new chat in a folder without a default terminal keeps the terminal you had selected instead of turning it off. [#33973](https://github.com/open-webui/open-webui/issues/33973)
|
||||
- **Terminal locked during replies.** The terminal and working folder pickers in the message input now stay locked while a reply is still being written, so the chat's terminal can no longer be switched in the middle of a reply. [#34383](https://github.com/open-webui/open-webui/issues/34383)
|
||||
- **Steadier Tether connections.** Requests to a computer connected through Tether are no longer cut off after five minutes while data keeps flowing, read-only requests interrupted by a brief disconnect are repeated once Tether reconnects, and a busy computer now refuses new operations right away instead of letting some of them time out.
|
||||
- **Your devices list updates live.** A computer that connects through Tether after the page has loaded now appears under Your devices in the terminal menu right away, and the menu also picks up disconnects and device name changes, instead of needing a page reload.
|
||||
- **Unsaved terminal file edits kept.** An edit not yet saved in a file opened from a terminal's Files tab now comes back with its unsaved mark after you open another chat and return, and a workbook saved while you leave the chat keeps the worksheet you had open. [#34135](https://github.com/open-webui/open-webui/pull/34135), [#34107](https://github.com/open-webui/open-webui/issues/34107)
|
||||
- **Long Markdown files.** Opening a long Markdown file from a terminal's Files, or typing in one of its code blocks, no longer freezes the page for many seconds, because code blocks without a known language now show as plain text instead of being checked against every language, which also keeps notes and the rich text message input responsive. [#34491](https://github.com/open-webui/open-webui/pull/34491), [#34486](https://github.com/open-webui/open-webui/issues/34486)
|
||||
- **File cards follow the terminal.** A file shown inline in a reply now gets its preview, Download and Open back as soon as its terminal is picked again, and stops reaching the file once another terminal is picked, instead of keeping its first state until a page reload. [#34101](https://github.com/open-webui/open-webui/issues/34101)
|
||||
- **Working folder stays put.** Browsing to another folder in a Files tab no longer changes the working folder shown in the working directory menu and used by a new chat, and opening Files again shows an existing Files tab where you left it instead of moving it to the working folder.
|
||||
- **Terminal skill mentions after reload.** A sent message that mentions a skill of the picked terminal now still shows it as a chip after a page reload, and the + menu lists that terminal's skills right away, instead of both only working after the skill list was opened once. [#34102](https://github.com/open-webui/open-webui/issues/34102)
|
||||
- **File sizes after Refresh.** In a terminal's file viewer, Refresh and the back and forward arrows now keep the open file's real size instead of showing 0 B, and Refresh shows the new size when the file changed. [#34459](https://github.com/open-webui/open-webui/pull/34459), [#34458](https://github.com/open-webui/open-webui/issues/34458)
|
||||
- **Files menu near edges.** The menu from a right click on the empty part of a Files list now opens upwards or to the left when there is no room below or beside the pointer, so all of its entries stay inside the window. [#34125](https://github.com/open-webui/open-webui/pull/34125), [#34097](https://github.com/open-webui/open-webui/issues/34097)
|
||||
- **Local embedding model folders.** With the embedding model set to a folder on disk, saving Admin Settings > Documents no longer shows a "Model filesystem path detected" error and now also saves the embedding settings such as the batch size, which were skipped before. [#33978](https://github.com/open-webui/open-webui/pull/33978), [#33977](https://github.com/open-webui/open-webui/issues/33977)
|
||||
- **PowerPoint decks with sections.** PowerPoint files that use sections now preview in the chat and the knowledge base file viewer and show their comments, instead of failing with "Missing slide relationship". [#34276](https://github.com/open-webui/open-webui/pull/34276), [#34270](https://github.com/open-webui/open-webui/issues/34270)
|
||||
- **Large workbook sheets.** Excel workbooks with a sheet too large to preview now still open with their sheet tabs in a terminal's Files tab, the chat and the knowledge base, where that sheet says it is too large to preview and can be downloaded, instead of the whole file failing to preview. [#34247](https://github.com/open-webui/open-webui/issues/34247)
|
||||
- **Notes with footnotes.** Notes containing footnote references such as "[^1]" now open and show their content instead of failing with an error. [#33987](https://github.com/open-webui/open-webui/pull/33987), [#33986](https://github.com/open-webui/open-webui/issues/33986)
|
||||
- **Note recordings on S3 storage.** Recordings made in a note now upload to S3-compatible storage that rejects colons in file names and are named like "Recording-2026-11-16 15-25-06.webm" in every language, instead of after a date that slashes could cut short. [#34545](https://github.com/open-webui/open-webui/pull/34545), [#34543](https://github.com/open-webui/open-webui/issues/34543)
|
||||
- **Optional valves set to Custom.** Switching an optional valve, such as an on/off setting, from Default to Custom in the Valves section of the chat controls no longer fails with "Error updating function user valves", and emptying an optional on/off or number valve sets it back to its default. [#34478](https://github.com/open-webui/open-webui/pull/34478), [#34475](https://github.com/open-webui/open-webui/issues/34475)
|
||||
- **Math in table headers.** Formulas in table headers now keep their letters as written instead of being capitalized along with the header text. [#34245](https://github.com/open-webui/open-webui/pull/34245), [#34238](https://github.com/open-webui/open-webui/issues/34238)
|
||||
- **Math next to hyphens.** Inline formulas written directly next to a hyphen or non-breaking hyphen, as some models write them, now render instead of staying plain text or showing a math error. [#34244](https://github.com/open-webui/open-webui/pull/34244), [#34237](https://github.com/open-webui/open-webui/issues/34237)
|
||||
- **Pinning keeps chat order.** Pinning, unpinning, archiving or restoring a chat no longer moves it to the top of the chat list as if it had just been updated, and pinning a chat or moving it to a folder no longer marks it as read.
|
||||
- **Drafts kept per folder.** Unsent text in a new chat now stays with the folder or home page you typed it on, so opening another folder shows that folder's own unsent text instead of bringing yours along.
|
||||
- **Links in messages.** A link to a folder in a chat or channel message now opens the folder in Open WebUI instead of a new browser tab, and Ctrl or Cmd clicking a link to a chat, note or channel in a message now opens it in a new browser tab instead of the current one. [#34464](https://github.com/open-webui/open-webui/issues/34464)
|
||||
- **Tagging chats in parallel.** Adding the same new tag to several chats at the same time, as an API client tagging a batch of chats or two chat imports can do, no longer fails with a server error for all but one chat and leaves the others untagged. [#34144](https://github.com/open-webui/open-webui/pull/34144), [#34143](https://github.com/open-webui/open-webui/issues/34143)
|
||||
- **Thread reply notifications.** Clicking the browser notification for a reply in a channel thread now opens that thread instead of the channel with the thread closed. [#34233](https://github.com/open-webui/open-webui/pull/34233), [#34232](https://github.com/open-webui/open-webui/issues/34232)
|
||||
- **Side chats after reload.** A saved side chat tab restored after a page reload or on another device now shows only the side conversation again, instead of also listing the messages copied from the parent chat. [#34002](https://github.com/open-webui/open-webui/issues/34002)
|
||||
- **Browser tab in two windows.** With the same chat open in two windows, a Browser tab in Chrome mode no longer keeps reconnecting in both, and the window that lost the tab shows that the browser opened in another viewer. [#34133](https://github.com/open-webui/open-webui/pull/34133), [#34095](https://github.com/open-webui/open-webui/issues/34095)
|
||||
- **Ports open in new tabs.** The Open in new tab button beside a port on the start page of a Browser tab now opens the server running on that port instead of a "404: Not Found" page. [#34120](https://github.com/open-webui/open-webui/pull/34120), [#34108](https://github.com/open-webui/open-webui/issues/34108)
|
||||
- **Smooth Browser tab resizing.** Dragging the divider of the side panel no longer makes the Browser tab flicker and resize the page in slow motion. [#33989](https://github.com/open-webui/open-webui/pull/33989), [#33988](https://github.com/open-webui/open-webui/issues/33988)
|
||||
- **Terminal proxy headers.** A "TERMINAL_PROXY_HEADERS" entry written in a different letter case now replaces the terminal's own header instead of being sent next to it, and repeated headers from the terminal such as several cookies are all passed on. [#34092](https://github.com/open-webui/open-webui/issues/34092)
|
||||
- **Groups need a name.** A new group can no longer be saved without a name from a tab other than General, because Save stays off until a name is typed and the server now rejects empty or blank group names. [#34518](https://github.com/open-webui/open-webui/issues/34518)
|
||||
- **User list API groups.** The admin endpoint that lists all users now includes each user's groups instead of an empty list. [#34489](https://github.com/open-webui/open-webui/pull/34489), [#26156](https://github.com/open-webui/open-webui/discussions/26156)
|
||||
- **Model filter tags update.** The tag filter of the model selector now also lists tags that models gain while a chat is open, instead of only the tags present when the page loaded. [#33990](https://github.com/open-webui/open-webui/pull/33990), [#33806](https://github.com/open-webui/open-webui/issues/33806)
|
||||
- **Mark folder chats read.** Mark all as read in the menu on a folder page now marks the folder's chats as read instead of doing nothing. [#34404](https://github.com/open-webui/open-webui/pull/34404), [#34403](https://github.com/open-webui/open-webui/issues/34403)
|
||||
- **Folder page kept.** Opening a chat in another browser tab no longer sends a folder's chat list back to page 1. [#34145](https://github.com/open-webui/open-webui/pull/34145), [#34142](https://github.com/open-webui/open-webui/issues/34142)
|
||||
- **Same-folder chat drops.** Dropping a chat back on the folder it is already in no longer moves it there again and reloads every folder in the sidebar. [#34461](https://github.com/open-webui/open-webui/pull/34461), [#34460](https://github.com/open-webui/open-webui/issues/34460)
|
||||
- **Comment box on Android.** Writing a comment on selected text on an Android phone no longer closes the comment box as soon as the keyboard opens.
|
||||
- **Steadier menu placement.** Menus that open above their button, such as Model controls and the + menu of the message input, now grow upward when their content changes instead of briefly covering the message input, and right-aligned menus in Firefox no longer creep sideways while they open. [#34052](https://github.com/open-webui/open-webui/pull/34052), [#34051](https://github.com/open-webui/open-webui/issues/34051), [#34227](https://github.com/open-webui/open-webui/pull/34227), [#34226](https://github.com/open-webui/open-webui/issues/34226)
|
||||
- **Long settings text boxes.** Long prompt templates and JSON fields in Admin Settings now stop growing at a set height and scroll, instead of stretching the page to fit all of their text. [#34569](https://github.com/open-webui/open-webui/issues/34569)
|
||||
- **Hover preview behind menus.** A chat's hover preview in the sidebar no longer opens on top of another chat's open menu and covers its items. [#34231](https://github.com/open-webui/open-webui/pull/34231), [#34230](https://github.com/open-webui/open-webui/issues/34230)
|
||||
- **Hover preview without bubbles.** With Chat Bubble UI turned off, your messages in a chat's hover preview now show as padded bubbles instead of text squeezed onto a grey block. [#34347](https://github.com/open-webui/open-webui/issues/34347)
|
||||
- **Translated automation schedules.** The Schedule button in the dialog that creates an automation now shows the schedule in the chosen language instead of always in English. [#34428](https://github.com/open-webui/open-webui/pull/34428), [#34426](https://github.com/open-webui/open-webui/issues/34426)
|
||||
- **Qdrant version warning.** Connecting to a Qdrant 1.20 server, as the vector database or for external Qdrant knowledge bases, no longer logs a client version warning, which servers on Qdrant 1.18 or older now get instead. [#34485](https://github.com/open-webui/open-webui/pull/34485), [#34483](https://github.com/open-webui/open-webui/issues/34483)
|
||||
- **Image zoom reset.** Resetting the zoom of an image preview from below 10% now returns it to 100% and centers it again. [#34080](https://github.com/open-webui/open-webui/pull/34080), [#34079](https://github.com/open-webui/open-webui/issues/34079)
|
||||
- **Steady Tools count.** The count on the Tools tab of the workspace no longer drops to 0 for a moment when the Tools page opens. [#34236](https://github.com/open-webui/open-webui/pull/34236)
|
||||
- **Unpin tooltip on notes.** The Unpin button on a pinned note in the sidebar now shows a tooltip, as it does on pinned models. [#34568](https://github.com/open-webui/open-webui/pull/34568), [#34567](https://github.com/open-webui/open-webui/issues/34567)
|
||||
|
||||
### Changed
|
||||
|
||||
- **Terminals 0.4.0 required.** Connections to a Terminals server no longer carry a policy in Admin Settings > Integrations, so the Policy ID, image, resource, storage, idle timeout and Terminal Contexts settings and the Refresh Terminals button are gone, the server has to run Terminals 0.4.0 or later, and models, folders, automations and chats that used the old connection need one of the new terminals selected. Upgrading Terminals from 0.3.x takes its manual migration, as there is no automatic one, new Terminals installations start without a template, Open WebUI now connects with the Terminals server key, and "TERMINALS_OPEN_WEBUI_URL" and "TERMINALS_TOKEN_CACHE_TTL" should be removed from the Terminals settings. Open Terminal and Tether terminal connections are not affected.
|
||||
- **Direct connections move to Tether.** Settings > Connections and Settings > Tools are gone together with the Direct Connections and Direct Integrations switches in Admin Settings, the Direct Tool Servers permission and the "ENABLE_DIRECT_CONNECTIONS", "ENABLE_DIRECT_INTEGRATIONS" and "USER_PERMISSIONS_FEATURES_DIRECT_TOOL_SERVERS" settings, so models, tool servers and terminals that users added in their own settings no longer appear. Users add them in the Tether app (0.1.14 or later, 0.1.16 for MCP servers) instead, where they stay on their own computer and work in every Open WebUI they connect.
|
||||
- **Image settings become connections.** On the first start of this version, the image generation and editing settings are turned into image connections that everyone who could use them before keeps using, and from then on the image environment variables such as "IMAGE_GENERATION_ENGINE", "IMAGES_OPENAI_API_BASE_URL" and "COMFYUI_BASE_URL" are no longer read unless "ENABLE_PERSISTENT_CONFIG" is turned off.
|
||||
- **Locked Docker dependencies.** The standard and slim Docker images now install every Python package except PyTorch from lock files pinned with hashes, so rebuilding the same version installs the same packages, and custom images that edit "backend/requirements.txt" must regenerate the locks with "backend/update-locks.sh" for the edit to take effect. [#33981](https://github.com/open-webui/open-webui/pull/33981), [#33979](https://github.com/open-webui/open-webui/issues/33979)
|
||||
- **New coding agent model IDs.** Coding agent models now get IDs made only of letters, digits, dashes and underscores, which makes pinned Cursor and Pi models work, and pins, default models and automations that point at an agent model whose name had other characters, dots included as in most Codex models, need the model picked again. [#34171](https://github.com/open-webui/open-webui/pull/34171), [#34168](https://github.com/open-webui/open-webui/issues/34168)
|
||||
- **Coding agent sessions restart once.** The first new message in a coding agent chat from an earlier version starts a new agent session that gets the chat so far as text, instead of resuming the agent's own session.
|
||||
- **Image API model checks.** Image generation and edit requests sent through the API now run on the model they name, which has to be one of the caller's image models or the request fails with an error, instead of image generation ignoring the named model.
|
||||
- **Live update events renamed.** Real-time updates for notes, comments, the inbox, access changes, encrypted channels and channel app errors now arrive as typed messages on the main "events" socket channel, so custom clients that listened for the old event names such as "events:note" or "note:presence" need to listen there instead.
|
||||
- **Chat write access field.** Chat responses from the API now carry the saved sharing mode in "share_mode" and report whether you can reply in a new "write_access" field, so custom clients that read "share_mode" for that need to switch.
|
||||
- **Terminal uploads go to files.** New terminal connections now start with Chat Uploads set to Filesystem and computers connected through Tether always use it, so files attached in a chat are saved into the selected terminal's working folder instead of being processed as regular chat uploads, while existing connections keep their setting. Open Terminal 0.17.20 or later is recommended, as it fixes uploads becoming unreadable in multi-user setups.
|
||||
- **Chat menu items moved.** Overview, Artifacts and Comments are no longer in the chat's menu and now open from the + menu of the tab bar, where Overview opens as a tab beside the chat instead of a full-screen window.
|
||||
- **Note comments button.** Comments on a note now open from a button in the note's top bar instead of from its menu, and in a note you can edit, commenting on selected text is now a Comment button in the formatting toolbar.
|
||||
- **One heading menu.** The formatting toolbar of the message input and of notes now offers Heading 1, 2 and 3 in a single heading menu instead of three separate buttons.
|
||||
- **Attachments menu renamed.** The Add Context entry in the + menu of the message input, which holds the options to attach web pages, files, notes, knowledge and chats, is now called Attachments. [#34431](https://github.com/open-webui/open-webui/pull/34431)
|
||||
- **Capabilities now Features.** The Capabilities section of the model editor is now called Features. [#34433](https://github.com/open-webui/open-webui/pull/34433)
|
||||
- **Knowledge base labels.** The knowledge picker in the chat, the knowledge selector of the model editor and attached knowledge bases now call them Knowledge or Knowledge Base instead of Collection, the vector database term, and the search box inside a knowledge base now says Search Files. [#34432](https://github.com/open-webui/open-webui/pull/34432)
|
||||
|
||||
## [0.13.3] - 2026-11-08
|
||||
|
||||
### Added
|
||||
|
||||
+4
-4
@@ -154,7 +154,7 @@ RUN apt-get update && \
|
||||
fi && rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# install python dependencies
|
||||
COPY --chown=$UID:$GID ./backend/requirements*.txt ./
|
||||
COPY --chown=$UID:$GID ./backend/requirements*.lock ./
|
||||
|
||||
# Set UV_LINK_MODE to copy to prevent 0-byte file corruption in QEMU arm64 cross-builds
|
||||
ENV UV_LINK_MODE=copy
|
||||
@@ -162,19 +162,19 @@ ENV UV_LINK_MODE=copy
|
||||
RUN --mount=from=ghcr.io/astral-sh/uv:0.12.10,source=/uv,target=/bin/uv \
|
||||
set -e; \
|
||||
if [ "$USE_SLIM" = "true" ]; then \
|
||||
uv pip install --system -r requirements-slim.txt --no-cache-dir; \
|
||||
uv pip install --system --no-deps --require-hashes -r requirements-slim.lock --no-cache-dir; \
|
||||
elif [ "$USE_CUDA" = "true" ]; then \
|
||||
# If you use CUDA the whisper and embedding model will be downloaded on first use
|
||||
# fix: pin torch<=2.9.1 - torch 2.10.0 aarch64 wheels cause SIGILL on ARM devices (RPi 4 Cortex-A72) #21349
|
||||
pip3 install 'torch<=2.9.1' torchvision torchaudio --index-url https://download.pytorch.org/whl/$USE_CUDA_DOCKER_VER --no-cache-dir; \
|
||||
uv pip install --system -r requirements.txt --no-cache-dir; \
|
||||
uv pip install --system --no-deps --require-hashes -r requirements.lock --no-cache-dir; \
|
||||
python -c "import os; from sentence_transformers import SentenceTransformer; SentenceTransformer(os.environ['RAG_EMBEDDING_MODEL'], device='cpu')"; \
|
||||
python -c "import os; from sentence_transformers import SentenceTransformer; SentenceTransformer(os.environ.get('AUXILIARY_EMBEDDING_MODEL', 'TaylorAI/bge-micro-v2'), device='cpu')"; \
|
||||
python -c "import os; from faster_whisper import WhisperModel; WhisperModel(os.environ['WHISPER_MODEL'], device='cpu', compute_type='int8', download_root=os.environ['WHISPER_MODEL_DIR'])"; \
|
||||
python -c "import os; import tiktoken; tiktoken.get_encoding(os.environ['TIKTOKEN_ENCODING_NAME'])"; \
|
||||
else \
|
||||
pip3 install 'torch<=2.9.1' torchvision torchaudio --index-url https://download.pytorch.org/whl/cpu --no-cache-dir; \
|
||||
uv pip install --system -r requirements.txt --no-cache-dir; \
|
||||
uv pip install --system --no-deps --require-hashes -r requirements.lock --no-cache-dir; \
|
||||
if [ "$USE_SLIM" != "true" ]; then \
|
||||
python -c "import os; from sentence_transformers import SentenceTransformer; SentenceTransformer(os.environ['RAG_EMBEDDING_MODEL'], device='cpu')"; \
|
||||
python -c "import os; from sentence_transformers import SentenceTransformer; SentenceTransformer(os.environ.get('AUXILIARY_EMBEDDING_MODEL', 'TaylorAI/bge-micro-v2'), device='cpu')"; \
|
||||
|
||||
@@ -219,11 +219,6 @@ if CUSTOM_NAME:
|
||||
pass
|
||||
|
||||
|
||||
# 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'
|
||||
@@ -1562,6 +1557,14 @@ except JSONCodec.JSONDecodeError:
|
||||
|
||||
IMAGES_EDIT_COMFYUI_WORKFLOW_NODES = images_edit_comfyui_workflow_nodes
|
||||
|
||||
# Videos
|
||||
|
||||
ENABLE_VIDEO_GENERATION = os.getenv('ENABLE_VIDEO_GENERATION', '').lower() == 'true'
|
||||
|
||||
# How long to wait for a video job to finish, and how often to check on it.
|
||||
VIDEO_GENERATION_TIMEOUT = int(os.getenv('VIDEO_GENERATION_TIMEOUT', '900'))
|
||||
VIDEO_GENERATION_POLL_INTERVAL = float(os.getenv('VIDEO_GENERATION_POLL_INTERVAL', '5'))
|
||||
|
||||
# Audio
|
||||
|
||||
# Transcription
|
||||
@@ -1936,16 +1939,17 @@ USER_PERMISSIONS_CHAT_TEMPORARY_ENFORCED = (
|
||||
)
|
||||
|
||||
|
||||
USER_PERMISSIONS_FEATURES_DIRECT_TOOL_SERVERS = (
|
||||
os.getenv('USER_PERMISSIONS_FEATURES_DIRECT_TOOL_SERVERS', 'False').lower() == 'true'
|
||||
)
|
||||
|
||||
USER_PERMISSIONS_FEATURES_WEB_SEARCH = os.getenv('USER_PERMISSIONS_FEATURES_WEB_SEARCH', 'True').lower() == 'true'
|
||||
|
||||
USER_PERMISSIONS_FEATURES_IMAGE_GENERATION = (
|
||||
os.getenv('USER_PERMISSIONS_FEATURES_IMAGE_GENERATION', 'True').lower() == 'true'
|
||||
)
|
||||
|
||||
# Off by default: video costs far more per request than images.
|
||||
USER_PERMISSIONS_FEATURES_VIDEO_GENERATION = (
|
||||
os.getenv('USER_PERMISSIONS_FEATURES_VIDEO_GENERATION', 'False').lower() == 'true'
|
||||
)
|
||||
|
||||
USER_PERMISSIONS_FEATURES_CODE_INTERPRETER = (
|
||||
os.getenv('USER_PERMISSIONS_FEATURES_CODE_INTERPRETER', 'True').lower() == 'true'
|
||||
)
|
||||
@@ -1964,6 +1968,8 @@ USER_PERMISSIONS_FEATURES_API_KEYS = os.getenv('USER_PERMISSIONS_FEATURES_API_KE
|
||||
|
||||
USER_PERMISSIONS_FEATURES_MEMORIES = os.getenv('USER_PERMISSIONS_FEATURES_MEMORIES', 'True').lower() == 'true'
|
||||
|
||||
USER_PERMISSIONS_FEATURES_SUBAGENTS = os.getenv('USER_PERMISSIONS_FEATURES_SUBAGENTS', 'True').lower() == 'true'
|
||||
|
||||
USER_PERMISSIONS_FEATURES_AUTOMATIONS = os.getenv('USER_PERMISSIONS_FEATURES_AUTOMATIONS', 'False').lower() == 'true'
|
||||
|
||||
USER_PERMISSIONS_FEATURES_CALENDAR = os.getenv('USER_PERMISSIONS_FEATURES_CALENDAR', 'True').lower() == 'true'
|
||||
@@ -2046,12 +2052,13 @@ DEFAULT_USER_PERMISSIONS = {
|
||||
'folders': USER_PERMISSIONS_FEATURES_FOLDERS,
|
||||
'channels': USER_PERMISSIONS_FEATURES_CHANNELS,
|
||||
'encrypted_channels': USER_PERMISSIONS_FEATURES_ENCRYPTED_CHANNELS,
|
||||
'direct_tool_servers': USER_PERMISSIONS_FEATURES_DIRECT_TOOL_SERVERS,
|
||||
# Chat features
|
||||
'web_search': USER_PERMISSIONS_FEATURES_WEB_SEARCH,
|
||||
'image_generation': USER_PERMISSIONS_FEATURES_IMAGE_GENERATION,
|
||||
'video_generation': USER_PERMISSIONS_FEATURES_VIDEO_GENERATION,
|
||||
'code_interpreter': USER_PERMISSIONS_FEATURES_CODE_INTERPRETER,
|
||||
'memories': USER_PERMISSIONS_FEATURES_MEMORIES,
|
||||
'subagents': USER_PERMISSIONS_FEATURES_SUBAGENTS,
|
||||
'automations': USER_PERMISSIONS_FEATURES_AUTOMATIONS,
|
||||
'calendar': USER_PERMISSIONS_FEATURES_CALENDAR,
|
||||
'webhooks': USER_PERMISSIONS_FEATURES_USER_WEBHOOKS,
|
||||
@@ -2283,6 +2290,8 @@ CONTEXT_COMPACTION_RETENTION_PERCENTAGE = min(
|
||||
|
||||
CONTEXT_COMPACTION_PROMPT_TEMPLATE = os.getenv('CONTEXT_COMPACTION_PROMPT_TEMPLATE', '')
|
||||
|
||||
VISUALIZATION_PROMPT_TEMPLATE = os.getenv('VISUALIZATION_PROMPT_TEMPLATE', '')
|
||||
|
||||
ENABLE_TOOL_SEARCH = os.getenv('ENABLE_TOOL_SEARCH', 'False').lower() == 'true'
|
||||
TOOL_SEARCH_ENGINE = os.getenv('TOOL_SEARCH_ENGINE', 'bm25')
|
||||
TOOL_SEARCH_DECISIONS_API_BASE_URL = os.getenv('TOOL_SEARCH_DECISIONS_API_BASE_URL', 'https://api.openai.com/v1')
|
||||
@@ -2962,8 +2971,6 @@ DEFAULT_CONFIG = {
|
||||
'skills.content_max_chars': SKILL_CONTENT_MAX_CHARS,
|
||||
'skills.preview_max_chars': SKILL_PREVIEW_MAX_CHARS,
|
||||
'chats.view_max_chars': VIEW_CHAT_MAX_CHARS,
|
||||
'direct.enable': ENABLE_DIRECT_CONNECTIONS,
|
||||
'direct.integrations.enable': ENABLE_DIRECT_INTEGRATIONS,
|
||||
'ollama.enable': ENABLE_OLLAMA_API,
|
||||
'ollama.base_urls': OLLAMA_BASE_URLS,
|
||||
'ollama.api_configs': OLLAMA_API_CONFIGS,
|
||||
@@ -3173,6 +3180,7 @@ DEFAULT_CONFIG = {
|
||||
'image_generation.size': IMAGE_SIZE,
|
||||
'image_generation.steps': IMAGE_STEPS,
|
||||
'image_generation.prompt.enable': ENABLE_IMAGE_PROMPT_GENERATION,
|
||||
'image_generation.default_model': '',
|
||||
'image_generation.automatic1111.base_url': AUTOMATIC1111_BASE_URL,
|
||||
'image_generation.automatic1111.api_auth': AUTOMATIC1111_API_AUTH,
|
||||
'image_generation.automatic1111.api_params': AUTOMATIC1111_PARAMS,
|
||||
@@ -3190,6 +3198,9 @@ DEFAULT_CONFIG = {
|
||||
'images.edit.enable': ENABLE_IMAGE_EDIT,
|
||||
'images.edit.engine': IMAGE_EDIT_ENGINE,
|
||||
'images.edit.model': IMAGE_EDIT_MODEL,
|
||||
'images.edit.default_model': '',
|
||||
'video_generation.enable': ENABLE_VIDEO_GENERATION,
|
||||
'video_generation.default_model': '',
|
||||
'images.edit.size': IMAGE_EDIT_SIZE,
|
||||
'images.edit.openai.api_base_url': IMAGES_EDIT_OPENAI_API_BASE_URL,
|
||||
'images.edit.openai.api_version': IMAGES_EDIT_OPENAI_API_VERSION,
|
||||
@@ -3302,6 +3313,7 @@ DEFAULT_CONFIG = {
|
||||
'chat.context_compaction.token_cap': CONTEXT_COMPACTION_TOKEN_CAP,
|
||||
'chat.context_compaction.retention_percentage': CONTEXT_COMPACTION_RETENTION_PERCENTAGE,
|
||||
'chat.context_compaction.prompt_template': CONTEXT_COMPACTION_PROMPT_TEMPLATE,
|
||||
'chat.visualizations.prompt_template': VISUALIZATION_PROMPT_TEMPLATE,
|
||||
'chat.tool_permissions.enable': ENABLE_TOOL_PERMISSIONS,
|
||||
'chat.tool_call_labels.enable': ENABLE_TOOL_CALL_LABELS,
|
||||
'chat.tool_permissions.auto.enable': ENABLE_TOOL_PERMISSIONS_AUTO,
|
||||
|
||||
@@ -695,6 +695,9 @@ class EventDefinitions(BaseModel):
|
||||
IMAGE_EDITED: EventDefinition = EventDefinition(
|
||||
name='image.edited', description='An image was edited.', message='Image edited'
|
||||
)
|
||||
VIDEO_GENERATED: EventDefinition = EventDefinition(
|
||||
name='video.generated', description='A video was generated.', message='Video generated'
|
||||
)
|
||||
AUDIO_SPEECH_REQUESTED: EventDefinition = EventDefinition(
|
||||
name='audio.speech_requested', description='Speech generation was requested.', message='Speech requested'
|
||||
)
|
||||
|
||||
@@ -31,7 +31,7 @@ from open_webui.env import (
|
||||
USE_SLIM,
|
||||
)
|
||||
from open_webui.utils.json_codec import JSONCodec
|
||||
from sqlalchemy import Dialect, MetaData, create_engine, event, types
|
||||
from sqlalchemy import Dialect, MetaData, create_engine, event, text, types
|
||||
from sqlalchemy.engine.url import make_url
|
||||
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
|
||||
from sqlalchemy.ext.declarative import declarative_base
|
||||
@@ -113,6 +113,62 @@ extract_ssl_mode_from_url = extract_ssl_params_from_url
|
||||
reattach_ssl_mode_to_url = reattach_ssl_params_to_url
|
||||
|
||||
|
||||
_SURROGATES = re.compile('[\ud800-\udfff]')
|
||||
|
||||
|
||||
def strip_unstorable_json(value):
|
||||
"""Drop U+0000 and lone surrogates from every string, keys included."""
|
||||
if isinstance(value, str):
|
||||
return _SURROGATES.sub('', value.replace('\x00', ''))
|
||||
if isinstance(value, dict):
|
||||
return {strip_unstorable_json(k): strip_unstorable_json(v) for k, v in value.items()}
|
||||
if isinstance(value, list):
|
||||
return [strip_unstorable_json(v) for v in value]
|
||||
return value
|
||||
|
||||
|
||||
def dumps_json_for_db(value) -> str:
|
||||
"""Serialize JSON for storage.
|
||||
|
||||
PostgreSQL's json type stores the ``\\u0000`` escape but every ``->``, ``->>`` and ``#>>``
|
||||
that reaches it fails, so one such row breaks any query navigating the column; lone
|
||||
surrogates are rejected outright. Both are stripped here, the single path every JSON
|
||||
write takes, so no model has to remember to.
|
||||
"""
|
||||
serialized = JSONCodec.dumps(value, ensure_ascii=False)
|
||||
# A literally typed backslash-u0000 also matches; the re-dump then leaves it as is.
|
||||
if '\\u0000' in serialized or (not serialized.isascii() and _SURROGATES.search(serialized)):
|
||||
serialized = JSONCodec.dumps(strip_unstorable_json(value), ensure_ascii=False)
|
||||
return serialized
|
||||
|
||||
|
||||
async def strip_nul_from_json(db: AsyncSession) -> None:
|
||||
"""Rewrite PostgreSQL json values still holding ``\\u0000`` from before ``dumps_json_for_db`` stripped it."""
|
||||
quote = db.get_bind().dialect.identifier_preparer.quote
|
||||
columns = await db.execute(
|
||||
text(
|
||||
'SELECT table_name, column_name FROM information_schema.columns '
|
||||
"WHERE table_schema = current_schema() AND data_type = 'json'"
|
||||
)
|
||||
)
|
||||
for table, column in columns.all():
|
||||
table, column = quote(table), quote(column)
|
||||
# json keeps its input text verbatim, so the escape is findable without parsing every row.
|
||||
rows = await db.execute(
|
||||
text(f'SELECT ctid::text, {column}::text FROM {table} WHERE strpos({column}::text, :escape) > 0'),
|
||||
{'escape': '\\u0000'},
|
||||
)
|
||||
for ctid, raw in rows.all():
|
||||
value = JSONCodec.loads(raw)
|
||||
cleaned = strip_unstorable_json(value)
|
||||
if cleaned != value:
|
||||
await db.execute(
|
||||
text(f'UPDATE {table} SET {column} = CAST(:value AS json) WHERE ctid = CAST(:ctid AS tid)'),
|
||||
{'value': dumps_json_for_db(cleaned), 'ctid': ctid},
|
||||
)
|
||||
await db.commit()
|
||||
|
||||
|
||||
class JSONField(types.TypeDecorator): # TEXT-backed JSON storage
|
||||
"""Store arbitrary Python objects as JSON-encoded TEXT.
|
||||
|
||||
@@ -125,7 +181,7 @@ class JSONField(types.TypeDecorator): # TEXT-backed JSON storage
|
||||
cache_ok = True
|
||||
|
||||
def process_bind_param(self, value: _T | None, dialect: Dialect) -> Any:
|
||||
return JSONCodec.dumps(value, ensure_ascii=False) if value is not None else None
|
||||
return dumps_json_for_db(value) if value is not None else None
|
||||
|
||||
def process_result_value(self, value: _T | None, dialect: Dialect) -> Any:
|
||||
return JSONCodec.loads(value) if value is not None else None
|
||||
@@ -256,7 +312,7 @@ def _json_codec_kwargs(kwargs: dict) -> dict:
|
||||
Unlike ``JSONField``, those serialize through the engine, which otherwise uses
|
||||
stdlib ``json``. With ``ENABLE_ORJSON`` off JSONCodec is stdlib ``json`` anyway.
|
||||
"""
|
||||
kwargs.setdefault('json_serializer', lambda value: JSONCodec.dumps(value, ensure_ascii=False))
|
||||
kwargs.setdefault('json_serializer', dumps_json_for_db)
|
||||
kwargs.setdefault('json_deserializer', JSONCodec.loads)
|
||||
return kwargs
|
||||
|
||||
|
||||
+62
-91
@@ -184,6 +184,7 @@ from open_webui.routers import (
|
||||
tools,
|
||||
users,
|
||||
utils,
|
||||
videos,
|
||||
)
|
||||
from open_webui.routers.retrieval import (
|
||||
get_ef,
|
||||
@@ -199,7 +200,6 @@ from open_webui.socket.main import (
|
||||
periodic_session_pool_cleanup,
|
||||
periodic_socket_authentication,
|
||||
periodic_usage_pool_cleanup,
|
||||
redis_event_listener,
|
||||
sio,
|
||||
)
|
||||
from open_webui.socket.main import (
|
||||
@@ -250,6 +250,7 @@ from open_webui.utils.chat_variables import (
|
||||
)
|
||||
from open_webui.utils.embeddings import generate_embeddings
|
||||
from open_webui.utils.headers import get_headers_and_cookies
|
||||
from open_webui.utils.images.connections import migrate_legacy_image_config
|
||||
from open_webui.utils.json_codec import JSONCodec
|
||||
from open_webui.utils.json_response import apply_orjson_http_json
|
||||
from open_webui.utils.logger import start_logger
|
||||
@@ -268,6 +269,7 @@ from open_webui.utils.models import (
|
||||
get_all_models,
|
||||
get_filtered_models,
|
||||
)
|
||||
from open_webui.routers.openai import get_tether_model, get_tether_models
|
||||
from open_webui.utils.payload import apply_model_controls
|
||||
from open_webui.utils.oauth import (
|
||||
OAuthClientInformationFull,
|
||||
@@ -367,8 +369,6 @@ https://github.com/open-webui/open-webui
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
# Store reference to main event loop for sync->async calls (e.g., embedding generation)
|
||||
# This allows sync functions to schedule work on the main loop without blocking health checks
|
||||
app.state.main_loop = asyncio.get_running_loop()
|
||||
|
||||
if THREAD_POOL_SIZE and THREAD_POOL_SIZE > 0:
|
||||
@@ -395,6 +395,7 @@ async def lifespan(app: FastAPI):
|
||||
await validate_mfa_configuration()
|
||||
await initialize_runtime_config(app)
|
||||
await migrate_legacy_webhook_config()
|
||||
await migrate_legacy_image_config()
|
||||
request = Request(
|
||||
{
|
||||
'type': 'http',
|
||||
@@ -437,7 +438,6 @@ async def lifespan(app: FastAPI):
|
||||
app.state.redis_task_heartbeat = asyncio.create_task(redis_task_heartbeat(app))
|
||||
|
||||
if WEBSOCKET_MANAGER == 'redis':
|
||||
app.state.redis_event_listener = asyncio.create_task(redis_event_listener())
|
||||
# socket.io only starts listening on its first connect; event call answers need it earlier
|
||||
sio.manager_initialized = True
|
||||
sio.manager.initialize()
|
||||
@@ -535,9 +535,6 @@ async def lifespan(app: FastAPI):
|
||||
if hasattr(app.state, 'redis_task_heartbeat'):
|
||||
app.state.redis_task_heartbeat.cancel()
|
||||
|
||||
if hasattr(app.state, 'redis_event_listener'):
|
||||
app.state.redis_event_listener.cancel()
|
||||
|
||||
app.state.periodic_socket_authentication.cancel()
|
||||
app.state.periodic_usage_pool_cleanup.cancel()
|
||||
app.state.periodic_session_pool_cleanup.cancel()
|
||||
@@ -822,6 +819,7 @@ app.include_router(openai.router, prefix='/openai', tags=['openai'])
|
||||
app.include_router(pipelines.router, prefix='/api/v1/pipelines', tags=['pipelines'])
|
||||
app.include_router(tasks.router, prefix='/api/v1/tasks', tags=['tasks'])
|
||||
app.include_router(images.router, prefix='/api/v1/images', tags=['images'])
|
||||
app.include_router(videos.router, prefix='/api/v1/videos', tags=['videos'])
|
||||
|
||||
app.include_router(audio.router, prefix='/api/v1/audio', tags=['audio'])
|
||||
app.include_router(retrieval.router, prefix='/api/v1/retrieval', tags=['retrieval'])
|
||||
@@ -898,6 +896,12 @@ async def get_models(
|
||||
# models the caller can actually see.
|
||||
models = await get_filtered_models(models, user)
|
||||
|
||||
# The user's own connections, reached through their Tether. Shared models win on id clashes.
|
||||
if refresh:
|
||||
await get_tether_models.cache.clear()
|
||||
known = {model['id'] for model in models}
|
||||
models.extend(model for model in (await get_tether_models(user)).values() if model['id'] not in known)
|
||||
|
||||
for model in models:
|
||||
info = model.get('info') if isinstance(model.get('info'), dict) else {}
|
||||
meta = info.get('meta') if isinstance(info.get('meta'), dict) else {}
|
||||
@@ -1089,17 +1093,6 @@ async def embeddings(request: Request, form_data: dict, user=Depends(get_verifie
|
||||
return await generate_embeddings(request, form_data, user)
|
||||
|
||||
|
||||
async def _set_direct_model(request: Request, model_item: dict, user) -> None:
|
||||
model_meta = (model_item.get('info') or {}).get('meta') or {}
|
||||
knowledge_items = model_meta.get('knowledge')
|
||||
if knowledge_items:
|
||||
from open_webui.utils.access_control.files import get_accessible_folder_files
|
||||
|
||||
model_meta['knowledge'] = await get_accessible_folder_files(knowledge_items, user)
|
||||
request.state.direct = True
|
||||
request.state.model = model_item
|
||||
|
||||
|
||||
@app.post('/api/chat/completions')
|
||||
@app.post('/api/v1/chat/completions') # Experimental: Compatibility with OpenAI API
|
||||
async def chat_completion(
|
||||
@@ -1112,7 +1105,6 @@ async def chat_completion(
|
||||
|
||||
model_id = form_data.get('model', None)
|
||||
request.state.model_id = model_id
|
||||
model_item = form_data.pop('model_item', {})
|
||||
tasks = form_data.pop('background_tasks', None)
|
||||
|
||||
from open_webui.utils.terminals import get_folder_terminal_defaults, initialize_terminal_directory
|
||||
@@ -1145,18 +1137,21 @@ async def chat_completion(
|
||||
agent_model = next((item for item in candidates if item['id'] == model_id), None)
|
||||
if agent_model is None:
|
||||
raise HTTPException(400, 'Agent model is unavailable in the selected terminal')
|
||||
model_item = {} # Never trust client-supplied model metadata or direct-provider flags.
|
||||
|
||||
metadata = {}
|
||||
try:
|
||||
model_info = None
|
||||
fallback_model = None
|
||||
missing_base_model = False
|
||||
if not model_item.get('direct', False):
|
||||
if agent_model is None and model_id not in request.app.state.MODELS:
|
||||
tether_model = None
|
||||
if agent_model is None and model_id not in request.app.state.MODELS:
|
||||
# The user's own connection, reached through their Tether.
|
||||
tether_model = await get_tether_model(request, user, model_id)
|
||||
if tether_model is None:
|
||||
raise Exception('Model not found')
|
||||
|
||||
model = agent_model or request.app.state.MODELS[model_id]
|
||||
model = agent_model or tether_model or request.app.state.MODELS[model_id]
|
||||
if tether_model is None:
|
||||
model_info = await Models.get_model_by_id(model_id)
|
||||
missing_base_model = bool(
|
||||
model_info and model_info.base_model_id and model_info.base_model_id not in request.app.state.MODELS
|
||||
@@ -1191,9 +1186,6 @@ async def chat_completion(
|
||||
await check_model_access(user, fallback_model)
|
||||
except Exception as e:
|
||||
raise e
|
||||
else:
|
||||
model = model_item
|
||||
await _set_direct_model(request, model, user)
|
||||
|
||||
# Read before the fallback below can rebind model to a different one.
|
||||
model_capabilities = ((model.get('info') or {}).get('meta') or {}).get('capabilities') or {}
|
||||
@@ -1281,22 +1273,6 @@ async def chat_completion(
|
||||
|
||||
chat_variables = normalize_chat_variables(chat_variables)
|
||||
|
||||
# Drop tool_servers if caller lacks features.direct_tool_servers —
|
||||
# mirrors the storage-side strip in user/settings/update.
|
||||
tool_servers = form_data.pop('tool_servers', None)
|
||||
if (
|
||||
tool_servers
|
||||
and user.role != 'admin'
|
||||
and not await has_permission(
|
||||
user.id,
|
||||
'features.direct_tool_servers',
|
||||
await Config.get('user.permissions'),
|
||||
)
|
||||
):
|
||||
tool_servers = None
|
||||
if tool_servers and not await Config.get('direct.integrations.enable', False):
|
||||
tool_servers = None
|
||||
|
||||
automation_id = form_data.pop('automation_id', None)
|
||||
from open_webui.utils.tool_permissions import resolve_tool_approval_mode
|
||||
|
||||
@@ -1306,6 +1282,7 @@ async def chat_completion(
|
||||
)
|
||||
approval_resume = getattr(request.state, 'tool_approval_resume', None)
|
||||
metadata = {
|
||||
'model_id': model_id,
|
||||
'tool_approval_resume': approval_resume[2]
|
||||
if approval_resume and approval_resume[:2] == (chat_id, form_data.get('assistant_message_id'))
|
||||
else None,
|
||||
@@ -1323,7 +1300,6 @@ async def chat_completion(
|
||||
'folder_id': form_data.pop('folder_id', None),
|
||||
'filter_ids': form_data.pop('filter_ids', []),
|
||||
'tool_ids': form_data.get('tool_ids', None),
|
||||
'tool_servers': tool_servers,
|
||||
'files': form_data.get('files', None),
|
||||
'features': form_data.get('features', {}),
|
||||
'variables': form_data.get('variables', {}),
|
||||
@@ -1341,7 +1317,6 @@ async def chat_completion(
|
||||
'chat_variables': copy.deepcopy(chat_variables),
|
||||
},
|
||||
'model': model,
|
||||
'direct': model_item.get('direct', False),
|
||||
'params': {
|
||||
'stream_delta_chunk_size': stream_delta_chunk_size,
|
||||
'reasoning_tags': reasoning_tags,
|
||||
@@ -1474,6 +1449,9 @@ async def chat_completion(
|
||||
'id': chat_id,
|
||||
'title': 'New Chat',
|
||||
'models': [entry['model_id'] for entry in message_ids],
|
||||
'terminal_id': (model.get('agent') or {}).get('terminal_id')
|
||||
or form_data.get('terminal_id'),
|
||||
'working_directory': requested_directory or '',
|
||||
'history': {
|
||||
'currentId': all_assistant_ids[0] if all_assistant_ids else user_message_id,
|
||||
'messages': history_messages,
|
||||
@@ -1573,6 +1551,14 @@ async def chat_completion(
|
||||
|
||||
user_message = metadata.get('user_message') or {}
|
||||
assistant_message_id = metadata.get('assistant_message_id')
|
||||
if parent_id and not (
|
||||
assistant_message_id or metadata.get('regeneration_message_id') or metadata['internal']
|
||||
):
|
||||
from open_webui.utils.subagents import queue_user_message
|
||||
|
||||
# A reply in this chat is still running: it takes this message at its next step.
|
||||
if await queue_user_message(request, chat_id, user, user_message, parent_id):
|
||||
return {'status': True, 'queued': True, 'chat_id': chat_id}
|
||||
if assistant_message_id:
|
||||
message = await Chats.get_message_by_id_and_message_id(chat_id, assistant_message_id)
|
||||
if not message or (message.get('user_id') or chat.user_id) != user.id:
|
||||
@@ -1620,8 +1606,11 @@ async def chat_completion(
|
||||
chat_fields = {'models': selected_chat_models}
|
||||
if metadata.get('files') is not None:
|
||||
chat_fields['files'] = metadata['files']
|
||||
await Chats.update_chat_by_id(chat_id, chat_fields, touch=False)
|
||||
await Chats.update_chat_variables_by_id(chat_id, chat_variables)
|
||||
# Rewriting the stored chat is slow on long chats; skip it when nothing changed.
|
||||
if any((chat.chat or {}).get(key) != value for key, value in chat_fields.items()):
|
||||
await Chats.update_chat_by_id(chat_id, chat_fields, touch=False)
|
||||
if chat_variables != chat.variables:
|
||||
await Chats.update_chat_variables_by_id(chat_id, chat_variables)
|
||||
else:
|
||||
tasks = {
|
||||
key: value
|
||||
@@ -1665,20 +1654,17 @@ async def chat_completion(
|
||||
response_meta.pop('response_ended_at', None)
|
||||
message['meta'] = response_meta
|
||||
message['done'] = False
|
||||
if not metadata.get('direct'):
|
||||
target = (
|
||||
model_info
|
||||
if form_data['model'] == model_id
|
||||
else await Models.get_model_by_id(form_data['model'])
|
||||
)
|
||||
controls = target.params.model_dump().get('model_controls', {}) if target else {}
|
||||
if model.get('agent'):
|
||||
controls = model.get('info', {}).get('params', {}).get('model_controls', {})
|
||||
form_data['params'] = apply_model_controls(
|
||||
copy.deepcopy(form_data.get('params') or {}),
|
||||
controls,
|
||||
model_controls.get(form_data['model'], {}),
|
||||
)
|
||||
target = (
|
||||
model_info if form_data['model'] == model_id else await Models.get_model_by_id(form_data['model'])
|
||||
)
|
||||
controls = target.params.model_dump().get('model_controls', {}) if target else {}
|
||||
if model.get('agent'):
|
||||
controls = model.get('info', {}).get('params', {}).get('model_controls', {})
|
||||
form_data['params'] = apply_model_controls(
|
||||
copy.deepcopy(form_data.get('params') or {}),
|
||||
controls,
|
||||
model_controls.get(form_data['model'], {}),
|
||||
)
|
||||
ctx = None
|
||||
if is_new_chat:
|
||||
await initialize_terminal_directory(
|
||||
@@ -1687,7 +1673,17 @@ async def chat_completion(
|
||||
if model.get('agent'):
|
||||
from open_webui.utils.agents.runner import run as run_agent
|
||||
|
||||
return await run_agent(request, form_data, user, metadata, model)
|
||||
response = await run_agent(request, form_data, user, metadata, model)
|
||||
if tasks and TASKS.TITLE_GENERATION in tasks:
|
||||
title_tasks = {TASKS.TITLE_GENERATION: tasks[TASKS.TITLE_GENERATION]}
|
||||
ctx = await build_chat_response_context(
|
||||
request, form_data, user, model, metadata, title_tasks, []
|
||||
)
|
||||
try:
|
||||
await background_tasks_handler(ctx)
|
||||
except Exception:
|
||||
log.exception('Error generating agent chat title')
|
||||
return response
|
||||
# Saved chats load the message after approved tool calls run, so their results are kept
|
||||
if metadata.get('assistant_message_id') and not is_saved_chat_id(metadata.get('chat_id')):
|
||||
ctx = await build_chat_response_context(request, form_data, user, model, metadata, tasks, [])
|
||||
@@ -1821,23 +1817,10 @@ async def chat_completion(
|
||||
and getattr(request.state, 'internal', False) is not True
|
||||
and not await has_active_tasks(request.app.state.redis, chat_id)
|
||||
):
|
||||
from open_webui.utils.subagents import process_pending_internal_messages
|
||||
from open_webui.utils.subagents import get_pending_run, process_pending_internal_messages
|
||||
|
||||
await process_pending_internal_messages(
|
||||
request,
|
||||
chat_id,
|
||||
user.id,
|
||||
{
|
||||
'model_id': metadata.get('model_id') or form_data.get('model'),
|
||||
'session_id': metadata.get('session_id'),
|
||||
'tool_ids': metadata.get('tool_ids') or [],
|
||||
'skill_ids': metadata.get('skill_ids') or [],
|
||||
'chat_context': metadata.get('chat_context'),
|
||||
'filter_ids': metadata.get('filter_ids') or [],
|
||||
'terminal_id': metadata.get('terminal_id'),
|
||||
'features': metadata.get('features') or {},
|
||||
'variables': metadata.get('variables') or {},
|
||||
},
|
||||
request, chat_id, user.id, get_pending_run(metadata, form_data.get('model'))
|
||||
)
|
||||
except Exception:
|
||||
log.exception('Failed to process pending internal messages for chat %s', metadata.get('chat_id'))
|
||||
@@ -1861,6 +1844,7 @@ async def chat_completion(
|
||||
# Per-model metadata: own message_id + model
|
||||
per_model_metadata = {
|
||||
**metadata,
|
||||
'model_id': entry['model_id'],
|
||||
'chat_context': copy.deepcopy(metadata['chat_context']),
|
||||
'message_id': assistant_message_id,
|
||||
'task_id': str(uuid4()),
|
||||
@@ -2172,11 +2156,6 @@ async def chat_completed(request: Request, form_data: dict, user=Depends(get_ver
|
||||
await verify_chat_ownership(form_data.get('chat_id'), user)
|
||||
|
||||
try:
|
||||
model_item = form_data.pop('model_item', {})
|
||||
|
||||
if model_item.get('direct', False):
|
||||
await _set_direct_model(request, model_item, user)
|
||||
|
||||
return await chat_completed_handler(request, form_data, user)
|
||||
except Exception as e:
|
||||
raise HTTPException(
|
||||
@@ -2190,11 +2169,6 @@ async def chat_action(request: Request, action_id: str, form_data: dict, user=De
|
||||
await verify_chat_ownership(form_data.get('chat_id'), user)
|
||||
|
||||
try:
|
||||
model_item = form_data.pop('model_item', {})
|
||||
|
||||
if model_item.get('direct', False):
|
||||
await _set_direct_model(request, model_item, user)
|
||||
|
||||
return await chat_action_handler(request, action_id, form_data, user)
|
||||
except Exception as e:
|
||||
raise HTTPException(
|
||||
@@ -2393,8 +2367,6 @@ async def get_app_config(request: Request):
|
||||
'ui.enable_login_form',
|
||||
'auth.enable_api_keys',
|
||||
'ui.enable_password_change_form',
|
||||
'direct.enable',
|
||||
'direct.integrations.enable',
|
||||
'terminal_server.connections',
|
||||
'folders.enable',
|
||||
'folders.max_file_count',
|
||||
@@ -2415,6 +2387,7 @@ async def get_app_config(request: Request):
|
||||
'code_execution.enable',
|
||||
'code_interpreter.enable',
|
||||
'image_generation.enable',
|
||||
'video_generation.enable',
|
||||
'task.autocomplete.enable',
|
||||
'task.title.enable',
|
||||
'task.follow_up.enable',
|
||||
@@ -2499,9 +2472,6 @@ async def get_app_config(request: Request):
|
||||
'enable_pyodide_file_persistence': ENABLE_PYODIDE_FILE_PERSISTENCE,
|
||||
'enable_public_active_users_count': ENABLE_PUBLIC_ACTIVE_USERS_COUNT,
|
||||
'enable_easter_eggs': ENABLE_EASTER_EGGS,
|
||||
'enable_direct_connections': config.get('direct.enable'),
|
||||
'enable_direct_integrations': ENABLE_TOOL_SERVERS
|
||||
and config.get('direct.integrations.enable', False),
|
||||
'enable_plugins': ENABLE_PLUGINS,
|
||||
'enable_tools': ENABLE_TOOLS,
|
||||
'enable_functions': ENABLE_FUNCTIONS,
|
||||
@@ -2532,6 +2502,7 @@ async def get_app_config(request: Request):
|
||||
'enable_code_execution': config.get('code_execution.enable'),
|
||||
'enable_code_interpreter': config.get('code_interpreter.enable'),
|
||||
'enable_image_generation': config.get('image_generation.enable'),
|
||||
'enable_video_generation': config.get('video_generation.enable'),
|
||||
'enable_autocomplete_generation': config.get('task.autocomplete.enable'),
|
||||
'enable_title_generation': config.get('task.title.enable'),
|
||||
'enable_follow_up_generation': config.get('task.follow_up.enable'),
|
||||
|
||||
@@ -575,6 +575,13 @@ class AccessGrantsTable:
|
||||
- There's a grant for the specific user with the requested permission
|
||||
- There's a grant for any of the user's groups with the requested permission
|
||||
"""
|
||||
if resource_type == 'knowledge':
|
||||
from open_webui.retrieval.external import has_virtual_knowledge_access, is_virtual_knowledge_id
|
||||
|
||||
# Knowledge listed from a connection takes the connection's access; it has no grant rows.
|
||||
if is_virtual_knowledge_id(resource_id):
|
||||
return await has_virtual_knowledge_access(user_id, resource_id, permission)
|
||||
|
||||
async with get_async_db_context(db) as db:
|
||||
if user_group_ids is None:
|
||||
from open_webui.models.groups import Groups
|
||||
|
||||
@@ -160,6 +160,14 @@ class AutomationTable:
|
||||
row = await db.get(Automation, id)
|
||||
return AutomationModel.model_validate(row) if row else None
|
||||
|
||||
async def get_by_folder(self, folder_id: str, db: Optional[AsyncSession] = None) -> list[AutomationModel]:
|
||||
"""Every automation that lives in a folder, whoever created it."""
|
||||
async with get_async_db_context(db) as db:
|
||||
result = await db.execute(
|
||||
select(Automation).filter_by(folder_id=folder_id).order_by(Automation.created_at.asc())
|
||||
)
|
||||
return [AutomationModel.model_validate(r) for r in result.scalars().all()]
|
||||
|
||||
async def get_active_by_user(self, user_id: str, db: Optional[AsyncSession] = None) -> list[AutomationModel]:
|
||||
"""Get active automations for a user (for calendar RRULE expansion)."""
|
||||
async with get_async_db_context(db) as db:
|
||||
|
||||
@@ -383,6 +383,20 @@ class ChatMessageTable:
|
||||
)
|
||||
return result.scalar_one_or_none() is not None
|
||||
|
||||
async def has_queued_message(self, chat_id: str, message_id: str, db: Optional[AsyncSession] = None) -> bool:
|
||||
"""Whether the user sent a message while this reply was still running."""
|
||||
async with get_async_db_context(db) as db:
|
||||
result = await db.execute(
|
||||
select(ChatMessage.meta)
|
||||
.where(ChatMessage.chat_id == chat_id)
|
||||
.where(ChatMessage.parent_id == message_id)
|
||||
.where(ChatMessage.role == 'user')
|
||||
)
|
||||
return any(
|
||||
(meta or {}).get('status') == 'pending' and (meta or {}).get('internal') is not True
|
||||
for meta in result.scalars()
|
||||
)
|
||||
|
||||
async def get_messages_by_chat_id(self, chat_id: str, db: Optional[AsyncSession] = None) -> list[ChatMessageModel]:
|
||||
async with get_async_db_context(db) as db:
|
||||
result = await db.execute(
|
||||
@@ -635,6 +649,7 @@ class ChatMessageTable:
|
||||
|
||||
stmt = select(
|
||||
ChatMessage.model_id,
|
||||
func.max(ChatMessage.meta['model_name'].as_string()).label('model_name'),
|
||||
func.count(ChatMessage.id).label('count'),
|
||||
func.count(distinct(ChatMessage.user_id)).label('unique_users'),
|
||||
func.count(distinct(ChatMessage.chat_id)).label('unique_chats'),
|
||||
@@ -655,6 +670,7 @@ class ChatMessageTable:
|
||||
result = await db.execute(stmt)
|
||||
return {
|
||||
row.model_id: {
|
||||
'name': row.model_name if isinstance(row.model_name, str) and row.model_name.strip() else None,
|
||||
'count': row.count,
|
||||
'unique_users': row.unique_users,
|
||||
'unique_chats': row.unique_chats,
|
||||
|
||||
@@ -15,12 +15,17 @@ class ViewModel(BaseModel):
|
||||
|
||||
class PanelTab(ViewModel):
|
||||
id: str
|
||||
kind: Literal['chat', 'comments', 'files', 'file', 'terminal', 'browser', 'desktop', 'side']
|
||||
kind: Literal['chat', 'comments', 'files', 'file', 'terminal', 'browser', 'desktop', 'side', 'page', 'overview']
|
||||
label: str
|
||||
href: str | None = None
|
||||
terminalId: str | None = None
|
||||
terminalNumber: int | None = None
|
||||
chatId: str | None = None
|
||||
chatNumber: int | None = None
|
||||
parentChatId: str | None = None
|
||||
# Accept layouts from older clients; current clients normalize these on read.
|
||||
sideChatNumber: int | None = None
|
||||
sideChat: bool | None = None
|
||||
path: str | None = None
|
||||
page: int | None = None
|
||||
sessionId: str | None = None
|
||||
|
||||
@@ -21,7 +21,9 @@ from open_webui.models.automations import AutomationRun
|
||||
from open_webui.models.chat_messages import ChatMessage, ChatMessages
|
||||
from open_webui.models.folders import Folders
|
||||
from open_webui.models.tags import Tag, TagModel, Tags
|
||||
from open_webui.tasks import has_active_tasks
|
||||
from open_webui.utils.misc import get_output_text, sanitize_data_for_db, sanitize_text_for_db
|
||||
from open_webui.utils.session_records import has_pending_tool_approval
|
||||
from pydantic import BaseModel, ConfigDict, field_validator
|
||||
from sqlalchemy import (
|
||||
JSON,
|
||||
@@ -49,6 +51,30 @@ from sqlalchemy.sql.expression import bindparam
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
ACTIVE_CHAT_GAP_SECONDS = 30 * 60
|
||||
# Filter token for chats without a folder status. The status itself is stored and returned as null;
|
||||
# only query strings, which can't carry null, need a name for it.
|
||||
NO_FOLDER_STATUS = 'none'
|
||||
|
||||
|
||||
def _as_seconds(value):
|
||||
# Older rows may hold numbers as strings; chats set before tracking have none.
|
||||
try:
|
||||
return int(value)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def folder_status_since(meta: dict, status: str | None):
|
||||
"""When the chat would have entered `status` had all its time there been one stretch.
|
||||
|
||||
Earlier stretches in the same status count, so moving away and back doesn't reset it.
|
||||
"""
|
||||
started = _as_seconds(meta.get('folder_status_at'))
|
||||
if status is None or started is None:
|
||||
return None
|
||||
return started - (_as_seconds((meta.get('folder_status_durations') or {}).get(status)) or 0)
|
||||
|
||||
|
||||
CHAT_SEARCH_FILTER_PREFIXES = ('tag:', 'folder:', 'pinned:', 'archived:', 'shared:')
|
||||
|
||||
|
||||
@@ -349,6 +375,10 @@ class ChatResponse(BaseModel):
|
||||
return value if isinstance(value, dict) else {}
|
||||
|
||||
|
||||
class ChatAccessResponse(ChatResponse):
|
||||
write_access: bool
|
||||
|
||||
|
||||
class ChatTitleIdResponse(BaseModel):
|
||||
id: str
|
||||
title: str
|
||||
@@ -550,6 +580,11 @@ class ChatTable:
|
||||
and child.get('id') == child_id
|
||||
and child.get('role')
|
||||
and child.get('parentId') == message_id
|
||||
# A queued message waits in the queue, not on the branch shown.
|
||||
and not (
|
||||
(child.get('meta') or {}).get('status') == 'pending'
|
||||
and (child.get('meta') or {}).get('internal') is not True
|
||||
)
|
||||
),
|
||||
None,
|
||||
)
|
||||
@@ -879,6 +914,7 @@ class ChatTable:
|
||||
):
|
||||
updated['history']['messages'][mid] = message
|
||||
updated['history'] = self.merge_history(updated['history'], {})
|
||||
self._repair_chat_current_id(updated)
|
||||
|
||||
updated = self._clean_null_bytes(updated)
|
||||
chat_item.chat = updated
|
||||
@@ -1621,8 +1657,6 @@ class ChatTable:
|
||||
async with get_async_db_context(db) as session:
|
||||
chat = await session.get(Chat, id)
|
||||
chat.pinned = not chat.pinned
|
||||
chat.updated_at = int(time.time())
|
||||
chat.last_read_at = int(time.time())
|
||||
await session.commit()
|
||||
return ChatModel.model_validate(chat)
|
||||
except Exception:
|
||||
@@ -1634,8 +1668,6 @@ class ChatTable:
|
||||
chat = await session.get(Chat, id)
|
||||
chat.archived = not chat.archived
|
||||
chat.folder_id = None
|
||||
chat.updated_at = int(time.time())
|
||||
chat.last_read_at = int(time.time())
|
||||
await session.commit()
|
||||
return ChatModel.model_validate(chat)
|
||||
except Exception:
|
||||
@@ -2101,6 +2133,7 @@ class ChatTable:
|
||||
folder_ids: list[str],
|
||||
db: AsyncSession | None = None,
|
||||
) -> dict[str, int]:
|
||||
"""Count unread or approval-pending chats for folder notification badges."""
|
||||
if not folder_ids:
|
||||
return {}
|
||||
|
||||
@@ -2124,7 +2157,25 @@ class ChatTable:
|
||||
)
|
||||
.group_by(Chat.folder_id)
|
||||
)
|
||||
return {folder_id: count for folder_id, count in result.all() if folder_id}
|
||||
counts = {folder_id: count for folder_id, count in result.all() if folder_id}
|
||||
result = await session.execute(
|
||||
select(Chat.folder_id, Chat.id, ChatMessage.output)
|
||||
.join(ChatMessage, ChatMessage.chat_id == Chat.id)
|
||||
.where(
|
||||
Chat.user_id == user_id,
|
||||
Chat.folder_id.in_(folder_ids),
|
||||
Chat.archived == False,
|
||||
ChatMessage.role == 'assistant',
|
||||
ChatMessage.done.is_(False),
|
||||
)
|
||||
)
|
||||
# Unfinished chats are excluded above; count each approval-pending chat once.
|
||||
pending_chats = {
|
||||
(folder_id, chat_id) for folder_id, chat_id, output in result.all() if has_pending_tool_approval(output)
|
||||
}
|
||||
for folder_id, _ in pending_chats:
|
||||
counts[folder_id] = counts.get(folder_id, 0) + 1
|
||||
return counts
|
||||
|
||||
async def get_chats(self, skip: int = 0, limit: int = 50, db: AsyncSession | None = None) -> list[ChatModel]:
|
||||
async with get_async_db_context(db) as session:
|
||||
@@ -2599,6 +2650,329 @@ class ChatTable:
|
||||
participants[chat_id].append(author_id)
|
||||
return participants
|
||||
|
||||
def _folder_chat_conditions(
|
||||
self,
|
||||
folder_id: str,
|
||||
dialect_name: str,
|
||||
search: str = '',
|
||||
tag_ids: list[str] | None = None,
|
||||
status_ids: list[str] | None = None,
|
||||
valid_status_ids: tuple[str, ...] = (),
|
||||
) -> list:
|
||||
conditions = [
|
||||
Chat.folder_id == folder_id,
|
||||
Chat.archived.is_(False),
|
||||
Chat.meta['internal'].as_boolean().is_not(True),
|
||||
]
|
||||
|
||||
# Same matching as the sidebar search: the phrase, or every term.
|
||||
phrase = chat_search_content_query(search)
|
||||
if phrase:
|
||||
|
||||
def match(key: str, value: str):
|
||||
return or_(
|
||||
Chat.title.ilike(f'%{value}%'),
|
||||
text(chat_search_message_content_match_sql(dialect_name, key)).bindparams(**{key: value}),
|
||||
)
|
||||
|
||||
terms = [term for term in chat_search_terms(phrase) if term != phrase]
|
||||
phrase_match = match('folder_phrase', phrase)
|
||||
conditions.append(
|
||||
or_(phrase_match, and_(*[match(f'folder_term_{i}', term) for i, term in enumerate(terms)]))
|
||||
if terms
|
||||
else phrase_match
|
||||
)
|
||||
|
||||
# 'none' means untagged, as in the sidebar search's tag:none.
|
||||
tag_ids = set(tag_ids or [])
|
||||
if tag_ids:
|
||||
if dialect_name == 'sqlite':
|
||||
tags = "json_each(CASE WHEN json_type(chat.meta, '$.tags') = 'array' THEN json_extract(chat.meta, '$.tags') ELSE '[]' END)"
|
||||
else:
|
||||
tags = "json_array_elements_text(CASE WHEN json_typeof(chat.meta->'tags') = 'array' THEN chat.meta->'tags' ELSE '[]'::json END)"
|
||||
named = sorted(tag_ids - {'none'})
|
||||
matches = [text(f'NOT EXISTS (SELECT 1 FROM {tags} tag)')] if 'none' in tag_ids else []
|
||||
if named:
|
||||
matches.append(
|
||||
text(f'EXISTS (SELECT 1 FROM {tags} tag WHERE tag.value IN :folder_tag_ids)').bindparams(
|
||||
bindparam('folder_tag_ids', named, expanding=True)
|
||||
)
|
||||
)
|
||||
conditions.append(or_(*matches))
|
||||
|
||||
# 'not_started' was the default status's earlier name.
|
||||
status_ids = {NO_FOLDER_STATUS if value == 'not_started' else value for value in status_ids or []}
|
||||
if status_ids:
|
||||
stored = Chat.meta['folder_status'].as_string()
|
||||
named = sorted(status_ids - {NO_FOLDER_STATUS})
|
||||
matches = [stored.in_(named)] if named else []
|
||||
if NO_FOLDER_STATUS in status_ids:
|
||||
# Unknown or deleted statuses read as no status.
|
||||
matches.append(or_(stored.is_(None), stored.not_in(list(valid_status_ids))))
|
||||
conditions.append(or_(*matches))
|
||||
return conditions
|
||||
|
||||
async def get_folder_chat_page(
|
||||
self,
|
||||
folder_id: str,
|
||||
user_id: str,
|
||||
folder_write_access: bool = False,
|
||||
skip: int = 0,
|
||||
limit: int = 50,
|
||||
search: str = '',
|
||||
tag_ids: list[str] | None = None,
|
||||
status_ids: list[str] | None = None,
|
||||
valid_status_ids: tuple[str, ...] = (),
|
||||
user_ids: list[str] | None = None,
|
||||
activity: str | None = None,
|
||||
updated_at_gte: int | None = None,
|
||||
sort_by: str = 'updated_at',
|
||||
sort_dir: str = 'desc',
|
||||
redis=None,
|
||||
db: AsyncSession | None = None,
|
||||
) -> tuple[list[dict], int]:
|
||||
"""A page of a folder's chats for the list and board views, filtered before paging."""
|
||||
async with get_async_db_context(db) as session:
|
||||
dialect_name = (await session.connection()).dialect.name
|
||||
conditions = self._folder_chat_conditions(
|
||||
folder_id, dialect_name, search, tag_ids, status_ids, valid_status_ids
|
||||
)
|
||||
|
||||
if user_ids:
|
||||
# Participants come from message history, so match them over this folder's chats.
|
||||
wanted = set(user_ids)
|
||||
rows = (await session.execute(select(Chat.id, Chat.user_id).where(*conditions))).all()
|
||||
authors = await self.get_participant_ids_by_chat_ids([row[0] for row in rows], db=session)
|
||||
conditions.append(
|
||||
Chat.id.in_(
|
||||
[
|
||||
chat_id
|
||||
for chat_id, owner in rows
|
||||
if owner in wanted or wanted.intersection(authors.get(chat_id, ()))
|
||||
]
|
||||
)
|
||||
)
|
||||
|
||||
if updated_at_gte is not None:
|
||||
conditions.append(Chat.updated_at >= updated_at_gte)
|
||||
|
||||
if activity:
|
||||
# Same precedence as the sidebar markers: approval > generating > unread.
|
||||
unfinished = (
|
||||
await session.execute(
|
||||
select(ChatMessage.chat_id, ChatMessage.output)
|
||||
.join(Chat, Chat.id == ChatMessage.chat_id)
|
||||
.where(*conditions, ChatMessage.role == 'assistant', ChatMessage.done.is_(False))
|
||||
)
|
||||
).all()
|
||||
pending_ids = {chat_id for chat_id, output in unfinished if has_pending_tool_approval(output)}
|
||||
if activity == 'waiting_for_approval':
|
||||
conditions.append(Chat.id.in_(pending_ids))
|
||||
else:
|
||||
active_ids = {
|
||||
chat_id for chat_id in {row[0] for row in unfinished} if await has_active_tasks(redis, chat_id)
|
||||
}
|
||||
if activity == 'generating':
|
||||
conditions.append(Chat.id.in_(active_ids - pending_ids))
|
||||
elif activity == 'unread':
|
||||
conditions.extend(
|
||||
[
|
||||
Chat.user_id == user_id,
|
||||
or_(
|
||||
Chat.last_read_at.is_(None),
|
||||
Chat.last_read_at == 0,
|
||||
Chat.updated_at > Chat.last_read_at,
|
||||
),
|
||||
Chat.id.not_in(active_ids | pending_ids),
|
||||
]
|
||||
)
|
||||
elif activity == 'idle':
|
||||
# Everything the other three leave out.
|
||||
conditions.extend(
|
||||
[
|
||||
Chat.id.not_in(active_ids | pending_ids),
|
||||
or_(
|
||||
Chat.user_id != user_id,
|
||||
and_(
|
||||
Chat.last_read_at.is_not(None),
|
||||
Chat.last_read_at != 0,
|
||||
Chat.updated_at <= Chat.last_read_at,
|
||||
),
|
||||
),
|
||||
]
|
||||
)
|
||||
|
||||
total = (await session.execute(select(func.count(Chat.id)).where(*conditions))).scalar_one()
|
||||
rows = (
|
||||
(
|
||||
await session.execute(
|
||||
select(
|
||||
Chat.id,
|
||||
Chat.title,
|
||||
Chat.user_id,
|
||||
Chat.updated_at,
|
||||
Chat.created_at,
|
||||
Chat.last_read_at,
|
||||
Chat.meta,
|
||||
)
|
||||
.where(*conditions)
|
||||
.order_by(*chat_list_order(sort_by, sort_dir, user_id))
|
||||
.offset(skip)
|
||||
.limit(limit)
|
||||
)
|
||||
)
|
||||
.mappings()
|
||||
.all()
|
||||
)
|
||||
|
||||
tag_ids = {tag_id for row in rows for tag_id in (row['meta'] or {}).get('tags', [])}
|
||||
owners = {row['user_id'] for row in rows}
|
||||
labels = (
|
||||
{
|
||||
(tag.user_id, tag.id): tag
|
||||
for tag in (await session.execute(select(Tag).where(Tag.user_id.in_(owners), Tag.id.in_(tag_ids))))
|
||||
.scalars()
|
||||
.all()
|
||||
}
|
||||
if tag_ids
|
||||
else {}
|
||||
)
|
||||
|
||||
bodies = {}
|
||||
if chat_search_content_query(search) and rows:
|
||||
bodies = dict(
|
||||
(
|
||||
await session.execute(
|
||||
select(Chat.id, Chat.chat).where(Chat.id.in_([row['id'] for row in rows]))
|
||||
)
|
||||
).all()
|
||||
)
|
||||
|
||||
terms = chat_search_content_query(search).split()
|
||||
chats = []
|
||||
for row in rows:
|
||||
chat = dict(row)
|
||||
meta = chat.pop('meta') or {}
|
||||
chat['tags'] = []
|
||||
for tag_id in dict.fromkeys(meta.get('tags', [])):
|
||||
tag = labels.get((chat['user_id'], tag_id))
|
||||
chat['tags'].append(
|
||||
{
|
||||
'id': tag_id,
|
||||
'name': tag.name if tag else tag_id.replace('_', ' '),
|
||||
# The palette and default color live in the frontend.
|
||||
'color': (tag.meta or {}).get('color') if tag else None,
|
||||
}
|
||||
)
|
||||
status = meta.get('folder_status')
|
||||
chat['status'] = status if status in valid_status_ids else None
|
||||
chat['status_since'] = folder_status_since(meta, chat['status'])
|
||||
# For the time-in-status tooltip: when the current stretch began, and earlier
|
||||
# time per status (statuses the folder no longer has are left out).
|
||||
chat['status_entered_at'] = _as_seconds(meta.get('folder_status_at')) if chat['status'] else None
|
||||
chat['status_durations'] = {
|
||||
key: seconds
|
||||
for key, value in (meta.get('folder_status_durations') or {}).items()
|
||||
if key in valid_status_ids and (seconds := _as_seconds(value))
|
||||
}
|
||||
# Folder editors may set tags (kept in the owner's tag records) and status on any chat here.
|
||||
chat['can_edit_tags'] = folder_write_access or chat['user_id'] == user_id
|
||||
chat['automation_id'] = meta.get('automation_id')
|
||||
chat['can_edit_status'] = folder_write_access or chat['user_id'] == user_id
|
||||
# Only explain matches the title doesn't already show.
|
||||
chat['search_snippet'] = (
|
||||
chat_search_snippet(bodies.get(chat['id']) or {}, search)
|
||||
if terms and not all(term in chat['title'].lower() for term in terms)
|
||||
else None
|
||||
)
|
||||
chats.append(chat)
|
||||
return chats, total
|
||||
|
||||
async def get_participant_counts_by_folder_id(
|
||||
self, folder_id: str, db: AsyncSession | None = None
|
||||
) -> dict[str, int]:
|
||||
"""How many of a folder's chats each person owns or wrote in."""
|
||||
async with get_async_db_context(db) as session:
|
||||
dialect_name = (await session.connection()).dialect.name
|
||||
rows = (
|
||||
await session.execute(
|
||||
select(Chat.id, Chat.user_id).where(*self._folder_chat_conditions(folder_id, dialect_name))
|
||||
)
|
||||
).all()
|
||||
authors = await self.get_participant_ids_by_chat_ids([row[0] for row in rows], db=session)
|
||||
counts: dict[str, int] = {}
|
||||
for chat_id, owner in rows:
|
||||
for participant_id in {owner, *authors.get(chat_id, ())}:
|
||||
counts[participant_id] = counts.get(participant_id, 0) + 1
|
||||
return counts
|
||||
|
||||
async def get_tag_counts_by_folder_id(self, folder_id: str, db: AsyncSession | None = None) -> list[dict]:
|
||||
"""Tags used in a folder with chat counts, aggregated in SQL without loading chats."""
|
||||
async with get_async_db_context(db) as session:
|
||||
dialect_name = (await session.connection()).dialect.name
|
||||
if dialect_name == 'sqlite':
|
||||
source = "json_each(chat.meta, '$.tags')"
|
||||
internal = "COALESCE(json_extract(chat.meta, '$.internal'), 0) != 1"
|
||||
color = "json_extract(label.meta, '$.color')"
|
||||
else:
|
||||
source = "json_array_elements_text(chat.meta->'tags')"
|
||||
internal = "COALESCE((chat.meta->>'internal')::boolean, false) = false"
|
||||
color = "label.meta->>'color'"
|
||||
query = text(f"""
|
||||
SELECT tag.value AS id, MIN(COALESCE(label.name, tag.value)) AS name,
|
||||
MIN({color}) AS color, COUNT(DISTINCT chat.id) AS count
|
||||
FROM chat CROSS JOIN {source} tag
|
||||
LEFT JOIN tag label ON label.id = tag.value AND label.user_id = chat.user_id
|
||||
WHERE chat.folder_id = :folder_id AND chat.archived = false AND {internal}
|
||||
GROUP BY tag.value ORDER BY name
|
||||
""")
|
||||
result = await session.execute(query, {'folder_id': folder_id})
|
||||
return [dict(row) for row in result.mappings()]
|
||||
|
||||
async def update_chat_folder_status_by_id(
|
||||
self, id: str, folder_id: str, user_id: str | None, status: str | None, db: AsyncSession | None = None
|
||||
) -> bool:
|
||||
"""Set (or with None, clear) a chat's folder status, banking the time spent in its previous one.
|
||||
|
||||
Time adds up per status, so moving away and coming back doesn't reset it.
|
||||
A user_id limits this to that user's chats; None allows any chat in the folder.
|
||||
"""
|
||||
async with get_async_db_context(db) as session:
|
||||
row = (
|
||||
await session.execute(
|
||||
select(Chat.meta).filter_by(id=id, folder_id=folder_id, **({'user_id': user_id} if user_id else {}))
|
||||
)
|
||||
).one_or_none()
|
||||
if row is None:
|
||||
return False
|
||||
meta = dict(row[0] or {})
|
||||
previous = meta.get('folder_status')
|
||||
if previous == status:
|
||||
return True # Same status: keep its clock running.
|
||||
now = int(time.time())
|
||||
started = _as_seconds(meta.get('folder_status_at'))
|
||||
durations = dict(meta.get('folder_status_durations') or {})
|
||||
if previous and previous != 'none' and started is not None: # 'none' was stored by older builds
|
||||
durations[previous] = (_as_seconds(durations.get(previous)) or 0) + max(0, now - started)
|
||||
await session.execute(
|
||||
update(Chat)
|
||||
.filter_by(id=id)
|
||||
.values(
|
||||
meta={
|
||||
# No status means no stored status, like chats that never had one.
|
||||
**{
|
||||
key: value
|
||||
for key, value in meta.items()
|
||||
if key not in ('folder_status', 'folder_status_at')
|
||||
},
|
||||
**({'folder_status': status, 'folder_status_at': now} if status is not None else {}),
|
||||
'folder_status_durations': durations,
|
||||
}
|
||||
)
|
||||
)
|
||||
await session.commit()
|
||||
return True
|
||||
|
||||
async def count_all_chats_by_folder_id(
|
||||
self,
|
||||
folder_id: str,
|
||||
@@ -2640,7 +3014,6 @@ class ChatTable:
|
||||
chat = await session.get(Chat, id)
|
||||
chat.folder_id = folder_id
|
||||
if chat.user_id == user_id:
|
||||
chat.last_read_at = int(time.time())
|
||||
chat.pinned = False
|
||||
if folder_id is not None:
|
||||
# Folder listings only show unarchived chats, so moving an archived
|
||||
|
||||
@@ -15,7 +15,7 @@ import time
|
||||
from typing import Any, ClassVar
|
||||
|
||||
from fastapi.encoders import jsonable_encoder
|
||||
from open_webui.internal.db import Base, get_async_db
|
||||
from open_webui.internal.db import Base, get_async_db, get_async_db_context
|
||||
from sqlalchemy import JSON, BigInteger, Column, Text, delete, select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
@@ -141,16 +141,16 @@ class Config(Base):
|
||||
return True
|
||||
|
||||
@staticmethod
|
||||
async def get(key: str, default: Any = None) -> Any:
|
||||
async def get(key: str, default: Any = None, *, db: AsyncSession | None = None) -> Any:
|
||||
"""Get a config value by key. Returns default if not set."""
|
||||
if not Config.persistent_enabled_for(key):
|
||||
return Config.default_value(key, default)
|
||||
async with get_async_db() as db:
|
||||
async with get_async_db_context(db) as db:
|
||||
row = await db.get(Config, key)
|
||||
return row.value if row else Config.default_value(key, default)
|
||||
|
||||
@staticmethod
|
||||
async def get_many(*keys: str) -> dict:
|
||||
async def get_many(*keys: str, db: AsyncSession | None = None) -> dict:
|
||||
"""Get multiple config values. Returns {key: value} for keys that exist."""
|
||||
disabled_values = {
|
||||
key: Config.default_value(key)
|
||||
@@ -160,7 +160,7 @@ class Config(Base):
|
||||
enabled_keys = {key for key in keys if Config.persistent_enabled_for(key)}
|
||||
if not enabled_keys:
|
||||
return disabled_values
|
||||
async with get_async_db() as db:
|
||||
async with get_async_db_context(db) as db:
|
||||
result = await db.execute(select(Config).where(Config.key.in_(enabled_keys)))
|
||||
values = {row.key: row.value for row in result.scalars().all()}
|
||||
return {
|
||||
|
||||
@@ -79,6 +79,22 @@ class SharedFolderResponse(BaseModel):
|
||||
# Forms
|
||||
|
||||
|
||||
def folder_status_ids(meta: dict | None) -> tuple[str, ...]:
|
||||
"""The statuses this folder defines in meta.statuses, in order. Chats may also have none (null)."""
|
||||
statuses = (meta or {}).get('statuses')
|
||||
ids: list[str] = []
|
||||
for item in statuses if isinstance(statuses, list) else []:
|
||||
if (
|
||||
isinstance(item, dict)
|
||||
and isinstance(item.get('id'), str)
|
||||
and 0 < len(item['id']) <= 64
|
||||
and item['id'] != 'none'
|
||||
and item['id'] not in ids
|
||||
):
|
||||
ids.append(item['id'])
|
||||
return tuple(ids)
|
||||
|
||||
|
||||
class FolderForm(BaseModel):
|
||||
name: str
|
||||
data: Optional[dict] = None
|
||||
|
||||
@@ -123,6 +123,14 @@ class GroupForm(BaseModel):
|
||||
permissions: Optional[dict] = None
|
||||
data: Optional[dict] = None
|
||||
|
||||
@field_validator('name')
|
||||
@classmethod
|
||||
def validate_name(cls, name: str) -> str:
|
||||
name = name.strip()
|
||||
if not name:
|
||||
raise ValueError('Group name cannot be empty.')
|
||||
return name
|
||||
|
||||
@field_validator('data')
|
||||
@classmethod
|
||||
def validate_default_models(cls, data):
|
||||
|
||||
@@ -371,7 +371,18 @@ class KnowledgeTable:
|
||||
)
|
||||
)
|
||||
|
||||
return KnowledgeListResponse(items=knowledge_bases, total=total)
|
||||
# Stores from connections are listed live, so they join the first page, not the query.
|
||||
filter = filter or {}
|
||||
if not skip and filter.get('view_option') != 'created' and filter.get('source') != 'local':
|
||||
from open_webui.retrieval.external import list_virtual_knowledge
|
||||
|
||||
virtual = await list_virtual_knowledge(filter.get('user_id'), filter.get('query'))
|
||||
knowledge_bases.extend(
|
||||
KnowledgeUserModel.model_validate({**item.model_dump(), 'file_count': 0}) for item in virtual
|
||||
)
|
||||
total += len(virtual)
|
||||
|
||||
return KnowledgeListResponse(items=knowledge_bases, total=total)
|
||||
except Exception as e:
|
||||
print(e)
|
||||
return KnowledgeListResponse(items=[], total=0)
|
||||
@@ -502,6 +513,10 @@ class KnowledgeTable:
|
||||
)
|
||||
|
||||
async def get_knowledge_by_id(self, id: str, db: Optional[AsyncSession] = None) -> Optional[KnowledgeModel]:
|
||||
from open_webui.retrieval.external import get_virtual_knowledge, is_virtual_knowledge_id
|
||||
|
||||
if is_virtual_knowledge_id(id):
|
||||
return await get_virtual_knowledge(id)
|
||||
try:
|
||||
async with get_async_db_context(db) as db:
|
||||
result = await db.execute(select(Knowledge).filter_by(id=id))
|
||||
|
||||
@@ -55,6 +55,10 @@ class ReminderData(NotificationData):
|
||||
start_at: int
|
||||
|
||||
|
||||
class ChatMentionData(NotificationData):
|
||||
model_name: str
|
||||
|
||||
|
||||
class SystemData(NotificationData):
|
||||
message: str = Field(min_length=1, max_length=2000)
|
||||
|
||||
@@ -64,6 +68,7 @@ DATA_TYPES = {
|
||||
'comment.replied': NotificationData,
|
||||
'comment.mentioned': NotificationData,
|
||||
'channel.mentioned': NotificationData,
|
||||
'chat.mentioned': ChatMentionData,
|
||||
'channel.replied': NotificationData,
|
||||
'calendar.alert': ReminderData,
|
||||
'automation.run_failed': NotificationData,
|
||||
@@ -76,7 +81,7 @@ async def emit_changes(user_ids):
|
||||
|
||||
for user_id in user_ids:
|
||||
try:
|
||||
await sio.emit('notifications:changed', {}, room=f'user:{user_id}')
|
||||
await sio.emit('events', {'data': {'type': 'notifications:changed'}}, room=f'user:{user_id}')
|
||||
except Exception:
|
||||
log.exception('Could not broadcast inbox change for %s', user_id)
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ import uuid
|
||||
# local imports
|
||||
from open_webui.internal.db import Base, JSONField, get_async_db_context
|
||||
from pydantic import BaseModel, ConfigDict
|
||||
from sqlalchemy import JSON, BigInteger, Column, Index, PrimaryKeyConstraint, String, delete, select
|
||||
from sqlalchemy import JSON, BigInteger, Column, Index, PrimaryKeyConstraint, String, delete, select, update
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
@@ -91,6 +91,20 @@ class TagTable:
|
||||
result = await db.execute(select(Tag).filter(Tag.id.in_(ids), Tag.user_id == user_id))
|
||||
return [TagModel.model_validate(tag) for tag in result.scalars().all()]
|
||||
|
||||
async def update_tag_color_by_name_and_user_id(
|
||||
self, name: str, user_id: str, color: str, db: AsyncSession | None = None
|
||||
) -> bool:
|
||||
async with get_async_db_context(db) as db:
|
||||
id = name.replace(' ', '_').lower()
|
||||
meta = (await db.execute(select(Tag.meta).filter_by(id=id, user_id=user_id))).one_or_none()
|
||||
if meta is None:
|
||||
return False
|
||||
await db.execute(
|
||||
update(Tag).filter_by(id=id, user_id=user_id).values(meta={**(meta[0] or {}), 'color': color})
|
||||
)
|
||||
await db.commit()
|
||||
return True
|
||||
|
||||
async def delete_tag_by_name_and_user_id(self, name: str, user_id: str, db: AsyncSession | None = None) -> bool:
|
||||
try:
|
||||
async with get_async_db_context(db) as db:
|
||||
@@ -120,6 +134,9 @@ class TagTable:
|
||||
|
||||
async def ensure_tags_exist(self, names: list[str], user_id: str, db: AsyncSession | None = None) -> None:
|
||||
"""Create tag rows for any *names* that don't already exist for *user_id*."""
|
||||
from sqlalchemy.dialects.postgresql import insert as pg_insert
|
||||
from sqlalchemy.dialects.sqlite import insert as sqlite_insert
|
||||
|
||||
if not names:
|
||||
return
|
||||
ids = [n.replace(' ', '_').lower() for n in names]
|
||||
@@ -127,10 +144,14 @@ class TagTable:
|
||||
result = await db.execute(select(Tag.id).filter(Tag.id.in_(ids), Tag.user_id == user_id))
|
||||
existing = {row[0] for row in result.all()}
|
||||
new_tags = [
|
||||
Tag(id=tag_id, name=name, user_id=user_id) for tag_id, name in zip(ids, names) if tag_id not in existing
|
||||
dict(id=tag_id, name=name, user_id=user_id)
|
||||
for tag_id, name in zip(ids, names)
|
||||
if tag_id not in existing
|
||||
]
|
||||
if new_tags:
|
||||
db.add_all(new_tags)
|
||||
insert = sqlite_insert if db.bind.dialect.name == 'sqlite' else pg_insert
|
||||
# A concurrent request may have created the same tag since the read above
|
||||
await db.execute(insert(Tag).on_conflict_do_nothing(index_elements=['id', 'user_id']), new_tags)
|
||||
await db.commit()
|
||||
|
||||
|
||||
|
||||
@@ -863,6 +863,9 @@ class UsersTable:
|
||||
from open_webui.models.chat_views import ChatViewState
|
||||
|
||||
await session.execute(delete(ChatViewState).where(ChatViewState.user_id == id))
|
||||
from open_webui.models.access_grants import AccessGrant
|
||||
|
||||
await session.execute(delete(AccessGrant).filter_by(principal_type='user', principal_id=id))
|
||||
await session.execute(delete(User).where(User.id == id))
|
||||
await session.commit()
|
||||
return True
|
||||
|
||||
@@ -4,15 +4,25 @@ import re
|
||||
import time
|
||||
from itertools import zip_longest
|
||||
from typing import Any, Optional
|
||||
from urllib.parse import quote
|
||||
|
||||
import aiohttp
|
||||
from open_webui.env import AIOHTTP_CLIENT_SESSION_SSL
|
||||
from open_webui.models.config import Config
|
||||
from open_webui.models.knowledge import KnowledgeModel
|
||||
from open_webui.utils.session_pool import get_session
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
EXTERNAL_KNOWLEDGE_CONNECTIONS_CONFIG_KEY = 'external_knowledge.connections'
|
||||
IDENTIFIER_RE = re.compile(r'^[A-Za-z_][A-Za-z0-9_]*$')
|
||||
|
||||
# OpenAI caps vector store search at 50 results and list pages at 100 stores.
|
||||
OPENAI_VECTOR_STORE_MAX_RESULTS = 50
|
||||
OPENAI_VECTOR_STORE_PAGE_SIZE = 100
|
||||
# Stops a server that always reports more pages; allows 10,000 stores.
|
||||
OPENAI_VECTOR_STORE_MAX_PAGES = 100
|
||||
|
||||
|
||||
async def _get_external_connection(connection_id: str) -> Optional[dict]:
|
||||
connections = await Config.get(EXTERNAL_KNOWLEDGE_CONNECTIONS_CONFIG_KEY, []) or []
|
||||
@@ -291,6 +301,288 @@ async def _retrieve_pgvector(connection, auth_config, knowledge, query, count, e
|
||||
return [_normalize_result(row, mapping, knowledge, distance=row.get('distance')) for row in rows]
|
||||
|
||||
|
||||
async def _openai_vector_store_request(
|
||||
connection: dict,
|
||||
auth_config: Optional[dict],
|
||||
method: str,
|
||||
path: str,
|
||||
params: Optional[dict] = None,
|
||||
json: Optional[dict] = None,
|
||||
) -> dict:
|
||||
"""Call an OpenAI-compatible vector store API (OpenAI, LiteLLM, Azure OpenAI v1 at /openai/v1)."""
|
||||
base_url = (connection.get('endpoint') or '').strip().rstrip('/')
|
||||
if not base_url:
|
||||
raise RuntimeError('Endpoint is not configured')
|
||||
|
||||
headers = {'Accept': 'application/json'}
|
||||
api_key = (auth_config or {}).get('api_key')
|
||||
if api_key:
|
||||
headers['Authorization'] = f'Bearer {api_key}'
|
||||
|
||||
timeout = aiohttp.ClientTimeout(total=(connection.get('config') or {}).get('timeout') or 30)
|
||||
session = await get_session()
|
||||
try:
|
||||
async with session.request(
|
||||
method,
|
||||
f'{base_url}{path}',
|
||||
headers=headers,
|
||||
params=params,
|
||||
json=json,
|
||||
timeout=timeout,
|
||||
ssl=AIOHTTP_CLIENT_SESSION_SSL,
|
||||
) as r:
|
||||
if r.status >= 400:
|
||||
detail = (await r.text())[:500]
|
||||
raise RuntimeError(f'Vector store request failed ({r.status}): {detail}')
|
||||
try:
|
||||
data = await r.json(content_type=None)
|
||||
except ValueError as exc:
|
||||
raise RuntimeError(f'Vector store endpoint returned a non-JSON response ({r.status})') from exc
|
||||
except aiohttp.ClientError as exc:
|
||||
raise RuntimeError(f'Vector store request failed: {exc}') from exc
|
||||
|
||||
if not isinstance(data, dict):
|
||||
raise RuntimeError('Vector store endpoint returned an unexpected response')
|
||||
return data
|
||||
|
||||
|
||||
def get_vector_store_ids(source: dict) -> list[str]:
|
||||
"""Store IDs a text-search source covers; older sources keep a single ID in `name`."""
|
||||
ids = (source.get('config') or {}).get('vector_store_ids')
|
||||
if not isinstance(ids, list):
|
||||
ids = (source.get('name') or '').split(',')
|
||||
return list(dict.fromkeys(str(store_id).strip() for store_id in ids if str(store_id).strip()))
|
||||
|
||||
|
||||
async def _search_openai_vector_store(connection, auth_config, knowledge, vector_store_id, query, count) -> list[dict]:
|
||||
data = await _openai_vector_store_request(
|
||||
connection,
|
||||
auth_config,
|
||||
'POST',
|
||||
f'/vector_stores/{quote(vector_store_id, safe="")}/search',
|
||||
json={
|
||||
'query': query,
|
||||
'max_num_results': max(1, min(count, OPENAI_VECTOR_STORE_MAX_RESULTS)),
|
||||
},
|
||||
)
|
||||
|
||||
normalized = []
|
||||
for item in data.get('data') or []:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
content = '\n'.join(
|
||||
part['text']
|
||||
for part in item.get('content') or []
|
||||
if isinstance(part, dict) and isinstance(part.get('text'), str) and part['text']
|
||||
)
|
||||
if not content:
|
||||
continue
|
||||
attributes = item.get('attributes') if isinstance(item.get('attributes'), dict) else {}
|
||||
result = {
|
||||
'content': content,
|
||||
'title': item.get('filename'),
|
||||
# Kept from the file's attributes, which _normalize_result would otherwise overwrite.
|
||||
'url': attributes.get('url'),
|
||||
'document_id': item.get('file_id'),
|
||||
'metadata': attributes,
|
||||
'score': item.get('score'),
|
||||
}
|
||||
normalized.append(_normalize_result(result, {}, knowledge, distance=item.get('score')))
|
||||
return normalized[:count]
|
||||
|
||||
|
||||
async def _retrieve_openai(connection, auth_config, knowledge, query, count, embedding_function) -> list[dict]:
|
||||
# The server embeds the query, so the Open WebUI embedding model is not involved.
|
||||
source = (knowledge.meta or {}).get('external', {}).get('source') or {}
|
||||
vector_store_ids = get_vector_store_ids(source)
|
||||
if not vector_store_ids:
|
||||
raise RuntimeError('Vector store ID is not configured')
|
||||
|
||||
results = await asyncio.gather(
|
||||
*(
|
||||
_search_openai_vector_store(connection, auth_config, knowledge, store_id, query, count)
|
||||
for store_id in vector_store_ids
|
||||
),
|
||||
return_exceptions=True,
|
||||
)
|
||||
# One unreachable store should not hide the others; fail only when every store failed.
|
||||
failures = [result for result in results if isinstance(result, BaseException)]
|
||||
for store_id, result in zip(vector_store_ids, results):
|
||||
if isinstance(result, BaseException):
|
||||
log.warning('Vector store %s search failed: %s', store_id, result)
|
||||
if len(failures) == len(results):
|
||||
raise failures[0]
|
||||
|
||||
# Stores may sit on different backends with incomparable scores, so interleave by rank.
|
||||
merged = [
|
||||
chunk
|
||||
for chunks_at_rank in zip_longest(*(result for result in results if not isinstance(result, BaseException)))
|
||||
for chunk in chunks_at_rank
|
||||
if chunk
|
||||
]
|
||||
return merged[:count]
|
||||
|
||||
|
||||
async def list_openai_vector_stores(connection: dict) -> list[dict]:
|
||||
"""List the vector stores a connection can search, as {id, name, description}.
|
||||
|
||||
LiteLLM's registry comes first since it covers every backend LiteLLM proxies; servers without
|
||||
it (OpenAI, Azure) are listed through the OpenAI vector stores API.
|
||||
"""
|
||||
auth_config = connection.get('auth_config') or {}
|
||||
|
||||
try:
|
||||
data = await _openai_vector_store_request(
|
||||
connection, auth_config, 'GET', '/vector_store/list', params={'page_size': 1000}
|
||||
)
|
||||
if isinstance(data.get('data'), list):
|
||||
return [
|
||||
{
|
||||
'id': item['vector_store_id'],
|
||||
'name': item.get('vector_store_name') or item['vector_store_id'],
|
||||
'description': item.get('vector_store_description') or '',
|
||||
}
|
||||
for item in data['data']
|
||||
if isinstance(item, dict) and item.get('vector_store_id')
|
||||
]
|
||||
except RuntimeError:
|
||||
pass
|
||||
|
||||
stores = []
|
||||
after = None
|
||||
for _ in range(OPENAI_VECTOR_STORE_MAX_PAGES):
|
||||
data = await _openai_vector_store_request(
|
||||
connection,
|
||||
auth_config,
|
||||
'GET',
|
||||
'/vector_stores',
|
||||
params={'limit': OPENAI_VECTOR_STORE_PAGE_SIZE, **({'after': after} if after else {})},
|
||||
)
|
||||
items = [item for item in data.get('data') or [] if isinstance(item, dict) and item.get('id')]
|
||||
stores.extend(
|
||||
{
|
||||
'id': item['id'],
|
||||
'name': item.get('name') or item['id'],
|
||||
'description': (
|
||||
item['metadata'].get('description') or '' if isinstance(item.get('metadata'), dict) else ''
|
||||
),
|
||||
}
|
||||
for item in items
|
||||
)
|
||||
if not data.get('has_more') or not items:
|
||||
break
|
||||
after = data.get('last_id') or items[-1]['id']
|
||||
return stores
|
||||
|
||||
|
||||
# A connection with `config.store_ids` lists its stores as read-only knowledge bases, like `model_ids` on
|
||||
# provider connections: empty means every store the endpoint lists. The endpoint stays the source of
|
||||
# truth; nothing is copied into the database, so stores added or removed upstream show up on the next listing.
|
||||
|
||||
VIRTUAL_KNOWLEDGE_PREFIX = 'ext:'
|
||||
STORE_LIST_CACHE_TTL = 60
|
||||
_store_list_cache: dict[str, tuple[float, Any, list[dict]]] = {}
|
||||
|
||||
|
||||
def is_virtual_knowledge_id(id: Any) -> bool:
|
||||
return isinstance(id, str) and id.startswith(VIRTUAL_KNOWLEDGE_PREFIX)
|
||||
|
||||
|
||||
async def _get_connections_with_store_ids() -> list[dict]:
|
||||
connections = await Config.get(EXTERNAL_KNOWLEDGE_CONNECTIONS_CONFIG_KEY, []) or []
|
||||
return [
|
||||
connection
|
||||
for connection in connections
|
||||
if connection.get('enabled', True) and isinstance((connection.get('config') or {}).get('store_ids'), list)
|
||||
]
|
||||
|
||||
|
||||
async def _get_connection_stores(connection: dict) -> list[dict]:
|
||||
"""The connection's stores narrowed by Store IDs. The endpoint's list is cached briefly per
|
||||
endpoint and key; a failed listing serves the last good one."""
|
||||
cached = _store_list_cache.get(connection['id'])
|
||||
# Only what reaches the endpoint keys the cache, so Store ID edits apply on the next read.
|
||||
version = (connection.get('endpoint'), (connection.get('auth_config') or {}).get('api_key'))
|
||||
if cached and cached[1] == version and time.monotonic() - cached[0] < STORE_LIST_CACHE_TTL:
|
||||
stores = cached[2]
|
||||
else:
|
||||
try:
|
||||
stores = await list_openai_vector_stores(connection)
|
||||
_store_list_cache[connection['id']] = (time.monotonic(), version, stores)
|
||||
except RuntimeError as e:
|
||||
log.warning('Listing vector stores for connection %s failed: %s', connection['id'], e)
|
||||
stores = cached[2] if cached and cached[1] == version else []
|
||||
|
||||
store_ids = (connection.get('config') or {}).get('store_ids') or []
|
||||
return [store for store in stores if store['id'] in store_ids] if store_ids else stores
|
||||
|
||||
|
||||
def _to_virtual_knowledge(connection: dict, store: dict) -> KnowledgeModel:
|
||||
return KnowledgeModel(
|
||||
id=f'{VIRTUAL_KNOWLEDGE_PREFIX}{connection["id"]}:{store["id"]}',
|
||||
# Owned by no one, so nobody gets owner rights; reading goes through the connection's access.
|
||||
user_id='',
|
||||
name=store['name'],
|
||||
description=store.get('description') or '',
|
||||
meta={
|
||||
'source': 'external',
|
||||
'read_only': True,
|
||||
'external': {
|
||||
'connection_id': connection['id'],
|
||||
'source': {'type': 'collection', 'name': store['id'], 'config': {'vector_store_ids': [store['id']]}},
|
||||
'provider': connection.get('provider'),
|
||||
'auth_mode': 'service_account',
|
||||
'capabilities': {'retrieve': True},
|
||||
},
|
||||
},
|
||||
created_at=connection.get('created_at') or 0,
|
||||
updated_at=connection.get('updated_at') or 0,
|
||||
)
|
||||
|
||||
|
||||
async def _can_read_connection(user_id: str, connection: dict) -> bool:
|
||||
from open_webui.models.users import Users
|
||||
from open_webui.utils.access_control import has_connection_access
|
||||
|
||||
user = await Users.get_user_by_id(user_id)
|
||||
return bool(user) and await has_connection_access(user, connection)
|
||||
|
||||
|
||||
async def _get_connection_for_virtual_knowledge(id: str) -> Optional[dict]:
|
||||
connection_id = id[len(VIRTUAL_KNOWLEDGE_PREFIX) :].partition(':')[0]
|
||||
return next((item for item in await _get_connections_with_store_ids() if item.get('id') == connection_id), None)
|
||||
|
||||
|
||||
async def get_virtual_knowledge(id: str) -> Optional[KnowledgeModel]:
|
||||
connection = await _get_connection_for_virtual_knowledge(id)
|
||||
if not connection:
|
||||
return None
|
||||
store_id = id[len(VIRTUAL_KNOWLEDGE_PREFIX) :].partition(':')[2]
|
||||
store = next((store for store in await _get_connection_stores(connection) if store['id'] == store_id), None)
|
||||
return _to_virtual_knowledge(connection, store) if store else None
|
||||
|
||||
|
||||
async def has_virtual_knowledge_access(user_id: str, id: str, permission: str = 'read') -> bool:
|
||||
if permission != 'read':
|
||||
return False
|
||||
connection = await _get_connection_for_virtual_knowledge(id)
|
||||
return bool(connection) and await _can_read_connection(user_id, connection)
|
||||
|
||||
|
||||
async def list_virtual_knowledge(user_id: Optional[str] = None, query: Optional[str] = None) -> list[KnowledgeModel]:
|
||||
"""Stores of every connection listing them that the user can read; no user_id means no filtering."""
|
||||
query = (query or '').lower()
|
||||
knowledge = []
|
||||
for connection in await _get_connections_with_store_ids():
|
||||
if user_id and not await _can_read_connection(user_id, connection):
|
||||
continue
|
||||
for store in await _get_connection_stores(connection):
|
||||
item = _to_virtual_knowledge(connection, store)
|
||||
if not query or query in f'{item.name} {item.description}'.lower():
|
||||
knowledge.append(item)
|
||||
return knowledge
|
||||
|
||||
|
||||
async def retrieve_external_knowledge(
|
||||
request,
|
||||
knowledge: KnowledgeModel,
|
||||
@@ -330,6 +622,7 @@ async def retrieve_external_knowledge_for_connection(
|
||||
'qdrant': _retrieve_qdrant,
|
||||
'milvus': _retrieve_milvus,
|
||||
'pgvector': _retrieve_pgvector,
|
||||
'openai': _retrieve_openai,
|
||||
}.get(provider)
|
||||
if not retrieve:
|
||||
raise RuntimeError(f'Unsupported external knowledge provider: {connection.get("provider")}')
|
||||
|
||||
@@ -340,7 +340,7 @@ def query_doc(collection_name: str, query_embedding: list[float], k: int, user:
|
||||
)
|
||||
|
||||
if result:
|
||||
log.info('query_doc:result %s %s', result.ids, result.metadatas)
|
||||
log.debug('query_doc:result %s %s', result.ids, result.metadatas)
|
||||
|
||||
return result
|
||||
|
||||
@@ -351,7 +351,7 @@ def get_doc(collection_name: str, user: UserModel = None):
|
||||
result = get_vector_db_client().get(collection_name=collection_name)
|
||||
|
||||
if result:
|
||||
log.info('query_doc:result %s %s', result.ids, result.metadatas)
|
||||
log.debug('query_doc:result %s %s', result.ids, result.metadatas)
|
||||
|
||||
return result
|
||||
except Exception as e:
|
||||
@@ -601,7 +601,7 @@ async def query_doc_with_hybrid_search(
|
||||
'metadatas': [metadatas],
|
||||
}
|
||||
|
||||
log.info('query_doc_with_hybrid_search:result %s %s', result['metadatas'], result['distances'])
|
||||
log.debug('query_doc_with_hybrid_search:result %s %s', result['metadatas'], result['distances'])
|
||||
return result
|
||||
|
||||
|
||||
|
||||
@@ -53,7 +53,7 @@ def search_external(
|
||||
)
|
||||
for result in results[:count]
|
||||
]
|
||||
log.info('External search results: %s', results)
|
||||
log.debug('External search results: %s', results)
|
||||
return results
|
||||
except Exception as e:
|
||||
log.error(f'Error in External search: {e}')
|
||||
|
||||
@@ -225,7 +225,7 @@ def search_firecrawl(
|
||||
)
|
||||
)
|
||||
|
||||
log.info('FireCrawl search results: %s', search_results)
|
||||
log.debug('FireCrawl search results: %s', search_results)
|
||||
return search_results
|
||||
except Exception as e:
|
||||
log.error(f'Error in FireCrawl search: {e}')
|
||||
|
||||
@@ -35,6 +35,6 @@ def search_kagi(api_key: str, query: str, count: int, filter_list: Optional[list
|
||||
for result in search_results
|
||||
]
|
||||
|
||||
print(results)
|
||||
log.debug('Kagi search results: %s', results)
|
||||
|
||||
return results
|
||||
@@ -25,7 +25,7 @@ def search_mojeek(api_key: str, query: str, count: int, filter_list: list[str] |
|
||||
response.raise_for_status()
|
||||
json_response = response.json()
|
||||
results = json_response.get('response', {}).get('results', [])
|
||||
print(results)
|
||||
log.debug('Mojeek search results: %s', results)
|
||||
if filter_list:
|
||||
results = get_filtered_results(results, filter_list)
|
||||
|
||||
|
||||
@@ -31,7 +31,7 @@ def search_serpapi(
|
||||
response = requests.request('GET', url)
|
||||
|
||||
json_response = response.json()
|
||||
log.info('results from serpapi search: %s', json_response)
|
||||
log.debug('results from serpapi search: %s', json_response)
|
||||
|
||||
results = sorted(json_response.get('organic_results', []), key=lambda x: x.get('position', 0))
|
||||
if filter_list:
|
||||
|
||||
@@ -51,7 +51,7 @@ def search_serply(
|
||||
response.raise_for_status()
|
||||
|
||||
json_response = response.json()
|
||||
log.info('results from serply search: %s', json_response)
|
||||
log.debug('results from serply search: %s', json_response)
|
||||
|
||||
results = sorted(json_response.get('results', []), key=lambda x: x.get('realPosition', 0))
|
||||
if filter_list:
|
||||
|
||||
@@ -316,6 +316,18 @@ _UNWRAP_EXTRA_MAINS = (
|
||||
'if (mains.length > 1) mains.forEach(main => main.replaceWith(...main.childNodes)); }'
|
||||
)
|
||||
|
||||
# unstructured drops definition lists, figures and figure captions, text included.
|
||||
_UNWRAP_DEFINITION_LISTS_AND_FIGURES = (
|
||||
'() => document.querySelectorAll("dl, dt, dd, figure, figcaption").forEach(element => { '
|
||||
'const div = document.createElement("div"); div.append(...element.childNodes); element.replaceWith(div); })'
|
||||
)
|
||||
|
||||
# unstructured drops <details> and <summary> as boilerplate, text included.
|
||||
_UNWRAP_DETAILS = (
|
||||
'() => document.querySelectorAll("details, summary").forEach(element => { '
|
||||
'const div = document.createElement("div"); div.append(...element.childNodes); element.replaceWith(div); })'
|
||||
)
|
||||
|
||||
|
||||
def _forwardable_request_headers(headers: Dict[str, str]) -> Dict[str, str]:
|
||||
forwardable = {name: value for name, value in headers.items() if name.lower() not in _DROPPED_REQUEST_HEADERS}
|
||||
@@ -353,10 +365,16 @@ def verify_ssl_cert(url: str) -> bool:
|
||||
return True
|
||||
|
||||
try:
|
||||
hostname = url.split('://')[-1].split('/')[0]
|
||||
context = ssl.create_default_context(cafile=certifi.where())
|
||||
parsed_url = urllib.parse.urlparse(url)
|
||||
hostname = parsed_url.hostname
|
||||
context = (
|
||||
AIOHTTP_CLIENT_SESSION_SSL
|
||||
if isinstance(AIOHTTP_CLIENT_SESSION_SSL, ssl.SSLContext)
|
||||
else ssl.create_default_context(cafile=certifi.where())
|
||||
)
|
||||
with context.wrap_socket(ssl.socket(), server_hostname=hostname) as s:
|
||||
s.connect((hostname, 443))
|
||||
s.settimeout(10)
|
||||
s.connect((hostname, parsed_url.port or 443))
|
||||
return True
|
||||
except ssl.SSLError:
|
||||
return False
|
||||
@@ -995,6 +1013,8 @@ class SafePlaywrightURLLoader(BaseLoader, RateLimitMixin, URLProcessingMixin):
|
||||
if element.is_visible():
|
||||
element.evaluate('element => element.remove()')
|
||||
page.evaluate(_UNWRAP_EXTRA_MAINS)
|
||||
page.evaluate(_UNWRAP_DEFINITION_LISTS_AND_FIGURES)
|
||||
page.evaluate(_UNWRAP_DETAILS)
|
||||
text = self._extract_html(page.content())
|
||||
page.unroute_all(behavior='ignoreErrors')
|
||||
metadata = {'source': url}
|
||||
@@ -1036,6 +1056,8 @@ class SafePlaywrightURLLoader(BaseLoader, RateLimitMixin, URLProcessingMixin):
|
||||
if await element.is_visible():
|
||||
await element.evaluate('element => element.remove()')
|
||||
await page.evaluate(_UNWRAP_EXTRA_MAINS)
|
||||
await page.evaluate(_UNWRAP_DEFINITION_LISTS_AND_FIGURES)
|
||||
await page.evaluate(_UNWRAP_DETAILS)
|
||||
text = await asyncio.to_thread(self._extract_html, await page.content())
|
||||
await page.unroute_all(behavior='ignoreErrors')
|
||||
metadata = {'source': url}
|
||||
|
||||
@@ -112,7 +112,7 @@ def search_yandex(
|
||||
for result in results[:count]
|
||||
]
|
||||
|
||||
log.info('Yandex search results: %s', results)
|
||||
log.debug('Yandex search results: %s', results)
|
||||
|
||||
return results
|
||||
except Exception as e:
|
||||
|
||||
@@ -25,6 +25,7 @@ router = APIRouter()
|
||||
|
||||
class ModelAnalyticsEntry(BaseModel):
|
||||
model_id: str
|
||||
name: Optional[str] = None
|
||||
count: int
|
||||
unique_users: int = 0
|
||||
unique_chats: int = 0
|
||||
|
||||
@@ -425,7 +425,7 @@ async def realtime_call(ws: WebSocket):
|
||||
if not ws.app.state.MODELS:
|
||||
await get_all_models(ws, user=user)
|
||||
model = ws.app.state.MODELS.get(model_id)
|
||||
if not model or model.get('direct'):
|
||||
if not model:
|
||||
raise ValueError('Bridge requires a server-configured chat model')
|
||||
model_info = await Models.get_model_by_id(model_id)
|
||||
if (
|
||||
|
||||
@@ -926,6 +926,11 @@ async def signout(request: Request, response: Response, db: AsyncSession = Depen
|
||||
from open_webui.models.auth_sessions import AuthSessions
|
||||
|
||||
await AuthSessions.revoke(data['sid'], data['id'])
|
||||
if session and data and session.user_id == data.get('id'):
|
||||
sessions = await OAuthSessions.get_sessions_by_user_id(session.user_id, db=db)
|
||||
# Keep the only session for this provider: automations and API key calls use it
|
||||
if any(other.provider == session.provider and other.id != session.id for other in sessions):
|
||||
await OAuthSessions.delete_session_by_id(session.id, db=db)
|
||||
await invalidate_token(request, token)
|
||||
await publish_event(
|
||||
request,
|
||||
|
||||
@@ -19,8 +19,10 @@ from open_webui.models.access_grants import AccessGrants, has_public_write_acces
|
||||
from open_webui.models.channels import Channels
|
||||
from open_webui.models.config import Config
|
||||
from open_webui.models.folders import Folders
|
||||
from open_webui.utils.access_control.folders import has_folder_write_access
|
||||
from open_webui.utils.access_control import has_permission
|
||||
from open_webui.utils.auth import get_admin_user, get_verified_user
|
||||
from open_webui.utils.agents.discovery import get_models as get_agent_models
|
||||
from open_webui.utils.automations import (
|
||||
execute_automation,
|
||||
next_n_runs_ns,
|
||||
@@ -95,16 +97,33 @@ async def check_automation_limits(request, user, rrule_str: str, db, is_create:
|
||||
|
||||
|
||||
async def check_automation_folder_access(folder_id: Optional[str], user, db: AsyncSession):
|
||||
"""An automation can live in any folder its creator can write to."""
|
||||
if folder_id is None:
|
||||
return
|
||||
folder = await Folders.get_folder_by_id_and_user_id(folder_id, user.id, db=db)
|
||||
if not folder:
|
||||
folder = await Folders.get_folder_by_id(folder_id, db=db)
|
||||
if not folder or not (user.role == 'admin' or await has_folder_write_access(user.id, folder_id, db=db)):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail=ERROR_MESSAGES.NOT_FOUND,
|
||||
)
|
||||
|
||||
|
||||
async def check_automation_manage_access(automation, user, db: AsyncSession):
|
||||
"""Pausing, running and run history: the creator, or anyone who can write to its folder."""
|
||||
if automation and automation.user_id == user.id:
|
||||
return
|
||||
if (
|
||||
automation
|
||||
and automation.folder_id
|
||||
and (user.role == 'admin' or await has_folder_write_access(user.id, automation.folder_id, db=db))
|
||||
):
|
||||
return
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail=ERROR_MESSAGES.NOT_FOUND,
|
||||
)
|
||||
|
||||
|
||||
async def check_automation_channel_access(form_data: AutomationForm, user, db: AsyncSession):
|
||||
target = form_data.data.target
|
||||
if not target or target.type != 'channel':
|
||||
@@ -207,14 +226,14 @@ async def get_automation_models(
|
||||
db: AsyncSession = Depends(get_async_session),
|
||||
):
|
||||
await check_automations_permission(request, user)
|
||||
automation = None
|
||||
if automation_id:
|
||||
automation = await Automations.get_by_id(automation_id, db=db)
|
||||
check_automation_access(automation, user)
|
||||
from open_webui.utils.agents.discovery import get_models as get_agent_models
|
||||
|
||||
return await get_agent_models(
|
||||
request, user, {'terminal_id': terminal_id, 'automation_id': automation_id or f'preview:{user.id}'}, cwd=cwd
|
||||
)
|
||||
metadata = {'terminal_id': terminal_id}
|
||||
if automation:
|
||||
metadata.update(model_id=automation.data.get('model_id'), automation_id=automation.id)
|
||||
return await get_agent_models(request, user, metadata, cwd=cwd)
|
||||
|
||||
|
||||
# Create New Automation
|
||||
@@ -323,7 +342,7 @@ async def toggle_automation_by_id(
|
||||
):
|
||||
await check_automations_permission(request, user)
|
||||
automation = await Automations.get_by_id(id, db=db)
|
||||
check_automation_access(automation, user)
|
||||
await check_automation_manage_access(automation, user, db)
|
||||
toggled = await Automations.toggle(id, await next_run_ns(automation.data['rrule'], tz=user.timezone), db=db)
|
||||
response = await enrich_automation(toggled, db, tz=user.timezone)
|
||||
await publish_event(
|
||||
@@ -349,7 +368,7 @@ async def run_automation_by_id(
|
||||
):
|
||||
await check_automations_permission(request, user)
|
||||
automation = await Automations.get_by_id(id, db=db)
|
||||
check_automation_access(automation, user)
|
||||
await check_automation_manage_access(automation, user, db)
|
||||
automation = await Automations.update_last_run_at(automation.id, db=db)
|
||||
asyncio.create_task(execute_automation(request.app, automation))
|
||||
await publish_event(
|
||||
@@ -402,7 +421,7 @@ async def get_automation_runs(
|
||||
):
|
||||
await check_automations_permission(request, user)
|
||||
automation = await Automations.get_by_id(id, db=db)
|
||||
check_automation_access(automation, user)
|
||||
await check_automation_manage_access(automation, user, db)
|
||||
return await AutomationRuns.get_by_automation(id, skip=skip, limit=limit, db=db)
|
||||
|
||||
|
||||
@@ -418,7 +437,7 @@ async def get_automation_run(
|
||||
|
||||
await check_automations_permission(request, user)
|
||||
automation = await Automations.get_by_id(id, db=db)
|
||||
check_automation_access(automation, user)
|
||||
await check_automation_manage_access(automation, user, db)
|
||||
run = await db.get(AutomationRun, run_id)
|
||||
if not run or run.automation_id != id:
|
||||
raise HTTPException(404, 'Run not found')
|
||||
|
||||
@@ -1,12 +1,11 @@
|
||||
import base64
|
||||
import io
|
||||
import logging
|
||||
import time
|
||||
import uuid
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException, Request, status
|
||||
from fastapi.responses import FileResponse, Response, StreamingResponse
|
||||
from fastapi.responses import FileResponse, Response
|
||||
from open_webui.config import ENABLE_ADMIN_CHAT_ACCESS, ENABLE_ADMIN_EXPORT
|
||||
from open_webui.constants import ERROR_MESSAGES
|
||||
from open_webui.env import ENABLE_PROFILE_IMAGE_URL_FORWARDING, STATIC_DIR
|
||||
@@ -1217,14 +1216,19 @@ async def app_channel_reply_handler(channel_id, message_id, user_id):
|
||||
# An inactive/removed app or one without write access cannot post a public reply.
|
||||
log.warning('Could not save app error reply: app=%s message=%s', app_id, message_id)
|
||||
await emit_to_users(
|
||||
'events:app',
|
||||
'events',
|
||||
{
|
||||
'app_id': app_id,
|
||||
'app_name': app_name,
|
||||
'channel_id': channel_id,
|
||||
'message_id': message_id,
|
||||
'parent_id': parent_id,
|
||||
'reply': {'type': 'error', 'content': detail},
|
||||
'data': {
|
||||
'type': 'channel:app',
|
||||
'data': {
|
||||
'app_id': app_id,
|
||||
'app_name': app_name,
|
||||
'channel_id': channel_id,
|
||||
'message_id': message_id,
|
||||
'parent_id': parent_id,
|
||||
'reply': {'type': 'error', 'content': detail},
|
||||
},
|
||||
}
|
||||
},
|
||||
[user_id],
|
||||
)
|
||||
@@ -2094,11 +2098,10 @@ async def get_webhook_profile_image(
|
||||
try:
|
||||
header, base64_data = webhook.profile_image_url.split(',', 1)
|
||||
image_data = base64.b64decode(base64_data)
|
||||
image_buffer = io.BytesIO(image_data)
|
||||
media_type = header.split(';')[0].lstrip('data:')
|
||||
|
||||
return StreamingResponse(
|
||||
image_buffer,
|
||||
return Response(
|
||||
content=image_data,
|
||||
media_type=media_type,
|
||||
headers={'Content-Disposition': 'inline'},
|
||||
)
|
||||
|
||||
@@ -25,6 +25,7 @@ from open_webui.models.chats import (
|
||||
ChatForm,
|
||||
ChatHistoryStats,
|
||||
ChatImportForm,
|
||||
ChatAccessResponse,
|
||||
ChatResponse,
|
||||
Chats,
|
||||
ChatsImportForm,
|
||||
@@ -65,6 +66,7 @@ CHAT_CONFIG_KEYS = {
|
||||
'CONTEXT_COMPACTION_TOKEN_CAP': 'chat.context_compaction.token_cap',
|
||||
'CONTEXT_COMPACTION_RETENTION_PERCENTAGE': 'chat.context_compaction.retention_percentage',
|
||||
'CONTEXT_COMPACTION_PROMPT_TEMPLATE': 'chat.context_compaction.prompt_template',
|
||||
'VISUALIZATION_PROMPT_TEMPLATE': 'chat.visualizations.prompt_template',
|
||||
'ENABLE_TOOL_PERMISSIONS': 'chat.tool_permissions.enable',
|
||||
'ENABLE_TOOL_CALL_LABELS': 'chat.tool_call_labels.enable',
|
||||
'ENABLE_TOOL_PERMISSIONS_AUTO': 'chat.tool_permissions.auto.enable',
|
||||
@@ -196,16 +198,16 @@ def set_message_authors(chat: dict, user: UserModel) -> None:
|
||||
|
||||
|
||||
async def add_active_state_to_chat_list(
|
||||
request: Request, chat_list: list[ChatTitleIdResponse]
|
||||
request: Request, chat_list: list[ChatTitleIdResponse], db: AsyncSession | None = None
|
||||
) -> list[ChatTitleIdResponse]:
|
||||
pending_approval_ids = await ChatMessages.get_chat_ids_with_pending_approval([chat.id for chat in chat_list])
|
||||
pending_approval_ids = await ChatMessages.get_chat_ids_with_pending_approval([chat.id for chat in chat_list], db=db)
|
||||
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
|
||||
|
||||
chat.active = await ChatMessages.has_unfinished_assistant_by_chat_id(chat.id)
|
||||
chat.active = await ChatMessages.has_unfinished_assistant_by_chat_id(chat.id, db=db)
|
||||
|
||||
return chat_list
|
||||
|
||||
@@ -235,6 +237,7 @@ class ChatConfigForm(BaseModel):
|
||||
CONTEXT_COMPACTION_TOKEN_CAP: int | None = None
|
||||
CONTEXT_COMPACTION_RETENTION_PERCENTAGE: int | None = None
|
||||
CONTEXT_COMPACTION_PROMPT_TEMPLATE: str
|
||||
VISUALIZATION_PROMPT_TEMPLATE: str = ''
|
||||
ENABLE_TOOL_PERMISSIONS: bool = False
|
||||
ENABLE_TOOL_CALL_LABELS: bool = False
|
||||
ENABLE_TOOL_PERMISSIONS_AUTO: bool = False
|
||||
@@ -265,7 +268,7 @@ class ChatConfigForm(BaseModel):
|
||||
def normalize_decisions_model(cls, value: str) -> str:
|
||||
return value.strip()
|
||||
|
||||
@field_validator('TOOL_SEARCH_DECISIONS_PROMPT', 'TOOL_PERMISSIONS_AUTO_PROMPT')
|
||||
@field_validator('TOOL_SEARCH_DECISIONS_PROMPT', 'TOOL_PERMISSIONS_AUTO_PROMPT', 'VISUALIZATION_PROMPT_TEMPLATE')
|
||||
@classmethod
|
||||
def normalize_review_prompt(cls, value: str) -> str:
|
||||
return value if value.strip() else ''
|
||||
@@ -365,7 +368,7 @@ async def get_session_user_chat_list(
|
||||
sort_dir=sort_dir,
|
||||
db=db,
|
||||
)
|
||||
return await add_active_state_to_chat_list(request, chats)
|
||||
return await add_active_state_to_chat_list(request, chats, db=db)
|
||||
except Exception as e:
|
||||
log.exception(e)
|
||||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.DEFAULT())
|
||||
@@ -841,7 +844,7 @@ async def get_user_chat_list_by_user_id(
|
||||
chats = await Chats.get_chat_list_by_user_id(
|
||||
user_id, include_archived=True, filter=filter, skip=skip, limit=limit, db=db
|
||||
)
|
||||
return await add_active_state_to_chat_list(request, chats)
|
||||
return await add_active_state_to_chat_list(request, chats, db=db)
|
||||
|
||||
|
||||
# Create New Chat
|
||||
@@ -927,7 +930,13 @@ async def set_chat_config(form_data: ChatConfigForm, user=Depends(get_admin_user
|
||||
current = await get_chat_config_values()
|
||||
for field in ChatConfigForm.model_fields:
|
||||
if (
|
||||
field in {'TOOL_SEARCH_ENGINE', 'ENABLE_TOOL_PERMISSIONS_AUTO', 'ENABLE_TOOL_CALL_LABELS'}
|
||||
field
|
||||
in {
|
||||
'TOOL_SEARCH_ENGINE',
|
||||
'ENABLE_TOOL_PERMISSIONS_AUTO',
|
||||
'ENABLE_TOOL_CALL_LABELS',
|
||||
'VISUALIZATION_PROMPT_TEMPLATE',
|
||||
}
|
||||
or field.startswith(('TOOL_SEARCH_DECISIONS_', 'TOOL_PERMISSIONS_AUTO_'))
|
||||
) and (field not in form_data.model_fields_set):
|
||||
updates[field] = current.get(field, updates[field])
|
||||
@@ -990,7 +999,7 @@ async def search_user_chats(
|
||||
log.debug('deleting tag: %s', tag_id)
|
||||
await Tags.delete_tag_by_name_and_user_id(tag_id, user.id, db=db)
|
||||
|
||||
return await add_active_state_to_chat_list(request, chat_list)
|
||||
return await add_active_state_to_chat_list(request, chat_list, db=db)
|
||||
|
||||
|
||||
@router.get('/{id}/search/snippet', response_model=str | None)
|
||||
@@ -1045,7 +1054,7 @@ async def get_chat_list_by_folder_id(
|
||||
sort_dir=sort_dir,
|
||||
db=db,
|
||||
)
|
||||
return await add_active_state_to_chat_list(request, chats)
|
||||
return await add_active_state_to_chat_list(request, chats, db=db)
|
||||
|
||||
except Exception as e:
|
||||
log.exception(e)
|
||||
@@ -1060,7 +1069,7 @@ async def get_user_pinned_chats(
|
||||
request: Request, user=Depends(get_verified_user), db: AsyncSession = Depends(get_async_session)
|
||||
):
|
||||
chats = await Chats.get_pinned_chats_by_user_id(user.id, db=db)
|
||||
return await add_active_state_to_chat_list(request, chats)
|
||||
return await add_active_state_to_chat_list(request, chats, db=db)
|
||||
|
||||
|
||||
# Get Chats
|
||||
@@ -1175,7 +1184,7 @@ async def get_archived_session_user_chat_list(
|
||||
limit=limit,
|
||||
db=db,
|
||||
)
|
||||
return await add_active_state_to_chat_list(request, chats)
|
||||
return await add_active_state_to_chat_list(request, chats, db=db)
|
||||
|
||||
|
||||
# Get Archived Chats Count
|
||||
@@ -1287,7 +1296,7 @@ async def get_shared_session_user_chat_list(
|
||||
# Get Shared Chat By Id
|
||||
|
||||
|
||||
@router.get('/share/{share_id}', response_model=ChatResponse | None)
|
||||
@router.get('/share/{share_id}', response_model=ChatAccessResponse | None)
|
||||
async def get_shared_chat_by_id(
|
||||
share_id: str, user=Depends(get_optional_verified_user), db: AsyncSession = Depends(get_async_session)
|
||||
):
|
||||
@@ -1308,7 +1317,8 @@ async def get_shared_chat_by_id(
|
||||
)
|
||||
if chat:
|
||||
data = await shared_chat_response(chat, user, db=db)
|
||||
data['chat']['share_mode'] = 'continue' if live else None
|
||||
data['write_access'] = live
|
||||
data['chat']['share_mode'] = shared.chat.get('share_mode')
|
||||
return data
|
||||
|
||||
raise HTTPException(
|
||||
@@ -1322,9 +1332,7 @@ async def get_shared_chat_by_id(
|
||||
chat = await Chats.get_chat_by_id(share_id, db=db)
|
||||
if chat:
|
||||
data = await shared_chat_response(chat, user, db=db)
|
||||
data['chat']['share_mode'] = (
|
||||
'continue' if await Chats.has_chat_access(chat.id, user, db=db, permission='write', chat=chat) else None
|
||||
)
|
||||
data['write_access'] = await Chats.has_chat_access(chat.id, user, db=db, permission='write', chat=chat)
|
||||
return data
|
||||
|
||||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.NOT_FOUND)
|
||||
@@ -1355,7 +1363,7 @@ async def get_user_chat_list_by_tag_name(
|
||||
if len(chats) == 0:
|
||||
await Tags.delete_tag_by_name_and_user_id(form_data.name, user.id, db=db)
|
||||
|
||||
return await add_active_state_to_chat_list(request, chats)
|
||||
return await add_active_state_to_chat_list(request, chats, db=db)
|
||||
|
||||
|
||||
# Compact Chat
|
||||
@@ -1453,7 +1461,7 @@ async def update_chat_view(
|
||||
# Get Chat By Id
|
||||
|
||||
|
||||
@router.get('/{id}', response_model=ChatResponse | None)
|
||||
@router.get('/{id}', response_model=ChatAccessResponse | None)
|
||||
async def get_chat_by_id(
|
||||
id: str,
|
||||
request: Request,
|
||||
@@ -1467,10 +1475,11 @@ async def get_chat_by_id(
|
||||
)
|
||||
|
||||
if chat:
|
||||
from open_webui.utils.agents.session import ensure_chat_selections
|
||||
|
||||
chat = await ensure_chat_selections(chat)
|
||||
data = await shared_chat_response(chat, user, db=db)
|
||||
data['chat']['share_mode'] = (
|
||||
'continue' if await Chats.has_chat_access(id, user, db=db, permission='write', chat=chat) else None
|
||||
)
|
||||
data['write_access'] = await Chats.has_chat_access(id, user, db=db, permission='write', chat=chat)
|
||||
data = overlay_response_streams(
|
||||
data,
|
||||
await get_response_streams_by_chat_id(request.app.state.redis, id),
|
||||
@@ -1484,7 +1493,7 @@ async def get_chat_by_id(
|
||||
# Update Chat By Id
|
||||
|
||||
|
||||
@router.post('/{id}', response_model=ChatResponse | None)
|
||||
@router.post('/{id}', response_model=ChatAccessResponse | None)
|
||||
async def update_chat_by_id(
|
||||
request: Request,
|
||||
id: str,
|
||||
@@ -1494,18 +1503,24 @@ async def update_chat_by_id(
|
||||
):
|
||||
chat = await Chats.get_chat_by_id(id, db=db)
|
||||
if chat and chat.user_id != user.id:
|
||||
folder = await Folders.get_folder_by_id_and_user_id(chat.folder_id, user.id, db=db) if chat.folder_id else None
|
||||
if (
|
||||
not folder
|
||||
or set(form_data.chat) != {'title'}
|
||||
or form_data.variables is not None
|
||||
or form_data.folder_id is not None
|
||||
):
|
||||
if form_data.variables is not None or form_data.folder_id is not None:
|
||||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.ACCESS_PROHIBITED)
|
||||
title = form_data.chat['title']
|
||||
if not isinstance(title, str) or not title.strip():
|
||||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.DEFAULT('Invalid title'))
|
||||
form_data.chat['title'] = title.strip()
|
||||
if not (
|
||||
bool(form_data.chat)
|
||||
and set(form_data.chat) <= {'models', 'terminal_id', 'working_directory'}
|
||||
and await Chats.has_chat_access(id, user, db=db, permission='write', chat=chat)
|
||||
):
|
||||
folder = (
|
||||
await Folders.get_folder_by_id_and_user_id(chat.folder_id, user.id, db=db) if chat.folder_id else None
|
||||
)
|
||||
if not folder or set(form_data.chat) != {'title'}:
|
||||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.ACCESS_PROHIBITED)
|
||||
title = form_data.chat['title']
|
||||
if not isinstance(title, str) or not title.strip():
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.DEFAULT('Invalid title')
|
||||
)
|
||||
form_data.chat['title'] = title.strip()
|
||||
if chat:
|
||||
set_message_authors(form_data.chat, user)
|
||||
touch = 'history' in form_data.chat or 'messages' in form_data.chat
|
||||
@@ -1528,9 +1543,9 @@ async def update_chat_by_id(
|
||||
subject_id=id,
|
||||
data={'title': chat.title},
|
||||
)
|
||||
if chat.user_id != user.id:
|
||||
return await shared_chat_response(chat, user, db=db)
|
||||
return ChatResponse.model_validate(chat, from_attributes=True)
|
||||
data = await shared_chat_response(chat, user, db=db)
|
||||
data['write_access'] = await Chats.has_chat_access(id, user, db=db, permission='write', chat=chat)
|
||||
return data
|
||||
else:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
@@ -2370,6 +2385,24 @@ async def get_chat_tags_by_id(id: str, user=Depends(get_verified_user), db: Asyn
|
||||
# Add Chat Tag By Id
|
||||
|
||||
|
||||
async def get_chat_with_tag_access(id: str, user, db: AsyncSession):
|
||||
"""The chat whose tags this user may change: their own, or any chat in a folder they can edit.
|
||||
|
||||
Tags are the chat owner's records, so a folder editor's change is made in the owner's tags.
|
||||
"""
|
||||
chat = await Chats.get_chat_by_id_and_user_id(id, user.id, db=db)
|
||||
if chat:
|
||||
return chat
|
||||
chat = await Chats.get_chat_by_id(id, db=db)
|
||||
if (
|
||||
chat
|
||||
and chat.folder_id
|
||||
and (user.role == 'admin' or await has_folder_write_access(user.id, chat.folder_id, db=db))
|
||||
):
|
||||
return chat
|
||||
return None
|
||||
|
||||
|
||||
@router.post('/{id}/tags', response_model=list[TagModel])
|
||||
async def add_tag_by_id_and_tag_name(
|
||||
request: Request,
|
||||
@@ -2378,8 +2411,9 @@ async def add_tag_by_id_and_tag_name(
|
||||
user=Depends(get_verified_user),
|
||||
db: AsyncSession = Depends(get_async_session),
|
||||
):
|
||||
chat = await Chats.get_chat_by_id_and_user_id(id, user.id, db=db)
|
||||
chat = await get_chat_with_tag_access(id, user, db)
|
||||
if chat:
|
||||
owner_id = chat.user_id
|
||||
tags = chat.meta.get('tags', [])
|
||||
tag_id = form_data.name.replace(' ', '_').lower()
|
||||
|
||||
@@ -2390,7 +2424,7 @@ async def add_tag_by_id_and_tag_name(
|
||||
)
|
||||
|
||||
if tag_id not in tags:
|
||||
await Chats.add_chat_tag_by_id_and_user_id_and_tag_name(id, user.id, form_data.name, db=db)
|
||||
await Chats.add_chat_tag_by_id_and_user_id_and_tag_name(id, owner_id, form_data.name, db=db)
|
||||
await publish_event(
|
||||
request,
|
||||
EVENTS.CHAT_TAG_ADDED,
|
||||
@@ -2399,9 +2433,9 @@ async def add_tag_by_id_and_tag_name(
|
||||
data={'tag': form_data.name},
|
||||
)
|
||||
|
||||
chat = await Chats.get_chat_by_id_and_user_id(id, user.id, db=db)
|
||||
chat = await Chats.get_chat_by_id_and_user_id(id, owner_id, db=db)
|
||||
tags = chat.meta.get('tags', [])
|
||||
return await Tags.get_tags_by_ids_and_user_id(tags, user.id, db=db)
|
||||
return await Tags.get_tags_by_ids_and_user_id(tags, owner_id, db=db)
|
||||
else:
|
||||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.DEFAULT())
|
||||
|
||||
@@ -2417,9 +2451,10 @@ async def delete_tag_by_id_and_tag_name(
|
||||
user=Depends(get_verified_user),
|
||||
db: AsyncSession = Depends(get_async_session),
|
||||
):
|
||||
chat = await Chats.get_chat_by_id_and_user_id(id, user.id, db=db)
|
||||
chat = await get_chat_with_tag_access(id, user, db)
|
||||
if chat:
|
||||
await Chats.delete_tag_by_id_and_user_id_and_tag_name(id, user.id, form_data.name, db=db)
|
||||
owner_id = chat.user_id
|
||||
await Chats.delete_tag_by_id_and_user_id_and_tag_name(id, owner_id, form_data.name, db=db)
|
||||
await publish_event(
|
||||
request,
|
||||
EVENTS.CHAT_TAG_REMOVED,
|
||||
@@ -2428,11 +2463,35 @@ async def delete_tag_by_id_and_tag_name(
|
||||
data={'tag': form_data.name},
|
||||
)
|
||||
|
||||
if await Chats.count_chats_by_tag_name_and_user_id(form_data.name, user.id, db=db) == 0:
|
||||
await Tags.delete_tag_by_name_and_user_id(form_data.name, user.id, db=db)
|
||||
if await Chats.count_chats_by_tag_name_and_user_id(form_data.name, owner_id, db=db) == 0:
|
||||
await Tags.delete_tag_by_name_and_user_id(form_data.name, owner_id, db=db)
|
||||
|
||||
chat = await Chats.get_chat_by_id_and_user_id(id, user.id, db=db)
|
||||
chat = await Chats.get_chat_by_id_and_user_id(id, owner_id, db=db)
|
||||
tags = chat.meta.get('tags', [])
|
||||
return await Tags.get_tags_by_ids_and_user_id(tags, user.id, db=db)
|
||||
return await Tags.get_tags_by_ids_and_user_id(tags, owner_id, db=db)
|
||||
else:
|
||||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.NOT_FOUND)
|
||||
|
||||
|
||||
class TagColorForm(BaseModel):
|
||||
name: str
|
||||
# A palette name chosen by the frontend, e.g. 'blue'; the server only stores it.
|
||||
color: str = Field(min_length=1, max_length=32, pattern=r'^[a-z][a-z0-9-]*$')
|
||||
|
||||
|
||||
@router.patch('/{id}/tags', response_model=list[TagModel])
|
||||
async def update_chat_tag_color(
|
||||
request: Request,
|
||||
id: str,
|
||||
form_data: TagColorForm,
|
||||
user=Depends(get_verified_user),
|
||||
db: AsyncSession = Depends(get_async_session),
|
||||
):
|
||||
tag_id = form_data.name.replace(' ', '_').lower()
|
||||
chat = await get_chat_with_tag_access(id, user, db)
|
||||
if not chat or tag_id not in (chat.meta or {}).get('tags', []):
|
||||
raise HTTPException(status_code=403, detail=ERROR_MESSAGES.ACCESS_PROHIBITED)
|
||||
if not await Tags.update_tag_color_by_name_and_user_id(form_data.name, chat.user_id, form_data.color, db=db):
|
||||
raise HTTPException(status_code=403, detail=ERROR_MESSAGES.ACCESS_PROHIBITED)
|
||||
await publish_event(request, EVENTS.CHAT_UPDATED, actor=user, subject_id=id, data={'tag': form_data.name})
|
||||
return await Tags.get_tags_by_ids_and_user_id((chat.meta or {}).get('tags', []), chat.user_id, db=db)
|
||||
@@ -44,8 +44,13 @@ async def changed(resource_type, resource_id):
|
||||
# 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},
|
||||
'events',
|
||||
{
|
||||
'data': {
|
||||
'type': 'comments:changed',
|
||||
'data': {'resource_type': resource_type, 'resource_id': resource_id},
|
||||
}
|
||||
},
|
||||
room=comment_room(resource_type, resource_id),
|
||||
)
|
||||
except Exception:
|
||||
|
||||
@@ -15,6 +15,7 @@ from open_webui.utils.auth import get_admin_user, get_verified_user
|
||||
from open_webui.utils.headers import bearer_auth_header, get_custom_headers
|
||||
from open_webui.utils.mcp.client import MCPClient
|
||||
from open_webui.utils.oauth import (
|
||||
OAUTH_MAX_FIELD_SIZE,
|
||||
OAuthClientInformationFull,
|
||||
apply_connection_oauth_options,
|
||||
decrypt_data,
|
||||
@@ -38,8 +39,6 @@ router = APIRouter()
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
CONNECTIONS_CONFIG_KEYS = {
|
||||
'ENABLE_DIRECT_CONNECTIONS': 'direct.enable',
|
||||
'ENABLE_DIRECT_INTEGRATIONS': 'direct.integrations.enable',
|
||||
'ENABLE_BASE_MODELS_CACHE': 'models.base_models_cache',
|
||||
}
|
||||
CODE_EXECUTION_CONFIG_KEYS = {
|
||||
@@ -145,8 +144,6 @@ async def set_interface_visibility(request: Request, form_data: InterfaceVisibil
|
||||
|
||||
|
||||
class ConnectionsConfigForm(BaseModel):
|
||||
ENABLE_DIRECT_CONNECTIONS: bool
|
||||
ENABLE_DIRECT_INTEGRATIONS: bool = False
|
||||
ENABLE_BASE_MODELS_CACHE: bool
|
||||
|
||||
|
||||
@@ -329,8 +326,6 @@ class TerminalServerConnection(BaseModel):
|
||||
config: dict | None = None
|
||||
|
||||
server_type: str | None = None
|
||||
policy_id: str | None = None
|
||||
|
||||
model_config = ConfigDict(extra='allow')
|
||||
|
||||
|
||||
@@ -374,7 +369,7 @@ async def verify_terminal_server_connection(
|
||||
"""
|
||||
Verify the connection to a terminal server by detecting its type.
|
||||
|
||||
Tries GET {url}/api/v1/policies (orchestrator) then GET {url}/api/config
|
||||
Tries GET {url}/api/v1/terminals/templates (orchestrator) then GET {url}/api/config
|
||||
(plain terminal). Returns ``{status: true, type: "orchestrator"|"terminal"}``.
|
||||
"""
|
||||
if not ENABLE_TOOL_SERVERS:
|
||||
@@ -393,10 +388,10 @@ async def verify_terminal_server_connection(
|
||||
trust_env=True,
|
||||
timeout=aiohttp.ClientTimeout(total=AIOHTTP_CLIENT_TIMEOUT),
|
||||
) as session:
|
||||
# Orchestrators expose a policies API; plain terminals don't.
|
||||
# Orchestrators expose a templates API; plain terminals don't.
|
||||
try:
|
||||
async with session.get(
|
||||
f'{base_url}/api/v1/policies', headers=headers, ssl=AIOHTTP_CLIENT_SESSION_SSL
|
||||
f'{base_url}/api/v1/terminals/templates', headers=headers, ssl=AIOHTTP_CLIENT_SESSION_SSL
|
||||
) as resp:
|
||||
if resp.ok:
|
||||
return {'status': True, 'type': 'orchestrator'}
|
||||
@@ -419,162 +414,6 @@ async def verify_terminal_server_connection(
|
||||
raise HTTPException(status_code=400, detail='Failed to connect to the terminal server')
|
||||
|
||||
|
||||
class TerminalServerPolicyForm(BaseModel):
|
||||
url: str
|
||||
key: str | None = ''
|
||||
auth_type: str | None = 'bearer'
|
||||
policy_id: str
|
||||
policy_data: dict | None = None
|
||||
|
||||
|
||||
class TerminalServerLifecycleForm(BaseModel):
|
||||
url: str
|
||||
key: str | None = ''
|
||||
auth_type: str | None = 'bearer'
|
||||
policy_id: str
|
||||
lifecycle_data: dict | None = None
|
||||
|
||||
|
||||
class TerminalServerRefreshForm(BaseModel):
|
||||
url: str
|
||||
key: str | None = ''
|
||||
auth_type: str | None = 'bearer'
|
||||
user_id: str | None = None
|
||||
policy_id: str | None = None
|
||||
only_idle: bool = True
|
||||
reset: bool = False
|
||||
|
||||
|
||||
@router.post('/terminal_servers/policy')
|
||||
async def put_terminal_server_policy(
|
||||
request: Request, form_data: TerminalServerPolicyForm, user=Depends(get_admin_user)
|
||||
):
|
||||
"""Proxy a policy read or update to an orchestrator terminal server."""
|
||||
if not ENABLE_TOOL_SERVERS:
|
||||
raise HTTPException(status_code=403, detail='Tool servers are disabled')
|
||||
|
||||
base_url = (form_data.url or '').rstrip('/')
|
||||
if not base_url:
|
||||
raise HTTPException(status_code=400, detail='Terminal server URL is required')
|
||||
|
||||
headers = {'Content-Type': 'application/json'}
|
||||
if form_data.auth_type in ('bearer', 'session') and form_data.key:
|
||||
headers.update(bearer_auth_header(form_data.key))
|
||||
|
||||
try:
|
||||
async with aiohttp.ClientSession(
|
||||
trust_env=True,
|
||||
timeout=aiohttp.ClientTimeout(total=AIOHTTP_CLIENT_TIMEOUT),
|
||||
) as session:
|
||||
policy_url = f'{base_url}/api/v1/policies/{form_data.policy_id}'
|
||||
async with session.request(
|
||||
'GET' if form_data.policy_data is None else 'PUT',
|
||||
policy_url,
|
||||
headers=headers,
|
||||
json=form_data.policy_data,
|
||||
ssl=AIOHTTP_CLIENT_SESSION_SSL,
|
||||
) as resp:
|
||||
if resp.ok:
|
||||
return await resp.json()
|
||||
detail = await resp.text()
|
||||
raise HTTPException(status_code=resp.status, detail=detail)
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception as e:
|
||||
log.debug('Failed to access policy on terminal server: %s', e)
|
||||
raise HTTPException(status_code=400, detail='Failed to access policy on terminal server')
|
||||
|
||||
|
||||
@router.post('/terminal_servers/lifecycle')
|
||||
async def put_terminal_server_lifecycle(
|
||||
request: Request, form_data: TerminalServerLifecycleForm, user=Depends(get_admin_user)
|
||||
):
|
||||
"""Proxy a lifecycle read or update to an orchestrator terminal server."""
|
||||
if not ENABLE_TOOL_SERVERS:
|
||||
raise HTTPException(status_code=403, detail='Tool servers are disabled')
|
||||
|
||||
base_url = (form_data.url or '').rstrip('/')
|
||||
if not base_url:
|
||||
raise HTTPException(status_code=400, detail='Terminal server URL is required')
|
||||
|
||||
headers = {'Content-Type': 'application/json'}
|
||||
if form_data.auth_type in ('bearer', 'session') and form_data.key:
|
||||
headers.update(bearer_auth_header(form_data.key))
|
||||
|
||||
try:
|
||||
async with aiohttp.ClientSession(
|
||||
trust_env=True,
|
||||
timeout=aiohttp.ClientTimeout(total=AIOHTTP_CLIENT_TIMEOUT),
|
||||
) as session:
|
||||
lifecycle_url = f'{base_url}/api/v1/policies/{form_data.policy_id}/lifecycle'
|
||||
async with session.request(
|
||||
'GET' if form_data.lifecycle_data is None else 'PUT',
|
||||
lifecycle_url,
|
||||
headers=headers,
|
||||
json=form_data.lifecycle_data,
|
||||
ssl=AIOHTTP_CLIENT_SESSION_SSL,
|
||||
) as resp:
|
||||
if resp.ok:
|
||||
return await resp.json()
|
||||
detail = await resp.text()
|
||||
raise HTTPException(status_code=resp.status, detail=detail)
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception as e:
|
||||
log.debug('Failed to access lifecycle on terminal server: %s', e)
|
||||
raise HTTPException(status_code=400, detail='Failed to access lifecycle on terminal server')
|
||||
|
||||
|
||||
@router.post('/terminal_servers/refresh')
|
||||
async def refresh_terminal_server_terminals(
|
||||
request: Request, form_data: TerminalServerRefreshForm, user=Depends(get_admin_user)
|
||||
):
|
||||
"""
|
||||
Proxy a terminal refresh request to an orchestrator terminal server.
|
||||
"""
|
||||
if not ENABLE_TOOL_SERVERS:
|
||||
raise HTTPException(status_code=403, detail='Tool servers are disabled')
|
||||
|
||||
base_url = (form_data.url or '').rstrip('/')
|
||||
if not base_url:
|
||||
raise HTTPException(status_code=400, detail='Terminal server URL is required')
|
||||
|
||||
headers = {'Content-Type': 'application/json'}
|
||||
if form_data.auth_type in ('bearer', 'session') and form_data.key:
|
||||
headers.update(bearer_auth_header(form_data.key))
|
||||
|
||||
body = {
|
||||
'only_idle': form_data.only_idle,
|
||||
'reset': form_data.reset,
|
||||
}
|
||||
if form_data.user_id:
|
||||
body['user_id'] = form_data.user_id
|
||||
if form_data.policy_id:
|
||||
body['policy_id'] = form_data.policy_id
|
||||
|
||||
try:
|
||||
async with aiohttp.ClientSession(
|
||||
trust_env=True,
|
||||
timeout=aiohttp.ClientTimeout(total=AIOHTTP_CLIENT_TIMEOUT),
|
||||
) as session:
|
||||
refresh_url = f'{base_url}/api/v1/terminals/refresh'
|
||||
async with session.post(
|
||||
refresh_url,
|
||||
headers=headers,
|
||||
json=body,
|
||||
ssl=AIOHTTP_CLIENT_SESSION_SSL,
|
||||
) as resp:
|
||||
if resp.ok:
|
||||
return await resp.json()
|
||||
detail = await resp.text()
|
||||
raise HTTPException(status_code=resp.status, detail=detail)
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception as e:
|
||||
log.debug('Failed to refresh terminals: %s', e)
|
||||
raise HTTPException(status_code=400, detail='Failed to refresh terminals')
|
||||
|
||||
|
||||
@router.post('/tool_servers/verify')
|
||||
async def verify_tool_servers_config(request: Request, form_data: ToolServerConnection, user=Depends(get_admin_user)):
|
||||
"""
|
||||
@@ -597,6 +436,7 @@ async def verify_tool_servers_config(request: Request, form_data: ToolServerConn
|
||||
async with aiohttp.ClientSession(
|
||||
trust_env=True,
|
||||
timeout=aiohttp.ClientTimeout(total=AIOHTTP_CLIENT_TIMEOUT),
|
||||
max_field_size=OAUTH_MAX_FIELD_SIZE,
|
||||
) as session:
|
||||
async with session.get(
|
||||
discovery_url, ssl=AIOHTTP_CLIENT_SESSION_SSL
|
||||
|
||||
@@ -4,6 +4,7 @@ import hashlib
|
||||
import logging
|
||||
import os
|
||||
import uuid
|
||||
from contextlib import nullcontext
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
from urllib.parse import quote
|
||||
@@ -21,7 +22,13 @@ from fastapi import (
|
||||
status,
|
||||
)
|
||||
from fastapi.responses import FileResponse, StreamingResponse
|
||||
from open_webui.config import BYPASS_ADMIN_ACCESS_CONTROL, STORAGE_LOCAL_CACHE, STORAGE_PROVIDER, UPLOAD_DIR
|
||||
from open_webui.config import (
|
||||
BYPASS_ADMIN_ACCESS_CONTROL,
|
||||
STORAGE_LOCAL_CACHE,
|
||||
STORAGE_PROVIDER,
|
||||
THREAD_POOL_SIZE,
|
||||
UPLOAD_DIR,
|
||||
)
|
||||
from open_webui.constants import ERROR_MESSAGES
|
||||
from open_webui.events import EVENTS, publish_event
|
||||
from open_webui.internal.db import get_async_db_context, get_async_session
|
||||
@@ -57,6 +64,11 @@ router = APIRouter()
|
||||
from open_webui.utils.access_control.files import has_access_to_file
|
||||
from open_webui.utils.json_codec import JSONCodec
|
||||
|
||||
# Leave half of the worker threads free for uploads while knowledge base syncs queue up.
|
||||
_knowledge_processing_semaphore: asyncio.Semaphore = asyncio.Semaphore(
|
||||
max((THREAD_POOL_SIZE if THREAD_POOL_SIZE and THREAD_POOL_SIZE > 0 else min(32, (os.cpu_count() or 1) + 4)) // 2, 1)
|
||||
)
|
||||
|
||||
# Upload File
|
||||
# What was entrusted here was given in good faith. Let it
|
||||
# be returned the same way, whole and undiminished.
|
||||
@@ -458,15 +470,19 @@ async def upload_file_handler(
|
||||
|
||||
if process:
|
||||
if background_tasks and process_in_background:
|
||||
background_tasks.add_task(
|
||||
process_uploaded_file,
|
||||
request,
|
||||
file,
|
||||
file_path,
|
||||
file_item,
|
||||
file_metadata,
|
||||
user,
|
||||
)
|
||||
|
||||
async def _background_handler():
|
||||
async with _knowledge_processing_semaphore if knowledge_id else nullcontext():
|
||||
await process_uploaded_file(
|
||||
request,
|
||||
file,
|
||||
file_path,
|
||||
file_item,
|
||||
file_metadata,
|
||||
user,
|
||||
)
|
||||
|
||||
background_tasks.add_task(_background_handler)
|
||||
return {'status': True, **file_item.model_dump()}
|
||||
else:
|
||||
await process_uploaded_file(
|
||||
|
||||
@@ -4,7 +4,7 @@ import os
|
||||
import shutil
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
from typing import Literal, Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, File, HTTPException, Query, Request, UploadFile, status
|
||||
from fastapi.responses import FileResponse, StreamingResponse
|
||||
@@ -13,7 +13,7 @@ from open_webui.constants import ERROR_MESSAGES
|
||||
from open_webui.events import EVENTS, publish_event
|
||||
from open_webui.internal.db import get_async_session
|
||||
from open_webui.models.access_grants import AccessGrants
|
||||
from open_webui.models.automations import Automations
|
||||
from open_webui.models.automations import AutomationResponse, AutomationRuns, Automations
|
||||
from open_webui.models.chat_messages import ChatMessages
|
||||
from open_webui.models.chats import Chats
|
||||
from open_webui.models.config import Config
|
||||
@@ -23,6 +23,7 @@ from open_webui.models.folders import (
|
||||
FolderNameIdResponse,
|
||||
Folders,
|
||||
FolderUpdateForm,
|
||||
folder_status_ids,
|
||||
)
|
||||
from open_webui.models.groups import Groups
|
||||
from open_webui.models.shared_chats import ChatShareMode
|
||||
@@ -34,7 +35,7 @@ from open_webui.utils.access_control import (
|
||||
)
|
||||
from open_webui.utils.access_control.files import can_read_all_folder_files, get_accessible_folder_files
|
||||
from open_webui.utils.auth import get_admin_user, get_verified_user
|
||||
from pydantic import BaseModel
|
||||
from pydantic import BaseModel, Field
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
@@ -42,6 +43,10 @@ log = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
# Folder list and board views page through a folder's chats this many at a time.
|
||||
FOLDER_PAGE_SIZE = 50
|
||||
FolderActivity = Literal['unread', 'generating', 'waiting_for_approval', 'idle']
|
||||
|
||||
|
||||
from open_webui.utils.access_control.folders import has_folder_access as _has_folder_access
|
||||
|
||||
@@ -578,6 +583,14 @@ async def get_shared_folder_chats(
|
||||
page: int | None = Query(None, ge=1),
|
||||
sort_by: str = Query('unread_updated_at'),
|
||||
sort_dir: str = Query('desc'),
|
||||
workspace: bool = False,
|
||||
search: str = Query('', max_length=256),
|
||||
tag_ids: list[str] = Query(default=[]),
|
||||
user_ids: list[str] = Query(default=[]),
|
||||
# `status` is taken by fastapi's status module here, hence the alias.
|
||||
status_filter: list[str] = Query(default=[], alias='status'),
|
||||
activity: FolderActivity | None = None,
|
||||
updated_at_gte: int | None = Query(None, ge=0),
|
||||
user=Depends(get_verified_user),
|
||||
db: AsyncSession = Depends(get_async_session),
|
||||
):
|
||||
@@ -601,19 +614,46 @@ async def get_shared_folder_chats(
|
||||
detail=ERROR_MESSAGES.ACCESS_PROHIBITED,
|
||||
)
|
||||
|
||||
limit = 10
|
||||
limit = FOLDER_PAGE_SIZE if workspace else 10
|
||||
skip = (page - 1) * limit if page is not None else 0
|
||||
chats = await Chats.get_all_chats_by_folder_id(
|
||||
id,
|
||||
skip=skip,
|
||||
limit=limit if page is not None else 60,
|
||||
sort_by=sort_by,
|
||||
sort_dir=sort_dir,
|
||||
unread_for_user_id=user.id,
|
||||
db=db,
|
||||
)
|
||||
total = await Chats.count_all_chats_by_folder_id(id, db=db) if page is not None else len(chats)
|
||||
|
||||
if workspace:
|
||||
if sort_by not in ('title', 'updated_at', 'unread_updated_at') or sort_dir not in ('asc', 'desc'):
|
||||
raise HTTPException(status_code=422, detail='Invalid sort')
|
||||
if len(tag_ids) > 50 or len(user_ids) > 50:
|
||||
raise HTTPException(status_code=422, detail='Too many filters')
|
||||
statuses = folder_status_ids(folder.meta)
|
||||
# 'none' (or the older 'not_started') filters for chats without a status.
|
||||
if any(value not in (*statuses, 'none', 'not_started') for value in status_filter):
|
||||
raise HTTPException(status_code=422, detail='Invalid status')
|
||||
chats, total = await Chats.get_folder_chat_page(
|
||||
id,
|
||||
user.id,
|
||||
folder_write_access=has_write,
|
||||
skip=skip,
|
||||
limit=limit,
|
||||
search=search.strip(),
|
||||
tag_ids=tag_ids,
|
||||
status_ids=status_filter,
|
||||
valid_status_ids=statuses,
|
||||
user_ids=user_ids,
|
||||
activity=activity,
|
||||
updated_at_gte=updated_at_gte,
|
||||
sort_by=sort_by,
|
||||
sort_dir=sort_dir,
|
||||
redis=request.app.state.redis,
|
||||
db=db,
|
||||
)
|
||||
else:
|
||||
chats = await Chats.get_all_chats_by_folder_id(
|
||||
id,
|
||||
skip=skip,
|
||||
limit=limit if page is not None else 60,
|
||||
sort_by=sort_by,
|
||||
sort_dir=sort_dir,
|
||||
unread_for_user_id=user.id,
|
||||
db=db,
|
||||
)
|
||||
total = await Chats.count_all_chats_by_folder_id(id, db=db) if page is not None else len(chats)
|
||||
participant_ids = await Chats.get_participant_ids_by_chat_ids([chat['id'] for chat in chats], db=db)
|
||||
user_ids = {chat['user_id'] for chat in chats}
|
||||
user_ids.update(uid for ids in participant_ids.values() for uid in ids)
|
||||
@@ -686,6 +726,105 @@ async def mark_folder_chats_read_by_id(
|
||||
}
|
||||
|
||||
|
||||
async def check_folder_read_access(request: Request, id: str, user, db: AsyncSession) -> FolderModel:
|
||||
"""Return the folder if the user may read it (owner, admin or shared), else raise."""
|
||||
await check_folders_permission(request, user, db=db)
|
||||
folder = await Folders.get_folder_by_id(id, db=db)
|
||||
if not folder:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail=ERROR_MESSAGES.NOT_FOUND,
|
||||
)
|
||||
if user.role != 'admin' and folder.user_id != user.id and not await _has_folder_access(user.id, folder, 'read', db):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail=ERROR_MESSAGES.ACCESS_PROHIBITED,
|
||||
)
|
||||
return folder
|
||||
|
||||
|
||||
@router.get('/{id}/automations')
|
||||
async def get_folder_automations(
|
||||
request: Request, id: str, user=Depends(get_verified_user), db: AsyncSession = Depends(get_async_session)
|
||||
):
|
||||
"""The folder's automations, whoever made them. Only creators edit; folder editors may pause and run."""
|
||||
folder = await check_folder_read_access(request, id, user, db)
|
||||
automations = await Automations.get_by_folder(id, db=db)
|
||||
if not automations:
|
||||
return []
|
||||
latest = await AutomationRuns.get_latest_batch([item.id for item in automations], db=db)
|
||||
creators = {u.id: u.name for u in await Users.get_users_by_user_ids(list({a.user_id for a in automations}), db=db)}
|
||||
has_write = (
|
||||
user.role == 'admin' or folder.user_id == user.id or await _has_folder_access(user.id, folder, 'write', db)
|
||||
)
|
||||
return [
|
||||
{
|
||||
**AutomationResponse(**item.model_dump(), last_run=latest.get(item.id)).model_dump(),
|
||||
'user_name': creators.get(item.user_id) or 'Unknown',
|
||||
'can_edit': item.user_id == user.id,
|
||||
'can_manage': item.user_id == user.id or has_write,
|
||||
}
|
||||
for item in automations
|
||||
]
|
||||
|
||||
|
||||
@router.get('/{id}/users')
|
||||
async def get_folder_users(
|
||||
request: Request, id: str, user=Depends(get_verified_user), db: AsyncSession = Depends(get_async_session)
|
||||
):
|
||||
await check_folder_read_access(request, id, user, db)
|
||||
counts = await Chats.get_participant_counts_by_folder_id(id, db=db)
|
||||
users = await Users.get_users_by_user_ids(list(counts), db=db) if counts else []
|
||||
names = {u.id: u.name for u in users}
|
||||
return sorted(
|
||||
[{'id': user_id, 'name': names.get(user_id) or 'Unknown', 'count': count} for user_id, count in counts.items()],
|
||||
key=lambda entry: (entry['id'] != user.id, entry['name'].casefold()),
|
||||
)
|
||||
|
||||
|
||||
@router.get('/{id}/tags')
|
||||
async def get_folder_tags(
|
||||
request: Request, id: str, user=Depends(get_verified_user), db: AsyncSession = Depends(get_async_session)
|
||||
):
|
||||
await check_folder_read_access(request, id, user, db)
|
||||
return await Chats.get_tag_counts_by_folder_id(id, db=db)
|
||||
|
||||
|
||||
class FolderChatStatusForm(BaseModel):
|
||||
# null clears the status.
|
||||
status: str | None = Field(default=None, min_length=1, max_length=64)
|
||||
|
||||
|
||||
@router.patch('/{id}/chats/{chat_id}/status')
|
||||
async def update_folder_chat_status(
|
||||
request: Request,
|
||||
id: str,
|
||||
chat_id: str,
|
||||
form_data: FolderChatStatusForm,
|
||||
user=Depends(get_verified_user),
|
||||
db: AsyncSession = Depends(get_async_session),
|
||||
):
|
||||
folder = await check_folder_read_access(request, id, user, db)
|
||||
if form_data.status is not None and form_data.status not in folder_status_ids(folder.meta):
|
||||
raise HTTPException(status_code=422, detail='Invalid status')
|
||||
# Folder editors may set status on any chat in the folder; others only on their own.
|
||||
has_write = (
|
||||
user.role == 'admin' or folder.user_id == user.id or await _has_folder_access(user.id, folder, 'write', db)
|
||||
)
|
||||
if not await Chats.update_chat_folder_status_by_id(
|
||||
chat_id, id, None if has_write else user.id, form_data.status, db=db
|
||||
):
|
||||
raise HTTPException(status_code=403, detail=ERROR_MESSAGES.ACCESS_PROHIBITED)
|
||||
await publish_event(
|
||||
request,
|
||||
EVENTS.CHAT_UPDATED,
|
||||
actor=user,
|
||||
subject_id=chat_id,
|
||||
data={'folder_id': id, 'folder_status': form_data.status},
|
||||
)
|
||||
return {'id': chat_id, 'status': form_data.status}
|
||||
|
||||
|
||||
# Delete Folder By Id
|
||||
|
||||
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -10,7 +10,7 @@ from typing import List, Optional
|
||||
from urllib.parse import quote
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, Request, status
|
||||
from fastapi.responses import StreamingResponse
|
||||
from fastapi.responses import Response, StreamingResponse
|
||||
from open_webui.config import (
|
||||
BYPASS_ADMIN_ACCESS_CONTROL,
|
||||
ENABLE_KNOWLEDGE_FILE_RETENTION,
|
||||
@@ -33,7 +33,12 @@ from open_webui.models.knowledge import (
|
||||
KnowledgeUserResponse,
|
||||
)
|
||||
from open_webui.models.models import ModelForm, Models
|
||||
from open_webui.retrieval.external import retrieve_external_knowledge, retrieve_external_knowledge_for_connection
|
||||
from open_webui.retrieval.external import (
|
||||
get_vector_store_ids,
|
||||
list_openai_vector_stores,
|
||||
retrieve_external_knowledge,
|
||||
retrieve_external_knowledge_for_connection,
|
||||
)
|
||||
from open_webui.retrieval.utils import is_media_content_type
|
||||
from open_webui.retrieval.vector.async_client import ASYNC_VECTOR_DB_CLIENT
|
||||
from open_webui.routers.retrieval import (
|
||||
@@ -562,8 +567,15 @@ class ExternalKnowledgeConnectionListResponse(BaseModel):
|
||||
total: int
|
||||
|
||||
|
||||
class ExternalKnowledgeStoreListForm(BaseModel):
|
||||
connection_id: Optional[str] = None
|
||||
connection: ExternalKnowledgeConnectionForm
|
||||
|
||||
|
||||
EXTERNAL_KNOWLEDGE_CONNECTIONS_CONFIG_KEY = 'external_knowledge.connections'
|
||||
EXTERNAL_KNOWLEDGE_PROVIDERS = {'qdrant', 'milvus', 'pgvector'}
|
||||
EXTERNAL_KNOWLEDGE_PROVIDERS = {'qdrant', 'milvus', 'pgvector', 'openai'}
|
||||
# Providers that search server-side by text, so a source needs no field mapping.
|
||||
EXTERNAL_KNOWLEDGE_TEXT_SEARCH_PROVIDERS = {'openai'}
|
||||
|
||||
|
||||
def _get_external_connection_provider_and_config(form_data: ExternalKnowledgeConnectionForm) -> tuple[str, dict]:
|
||||
@@ -584,8 +596,16 @@ def _get_external_connection_provider_and_config(form_data: ExternalKnowledgeCon
|
||||
allowed_config_keys = {'timeout'}
|
||||
if provider == 'milvus':
|
||||
allowed_config_keys.add('db_name')
|
||||
normalized = {key: value for key, value in config.items() if key in allowed_config_keys}
|
||||
|
||||
return provider, {key: value for key, value in config.items() if key in allowed_config_keys}
|
||||
# Like model_ids on provider connections: a store_ids list (empty means all) lists the stores as
|
||||
# knowledge bases, readable by whoever access_grants allows.
|
||||
if provider in EXTERNAL_KNOWLEDGE_TEXT_SEARCH_PROVIDERS and isinstance(config.get('store_ids'), list):
|
||||
normalized['store_ids'] = list(dict.fromkeys(str(i).strip() for i in config['store_ids'] if str(i).strip()))
|
||||
access_grants = config.get('access_grants')
|
||||
normalized['access_grants'] = access_grants if isinstance(access_grants, list) else []
|
||||
|
||||
return provider, normalized
|
||||
|
||||
|
||||
def _get_external_auth_config(provider: str, incoming: Optional[dict], existing: Optional[dict] = None) -> dict:
|
||||
@@ -603,6 +623,14 @@ def _get_normalized_external_source(source: ExternalKnowledgeSourceForm, provide
|
||||
if not source.name:
|
||||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail='Collection name is required.')
|
||||
|
||||
if provider in EXTERNAL_KNOWLEDGE_TEXT_SEARCH_PROVIDERS:
|
||||
vector_store_ids = get_vector_store_ids(source.model_dump())
|
||||
if not vector_store_ids:
|
||||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail='Vector store ID is required.')
|
||||
source.name = ', '.join(vector_store_ids)
|
||||
source.config = {'vector_store_ids': vector_store_ids}
|
||||
return source
|
||||
|
||||
config = source.config or {}
|
||||
allowed_keys = {'content_field', 'metadata_field', 'document_id_field'}
|
||||
if provider in {'qdrant', 'milvus'}:
|
||||
@@ -828,17 +856,7 @@ async def _get_external_source_test_result(
|
||||
user_id=user.id,
|
||||
name=connection.get('name'),
|
||||
description='',
|
||||
meta={
|
||||
'source': 'external',
|
||||
'read_only': True,
|
||||
'external': {
|
||||
'connection_id': connection.get('id'),
|
||||
'source': source.model_dump(),
|
||||
'provider': connection.get('provider'),
|
||||
'auth_mode': 'service_account',
|
||||
'capabilities': {'retrieve': True},
|
||||
},
|
||||
},
|
||||
meta=_get_external_knowledge_meta(connection, source),
|
||||
access_grants=[],
|
||||
created_at=int(time.time()),
|
||||
updated_at=int(time.time()),
|
||||
@@ -897,6 +915,45 @@ async def test_external_knowledge_retrieval(
|
||||
return await _get_external_source_test_result(request, connection, source, form_data.query, form_data.count, user)
|
||||
|
||||
|
||||
@router.post('/external/source/stores', response_model=dict)
|
||||
async def list_external_knowledge_stores(
|
||||
form_data: ExternalKnowledgeStoreListForm,
|
||||
user=Depends(get_admin_user),
|
||||
):
|
||||
if form_data.connection_id:
|
||||
existing_connection = await _get_external_connection_by_id(form_data.connection_id)
|
||||
if not existing_connection:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail='External connection not found.')
|
||||
connection = _get_external_connection_update_from_form(form_data.connection, existing_connection)
|
||||
else:
|
||||
connection = _get_external_connection_from_form(form_data.connection, user.id, id='external-test')
|
||||
|
||||
if connection['provider'] not in EXTERNAL_KNOWLEDGE_TEXT_SEARCH_PROVIDERS:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail='Listing is only supported for OpenAI-compatible sources.',
|
||||
)
|
||||
|
||||
try:
|
||||
return {'items': await list_openai_vector_stores(connection)}
|
||||
except RuntimeError as e:
|
||||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))
|
||||
|
||||
|
||||
def _get_external_knowledge_meta(connection: dict, source: ExternalKnowledgeSourceForm) -> dict:
|
||||
return {
|
||||
'source': 'external',
|
||||
'read_only': True,
|
||||
'external': {
|
||||
'connection_id': connection.get('id'),
|
||||
'source': source.model_dump(),
|
||||
'provider': connection.get('provider'),
|
||||
'auth_mode': 'service_account',
|
||||
'capabilities': {'retrieve': True},
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@router.post('/external/knowledge/create', response_model=KnowledgeResponse | None)
|
||||
async def create_external_knowledge(
|
||||
request: Request,
|
||||
@@ -931,17 +988,7 @@ async def create_external_knowledge(
|
||||
if not knowledge:
|
||||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.FILE_EXISTS)
|
||||
|
||||
meta = {
|
||||
'source': 'external',
|
||||
'read_only': True,
|
||||
'external': {
|
||||
'connection_id': form_data.connection_id,
|
||||
'source': source.model_dump(),
|
||||
'provider': connection.get('provider'),
|
||||
'auth_mode': 'service_account',
|
||||
'capabilities': {'retrieve': True},
|
||||
},
|
||||
}
|
||||
meta = _get_external_knowledge_meta(connection, source)
|
||||
knowledge = await Knowledges.update_knowledge_meta_by_id(knowledge.id, meta, db=db)
|
||||
await embed_knowledge_base_metadata(request, knowledge.id, knowledge.name, knowledge.description)
|
||||
return knowledge
|
||||
@@ -996,17 +1043,7 @@ async def create_external_knowledge_source(
|
||||
await _set_external_connections(connections)
|
||||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.FILE_EXISTS)
|
||||
|
||||
meta = {
|
||||
'source': 'external',
|
||||
'read_only': True,
|
||||
'external': {
|
||||
'connection_id': connection.get('id'),
|
||||
'source': source.model_dump(),
|
||||
'provider': connection.get('provider'),
|
||||
'auth_mode': 'service_account',
|
||||
'capabilities': {'retrieve': True},
|
||||
},
|
||||
}
|
||||
meta = _get_external_knowledge_meta(connection, source)
|
||||
knowledge = await Knowledges.update_knowledge_meta_by_id(knowledge.id, meta, db=db)
|
||||
await embed_knowledge_base_metadata(request, knowledge.id, knowledge.name, knowledge.description)
|
||||
return knowledge
|
||||
@@ -1063,17 +1100,7 @@ async def update_external_knowledge_source(
|
||||
await _set_external_connections(connections)
|
||||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.DEFAULT())
|
||||
|
||||
meta = {
|
||||
'source': 'external',
|
||||
'read_only': True,
|
||||
'external': {
|
||||
'connection_id': connection.get('id'),
|
||||
'source': source.model_dump(),
|
||||
'provider': connection.get('provider'),
|
||||
'auth_mode': 'service_account',
|
||||
'capabilities': {'retrieve': True},
|
||||
},
|
||||
}
|
||||
meta = _get_external_knowledge_meta(connection, source)
|
||||
updated = await Knowledges.update_knowledge_meta_by_id(id, meta, db=db)
|
||||
if not updated:
|
||||
connections[idx] = existing_connection
|
||||
@@ -2274,24 +2301,26 @@ async def export_knowledge_by_id(id: str, user=Depends(get_admin_user), db: Asyn
|
||||
|
||||
# Create zip file in memory
|
||||
zip_buffer = io.BytesIO()
|
||||
with zipfile.ZipFile(zip_buffer, 'w', zipfile.ZIP_DEFLATED) as zf:
|
||||
for file in files:
|
||||
content = file.data.get('content', '') if file.data else ''
|
||||
if content:
|
||||
# Use original filename with .txt extension
|
||||
filename = file.filename
|
||||
if not filename.endswith('.txt'):
|
||||
filename = f'{filename}.txt'
|
||||
zf.writestr(filename, content)
|
||||
|
||||
zip_buffer.seek(0)
|
||||
def write_zip():
|
||||
with zipfile.ZipFile(zip_buffer, 'w', zipfile.ZIP_DEFLATED) as zf:
|
||||
for file in files:
|
||||
content = file.data.get('content', '') if file.data else ''
|
||||
if content:
|
||||
# Use original filename with .txt extension
|
||||
filename = file.filename
|
||||
if not filename.endswith('.txt'):
|
||||
filename = f'{filename}.txt'
|
||||
zf.writestr(filename, content)
|
||||
|
||||
await asyncio.to_thread(write_zip)
|
||||
|
||||
# Sanitize knowledge name for filename
|
||||
safe_name = ''.join(c if c.isalnum() or c in ' -_' else '_' for c in knowledge.name)
|
||||
zip_filename = f'{safe_name}.zip'
|
||||
|
||||
return StreamingResponse(
|
||||
zip_buffer,
|
||||
return Response(
|
||||
content=zip_buffer.getvalue(),
|
||||
media_type='application/zip',
|
||||
headers={'Content-Disposition': f"attachment; filename*=UTF-8''{quote(zip_filename, safe='')}"},
|
||||
)
|
||||
|
||||
@@ -18,7 +18,7 @@ from fastapi import (
|
||||
Response,
|
||||
status,
|
||||
)
|
||||
from fastapi.responses import RedirectResponse, StreamingResponse
|
||||
from fastapi.responses import RedirectResponse
|
||||
from open_webui.config import BYPASS_ADMIN_ACCESS_CONTROL
|
||||
from open_webui.constants import ERROR_MESSAGES
|
||||
from open_webui.env import (
|
||||
@@ -85,7 +85,7 @@ async def _check_model_controls(form, previous, user, request):
|
||||
if not request.app.state.MODELS:
|
||||
await get_all_models(request, user=user)
|
||||
base = request.app.state.MODELS.get(form.base_model_id or form.id, {})
|
||||
if 'pipe' in base or base.get('direct') or base.get('owned_by') == 'arena':
|
||||
if 'pipe' in base or base.get('owned_by') == 'arena':
|
||||
raise HTTPException(400, 'Model controls require a server-managed provider model.')
|
||||
|
||||
|
||||
@@ -1020,7 +1020,6 @@ async def get_model_profile_image(
|
||||
try:
|
||||
header, base64_data = profile_image_url.split(',', 1)
|
||||
image_data = base64.b64decode(base64_data)
|
||||
image_buffer = io.BytesIO(image_data)
|
||||
media_type = header.split(';')[0].lstrip('data:').lower()
|
||||
|
||||
# only serve known-safe raster types inline; reject SVG/unknown (can run script on our origin)
|
||||
@@ -1040,8 +1039,8 @@ async def get_model_profile_image(
|
||||
if updated_at:
|
||||
headers['ETag'] = f'"{updated_at}"'
|
||||
|
||||
return StreamingResponse(
|
||||
image_buffer,
|
||||
return Response(
|
||||
content=image_data,
|
||||
media_type=media_type,
|
||||
headers=headers,
|
||||
)
|
||||
|
||||
@@ -566,8 +566,8 @@ async def update_note_by_id(
|
||||
event_data['data'] = note.data
|
||||
|
||||
await sio.emit(
|
||||
'events:note',
|
||||
event_data,
|
||||
'events',
|
||||
{'data': {'type': 'note:updated', 'data': event_data}},
|
||||
to=f'note:{note.id}',
|
||||
)
|
||||
|
||||
|
||||
@@ -1210,7 +1210,7 @@ class OpenAIChatMessage(BaseModel):
|
||||
"""A single message in an OpenAI-compatible chat request."""
|
||||
|
||||
role: str
|
||||
content: Union[str | None, list[OpenAIChatMessageContent]]
|
||||
content: Union[str | None, list[OpenAIChatMessageContent]] = None
|
||||
model_config = ConfigDict(extra='allow')
|
||||
|
||||
|
||||
|
||||
@@ -37,11 +37,12 @@ from open_webui.models.access_grants import AccessGrants
|
||||
from open_webui.models.config import Config
|
||||
from open_webui.models.groups import Groups
|
||||
from open_webui.models.models import Models
|
||||
from open_webui.utils.tether import RelayClient, get_tether_connections
|
||||
from open_webui.models.users import UserModel
|
||||
from open_webui.utils.access_control import check_model_access, has_connection_access, has_permission
|
||||
from open_webui.utils.anthropic import ANTHROPIC_VERSION, get_anthropic_models, is_anthropic_url
|
||||
from open_webui.utils.auth import get_admin_user, get_verified_user
|
||||
from open_webui.utils.headers import get_headers_and_cookies, include_user_info_headers
|
||||
from open_webui.utils.headers import bearer_auth_header, get_headers_and_cookies, include_user_info_headers
|
||||
from open_webui.utils.json_codec import JSONCodec
|
||||
from open_webui.utils.misc import convert_logit_bias_input_to_json, get_provider_function, merge_tool_call_batches
|
||||
from open_webui.utils.model_ids import strip_provider_model_prefix
|
||||
@@ -254,8 +255,55 @@ async def get_openai_connection(idx: int) -> tuple[str, str, dict]:
|
||||
return url, key, api_config
|
||||
|
||||
|
||||
@cached(ttl=MODELS_CACHE_TTL, key_builder=lambda _func, user: f'openai_tether_models_{user.id}')
|
||||
async def get_tether_models(user) -> dict[str, dict]:
|
||||
"""Models of the OpenAI-compatible connections the user added in Tether, listed through it."""
|
||||
|
||||
async def fetch(presence, item) -> list[dict]:
|
||||
base_url = f'tether://{presence["connection_id"]}'
|
||||
async with RelayClient(user.id, item['service'], timeout=10) as client:
|
||||
async with client.get(f'{base_url}/models') as response:
|
||||
if response.status >= 400:
|
||||
raise RuntimeError(f'HTTP {response.status}')
|
||||
ids = [model['id'] for model in (await response.json()).get('data', []) if model.get('id')]
|
||||
return [
|
||||
{
|
||||
'id': model_id,
|
||||
'name': model_id,
|
||||
'object': 'model',
|
||||
'created': int(time.time()),
|
||||
'owned_by': 'openai',
|
||||
'connection_type': 'local',
|
||||
'tags': [{'name': f'{presence["name"]} · {item["name"]}'}],
|
||||
'owner_id': user.id,
|
||||
'base_url': base_url,
|
||||
'service': item['service'],
|
||||
}
|
||||
for model_id in ids
|
||||
]
|
||||
|
||||
sources = await get_tether_connections(user.id, 'openai')
|
||||
results = await asyncio.gather(*(fetch(*source) for source in sources), return_exceptions=True)
|
||||
models = {}
|
||||
for (presence, item), result in zip(sources, results):
|
||||
if isinstance(result, BaseException):
|
||||
log.info('Could not list models from %s on %s: %s', item['name'], presence['name'], result)
|
||||
continue
|
||||
for model in result:
|
||||
models.setdefault(model['id'], model)
|
||||
return models
|
||||
|
||||
|
||||
async def get_tether_model(request: Request, user, model_id) -> dict | None:
|
||||
"""The user's own model with this id, unless a shared model already has it."""
|
||||
if not user or not isinstance(model_id, str) or request.app.state.MODELS.get(model_id) is not None:
|
||||
return None
|
||||
return (await get_tether_models(user)).get(model_id)
|
||||
|
||||
|
||||
async def clear_models_cache(request: Request):
|
||||
await get_all_models.cache.clear()
|
||||
await get_tether_models.cache.clear()
|
||||
redis = getattr(request.app.state, 'redis', None)
|
||||
if redis is not None:
|
||||
await redis.delete(BASE_MODELS_CACHE_KEY)
|
||||
@@ -1432,6 +1480,8 @@ async def generate_chat_completion(
|
||||
if not hasattr(request.state, 'model_id'):
|
||||
request.state.model_id = model_id
|
||||
model_info = await Models.get_model_by_id(model_id)
|
||||
# The user's own connection, reached through their Tether. Only they can resolve it.
|
||||
tether_model = None if model_info else await get_tether_model(request, user, model_id)
|
||||
|
||||
# Check model info and override the payload
|
||||
if model_info:
|
||||
@@ -1452,25 +1502,32 @@ async def generate_chat_completion(
|
||||
payload = await apply_system_prompt_to_body(system, payload, metadata, user)
|
||||
|
||||
await check_model_access(user, model_info, bypass_filter)
|
||||
else:
|
||||
elif tether_model is None:
|
||||
await check_model_access(user, None, bypass_filter)
|
||||
|
||||
# Check if model is already in app state cache to avoid expensive get_all_models() call
|
||||
models = request.app.state.OPENAI_MODELS
|
||||
if not models or model_id not in models:
|
||||
await get_all_models(request, user=user)
|
||||
models = request.app.state.OPENAI_MODELS
|
||||
model = models.get(model_id)
|
||||
|
||||
if model:
|
||||
idx = model['urlIdx']
|
||||
# `relay` is closed with the response; the shared pool session never is.
|
||||
session = relay = None
|
||||
if tether_model is not None:
|
||||
# Tether adds the key; the URL and key never reach this server.
|
||||
model, url, key, api_config = tether_model, tether_model['base_url'], '', {}
|
||||
session = relay = RelayClient(user.id, tether_model['service'])
|
||||
else:
|
||||
raise HTTPException(
|
||||
status_code=404,
|
||||
detail=ERROR_MESSAGES.MODEL_NOT_FOUND(),
|
||||
)
|
||||
# Check if model is already in app state cache to avoid expensive get_all_models() call
|
||||
models = request.app.state.OPENAI_MODELS
|
||||
if not models or model_id not in models:
|
||||
await get_all_models(request, user=user)
|
||||
models = request.app.state.OPENAI_MODELS
|
||||
model = models.get(model_id)
|
||||
|
||||
url, key, api_config = await get_openai_connection(idx)
|
||||
if model:
|
||||
idx = model['urlIdx']
|
||||
else:
|
||||
raise HTTPException(
|
||||
status_code=404,
|
||||
detail=ERROR_MESSAGES.MODEL_NOT_FOUND(),
|
||||
)
|
||||
|
||||
url, key, api_config = await get_openai_connection(idx)
|
||||
|
||||
prefix_id = api_config.get('prefix_id', None)
|
||||
payload['model'] = strip_provider_model_prefix(payload['model'], prefix_id)
|
||||
@@ -1580,7 +1637,7 @@ async def generate_chat_completion(
|
||||
response = None
|
||||
|
||||
try:
|
||||
session = await get_session()
|
||||
session = session or await get_session()
|
||||
|
||||
r = await session.request(
|
||||
method='POST',
|
||||
@@ -1637,7 +1694,7 @@ async def generate_chat_completion(
|
||||
|
||||
streaming = True
|
||||
return StreamingResponse(
|
||||
stream_wrapper(r),
|
||||
stream_wrapper(r, relay),
|
||||
status_code=r.status,
|
||||
headers=_clean_proxy_headers(r.headers),
|
||||
)
|
||||
@@ -1679,7 +1736,7 @@ async def generate_chat_completion(
|
||||
)
|
||||
finally:
|
||||
if not streaming:
|
||||
await cleanup_response(r)
|
||||
await cleanup_response(r, relay)
|
||||
|
||||
|
||||
async def embeddings(request: Request, form_data: dict, user):
|
||||
|
||||
@@ -64,6 +64,7 @@ from open_webui.events import EVENTS, publish_event
|
||||
from open_webui.internal.db import get_async_db, get_async_session
|
||||
from open_webui.models.files import FileModel, Files, FileUpdateForm
|
||||
from open_webui.models.knowledge import Knowledges
|
||||
from open_webui.models.users import UserModel
|
||||
|
||||
# Document loaders
|
||||
from open_webui.retrieval.loaders.youtube import YoutubeLoader, YoutubeTranscriptError
|
||||
@@ -1407,17 +1408,14 @@ def has_duplicate_content(collection_name: str, hash: str, file_id: str | None)
|
||||
return False
|
||||
|
||||
|
||||
def save_docs_to_vector_db(
|
||||
def _chunk_docs(
|
||||
request: Request,
|
||||
docs,
|
||||
collection_name,
|
||||
docs: list[Document],
|
||||
collection_name: str,
|
||||
config: dict,
|
||||
metadata: dict | None = None,
|
||||
overwrite: bool = False,
|
||||
split: bool = True,
|
||||
add: bool = False,
|
||||
user=None,
|
||||
) -> bool:
|
||||
) -> tuple[list[str], list[dict]]:
|
||||
def _get_docs_info(docs: list[Document]) -> str:
|
||||
docs_info = set()
|
||||
|
||||
@@ -1521,13 +1519,30 @@ def save_docs_to_vector_db(
|
||||
}
|
||||
for doc in docs
|
||||
]
|
||||
return texts, metadatas
|
||||
|
||||
|
||||
async def save_docs_to_vector_db(
|
||||
request: Request,
|
||||
docs: list[Document],
|
||||
collection_name: str,
|
||||
config: dict,
|
||||
metadata: dict | None = None,
|
||||
overwrite: bool = False,
|
||||
split: bool = True,
|
||||
add: bool = False,
|
||||
user: UserModel | None = None,
|
||||
) -> bool:
|
||||
texts, metadatas = await run_in_threadpool(
|
||||
_chunk_docs, request, docs, collection_name, config, metadata=metadata, split=split
|
||||
)
|
||||
|
||||
try:
|
||||
if get_vector_db_client().has_collection(collection_name=collection_name):
|
||||
if await ASYNC_VECTOR_DB_CLIENT.has_collection(collection_name=collection_name):
|
||||
log.info('collection %s already exists', collection_name)
|
||||
|
||||
if overwrite:
|
||||
get_vector_db_client().delete_collection(collection_name=collection_name)
|
||||
await ASYNC_VECTOR_DB_CLIENT.delete_collection(collection_name=collection_name)
|
||||
log.info('deleting existing collection %s', collection_name)
|
||||
elif add is False:
|
||||
log.info('collection %s already exists, overwrite is False and add is False', collection_name)
|
||||
@@ -1570,8 +1585,6 @@ def save_docs_to_vector_db(
|
||||
# Round up to whole provider batches to preserve request boundaries.
|
||||
buffer_size = batch_size * ((buffer_size + batch_size - 1) // batch_size)
|
||||
|
||||
# Run async embedding in sync context using the main event loop
|
||||
# This allows the main loop to stay responsive to health checks during long operations
|
||||
embedding_timeout = RAG_EMBEDDING_TIMEOUT
|
||||
|
||||
log.info('adding to collection %s', collection_name)
|
||||
@@ -1579,20 +1592,15 @@ def save_docs_to_vector_db(
|
||||
try:
|
||||
for start in range(0, len(texts), buffer_size):
|
||||
buffer_texts = texts[start : start + buffer_size]
|
||||
future = asyncio.run_coroutine_threadsafe(
|
||||
started_at = time.monotonic()
|
||||
embeddings = await asyncio.wait_for(
|
||||
embedding_function(
|
||||
[text.replace('\n', ' ') for text in buffer_texts],
|
||||
prefix=config['rag.embedding_content_prefix'],
|
||||
user=user,
|
||||
),
|
||||
request.app.state.main_loop,
|
||||
timeout=embedding_timeout,
|
||||
)
|
||||
started_at = time.monotonic()
|
||||
try:
|
||||
embeddings = future.result(timeout=embedding_timeout)
|
||||
except TimeoutError:
|
||||
future.cancel()
|
||||
raise
|
||||
if embedding_timeout is not None:
|
||||
embedding_timeout = max(embedding_timeout - (time.monotonic() - started_at), 0)
|
||||
log.info('embeddings generated %s for %s items', len(embeddings), len(buffer_texts))
|
||||
@@ -1608,19 +1616,21 @@ def save_docs_to_vector_db(
|
||||
]
|
||||
|
||||
inserted_ids.extend(item['id'] for item in items)
|
||||
get_vector_db_client().insert(
|
||||
await ASYNC_VECTOR_DB_CLIENT.insert(
|
||||
collection_name=collection_name,
|
||||
items=items,
|
||||
)
|
||||
del items, embeddings, future
|
||||
except Exception:
|
||||
del items, embeddings
|
||||
except BaseException:
|
||||
# Also on cancellation: a partial collection would make retries skip indexing.
|
||||
if inserted_ids:
|
||||
try:
|
||||
if add:
|
||||
get_vector_db_client().delete(collection_name=collection_name, ids=inserted_ids)
|
||||
await asyncio.shield(
|
||||
ASYNC_VECTOR_DB_CLIENT.delete(collection_name=collection_name, ids=inserted_ids)
|
||||
)
|
||||
else:
|
||||
# This call created/replaced the collection; an empty one would make retries skip indexing.
|
||||
get_vector_db_client().delete_collection(collection_name=collection_name)
|
||||
await asyncio.shield(ASYNC_VECTOR_DB_CLIENT.delete_collection(collection_name=collection_name))
|
||||
except Exception:
|
||||
log.exception('failed to remove partially added items from collection %s', collection_name)
|
||||
raise
|
||||
@@ -1830,14 +1840,9 @@ async def index_file(
|
||||
|
||||
# External embedding API takes time (5-60s+).
|
||||
# Subsequent updates use fresh async sessions.
|
||||
# NOTE: save_docs_to_vector_db is a sync function that
|
||||
# calls asyncio.run_coroutine_threadsafe(..., main_loop).result()
|
||||
# which blocks the calling thread. We MUST run it in a
|
||||
# worker thread to avoid deadlocking the event loop.
|
||||
result = True
|
||||
for name in collection_names:
|
||||
result = await run_in_threadpool(
|
||||
save_docs_to_vector_db,
|
||||
result = await save_docs_to_vector_db(
|
||||
request,
|
||||
docs=docs,
|
||||
collection_name=name,
|
||||
@@ -1952,7 +1957,7 @@ async def process_text(
|
||||
log.debug('text_content: %s', text_content)
|
||||
|
||||
config = await Config.get_many(*RETRIEVAL_CONFIG_KEYS.values())
|
||||
result = await run_in_threadpool(save_docs_to_vector_db, request, docs, collection_name, config, user=user)
|
||||
result = await save_docs_to_vector_db(request, docs, collection_name, config, user=user)
|
||||
if result:
|
||||
await publish_event(
|
||||
request,
|
||||
@@ -2216,8 +2221,7 @@ async def process_web(
|
||||
await _validate_collection_access([collection_name], user, access_type='write')
|
||||
|
||||
if not config['web.search.bypass_embedding_and_retrieval']:
|
||||
await run_in_threadpool(
|
||||
save_docs_to_vector_db,
|
||||
await save_docs_to_vector_db(
|
||||
request,
|
||||
docs,
|
||||
collection_name,
|
||||
@@ -2773,8 +2777,7 @@ async def process_web_search(request: Request, form_data: SearchForm, user=Depen
|
||||
collection_name = f'web-search-{user.id}-{calculate_sha256_string("-".join(form_data.queries))}'[:63]
|
||||
|
||||
try:
|
||||
await run_in_threadpool(
|
||||
save_docs_to_vector_db,
|
||||
await save_docs_to_vector_db(
|
||||
request,
|
||||
docs,
|
||||
collection_name,
|
||||
@@ -3174,8 +3177,7 @@ async def process_files_batch(
|
||||
# Save all documents in one batch
|
||||
if all_docs:
|
||||
try:
|
||||
await run_in_threadpool(
|
||||
save_docs_to_vector_db,
|
||||
await save_docs_to_vector_db(
|
||||
request,
|
||||
all_docs,
|
||||
collection_name,
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
"""Permission-scoped workspace search. Shared snapshots never read the live chat."""
|
||||
|
||||
import logging
|
||||
from typing import Literal
|
||||
from urllib.parse import urlencode
|
||||
|
||||
from fastapi import APIRouter, Depends, Query
|
||||
from open_webui.internal.db import get_async_session
|
||||
from open_webui.internal.db import get_async_session, strip_nul_from_json
|
||||
from open_webui.models.access_grants import AccessGrant, AccessGrants
|
||||
from open_webui.models.channels import ChannelMember, Channels
|
||||
from open_webui.models.chat_messages import ChatMessage
|
||||
@@ -20,8 +21,10 @@ from open_webui.utils.access_control import has_permission
|
||||
from open_webui.utils.auth import get_verified_user
|
||||
from pydantic import BaseModel, Field
|
||||
from sqlalchemy import BigInteger, and_, case, cast, func, literal, or_, select, text, union_all
|
||||
from sqlalchemy.exc import DBAPIError
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
router = APIRouter()
|
||||
PAGE_SIZE = 24
|
||||
|
||||
@@ -493,4 +496,13 @@ async def search(
|
||||
user.role == 'admin' or await has_permission(user.id, 'features.' + feature, permissions, db=db)
|
||||
):
|
||||
enabled.append(result_kind)
|
||||
return await search_workspace(db, user, q, kind, sharing, scope, page, tuple(enabled))
|
||||
try:
|
||||
return await search_workspace(db, user, q, kind, sharing, scope, page, tuple(enabled))
|
||||
except DBAPIError as e:
|
||||
# PostgreSQL can't read \u0000 out of json; rows stored before writes stripped it get cleaned once.
|
||||
if getattr(e.orig, 'sqlstate', None) != '22P05':
|
||||
raise
|
||||
log.warning('Stripping \\u0000 from stored JSON so search can read it')
|
||||
await db.rollback()
|
||||
await strip_nul_from_json(db)
|
||||
return await search_workspace(db, user, q, kind, sharing, scope, page, tuple(enabled))
|
||||
@@ -21,6 +21,7 @@ from open_webui.models.config import Config
|
||||
from open_webui.routers.pipelines import process_pipeline_inlet_filter
|
||||
from open_webui.utils.auth import get_admin_user, get_verified_user
|
||||
from open_webui.utils.chat import generate_chat_completion
|
||||
from open_webui.utils.models import add_tether_model
|
||||
from open_webui.utils.payload import apply_params_to_form_data
|
||||
from open_webui.utils.task import (
|
||||
autocomplete_generation_template,
|
||||
@@ -146,13 +147,7 @@ async def generate_title(request: Request, form_data: dict, user=Depends(get_ver
|
||||
content={'detail': 'Title generation is disabled'},
|
||||
)
|
||||
|
||||
if getattr(request.state, 'direct', False) and hasattr(request.state, 'model'):
|
||||
models = {
|
||||
**dict(request.app.state.MODELS.items()),
|
||||
request.state.model['id']: request.state.model,
|
||||
}
|
||||
else:
|
||||
models = request.app.state.MODELS
|
||||
models = await add_tether_model(request, user, form_data.get('model'))
|
||||
|
||||
model_id = form_data['model']
|
||||
if not model_id:
|
||||
@@ -221,13 +216,7 @@ async def generate_follow_ups(request: Request, form_data: dict, user=Depends(ge
|
||||
content={'detail': 'Follow-up generation is disabled'},
|
||||
)
|
||||
|
||||
if getattr(request.state, 'direct', False) and hasattr(request.state, 'model'):
|
||||
models = {
|
||||
**dict(request.app.state.MODELS.items()),
|
||||
request.state.model['id']: request.state.model,
|
||||
}
|
||||
else:
|
||||
models = request.app.state.MODELS
|
||||
models = await add_tether_model(request, user, form_data.get('model'))
|
||||
|
||||
model_id = form_data['model']
|
||||
if model_id not in models:
|
||||
@@ -288,13 +277,7 @@ async def generate_chat_tags(request: Request, form_data: dict, user=Depends(get
|
||||
content={'detail': 'Tags generation is disabled'},
|
||||
)
|
||||
|
||||
if getattr(request.state, 'direct', False) and hasattr(request.state, 'model'):
|
||||
models = {
|
||||
**dict(request.app.state.MODELS.items()),
|
||||
request.state.model['id']: request.state.model,
|
||||
}
|
||||
else:
|
||||
models = request.app.state.MODELS
|
||||
models = await add_tether_model(request, user, form_data.get('model'))
|
||||
|
||||
model_id = form_data['model']
|
||||
if model_id not in models:
|
||||
@@ -347,13 +330,7 @@ async def generate_chat_tags(request: Request, form_data: dict, user=Depends(get
|
||||
|
||||
@router.post('/image_prompt/completions')
|
||||
async def generate_image_prompt(request: Request, form_data: dict, user=Depends(get_verified_user)):
|
||||
if getattr(request.state, 'direct', False) and hasattr(request.state, 'model'):
|
||||
models = {
|
||||
**dict(request.app.state.MODELS.items()),
|
||||
request.state.model['id']: request.state.model,
|
||||
}
|
||||
else:
|
||||
models = request.app.state.MODELS
|
||||
models = await add_tether_model(request, user, form_data.get('model'))
|
||||
|
||||
model_id = form_data['model']
|
||||
if model_id not in models:
|
||||
@@ -424,13 +401,7 @@ async def generate_queries(request: Request, form_data: dict, user=Depends(get_v
|
||||
log.info('Reusing cached queries')
|
||||
return request.state.cached_queries
|
||||
|
||||
if getattr(request.state, 'direct', False) and hasattr(request.state, 'model'):
|
||||
models = {
|
||||
**dict(request.app.state.MODELS.items()),
|
||||
request.state.model['id']: request.state.model,
|
||||
}
|
||||
else:
|
||||
models = request.app.state.MODELS
|
||||
models = await add_tether_model(request, user, form_data.get('model'))
|
||||
|
||||
model_id = form_data['model']
|
||||
if model_id not in models:
|
||||
@@ -500,13 +471,7 @@ async def generate_autocompletion(request: Request, form_data: dict, user=Depend
|
||||
detail=ERROR_MESSAGES.INPUT_TOO_LONG(autocomplete_input_max_length),
|
||||
)
|
||||
|
||||
if getattr(request.state, 'direct', False) and hasattr(request.state, 'model'):
|
||||
models = {
|
||||
**dict(request.app.state.MODELS.items()),
|
||||
request.state.model['id']: request.state.model,
|
||||
}
|
||||
else:
|
||||
models = request.app.state.MODELS
|
||||
models = await add_tether_model(request, user, form_data.get('model'))
|
||||
|
||||
model_id = form_data['model']
|
||||
if model_id not in models and not model_id.startswith('agent:'):
|
||||
@@ -561,13 +526,7 @@ async def generate_autocompletion(request: Request, form_data: dict, user=Depend
|
||||
|
||||
@router.post('/emoji/completions')
|
||||
async def generate_emoji(request: Request, form_data: dict, user=Depends(get_verified_user)):
|
||||
if getattr(request.state, 'direct', False) and hasattr(request.state, 'model'):
|
||||
models = {
|
||||
**dict(request.app.state.MODELS.items()),
|
||||
request.state.model['id']: request.state.model,
|
||||
}
|
||||
else:
|
||||
models = request.app.state.MODELS
|
||||
models = await add_tether_model(request, user, form_data.get('model'))
|
||||
|
||||
model_id = form_data['model']
|
||||
if model_id not in models:
|
||||
@@ -615,13 +574,7 @@ async def generate_emoji(request: Request, form_data: dict, user=Depends(get_ver
|
||||
|
||||
@router.post('/moa/completions')
|
||||
async def generate_moa_response(request: Request, form_data: dict, user=Depends(get_verified_user)):
|
||||
if getattr(request.state, 'direct', False) and hasattr(request.state, 'model'):
|
||||
models = {
|
||||
**dict(request.app.state.MODELS.items()),
|
||||
request.state.model['id']: request.state.model,
|
||||
}
|
||||
else:
|
||||
models = request.app.state.MODELS
|
||||
models = await add_tether_model(request, user, form_data.get('model'))
|
||||
|
||||
model_id = form_data['model']
|
||||
|
||||
|
||||
@@ -0,0 +1,229 @@
|
||||
"""Template management and context-authorized terminal lifecycle operations."""
|
||||
|
||||
from urllib.parse import quote
|
||||
from uuid import UUID
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request
|
||||
from pydantic import BaseModel, Field
|
||||
from open_webui.models.access_grants import AccessGrants
|
||||
from open_webui.models.config import Config
|
||||
from open_webui.utils.access_control import validate_access_grants
|
||||
from open_webui.utils.auth import get_verified_user
|
||||
from open_webui.utils.terminals import (
|
||||
has_connection_write_access,
|
||||
get_connection,
|
||||
server_request,
|
||||
template_terminal_id,
|
||||
template_connection,
|
||||
get_terminal_context,
|
||||
find_terminal_connection,
|
||||
)
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
class CreateForm(BaseModel):
|
||||
id: UUID
|
||||
connection_id: str
|
||||
data: dict = Field(default_factory=dict)
|
||||
|
||||
|
||||
class ShareForm(BaseModel):
|
||||
access_grants: list[dict]
|
||||
|
||||
|
||||
class InstanceForm(BaseModel):
|
||||
user_id: str | None = Field(default=None, min_length=1)
|
||||
chat_id: str | None = None
|
||||
model_id: str | None = None
|
||||
|
||||
|
||||
def path(template_id, suffix=''):
|
||||
return f'api/v1/terminals/templates/{quote(template_id, safe="")}{suffix}'
|
||||
|
||||
|
||||
async def changed(user_id, terminal_id, previous=()):
|
||||
from open_webui.socket.main import emit_to_users
|
||||
|
||||
current = await AccessGrants.get_grants_by_resource('terminal', terminal_id)
|
||||
recipients = {user_id}
|
||||
recipients.update(await AccessGrants.get_user_ids_by_access_grants([*previous, *current], 'read'))
|
||||
await emit_to_users('events', {'data': {'type': 'terminals:changed'}}, list(recipients))
|
||||
|
||||
|
||||
@router.get('/connections')
|
||||
async def management_connections(user=Depends(get_verified_user)):
|
||||
result = []
|
||||
for connection in await Config.get('terminal_server.connections', []) or []:
|
||||
if connection.get('server_type') != 'orchestrator' or not connection.get('enabled', True):
|
||||
continue
|
||||
try:
|
||||
await get_connection(user, connection['id'])
|
||||
except HTTPException:
|
||||
continue
|
||||
if await has_connection_write_access(user, connection):
|
||||
result.append({'id': connection['id'], 'name': connection.get('name', connection['id'])})
|
||||
return result
|
||||
|
||||
|
||||
@router.get('/connections/{connection_id}/status')
|
||||
async def connection_status(connection_id: str, user=Depends(get_verified_user)):
|
||||
connection = await get_connection(user, connection_id)
|
||||
if not await has_connection_write_access(user, connection):
|
||||
raise HTTPException(403, 'Creation is not allowed')
|
||||
return await server_request(connection, 'api/v1/terminals/status')
|
||||
|
||||
|
||||
@router.post('', status_code=201)
|
||||
async def create_template(body: CreateForm, user=Depends(get_verified_user)):
|
||||
connection = await get_connection(user, body.connection_id)
|
||||
if not await has_connection_write_access(user, connection):
|
||||
raise HTTPException(403, 'Creation is not allowed')
|
||||
row = await server_request(
|
||||
connection, 'api/v1/terminals/templates', method='POST', body={'id': str(body.id), 'data': body.data}
|
||||
)
|
||||
selector = template_terminal_id(connection['id'], row['id'])
|
||||
try:
|
||||
await AccessGrants.set_access_grants(
|
||||
'terminal', selector, [{'principal_type': 'user', 'principal_id': user.id, 'permission': 'read'}]
|
||||
)
|
||||
except Exception:
|
||||
await server_request(connection, path(row['id']), method='DELETE')
|
||||
raise
|
||||
await changed(user.id, selector)
|
||||
return {**row, 'terminal_id': selector}
|
||||
|
||||
|
||||
@router.get('/{terminal_id}')
|
||||
async def get_template(terminal_id: str, user=Depends(get_verified_user)):
|
||||
_, template = await template_connection(user, terminal_id, 'write')
|
||||
return template
|
||||
|
||||
|
||||
@router.patch('/{terminal_id}')
|
||||
async def update_template(terminal_id: str, body: dict, user=Depends(get_verified_user)):
|
||||
connection, template = await template_connection(user, terminal_id, 'write')
|
||||
result = await server_request(connection, path(template['id']), method='PATCH', body=body)
|
||||
await changed(user.id, terminal_id)
|
||||
return result
|
||||
|
||||
|
||||
@router.delete('/{terminal_id}')
|
||||
async def delete_template(terminal_id: str, user=Depends(get_verified_user)):
|
||||
connection, template = await template_connection(user, terminal_id, 'write')
|
||||
previous = await AccessGrants.get_grants_by_resource('terminal', terminal_id)
|
||||
result = await server_request(connection, path(template['id']), method='DELETE')
|
||||
await AccessGrants.set_access_grants('terminal', terminal_id, [])
|
||||
await changed(user.id, terminal_id, previous)
|
||||
return result
|
||||
|
||||
|
||||
@router.get('/{terminal_id}/access')
|
||||
async def get_shares(terminal_id: str, user=Depends(get_verified_user)):
|
||||
await template_connection(user, terminal_id, 'write')
|
||||
return [
|
||||
grant
|
||||
for grant in await AccessGrants.get_grants_by_resource('terminal', terminal_id)
|
||||
if grant.permission == 'read'
|
||||
]
|
||||
|
||||
|
||||
@router.post('/{terminal_id}/access')
|
||||
async def set_shares(terminal_id: str, body: ShareForm, user=Depends(get_verified_user)):
|
||||
await template_connection(user, terminal_id, 'write')
|
||||
if any(
|
||||
g.get('principal_type') not in ('user', 'group') or g.get('principal_id') in (None, '', '*')
|
||||
for g in body.access_grants
|
||||
):
|
||||
raise HTTPException(400, 'Public terminal sharing is not allowed')
|
||||
grants = await validate_access_grants(
|
||||
await Config.get('user.permissions'), user.id, user.role, body.access_grants, resource_type='terminal'
|
||||
)
|
||||
previous = await AccessGrants.get_grants_by_resource('terminal', terminal_id)
|
||||
await AccessGrants.set_access_grants('terminal', terminal_id, grants)
|
||||
await changed(user.id, terminal_id, previous)
|
||||
return {'ok': True}
|
||||
|
||||
|
||||
@router.get('/{terminal_id}/instance')
|
||||
async def current_instance(
|
||||
terminal_id: str,
|
||||
request: Request,
|
||||
chat_id: str | None = None,
|
||||
model_id: str | None = None,
|
||||
user=Depends(get_verified_user),
|
||||
):
|
||||
connection = await find_terminal_connection(
|
||||
user, terminal_id, {'chat_id': chat_id, 'model_id': model_id}, request=request
|
||||
)
|
||||
if not connection or not connection.get('template_id'):
|
||||
raise HTTPException(404, 'Template not found')
|
||||
result = await server_request(
|
||||
connection,
|
||||
path(connection['template_id'], '/instance'),
|
||||
params={k: v for k, v in connection['terminal_context'].items() if v is not None},
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
@router.get('/{terminal_id}/instances')
|
||||
async def list_instances(terminal_id: str, user=Depends(get_verified_user)):
|
||||
from open_webui.models.chats import Chats
|
||||
from open_webui.models.models import Models
|
||||
from open_webui.models.users import Users
|
||||
|
||||
connection, template = await template_connection(user, terminal_id, 'write')
|
||||
rows = await server_request(connection, path(template['id'], '/instances'))
|
||||
for row in rows:
|
||||
kind, _, value = (row.get('context_id') or '').partition(':')
|
||||
row['context'] = {f'{kind}_id': value} if value else {}
|
||||
if kind == 'chat':
|
||||
chat = await Chats.get_chat_by_id(value)
|
||||
owner = await Users.get_user_by_id(chat.user_id) if chat else None
|
||||
row['label'] = chat.title if chat else None
|
||||
row['user_name'] = owner.name if owner else None
|
||||
elif kind == 'user':
|
||||
owner = await Users.get_user_by_id(value)
|
||||
row['label'] = owner.name if owner else None
|
||||
elif kind == 'model':
|
||||
model = await Models.get_model_by_id(value)
|
||||
row['label'] = model.name if model else value
|
||||
return rows
|
||||
|
||||
|
||||
async def instance_action(terminal_id, action, body, user):
|
||||
connection, template = await template_connection(user, terminal_id, 'write')
|
||||
context = get_terminal_context(template, body.user_id or user.id, body.model_dump(exclude_none=True))
|
||||
result = await server_request(
|
||||
connection,
|
||||
path(template['id'], '/instance' if action == 'delete' else '/' + action),
|
||||
method='DELETE' if action == 'delete' else 'POST',
|
||||
body=context,
|
||||
)
|
||||
await changed(user.id, terminal_id)
|
||||
return result
|
||||
|
||||
|
||||
@router.post('/{terminal_id}/restart')
|
||||
async def restart(terminal_id: str, body: InstanceForm, user=Depends(get_verified_user)):
|
||||
return await instance_action(terminal_id, 'restart', body, user)
|
||||
|
||||
|
||||
@router.post('/{terminal_id}/stop')
|
||||
async def stop(terminal_id: str, body: InstanceForm, user=Depends(get_verified_user)):
|
||||
return await instance_action(terminal_id, 'stop', body, user)
|
||||
|
||||
|
||||
@router.post('/{terminal_id}/start')
|
||||
async def start(terminal_id: str, body: InstanceForm, user=Depends(get_verified_user)):
|
||||
return await instance_action(terminal_id, 'start', body, user)
|
||||
|
||||
|
||||
@router.post('/{terminal_id}/reset')
|
||||
async def reset(terminal_id: str, body: InstanceForm, user=Depends(get_verified_user)):
|
||||
return await instance_action(terminal_id, 'reset', body, user)
|
||||
|
||||
|
||||
@router.delete('/{terminal_id}/instance')
|
||||
async def delete_instance(terminal_id: str, body: InstanceForm, user=Depends(get_verified_user)):
|
||||
return await instance_action(terminal_id, 'delete', body, user)
|
||||
@@ -17,25 +17,23 @@ from urllib.parse import quote, unquote, urljoin, urlsplit
|
||||
import aiohttp
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request, Response, WebSocket, WebSocketDisconnect
|
||||
from fastapi.responses import JSONResponse, StreamingResponse
|
||||
from multidict import CIMultiDict
|
||||
from open_webui.config import TERMINAL_PROXY_HEADERS
|
||||
from open_webui.env import AIOHTTP_CLIENT_SESSION_SSL, ENABLE_TOOL_SERVERS
|
||||
from open_webui.events import EVENTS, publish_event
|
||||
from open_webui.models.groups import Groups
|
||||
from open_webui.routers.templates import router as templates_router
|
||||
from open_webui.utils.access_control import has_connection_access
|
||||
from open_webui.utils.auth import get_verified_user, get_verified_user_by_token
|
||||
from open_webui.utils.browser import browser_access, browser_ticket
|
||||
from open_webui.utils.browser import browser_access, create_browser_token
|
||||
from open_webui.utils.tether import RelayInterrupted, get_terminal_connections, get_terminal_client
|
||||
from open_webui.utils.headers import bearer_auth_header, normalize_bearer_token
|
||||
from open_webui.utils.json_codec import JSONCodec
|
||||
from open_webui.utils.terminals import (
|
||||
TERMINAL_CONTEXT_HEADER,
|
||||
find_terminal_connection,
|
||||
terminal_headers,
|
||||
get_terminal_server_url,
|
||||
is_terminal_orchestrator,
|
||||
terminal_chat_uploads,
|
||||
terminal_context_available,
|
||||
terminal_context_config,
|
||||
terminal_context_id,
|
||||
terminal_contexts,
|
||||
)
|
||||
from starlette.background import BackgroundTask
|
||||
from starlette.requests import ClientDisconnect
|
||||
@@ -44,6 +42,7 @@ from yarl import URL
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter()
|
||||
router.include_router(templates_router, prefix='/templates')
|
||||
|
||||
STREAMING_CONTENT_TYPES = ('application/octet-stream', 'image/', 'application/pdf', 'text/event-stream')
|
||||
ADMIN_API_PATHS = ('api/v1/policies', 'api/v1/status', 'api/v1/terminals')
|
||||
@@ -160,14 +159,28 @@ def _sanitize_proxy_path(path: str) -> str | None:
|
||||
|
||||
|
||||
@router.api_route(
|
||||
'/{server_id}/browser/view/{sid}/{ticket}/{path:path}',
|
||||
'/{server_id}/browser/view/{sid}/{browser_token}/{path:path}',
|
||||
methods=['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'],
|
||||
)
|
||||
async def browser_http(request: Request, server_id: str, sid: str, ticket: str, path: str):
|
||||
user, data = await browser_access(server_id, sid, ticket)
|
||||
request.state.browser_auth = data['relay']
|
||||
request.scope['path_params']['chat_id'] = data.get('chat', '')
|
||||
return await proxy_terminal(server_id, f'browser/view/{sid}/{data["capability"]}/{path}', request, user)
|
||||
async def browser_http(request: Request, server_id: str, sid: str, browser_token: str, path: str):
|
||||
user, data = await browser_access(server_id, sid, browser_token)
|
||||
if data.get('resource') == 'files':
|
||||
if request.method not in ('GET', 'HEAD', 'OPTIONS'):
|
||||
raise HTTPException(405, 'File preview tokens are read-only')
|
||||
file_path = _sanitize_proxy_path(path)
|
||||
if file_path is None:
|
||||
raise HTTPException(400, 'Invalid file path')
|
||||
path = f'files/serve/{file_path}'
|
||||
else:
|
||||
path = f'browser/view/{sid}/{data["capability"]}/{path}'
|
||||
return await _proxy_terminal(
|
||||
server_id,
|
||||
path,
|
||||
request,
|
||||
user,
|
||||
context=browser_context(data),
|
||||
browser_auth=data['relay'],
|
||||
)
|
||||
|
||||
|
||||
async def relay_from_browser(ws, upstream):
|
||||
@@ -189,58 +202,49 @@ async def relay_to_browser(ws, upstream):
|
||||
await ws.send_bytes(msg.data)
|
||||
else:
|
||||
return
|
||||
code = upstream.close_code or 1011
|
||||
await ws.close(code=1011 if code in (1005, 1006, 1015) else code)
|
||||
|
||||
|
||||
async def watch_access(server_id, sid, ticket):
|
||||
async def watch_access(server_id, sid, browser_token, request):
|
||||
while True:
|
||||
await asyncio.sleep(10)
|
||||
current_user, _ = await browser_access(server_id, sid, ticket)
|
||||
latest = await get_terminal_connections(current_user)
|
||||
current = next((c for c in latest if c.get('id') == server_id), None)
|
||||
if (
|
||||
not current
|
||||
or not current.get('enabled', True)
|
||||
or not ENABLE_TOOL_SERVERS
|
||||
or not await has_connection_access(current_user, current)
|
||||
or not terminal_context_available(current, 'chat')
|
||||
):
|
||||
current_user, data = await browser_access(server_id, sid, browser_token)
|
||||
current = await find_terminal_connection(current_user, server_id, browser_context(data), request=request)
|
||||
if not current:
|
||||
return
|
||||
|
||||
|
||||
@router.websocket('/{server_id}/browser/view/{sid}/{ticket}/{kind}')
|
||||
async def browser_ws(ws: WebSocket, server_id: str, sid: str, ticket: str, kind: str):
|
||||
@router.websocket('/{server_id}/browser/view/{sid}/{browser_token}/{kind}')
|
||||
async def browser_ws(ws: WebSocket, server_id: str, sid: str, browser_token: str, kind: str):
|
||||
try:
|
||||
user, data = await browser_access(server_id, sid, ticket)
|
||||
connections = await get_terminal_connections(user)
|
||||
connection = next((c for c in connections if c.get('id') == server_id), None)
|
||||
user, data = await browser_access(server_id, sid, browser_token)
|
||||
connection = await find_terminal_connection(user, server_id, browser_context(data), request=ws)
|
||||
if (
|
||||
kind not in ('ws', 'stream', 'vnc')
|
||||
or data.get('resource') == 'files'
|
||||
or not ENABLE_TOOL_SERVERS
|
||||
or not connection
|
||||
or not connection.get('enabled', True)
|
||||
or not await has_connection_access(user, connection)
|
||||
or not terminal_context_available(connection, 'chat')
|
||||
):
|
||||
raise HTTPException(403, 'Browser access denied')
|
||||
chat = data.get('chat', '')
|
||||
context = terminal_context_id(connection, {'chat_id': chat}, 'chat')
|
||||
if terminal_context_config(connection, 'chat').get('context_id') == 'chat_id' and not context:
|
||||
raise HTTPException(403, 'Saved chat required')
|
||||
except HTTPException:
|
||||
await ws.close(code=4001)
|
||||
return
|
||||
await ws.accept()
|
||||
base = get_terminal_server_url(connection).replace('https://', 'wss://').replace('http://', 'ws://')
|
||||
url = f'{base}/browser/view/{sid}/{quote(data["capability"], safe="")}/{kind}'
|
||||
headers = {'X-User-Id': user.id, 'X-Session-Id': chat}
|
||||
if context:
|
||||
headers[TERMINAL_CONTEXT_HEADER] = context
|
||||
headers = {'X-User-Id': user.id, 'X-Session-Id': chat, **terminal_headers(connection)}
|
||||
if data['relay'].get('authorization'):
|
||||
headers['Authorization'] = data['relay']['authorization']
|
||||
tasks = []
|
||||
try:
|
||||
async with get_terminal_client(
|
||||
base, user.id, cookies=data['relay'].get('cookies', {}), trust_env=True
|
||||
base,
|
||||
connection.get('instance_user_id', user.id),
|
||||
service=connection.get('service', 'open_terminal'),
|
||||
cookies=data['relay'].get('cookies', {}),
|
||||
trust_env=True,
|
||||
) as client:
|
||||
async with client.ws_connect(
|
||||
url,
|
||||
@@ -251,7 +255,7 @@ async def browser_ws(ws: WebSocket, server_id: str, sid: str, ticket: str, kind:
|
||||
tasks = [
|
||||
asyncio.create_task(relay_from_browser(ws, upstream)),
|
||||
asyncio.create_task(relay_to_browser(ws, upstream)),
|
||||
asyncio.create_task(watch_access(server_id, sid, ticket)),
|
||||
asyncio.create_task(watch_access(server_id, sid, browser_token, ws)),
|
||||
]
|
||||
await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)
|
||||
except aiohttp.WSServerHandshakeError as exc:
|
||||
@@ -280,11 +284,13 @@ async def list_terminal_servers(request: Request, user=Depends(get_verified_user
|
||||
'id': connection.get('id', ''),
|
||||
'url': '' if connection.get('owner_id') else connection.get('url', ''),
|
||||
'name': connection.get('name', ''),
|
||||
'contexts': terminal_contexts(connection),
|
||||
'template_id': connection.get('template_id'),
|
||||
'scope': connection.get('scope'),
|
||||
'config': {'chat_uploads': terminal_chat_uploads(connection)},
|
||||
}
|
||||
for connection in connections
|
||||
if connection.get('enabled', True) and await has_connection_access(user, connection, user_group_ids)
|
||||
if connection.get('enabled', True)
|
||||
and (connection.get('template_id') or await has_connection_access(user, connection, user_group_ids))
|
||||
]
|
||||
|
||||
|
||||
@@ -300,23 +306,28 @@ async def proxy_terminal(
|
||||
request: Request,
|
||||
user=Depends(get_verified_user),
|
||||
):
|
||||
"""Proxy a request to the admin terminal server identified by *server_id*."""
|
||||
return await _proxy_terminal(
|
||||
server_id,
|
||||
path,
|
||||
request,
|
||||
user,
|
||||
context={
|
||||
'instance_user_id': request.headers.get('x-terminal-user-id'),
|
||||
'chat_id': request.path_params.get('chat_id') or request.headers.get('x-session-id'),
|
||||
'model_id': request.headers.get('x-terminal-model-id'),
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
async def _proxy_terminal(server_id, path, request, user, *, context, browser_auth=None):
|
||||
if not ENABLE_TOOL_SERVERS:
|
||||
return JSONResponse({'error': 'Tool servers are disabled'}, status_code=403)
|
||||
|
||||
connections = await get_terminal_connections(user)
|
||||
connection = next((c for c in connections if c.get('id') == server_id), None)
|
||||
connection = await find_terminal_connection(user, server_id, context, request=request)
|
||||
|
||||
if connection is None:
|
||||
return JSONResponse({'error': f"Terminal server '{server_id}' not found"}, status_code=404)
|
||||
|
||||
if not connection.get('enabled', True):
|
||||
return JSONResponse({'error': 'Terminal server disabled'}, status_code=403)
|
||||
|
||||
user_group_ids = {group.id for group in await Groups.get_groups_by_member_id(user.id, include_inherited=True)}
|
||||
if not await has_connection_access(user, connection, user_group_ids):
|
||||
return JSONResponse({'error': 'Access denied'}, status_code=403)
|
||||
|
||||
base_url = get_terminal_server_url(connection)
|
||||
if not base_url:
|
||||
return JSONResponse({'error': 'Terminal server URL not configured'}, status_code=503)
|
||||
@@ -341,26 +352,12 @@ async def proxy_terminal(
|
||||
|
||||
headers = {'X-User-Id': user.id}
|
||||
# Forward per-session cwd tracking header
|
||||
session_id = request.path_params.get('chat_id') or request.headers.get('x-session-id')
|
||||
if (
|
||||
safe_path.rstrip('/') == 'system/info'
|
||||
and (terminal_context_config(connection, 'chat') or {}).get('context_id') == 'chat_id'
|
||||
and not terminal_context_id(connection, {'chat_id': session_id}, 'chat')
|
||||
):
|
||||
return JSONResponse({'error': 'A saved chat is required for this terminal'}, status_code=409)
|
||||
session_id = context.get('chat_id')
|
||||
if session_id:
|
||||
headers['X-Session-Id'] = session_id
|
||||
if not terminal_context_available(connection, 'chat'):
|
||||
return JSONResponse({'error': 'Terminal server is not available in chats'}, status_code=403)
|
||||
context_id = terminal_context_id(connection, {'chat_id': session_id}, 'chat')
|
||||
if terminal_context_config(connection, 'chat').get('context_id') == 'chat_id' and not context_id:
|
||||
return JSONResponse({'error': 'A saved chat is required for this terminal'}, status_code=409)
|
||||
if context_id:
|
||||
headers[TERMINAL_CONTEXT_HEADER] = context_id
|
||||
cookies = getattr(request, 'cookies', {}) if connection.get('forward_cookies', False) else {}
|
||||
auth_type = connection.get('auth_type', 'bearer')
|
||||
|
||||
browser_auth = getattr(request.state, 'browser_auth', None)
|
||||
if browser_auth is not None:
|
||||
cookies = browser_auth.get('cookies', {})
|
||||
if browser_auth.get('authorization'):
|
||||
@@ -396,19 +393,36 @@ async def proxy_terminal(
|
||||
if value := request.headers.get(name):
|
||||
headers[name] = value
|
||||
|
||||
headers.update(terminal_headers(connection))
|
||||
content_type = request.headers.get('content-type')
|
||||
if content_type:
|
||||
headers['Content-Type'] = content_type
|
||||
|
||||
if connection.get('template_id') and safe_path == 'files/preview' and request.method == 'POST':
|
||||
browser_token = create_browser_token(
|
||||
server_id,
|
||||
user.id,
|
||||
context.get('instance_user_id'),
|
||||
session_id or '',
|
||||
{'id': 'files', 'token': ''},
|
||||
headers,
|
||||
cookies,
|
||||
resource='files',
|
||||
)
|
||||
base = request.url.path.removesuffix('/files/preview')
|
||||
return {'url': f'{base}/browser/view/files/{quote(browser_token, safe="")}/'}
|
||||
|
||||
session = get_terminal_client(
|
||||
base_url,
|
||||
user.id,
|
||||
connection.get('instance_user_id', user.id),
|
||||
service=connection.get('service', 'open_terminal'),
|
||||
timeout=aiohttp.ClientTimeout(total=300, connect=10),
|
||||
trust_env=True,
|
||||
)
|
||||
|
||||
try:
|
||||
body = request.stream()
|
||||
has_body = 'content-length' in request.headers or 'transfer-encoding' in request.headers
|
||||
body = request.stream() if has_body else None
|
||||
|
||||
upstream_response = await session.request(
|
||||
method=request.method,
|
||||
@@ -421,13 +435,14 @@ async def proxy_terminal(
|
||||
)
|
||||
|
||||
upstream_content_type = upstream_response.headers.get('content-type', '')
|
||||
filtered_headers = {
|
||||
key: value
|
||||
# Case-insensitive and multi-valued, like the upstream headers: admin headers replace the
|
||||
# terminal's whatever their case, and repeated headers such as Set-Cookie all survive.
|
||||
filtered_headers = CIMultiDict(
|
||||
(key, value)
|
||||
for key, value in upstream_response.headers.items()
|
||||
if key.lower() not in STRIPPED_RESPONSE_HEADERS
|
||||
}
|
||||
if TERMINAL_PROXY_HEADERS:
|
||||
filtered_headers.update(TERMINAL_PROXY_HEADERS)
|
||||
)
|
||||
filtered_headers.update(TERMINAL_PROXY_HEADERS)
|
||||
|
||||
port_match = re.match(r'^proxy/(\d+)/', safe_path)
|
||||
port_prefix = None
|
||||
@@ -438,9 +453,6 @@ async def proxy_terminal(
|
||||
remote_origin = f'http://localhost:{port_match[1]}'
|
||||
destination = urlsplit(urljoin(f'{remote_origin}/{safe_path[len(port_match[0]) :]}', location))
|
||||
if destination.netloc == urlsplit(remote_origin).netloc:
|
||||
filtered_headers = {
|
||||
key: value for key, value in filtered_headers.items() if key.lower() != 'location'
|
||||
}
|
||||
filtered_headers['Location'] = (
|
||||
port_prefix
|
||||
+ destination.path.lstrip('/')
|
||||
@@ -471,8 +483,14 @@ async def proxy_terminal(
|
||||
):
|
||||
browser_session = json.loads(response_body)
|
||||
if isinstance(browser_session, dict) and browser_session.get('id') and browser_session.get('token'):
|
||||
browser_session['token'] = browser_ticket(
|
||||
server_id, user.id, session_id or '', browser_session, headers, cookies
|
||||
browser_session['token'] = create_browser_token(
|
||||
server_id,
|
||||
user.id,
|
||||
context.get('instance_user_id'),
|
||||
session_id or '',
|
||||
browser_session,
|
||||
headers,
|
||||
cookies,
|
||||
)
|
||||
response_body = json.dumps(browser_session).encode()
|
||||
if port_prefix and 'text/html' in upstream_content_type:
|
||||
@@ -528,11 +546,11 @@ async def _resolve_authenticated_connection(ws: WebSocket, server_id: str):
|
||||
await ws.close(code=4001, reason='Invalid token')
|
||||
return None
|
||||
|
||||
ws.state.auth = payload
|
||||
result = await _resolve_terminal_access(ws, server_id, token)
|
||||
if result is None:
|
||||
return None
|
||||
user, connection = result
|
||||
ws.state.auth = payload
|
||||
chat_id = payload.get('chat_id', '')
|
||||
return user, connection, chat_id if isinstance(chat_id, str) else '', token
|
||||
|
||||
@@ -553,8 +571,11 @@ async def _resolve_terminal_access(ws: WebSocket, server_id: str, token: str):
|
||||
return None
|
||||
|
||||
# Resolve terminal server
|
||||
connections = await get_terminal_connections(user)
|
||||
connection = next((c for c in connections if c.get('id') == server_id), None)
|
||||
try:
|
||||
connection = await find_terminal_connection(user, server_id, socket_metadata(ws), request=ws)
|
||||
except HTTPException as exc:
|
||||
await ws.close(code=4003, reason=str(exc.detail))
|
||||
return None
|
||||
|
||||
if connection is None:
|
||||
if server_id.startswith('tether:'):
|
||||
@@ -563,17 +584,6 @@ async def _resolve_terminal_access(ws: WebSocket, server_id: str, token: str):
|
||||
await ws.close(code=4004, reason='Terminal server not found')
|
||||
return None
|
||||
|
||||
if not connection.get('enabled', True):
|
||||
await ws.close(code=4003, reason='Terminal server disabled')
|
||||
return None
|
||||
|
||||
if not await has_connection_access(user, connection):
|
||||
await ws.close(code=4003, reason='Access denied')
|
||||
return None
|
||||
|
||||
if not terminal_context_available(connection, 'chat'):
|
||||
await ws.close(code=4003, reason='Terminal server is not available in chats')
|
||||
return None
|
||||
return user, connection
|
||||
|
||||
|
||||
@@ -638,19 +648,12 @@ async def _proxy_terminal_websocket(
|
||||
|
||||
upstream_params = {}
|
||||
# For orchestrator-backed servers, pass user_id
|
||||
upstream_params['user_id'] = user.id
|
||||
upstream_params['user_id'] = connection.get('instance_user_id', user.id)
|
||||
if stream_path.startswith('execute/'):
|
||||
for key in ('offset', 'tail'):
|
||||
if key in ws.query_params:
|
||||
upstream_params[key] = ws.query_params[key]
|
||||
context_id = terminal_context_id(connection, {'chat_id': chat_id}, 'chat')
|
||||
upstream_headers = {'X-User-Id': user.id, 'X-Session-Id': chat_id}
|
||||
if terminal_context_config(connection, 'chat').get('context_id') == 'chat_id' and not context_id:
|
||||
await ws.close(code=4003, reason='A saved chat is required for this terminal')
|
||||
return
|
||||
if context_id:
|
||||
upstream_headers[TERMINAL_CONTEXT_HEADER] = context_id
|
||||
|
||||
upstream_headers = {'X-User-Id': user.id, 'X-Session-Id': chat_id, **terminal_headers(connection)}
|
||||
import urllib.parse
|
||||
|
||||
# Encode session_id as an opaque path segment so it cannot smuggle '?'/'#'/'&' (at any
|
||||
@@ -664,7 +667,9 @@ async def _proxy_terminal_websocket(
|
||||
|
||||
request = Request({**ws.scope, 'type': 'http', 'method': 'GET'})
|
||||
opened = False
|
||||
session = get_terminal_client(base_url, user.id)
|
||||
session = get_terminal_client(
|
||||
base_url, connection.get('instance_user_id', user.id), service=connection.get('service', 'open_terminal')
|
||||
)
|
||||
try:
|
||||
async with session.ws_connect(
|
||||
upstream_url,
|
||||
@@ -678,8 +683,6 @@ async def _proxy_terminal_websocket(
|
||||
if auth_type == 'bearer':
|
||||
key = normalize_bearer_token(connection.get('key', ''))
|
||||
await upstream.send_str(_json.dumps({**ws.state.auth, 'token': key}))
|
||||
elif auth_type == 'session' and is_terminal_orchestrator(connection):
|
||||
await upstream.send_str(_json.dumps({**ws.state.auth, 'token': token}))
|
||||
else:
|
||||
await upstream.send_str(_json.dumps({**ws.state.auth, 'token': ''}))
|
||||
|
||||
@@ -775,3 +778,16 @@ async def _proxy_terminal_websocket(
|
||||
await ws.close()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def browser_context(data):
|
||||
return {'instance_user_id': data.get('instance_user'), 'chat_id': data.get('chat'), 'model_id': data.get('model')}
|
||||
|
||||
|
||||
def socket_metadata(ws):
|
||||
auth = getattr(ws.state, 'auth', {})
|
||||
return {
|
||||
'instance_user_id': auth.get('instance_user_id'),
|
||||
'chat_id': auth.get('chat_id'),
|
||||
'model_id': auth.get('model_id'),
|
||||
}
|
||||
@@ -3,17 +3,34 @@
|
||||
import asyncio
|
||||
import json
|
||||
from contextlib import suppress
|
||||
from types import SimpleNamespace
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
from fastapi import APIRouter, WebSocket
|
||||
from open_webui.models.auth_sessions import AuthSessions
|
||||
from open_webui.utils.auth import decode_token, get_verified_user_by_token
|
||||
from open_webui.utils.tether import CHUNK, WINDOW, hub, encode, decode, get_services
|
||||
from open_webui.utils.tether import (
|
||||
CHUNK,
|
||||
WINDOW,
|
||||
Connection,
|
||||
hub,
|
||||
decode,
|
||||
get_connections,
|
||||
get_max_concurrent_streams,
|
||||
get_services,
|
||||
)
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
async def changed(user_id):
|
||||
"""A device connected, left or changed what it offers: drop cached models and tell open pages."""
|
||||
from open_webui.routers.openai import get_tether_models
|
||||
from open_webui.socket.main import emit_to_users
|
||||
|
||||
await get_tether_models.cache.clear()
|
||||
await emit_to_users('events', {'data': {'type': 'terminals:changed'}}, [user_id])
|
||||
|
||||
|
||||
@router.websocket('/connect')
|
||||
async def connect(ws: WebSocket):
|
||||
await ws.accept()
|
||||
@@ -27,6 +44,11 @@ async def connect(ws: WebSocket):
|
||||
if type(window) is not int or window < CHUNK:
|
||||
raise ValueError('Invalid relay window')
|
||||
window = min(window, WINDOW)
|
||||
max_concurrent_streams = get_max_concurrent_streams(hello, window)
|
||||
# Version 1 predates service lists and only offered a terminal.
|
||||
services = get_services(hello.get('services', ['open_terminal'] if hello['version'] == 1 else None))
|
||||
notifications = hello.get('notifications') is True
|
||||
connections = get_connections(hello.get('connections'))
|
||||
token = hello.get('token', '')
|
||||
user = await get_verified_user_by_token(token, getattr(ws.app.state, 'redis', None))
|
||||
claims = decode_token(token)
|
||||
@@ -39,43 +61,36 @@ async def connect(ws: WebSocket):
|
||||
name = hello.get('name')
|
||||
if not isinstance(name, str) or not 1 <= len(name.strip()) <= 100:
|
||||
raise ValueError('A connection name of 1–100 characters is required')
|
||||
name = name.strip()
|
||||
await hub.start()
|
||||
presence = {
|
||||
'connection': str(uuid4()),
|
||||
'worker': hub.worker,
|
||||
'session': row.id,
|
||||
'user': user.id,
|
||||
'connection_id': connection_id,
|
||||
'name': name.strip(),
|
||||
'notifications': hello.get('notifications') is True,
|
||||
'window': window,
|
||||
'services': get_services(hello.get('services', ['open_terminal'] if hello['version'] == 1 else None)),
|
||||
}
|
||||
connection = SimpleNamespace(ws=ws, presence=presence, routes={}, lock=asyncio.Lock(), pending=0)
|
||||
|
||||
async def send(header, data):
|
||||
if connection.pending >= 64:
|
||||
raise ConnectionError('Relay send queue full')
|
||||
connection.pending += 1
|
||||
try:
|
||||
# Lock waiters are FIFO; each stream yields after one chunk.
|
||||
async with connection.lock:
|
||||
await asyncio.wait_for(ws.send_bytes(encode(header, data)), 10)
|
||||
finally:
|
||||
connection.pending -= 1
|
||||
|
||||
connection.send = send
|
||||
presence = dict(
|
||||
connection=str(uuid4()),
|
||||
worker=hub.worker,
|
||||
session=row.id,
|
||||
user=user.id,
|
||||
connection_id=connection_id,
|
||||
name=name,
|
||||
notifications=notifications,
|
||||
window=window,
|
||||
max_concurrent_streams=max_concurrent_streams,
|
||||
services=services,
|
||||
connections=connections,
|
||||
)
|
||||
connection = Connection(ws, presence)
|
||||
key = hub.key(user.id, connection_id)
|
||||
record = json.dumps(presence)
|
||||
# A reconnect replaces the previous connection, including on another worker.
|
||||
for old in list(hub.connections.values()):
|
||||
if old.presence['user'] == user.id and old.presence['connection_id'] == connection_id:
|
||||
await old.ws.close(code=1000)
|
||||
await ws.send_json({'type': 'ready', 'notifications': True, 'window': window})
|
||||
await ws.send_json(
|
||||
{'type': 'ready', 'notifications': True, 'window': window, 'max_concurrent_streams': max_concurrent_streams}
|
||||
)
|
||||
hub.connections[presence['connection']] = connection
|
||||
presence_lock = asyncio.Lock()
|
||||
if hub.redis:
|
||||
await hub.redis.set(key, record, ex=60)
|
||||
await changed(user.id)
|
||||
|
||||
async def watch():
|
||||
while True:
|
||||
@@ -115,11 +130,14 @@ async def connect(ws: WebSocket):
|
||||
update = json.loads(message['text'])
|
||||
if update.get('type') == 'services':
|
||||
services = get_services(update.get('services'))
|
||||
connections = get_connections(update.get('connections'))
|
||||
name = update.get('name', presence['name'])
|
||||
if not isinstance(name, str) or not 1 <= len(name.strip()) <= 100:
|
||||
raise ValueError('A device name of 1–100 characters is required')
|
||||
async with presence_lock:
|
||||
updated_record = json.dumps({**presence, 'services': services, 'name': name.strip()})
|
||||
updated_record = json.dumps(
|
||||
{**presence, 'services': services, 'connections': connections, 'name': name.strip()}
|
||||
)
|
||||
if hub.redis:
|
||||
replaced = await hub.redis.eval(
|
||||
"if redis.call('get', KEYS[1]) == ARGV[1] then redis.call('set', KEYS[1], ARGV[2], 'EX', 60); return 1 else return 0 end",
|
||||
@@ -131,8 +149,10 @@ async def connect(ws: WebSocket):
|
||||
if not replaced:
|
||||
raise ValueError('Tether connection was replaced')
|
||||
presence['services'] = services
|
||||
presence['connections'] = connections
|
||||
presence['name'] = name.strip()
|
||||
record = updated_record
|
||||
await changed(user.id)
|
||||
continue
|
||||
updated = decode_token(update.get('token', ''))
|
||||
current = await get_verified_user_by_token(
|
||||
@@ -156,6 +176,7 @@ async def connect(ws: WebSocket):
|
||||
watcher.cancel()
|
||||
await asyncio.gather(watcher, return_exceptions=True)
|
||||
if connection:
|
||||
await connection.close()
|
||||
hub.connections.pop(connection.presence['connection'], None)
|
||||
if hub.redis:
|
||||
with suppress(Exception):
|
||||
@@ -165,26 +186,11 @@ async def connect(ws: WebSocket):
|
||||
key,
|
||||
record,
|
||||
)
|
||||
for stream_id in list(connection.routes):
|
||||
await changed(connection.presence['user'])
|
||||
for stream_id, worker in list(connection.routes.items()):
|
||||
stream = hub.streams.get(stream_id)
|
||||
if stream:
|
||||
stream.fail('Tether disconnected; operation completion may be unknown')
|
||||
else:
|
||||
worker = connection.routes[stream_id]
|
||||
if hub.redis:
|
||||
# An explicit failure is terminal even if a preceding frame was lost.
|
||||
with suppress(Exception):
|
||||
await hub.redis.publish(
|
||||
hub.channel(worker),
|
||||
encode(
|
||||
{
|
||||
'type': 'error',
|
||||
'stream': stream_id,
|
||||
'sequence': 0,
|
||||
'route': 'stream',
|
||||
'connection': connection.presence['connection'],
|
||||
'message': 'Tether disconnected',
|
||||
},
|
||||
b'',
|
||||
),
|
||||
)
|
||||
stream.fail('Tether disconnected; operation completion may be unknown', disconnected=True)
|
||||
elif hub.redis:
|
||||
# An explicit failure is terminal even if a preceding frame was lost.
|
||||
await hub.reject(worker, connection, stream_id, 'Tether disconnected', disconnected=True)
|
||||
@@ -32,6 +32,7 @@ from open_webui.models.tools import (
|
||||
Tools,
|
||||
ToolUserResponse,
|
||||
)
|
||||
from open_webui.utils.tools import get_tether_tool_servers
|
||||
from open_webui.utils.access_control import (
|
||||
filter_allowed_access_grants,
|
||||
has_connection_access,
|
||||
@@ -42,6 +43,7 @@ from open_webui.utils.auth import get_admin_user, get_verified_user
|
||||
from open_webui.utils.mcp.apps import app_csp, ui_resource_uri, verify_app_binding
|
||||
from open_webui.utils.mcp.client import tool_visible_to
|
||||
from open_webui.utils.misc import is_string_allowed
|
||||
from open_webui.utils.oauth import get_system_oauth_token
|
||||
from open_webui.utils.plugin import (
|
||||
get_tool_contents_cache,
|
||||
get_tool_module_from_cache,
|
||||
@@ -115,6 +117,23 @@ async def get_tools(
|
||||
)
|
||||
)
|
||||
|
||||
# Tool servers that forward the user's SSO token fail once that SSO session is gone.
|
||||
# Only flag them for browsers signed in through SSO, where signing in again fixes it.
|
||||
oauth_session_expired = (
|
||||
ENABLE_TOOL_SERVERS
|
||||
and 'oauth_session_id' in request.cookies
|
||||
and any(
|
||||
connection.get('auth_type') == 'system_oauth' and (connection.get('config') or {}).get('enable')
|
||||
for connection in await Config.get('tool_server.connections', [])
|
||||
)
|
||||
and await get_system_oauth_token(request, user) is None
|
||||
)
|
||||
|
||||
def get_system_oauth_status(auth_type: str) -> dict:
|
||||
if auth_type == 'system_oauth' and oauth_session_expired:
|
||||
return {'authenticated': False, 'auth_type': 'system_oauth'}
|
||||
return {}
|
||||
|
||||
# OpenAPI Tool Servers
|
||||
server_connections = {}
|
||||
for server in await get_tool_servers(request):
|
||||
@@ -150,6 +169,7 @@ async def get_tools(
|
||||
],
|
||||
'updated_at': int(time.time()),
|
||||
'created_at': int(time.time()),
|
||||
**get_system_oauth_status(connection.get('auth_type')),
|
||||
}
|
||||
)
|
||||
)
|
||||
@@ -191,6 +211,7 @@ async def get_tools(
|
||||
if auth_type in ('oauth_2.1', 'oauth_2.1_static')
|
||||
else {}
|
||||
),
|
||||
**get_system_oauth_status(auth_type),
|
||||
}
|
||||
)
|
||||
)
|
||||
@@ -207,6 +228,31 @@ async def get_tools(
|
||||
)
|
||||
]
|
||||
|
||||
# Tool servers the user added in Tether, reached through it.
|
||||
for server in await get_tether_tool_servers(user):
|
||||
tools.append(
|
||||
ToolUserResponse(
|
||||
id=f'server:tether:{server["id"]}',
|
||||
user_id=user.id,
|
||||
name=server['name'],
|
||||
meta={'description': ''},
|
||||
updated_at=int(time.time()),
|
||||
created_at=int(time.time()),
|
||||
)
|
||||
)
|
||||
|
||||
for server in await get_tether_tool_servers(user, 'mcp'):
|
||||
tools.append(
|
||||
ToolUserResponse(
|
||||
id=f'server:mcp:tether:{server["id"]}',
|
||||
user_id=user.id,
|
||||
name=server['name'],
|
||||
meta={'description': ''},
|
||||
updated_at=int(time.time()),
|
||||
created_at=int(time.time()),
|
||||
)
|
||||
)
|
||||
|
||||
if query:
|
||||
q = query.casefold()
|
||||
tools = [tool for tool in tools if q in (tool.name or '').casefold()]
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import io
|
||||
import logging
|
||||
import time
|
||||
from collections import Counter
|
||||
@@ -10,7 +9,7 @@ from datetime import datetime, timedelta
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, Request, status
|
||||
from fastapi.responses import FileResponse, Response, StreamingResponse
|
||||
from fastapi.responses import FileResponse, Response
|
||||
from open_webui.config import DEFAULT_USER_PERMISSIONS
|
||||
from open_webui.constants import ERROR_MESSAGES
|
||||
from open_webui.events import EVENTS, publish_event
|
||||
@@ -130,7 +129,25 @@ async def get_all_users(
|
||||
user=Depends(get_admin_user),
|
||||
db: AsyncSession = Depends(get_async_session),
|
||||
):
|
||||
return await Users.get_users(db=db)
|
||||
result = await Users.get_users(db=db)
|
||||
users = result['users']
|
||||
total = result['total']
|
||||
|
||||
# Look up by group: binding one IN parameter per user breaks past ~32k users
|
||||
groups = await Groups.get_all_groups(db=db)
|
||||
group_user_ids = await Groups.get_group_user_ids_by_ids([group.id for group in groups], db=db)
|
||||
|
||||
groups_by_user = {}
|
||||
for group in groups:
|
||||
for user_id in group_user_ids[group.id]:
|
||||
groups_by_user.setdefault(user_id, []).append({'id': group.id, 'name': group.name})
|
||||
|
||||
return {
|
||||
'users': [
|
||||
UserInfoResponse(**{**user.model_dump(), 'groups': groups_by_user.get(user.id, [])}) for user in users
|
||||
],
|
||||
'total': total,
|
||||
}
|
||||
|
||||
|
||||
@router.get('/search', response_model=UserInfoListResponse)
|
||||
@@ -259,12 +276,13 @@ class FeaturesPermissions(BaseModel):
|
||||
channels: bool = True
|
||||
encrypted_channels: bool = False
|
||||
folders: bool = True
|
||||
direct_tool_servers: bool = False
|
||||
|
||||
web_search: bool = True
|
||||
image_generation: bool = True
|
||||
video_generation: bool = False
|
||||
code_interpreter: bool = True
|
||||
memories: bool = True
|
||||
subagents: bool = True
|
||||
automations: bool = False
|
||||
calendar: bool = True
|
||||
webhooks: bool = False
|
||||
@@ -428,7 +446,7 @@ async def update_default_user_permissions(request: Request, form_data: UserPermi
|
||||
from open_webui.socket.main import sio
|
||||
|
||||
try:
|
||||
await sio.emit('access:updated', {})
|
||||
await sio.emit('events', {'data': {'type': 'access:updated'}})
|
||||
except Exception:
|
||||
log.exception('Unable to refresh default user permissions')
|
||||
await publish_event(
|
||||
@@ -509,18 +527,6 @@ async def update_user_settings_by_session_user(
|
||||
):
|
||||
ui_settings.pop('system', None)
|
||||
|
||||
if (
|
||||
user.role != 'admin'
|
||||
and ui_settings is not None
|
||||
and 'toolServers' in ui_settings
|
||||
and not await has_permission(
|
||||
user.id,
|
||||
'features.direct_tool_servers',
|
||||
await Config.get('user.permissions'),
|
||||
)
|
||||
):
|
||||
ui_settings.pop('toolServers', None)
|
||||
|
||||
ui_notifications = ui_settings.get('notifications') if isinstance(ui_settings, dict) else None
|
||||
if (
|
||||
user.role != 'admin'
|
||||
@@ -843,14 +849,13 @@ async def get_user_profile_image_by_id(user_id: str, user=Depends(get_verified_u
|
||||
try:
|
||||
header, base64_data = user.profile_image_url.split(',', 1)
|
||||
image_data = base64.b64decode(base64_data)
|
||||
image_buffer = io.BytesIO(image_data)
|
||||
media_type = header.split(';')[0].lstrip('data:').lower()
|
||||
|
||||
if media_type not in PROFILE_IMAGE_ALLOWED_MIME_TYPES:
|
||||
return FileResponse(f'{STATIC_DIR}/user.png')
|
||||
|
||||
return StreamingResponse(
|
||||
image_buffer,
|
||||
return Response(
|
||||
content=image_data,
|
||||
media_type=media_type,
|
||||
headers={
|
||||
'Content-Disposition': 'inline',
|
||||
|
||||
@@ -0,0 +1,323 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import time
|
||||
|
||||
import aiohttp
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request
|
||||
from open_webui.config import VIDEO_GENERATION_POLL_INTERVAL, VIDEO_GENERATION_TIMEOUT
|
||||
from open_webui.constants import ERROR_MESSAGES
|
||||
from open_webui.env import AIOHTTP_CLIENT_SESSION_SSL
|
||||
from open_webui.events import EVENTS, publish_event
|
||||
from open_webui.models.config import Config
|
||||
from open_webui.routers.images import (
|
||||
get_image_file_item,
|
||||
load_url_image,
|
||||
raise_for_provider_status,
|
||||
upload_image,
|
||||
)
|
||||
from open_webui.utils.access_control import has_permission
|
||||
from open_webui.utils.auth import get_admin_user, get_verified_user
|
||||
from open_webui.utils.headers import get_headers_and_cookies
|
||||
from open_webui.utils.session_pool import get_session
|
||||
from open_webui.utils.videos.connections import (
|
||||
VIDEO_CONNECTIONS_CONFIG_KEY,
|
||||
VIDEO_GENERATION_DEFAULT_MODEL_CONFIG_KEY,
|
||||
get_video_connection_models,
|
||||
get_video_connection_provider,
|
||||
get_video_models,
|
||||
normalize_video_connection,
|
||||
resolve_video_model,
|
||||
)
|
||||
from pydantic import BaseModel, ConfigDict
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
VIDEO_CONFIG_KEYS = {
|
||||
'ENABLE_VIDEO_GENERATION': 'video_generation.enable',
|
||||
'VIDEO_GENERATION_DEFAULT_MODEL': VIDEO_GENERATION_DEFAULT_MODEL_CONFIG_KEY,
|
||||
'VIDEO_CONNECTIONS': VIDEO_CONNECTIONS_CONFIG_KEY,
|
||||
}
|
||||
|
||||
|
||||
class VideoConnection(BaseModel):
|
||||
id: str | None = None
|
||||
name: str = ''
|
||||
type: str = 'openai'
|
||||
url: str = ''
|
||||
key: str = ''
|
||||
config: dict = {}
|
||||
|
||||
model_config = ConfigDict(extra='allow')
|
||||
|
||||
|
||||
class VideosConfig(BaseModel):
|
||||
ENABLE_VIDEO_GENERATION: bool
|
||||
VIDEO_GENERATION_DEFAULT_MODEL: str = ''
|
||||
VIDEO_CONNECTIONS: list[VideoConnection] = []
|
||||
|
||||
|
||||
async def get_video_config_values() -> dict:
|
||||
values = await Config.get_many(*VIDEO_CONFIG_KEYS.values())
|
||||
return {
|
||||
'ENABLE_VIDEO_GENERATION': bool(values.get('video_generation.enable')),
|
||||
'VIDEO_GENERATION_DEFAULT_MODEL': values.get(VIDEO_GENERATION_DEFAULT_MODEL_CONFIG_KEY) or '',
|
||||
'VIDEO_CONNECTIONS': values.get(VIDEO_CONNECTIONS_CONFIG_KEY) or [],
|
||||
}
|
||||
|
||||
|
||||
@router.get('/config', response_model=VideosConfig)
|
||||
async def get_config(request: Request, user=Depends(get_admin_user)):
|
||||
return await get_video_config_values()
|
||||
|
||||
|
||||
@router.post('/config/update')
|
||||
async def update_config(request: Request, form_data: VideosConfig, user=Depends(get_admin_user)):
|
||||
connections = []
|
||||
try:
|
||||
for connection in form_data.VIDEO_CONNECTIONS:
|
||||
connections.append(normalize_video_connection(connection.model_dump()))
|
||||
except (ValueError, TypeError) as e:
|
||||
raise HTTPException(status_code=400, detail=ERROR_MESSAGES.DEFAULT(e))
|
||||
|
||||
if len({connection['id'] for connection in connections}) != len(connections):
|
||||
raise HTTPException(status_code=400, detail=ERROR_MESSAGES.DEFAULT('Video connection IDs must be unique'))
|
||||
|
||||
await Config.upsert(
|
||||
{
|
||||
'video_generation.enable': form_data.ENABLE_VIDEO_GENERATION,
|
||||
VIDEO_GENERATION_DEFAULT_MODEL_CONFIG_KEY: form_data.VIDEO_GENERATION_DEFAULT_MODEL,
|
||||
VIDEO_CONNECTIONS_CONFIG_KEY: connections,
|
||||
}
|
||||
)
|
||||
|
||||
values = await get_video_config_values()
|
||||
await publish_event(
|
||||
request,
|
||||
EVENTS.CONFIG_UPDATED,
|
||||
actor=user,
|
||||
subject_id='videos',
|
||||
data={
|
||||
'video_generation_enabled': values['ENABLE_VIDEO_GENERATION'],
|
||||
'video_connections': [
|
||||
{'id': connection['id'], 'name': connection['name'], 'type': connection['type']}
|
||||
for connection in connections
|
||||
],
|
||||
},
|
||||
)
|
||||
return values
|
||||
|
||||
|
||||
@router.post('/connections/verify')
|
||||
async def verify_video_connection(request: Request, form_data: VideoConnection, user=Depends(get_admin_user)):
|
||||
"""Reach a connection before saving it and list the models it serves."""
|
||||
try:
|
||||
connection = normalize_video_connection(form_data.model_dump())
|
||||
except (ValueError, TypeError) as e:
|
||||
raise HTTPException(status_code=400, detail=ERROR_MESSAGES.DEFAULT(e))
|
||||
|
||||
if not connection['url']:
|
||||
raise HTTPException(status_code=400, detail=ERROR_MESSAGES.INVALID_URL)
|
||||
|
||||
try:
|
||||
return await get_video_connection_models(request, connection, user)
|
||||
except Exception as e:
|
||||
log.error(
|
||||
f'Failed to verify video connection {connection["url"]}: {str(e) or type(e).__name__}',
|
||||
exc_info=not isinstance(e, (aiohttp.ClientConnectionError, aiohttp.ClientResponseError, TimeoutError)),
|
||||
)
|
||||
error = e.message if isinstance(e, aiohttp.ClientResponseError) else e
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=ERROR_MESSAGES.DEFAULT(error, 'Failed to connect to the video generation server'),
|
||||
)
|
||||
|
||||
|
||||
def public_video_model(model: dict) -> dict:
|
||||
return {key: value for key, value in model.items() if key != 'connection'}
|
||||
|
||||
|
||||
@router.get('/models')
|
||||
async def get_models(request: Request, user=Depends(get_verified_user)):
|
||||
"""Video models this user can pick from."""
|
||||
if not await Config.get('video_generation.enable'):
|
||||
return []
|
||||
|
||||
if user.role != 'admin' and not await has_permission(
|
||||
user.id, 'features.video_generation', await Config.get('user.permissions')
|
||||
):
|
||||
return []
|
||||
|
||||
return [public_video_model(model) for model in await get_video_models(request, user)]
|
||||
|
||||
|
||||
@router.get('/connections/models')
|
||||
async def get_connection_models(request: Request, user=Depends(get_admin_user)):
|
||||
"""Every model the enabled connections offer, whoever may use them, for choosing the default model."""
|
||||
return [public_video_model(model) for model in await get_video_models(request, user, bypass_access=True)]
|
||||
|
||||
|
||||
class CreateVideoForm(BaseModel):
|
||||
model: str | None = None
|
||||
prompt: str
|
||||
seconds: int | None = None
|
||||
size: str | None = None
|
||||
image: str | None = None # starting frame: a data URL, a URL or an Open WebUI file
|
||||
|
||||
|
||||
@router.post('/generations')
|
||||
async def generate_videos(request: Request, form_data: CreateVideoForm, user=Depends(get_verified_user)):
|
||||
if not await Config.get('video_generation.enable'):
|
||||
raise HTTPException(
|
||||
status_code=403,
|
||||
detail=ERROR_MESSAGES.ACCESS_PROHIBITED,
|
||||
)
|
||||
|
||||
if user.role != 'admin' and not await has_permission(
|
||||
user.id, 'features.video_generation', await Config.get('user.permissions')
|
||||
):
|
||||
raise HTTPException(
|
||||
status_code=403,
|
||||
detail=ERROR_MESSAGES.ACCESS_PROHIBITED,
|
||||
)
|
||||
|
||||
result = await video_generations(request, form_data, user=user, strict=True)
|
||||
await publish_event(
|
||||
request,
|
||||
EVENTS.VIDEO_GENERATED,
|
||||
actor=user,
|
||||
subject_id=None,
|
||||
subject_type='video',
|
||||
data={
|
||||
'model': form_data.model,
|
||||
'size': form_data.size,
|
||||
'seconds': form_data.seconds,
|
||||
'prompt_preview': form_data.prompt[:300],
|
||||
},
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
async def video_generations(
|
||||
request: Request,
|
||||
form_data: CreateVideoForm,
|
||||
metadata: dict | None = None,
|
||||
user=None,
|
||||
strict: bool = False,
|
||||
):
|
||||
"""Start a video job, wait for it to finish, and save the finished video as a file.
|
||||
|
||||
Video models take minutes, so the provider runs each request as a job: create it with
|
||||
``POST /videos``, check ``GET /videos/{id}`` until it is done, then download ``/videos/{id}/content``.
|
||||
OpenAI's API (which LiteLLM follows) takes a multipart form; OpenRouter's takes JSON.
|
||||
"""
|
||||
connection, model = await resolve_video_model(request, user, form_data.model, strict=strict)
|
||||
connection_config = connection.get('config') or {}
|
||||
seconds = form_data.seconds or connection_config.get('seconds')
|
||||
size = form_data.size or connection_config.get('size')
|
||||
metadata = metadata or {}
|
||||
|
||||
try:
|
||||
headers, cookies = await get_headers_and_cookies(
|
||||
request, connection['url'], connection['key'], connection_config, metadata, user=user
|
||||
)
|
||||
|
||||
api_version = connection_config.get('api_version')
|
||||
query = f'?api-version={api_version}' if api_version else ''
|
||||
base_url = f'{connection["url"]}/videos'
|
||||
image = await load_url_image(form_data.image, user) if form_data.image else None
|
||||
params = connection_config.get('params') or {}
|
||||
|
||||
if get_video_connection_provider(connection) == 'openrouter':
|
||||
body = {
|
||||
'json': {
|
||||
'model': model,
|
||||
'prompt': form_data.prompt,
|
||||
**({'duration': seconds} if seconds else {}),
|
||||
**({'size': size} if size else {}),
|
||||
**(
|
||||
{
|
||||
'frame_images': [
|
||||
{'type': 'image_url', 'image_url': {'url': image}, 'frame_type': 'first_frame'}
|
||||
]
|
||||
}
|
||||
if image
|
||||
else {}
|
||||
),
|
||||
**params,
|
||||
}
|
||||
}
|
||||
else:
|
||||
# The create request is multipart, so the connection's JSON content type does not apply.
|
||||
headers.pop('Content-Type', None)
|
||||
form = aiohttp.FormData()
|
||||
if model:
|
||||
form.add_field('model', model)
|
||||
form.add_field('prompt', form_data.prompt)
|
||||
if seconds:
|
||||
form.add_field('seconds', str(seconds))
|
||||
if size:
|
||||
form.add_field('size', size)
|
||||
if image:
|
||||
name, (filename, file, content_type) = get_image_file_item(image, 'input_reference')
|
||||
form.add_field(name, file, filename=filename, content_type=content_type)
|
||||
for key, value in params.items():
|
||||
form.add_field(key, value if isinstance(value, str) else str(value))
|
||||
body = {'data': form}
|
||||
|
||||
session = await get_session()
|
||||
async with session.post(
|
||||
url=f'{base_url}{query}', headers=headers, cookies=cookies, ssl=AIOHTTP_CLIENT_SESSION_SSL, **body
|
||||
) as r:
|
||||
await raise_for_provider_status(r)
|
||||
job = await r.json(content_type=None)
|
||||
|
||||
deadline = time.monotonic() + VIDEO_GENERATION_TIMEOUT
|
||||
# Providers name the waiting states differently (queued, pending, in_progress), so wait for the end.
|
||||
while job.get('status') not in ('completed', 'failed'):
|
||||
if time.monotonic() > deadline:
|
||||
raise HTTPException(
|
||||
status_code=400, detail=f'The video was not ready after {VIDEO_GENERATION_TIMEOUT} seconds'
|
||||
)
|
||||
|
||||
await asyncio.sleep(VIDEO_GENERATION_POLL_INTERVAL)
|
||||
async with session.get(
|
||||
url=f'{base_url}/{job["id"]}{query}', headers=headers, cookies=cookies, ssl=AIOHTTP_CLIENT_SESSION_SSL
|
||||
) as r:
|
||||
await raise_for_provider_status(r)
|
||||
job = await r.json(content_type=None)
|
||||
|
||||
if job.get('status') != 'completed':
|
||||
error = job.get('error')
|
||||
message = error.get('message') if isinstance(error, dict) else error
|
||||
raise HTTPException(status_code=400, detail=message or f'The video job {job.get("status")}')
|
||||
|
||||
async with session.get(
|
||||
url=f'{base_url}/{job["id"]}/content{query}',
|
||||
headers=headers,
|
||||
cookies=cookies,
|
||||
ssl=AIOHTTP_CLIENT_SESSION_SSL,
|
||||
) as r:
|
||||
await raise_for_provider_status(r)
|
||||
video_data = await r.read()
|
||||
content_type = r.headers.get('content-type', 'video/mp4').split(';')[0] or 'video/mp4'
|
||||
|
||||
_, video_file = await upload_image(
|
||||
request,
|
||||
video_data,
|
||||
content_type,
|
||||
{'model': model, 'prompt': form_data.prompt, 'video_id': job['id'], **metadata},
|
||||
user,
|
||||
name='generated-video',
|
||||
)
|
||||
return [video_file]
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception as e:
|
||||
log.exception(f'Video generation failed: {e}')
|
||||
error = e.message if isinstance(e, aiohttp.ClientResponseError) else e
|
||||
raise HTTPException(status_code=400, detail=ERROR_MESSAGES.DEFAULT(error))
|
||||
@@ -81,4 +81,13 @@ async def revalidate_comment_subscription(sio, sid, session_user):
|
||||
key: value for key, value in session['comments_resources'].items() if tuple(value) != resource
|
||||
}
|
||||
await sio.save_session(sid, session)
|
||||
await sio.emit('comments:unavailable', {'resource_type': resource[0], 'resource_id': resource[1]}, to=sid)
|
||||
await sio.emit(
|
||||
'events',
|
||||
{
|
||||
'data': {
|
||||
'type': 'comments:unavailable',
|
||||
'data': {'resource_type': resource[0], 'resource_id': resource[1]},
|
||||
}
|
||||
},
|
||||
to=sid,
|
||||
)
|
||||
@@ -156,8 +156,13 @@ class Relay:
|
||||
|
||||
async def invite(self, state, channel):
|
||||
await self.sio.emit(
|
||||
'encryption:available',
|
||||
{'channel': channel, 'session': state['session'] if state else None},
|
||||
'events',
|
||||
{
|
||||
'data': {
|
||||
'type': 'encryption:available',
|
||||
'data': {'channel': channel, 'session': state['session'] if state else None},
|
||||
}
|
||||
},
|
||||
room=f'channel:{channel}',
|
||||
)
|
||||
|
||||
|
||||
@@ -222,11 +222,6 @@ YDOC_MANAGER = YdocManager(
|
||||
redis_key_prefix=f'{REDIS_KEY_PREFIX}:ydoc:documents',
|
||||
)
|
||||
|
||||
REDIS_EVENT_CHANNEL = f'{REDIS_KEY_PREFIX}:direct_completion'
|
||||
|
||||
EVENT_QUEUES: dict[str, asyncio.Queue] = {}
|
||||
EVENT_PUBLISH_LOCK = asyncio.Lock()
|
||||
|
||||
|
||||
def get_session_pool_batches():
|
||||
"""All session pool entries, in bounded batches for the Redis backing."""
|
||||
@@ -304,8 +299,13 @@ async def publish_note_presence(note_id: str):
|
||||
if REDIS is not None and not await lock.owned():
|
||||
return
|
||||
await sio.emit(
|
||||
'note:presence',
|
||||
{'note_id': note_id, 'users': sorted(people.values(), key=lambda person: person['id'])},
|
||||
'events',
|
||||
{
|
||||
'data': {
|
||||
'type': 'note:presence',
|
||||
'data': {'note_id': note_id, 'users': sorted(people.values(), key=lambda person: person['id'])},
|
||||
}
|
||||
},
|
||||
room=f'note:{note_id}',
|
||||
)
|
||||
|
||||
@@ -592,7 +592,7 @@ async def disconnect_sessions_for_users(user_ids: list[str], *, refresh_access:
|
||||
for sid in session_ids:
|
||||
if refresh_access:
|
||||
try:
|
||||
await sio.emit('access:updated', {}, to=sid)
|
||||
await sio.emit('events', {'data': {'type': 'access:updated'}}, to=sid)
|
||||
except Exception:
|
||||
log.exception('Failed to notify session %s about changed access', sid)
|
||||
try:
|
||||
@@ -1159,11 +1159,16 @@ async def document_save_handler(document_id, data, user):
|
||||
)
|
||||
if saved:
|
||||
await sio.emit(
|
||||
'events:note',
|
||||
'events',
|
||||
{
|
||||
'id': note_id,
|
||||
'page': get_page(saved.data, page['id']),
|
||||
'updated_at': saved.updated_at,
|
||||
'data': {
|
||||
'type': 'note:updated',
|
||||
'data': {
|
||||
'id': note_id,
|
||||
'page': get_page(saved.data, page['id']),
|
||||
'updated_at': saved.updated_at,
|
||||
},
|
||||
}
|
||||
},
|
||||
to=f'note:{note_id}',
|
||||
)
|
||||
@@ -1444,65 +1449,6 @@ async def disconnect(sid, reason=None):
|
||||
await remove_document_session(sid)
|
||||
|
||||
|
||||
async def redis_event_listener() -> None:
|
||||
"""Route events received over Redis to their local queues."""
|
||||
reconnect_interval = REDIS_PUBSUB_RECONNECT_INTERVAL
|
||||
|
||||
while True:
|
||||
pubsub = None
|
||||
try:
|
||||
# RedisCluster can't route a pubsub subscribe until initialize() fills its slot cache.
|
||||
await REDIS.initialize()
|
||||
|
||||
pubsub = REDIS.pubsub()
|
||||
await pubsub.subscribe(REDIS_EVENT_CHANNEL)
|
||||
reconnect_interval = REDIS_PUBSUB_RECONNECT_INTERVAL
|
||||
|
||||
async for message in pubsub.listen():
|
||||
if message['type'] != 'message':
|
||||
continue
|
||||
event = JSONCodec.loads(message['data'])
|
||||
queue = EVENT_QUEUES.get(event['channel'])
|
||||
if queue is not None:
|
||||
await queue.put(event['data'])
|
||||
log.warning('Redis event listener stopped. Retrying.')
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
except Exception:
|
||||
log.exception('Redis event listener failed. Retrying.')
|
||||
finally:
|
||||
if pubsub:
|
||||
with suppress(Exception):
|
||||
await pubsub.aclose()
|
||||
|
||||
await asyncio.sleep(reconnect_interval)
|
||||
reconnect_interval = min(reconnect_interval * 2, REDIS_PUBSUB_MAX_RECONNECT_INTERVAL)
|
||||
|
||||
|
||||
@sio.on('*')
|
||||
async def socket_event_handler(event: Any, sid: str, *args: Any) -> None:
|
||||
"""Route user-owned stream events to a local queue or another worker."""
|
||||
if not isinstance(event, str) or event.count(':') != 2 or not args:
|
||||
return
|
||||
|
||||
# The lock keeps arrival order; the sid re-check drops every event after a failed check
|
||||
session_check = asyncio.create_task(get_socket_session_user(sid))
|
||||
async with SOCKET_EVENT_LOCKS.setdefault(('session', sid), asyncio.Lock()):
|
||||
user = await session_check
|
||||
if not user or sid not in LOCAL_AUTHENTICATED_SIDS or user.get('id') != event.split(':', 1)[0]:
|
||||
return
|
||||
|
||||
queue = EVENT_QUEUES.get(event)
|
||||
if queue is not None:
|
||||
await queue.put(args[0])
|
||||
elif WEBSOCKET_MANAGER == 'redis':
|
||||
try:
|
||||
async with EVENT_PUBLISH_LOCK:
|
||||
await REDIS.publish(REDIS_EVENT_CHANNEL, dumps_bytes({'channel': event, 'data': args[0]}))
|
||||
except RedisError as e:
|
||||
log.debug('Failed to relay socket event %s: %s', event, e)
|
||||
|
||||
|
||||
async def _make_channel_emitter(request_info):
|
||||
"""Event emitter that routes pipeline output to a channel message.
|
||||
|
||||
@@ -1645,7 +1591,11 @@ async def get_event_emitter(request_info, update_db=True):
|
||||
pending_approval_ids = await ChatMessages.get_chat_ids_with_pending_approval([chat_id])
|
||||
event_data = {
|
||||
**event_data,
|
||||
'data': {**(event_data.get('data') or {}), 'pending_approval': chat_id in pending_approval_ids},
|
||||
'data': {
|
||||
**(event_data.get('data') or {}),
|
||||
'pending_approval': chat_id in pending_approval_ids,
|
||||
**({'folder_unread_counts': await get_folder_unread_counts(user_id)} if not internal else {}),
|
||||
},
|
||||
}
|
||||
|
||||
room = f'user:{user_id}'
|
||||
@@ -1831,6 +1781,8 @@ async def get_event_call(request_info):
|
||||
|
||||
async def __event_caller__(event_data):
|
||||
session_id = request_info['session_id']
|
||||
chat_id = request_info['chat_id']
|
||||
message_id = request_info['message_id']
|
||||
if is_temporary_chat_id(request_info['chat_id']):
|
||||
owner = await get_temporary_chat(redis, request_info['chat_id'])
|
||||
if owner and owner['user_id'] == request_info['user_id']:
|
||||
@@ -1838,6 +1790,15 @@ async def get_event_call(request_info):
|
||||
if 'session_id' in (event_data.get('data') or {}):
|
||||
event_data = {**event_data, 'data': {**event_data['data'], 'session_id': session_id}}
|
||||
|
||||
if request_info.get('internal') is True and 'session_id' not in (event_data.get('data') or {}):
|
||||
# The page only answers for its open chat.
|
||||
metas = await Chats.get_chat_metas_by_chat_ids([chat_id], include_archived=True)
|
||||
if not metas:
|
||||
return {'error': 'Client session disconnected.'}
|
||||
chat_id, message_id = metas[0]['parent_chat_id'], metas[0]['parent_message_id']
|
||||
if chat_id not in ((SESSION_POOL.get(session_id) or {}).get('chat_ids') or []):
|
||||
session_id = await asyncio.to_thread(get_user_chat_session_id, request_info['user_id'], chat_id)
|
||||
|
||||
# session_id is client-supplied; only the requesting user's own live session may be targeted.
|
||||
session = SESSION_POOL.get(session_id)
|
||||
if session is None or session.get('id') != request_info.get('user_id'):
|
||||
@@ -1877,8 +1838,8 @@ async def get_event_call(request_info):
|
||||
sio.call(
|
||||
'events',
|
||||
{
|
||||
'chat_id': request_info['chat_id'],
|
||||
'message_id': request_info['message_id'],
|
||||
'chat_id': chat_id,
|
||||
'message_id': message_id,
|
||||
'data': event_data,
|
||||
},
|
||||
to=session_id,
|
||||
@@ -1914,7 +1875,7 @@ async def get_event_call(request_info):
|
||||
next_session_id = None
|
||||
else:
|
||||
next_session_id = await asyncio.to_thread(
|
||||
get_user_chat_session_id, request_info['user_id'], request_info['chat_id']
|
||||
get_user_chat_session_id, request_info['user_id'], chat_id
|
||||
)
|
||||
if next_session_id is not None:
|
||||
session_id = request_info['session_id'] = next_session_id
|
||||
@@ -1930,8 +1891,8 @@ async def get_event_call(request_info):
|
||||
await sio.emit(
|
||||
'events',
|
||||
{
|
||||
'chat_id': request_info.get('chat_id'),
|
||||
'message_id': request_info.get('message_id'),
|
||||
'chat_id': chat_id,
|
||||
'message_id': message_id,
|
||||
'data': {'type': 'request:interaction:done', 'data': {'interaction_id': interaction_id}},
|
||||
},
|
||||
to=session_id,
|
||||
|
||||
@@ -37,6 +37,9 @@ from open_webui.routers.images import (
|
||||
image_edits,
|
||||
image_generations,
|
||||
)
|
||||
from open_webui.routers.videos import CreateVideoForm, video_generations
|
||||
from open_webui.utils.images.connections import get_requested_image_model
|
||||
from open_webui.utils.videos.connections import get_requested_video_model
|
||||
from open_webui.routers.memories import (
|
||||
AddMemoryForm,
|
||||
ListMemoryPathsForm,
|
||||
@@ -63,6 +66,7 @@ from open_webui.routers.memories import (
|
||||
)
|
||||
from open_webui.routers.retrieval import search_web as _search_web
|
||||
from open_webui.socket.main import close_changed_note_documents, sio
|
||||
from open_webui.tools.visualizations import render_visualization # noqa: F401 — re-exported
|
||||
from open_webui.tools.knowledge_fs import kb_exec # noqa: F401 — re-exported
|
||||
from open_webui.utils.access_control.files import has_access_to_note_files
|
||||
from open_webui.utils.chat_id import is_saved_chat_id
|
||||
@@ -94,7 +98,7 @@ async def _has_write_access_to_note(note, user_id: str) -> bool:
|
||||
|
||||
|
||||
async def _emit_note_updated(request: Request, user: dict, note) -> None:
|
||||
await sio.emit('events:note', note.model_dump(), to=f'note:{note.id}')
|
||||
await sio.emit('events', {'data': {'type': 'note:updated', 'data': note.model_dump()}}, to=f'note:{note.id}')
|
||||
await publish_event(
|
||||
request,
|
||||
EVENTS.NOTE_UPDATED,
|
||||
@@ -390,7 +394,7 @@ async def generate_image(
|
||||
|
||||
images = await image_generations(
|
||||
request=__request__,
|
||||
form_data=CreateImageForm(prompt=prompt, size=size),
|
||||
form_data=CreateImageForm(prompt=prompt, size=size, model=get_requested_image_model(__metadata__)),
|
||||
metadata=(
|
||||
{'channel_id': __chat_id__.removeprefix('channel:'), 'message_id': __message_id__}
|
||||
if isinstance(__chat_id__, str) and __chat_id__.startswith('channel:')
|
||||
@@ -481,7 +485,9 @@ async def edit_image(
|
||||
resolved_images.append(url)
|
||||
images = await image_edits(
|
||||
request=__request__,
|
||||
form_data=EditImageForm(prompt=prompt, image=resolved_images, size=size),
|
||||
form_data=EditImageForm(
|
||||
prompt=prompt, image=resolved_images, size=size, model=get_requested_image_model(__metadata__)
|
||||
),
|
||||
metadata=(
|
||||
{'channel_id': __chat_id__.removeprefix('channel:'), 'message_id': __message_id__}
|
||||
if isinstance(__chat_id__, str) and __chat_id__.startswith('channel:')
|
||||
@@ -536,6 +542,106 @@ async def edit_image(
|
||||
return JSONCodec.dumps({'error': str(e)})
|
||||
|
||||
|
||||
# Video generation tools
|
||||
|
||||
|
||||
async def generate_video(
|
||||
prompt: str,
|
||||
seconds: Optional[int] = None,
|
||||
size: Optional[str] = None,
|
||||
image_url: Optional[str] = None,
|
||||
__request__: Request = None,
|
||||
__user__: dict = None,
|
||||
__event_emitter__: callable = None,
|
||||
__chat_id__: str = None,
|
||||
__message_id__: str = None,
|
||||
__metadata__: dict = None,
|
||||
__event_call__: callable = None,
|
||||
) -> str:
|
||||
"""
|
||||
Generate a video based on a text prompt.
|
||||
|
||||
:param prompt: A detailed description of the video to generate
|
||||
:param seconds: Optional length in seconds (e.g. 8), supported by the configured video model.
|
||||
Omit to use the configured default.
|
||||
:param size: Optional output size in WIDTHxHEIGHT pixels (e.g. "1280x720"), supported by the configured video model.
|
||||
Omit to use the configured default.
|
||||
:param image_url: Optional image to start the video from, as a URL from the conversation or a terminal path.
|
||||
:return: Video URLs and, when a terminal is selected, terminal_path for display_file or further processing.
|
||||
"""
|
||||
if __request__ is None:
|
||||
return JSONCodec.dumps({'error': 'Request context not available'})
|
||||
|
||||
try:
|
||||
user = UserModel(**__user__) if __user__ else None
|
||||
|
||||
if image_url and image_url.startswith('/') and not image_url.startswith('/api/v1/files/'):
|
||||
data = await get_terminal_file(__request__, user, __metadata__ or {}, image_url, max_bytes=50 * 1024 * 1024)
|
||||
image_url = await asyncio.to_thread(get_image_data_url, data)
|
||||
|
||||
videos = await video_generations(
|
||||
request=__request__,
|
||||
form_data=CreateVideoForm(
|
||||
prompt=prompt,
|
||||
seconds=seconds,
|
||||
size=size,
|
||||
image=image_url,
|
||||
model=get_requested_video_model(__metadata__),
|
||||
),
|
||||
metadata=(
|
||||
{'channel_id': __chat_id__.removeprefix('channel:'), 'message_id': __message_id__}
|
||||
if isinstance(__chat_id__, str) and __chat_id__.startswith('channel:')
|
||||
else None
|
||||
),
|
||||
user=user,
|
||||
)
|
||||
|
||||
await upload_files_to_terminal(
|
||||
__request__, user, videos, __metadata__ or {}, {'__event_call__': __event_call__}
|
||||
)
|
||||
|
||||
# Prepare file entries for the videos
|
||||
video_files = [{'type': 'video', **video} for video in videos]
|
||||
|
||||
# Persist files to DB if chat context is available
|
||||
if is_saved_chat_id(__chat_id__) and __message_id__ and videos:
|
||||
db_files = await Chats.add_message_files_by_id_and_message_id(
|
||||
__chat_id__,
|
||||
__message_id__,
|
||||
video_files,
|
||||
)
|
||||
if db_files is not None:
|
||||
video_files = db_files
|
||||
|
||||
# Emit the videos to the UI if event emitter is available
|
||||
if __event_emitter__ and video_files:
|
||||
await __event_emitter__(
|
||||
{
|
||||
'type': 'chat:message:files',
|
||||
'data': {
|
||||
'files': video_files,
|
||||
},
|
||||
}
|
||||
)
|
||||
# Return a message indicating the video is already displayed
|
||||
return JSONCodec.dumps(
|
||||
{
|
||||
'status': 'success',
|
||||
'message': (
|
||||
'The video is already visible in chat. Use terminal_path with terminal tools or '
|
||||
'display_file when available to continue the requested task.'
|
||||
),
|
||||
'videos': videos,
|
||||
},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
|
||||
return JSONCodec.dumps({'status': 'success', 'videos': videos}, ensure_ascii=False)
|
||||
except Exception as e:
|
||||
log.exception(f'generate_video error: {e}')
|
||||
return JSONCodec.dumps({'error': str(getattr(e, 'detail', None) or e)})
|
||||
|
||||
|
||||
# User input tools
|
||||
|
||||
|
||||
@@ -1630,6 +1736,40 @@ async def replace_note_content(
|
||||
# Chats tools
|
||||
|
||||
|
||||
async def search_users(
|
||||
query: str,
|
||||
count: int = 5,
|
||||
__user__: dict = None,
|
||||
) -> str:
|
||||
"""
|
||||
Search users by name or email, including to resolve @mentions. To mention a user,
|
||||
copy their exact mention token into your reply. Only users with chat access are notified.
|
||||
|
||||
:param query: Name or email to search for
|
||||
:param count: Maximum results to return (default: 5, maximum: 20)
|
||||
:return: JSON list of users with id, name, email, and mention token
|
||||
"""
|
||||
if not __user__ or __user__.get('role') not in {'user', 'admin'}:
|
||||
return JSONCodec.dumps({'error': 'Verified user context required'})
|
||||
|
||||
try:
|
||||
result = await Users.get_users(
|
||||
filter={'query': query, 'roles': ['user', 'admin']},
|
||||
sort={'order_by': 'name', 'direction': 'asc'},
|
||||
limit=max(1, min(count, 20)),
|
||||
)
|
||||
return JSONCodec.dumps(
|
||||
[
|
||||
{'id': user.id, 'name': user.name, 'email': user.email, 'mention': f'<@U:{user.id}>'}
|
||||
for user in result['users']
|
||||
],
|
||||
ensure_ascii=False,
|
||||
)
|
||||
except Exception:
|
||||
log.exception('search_users failed')
|
||||
return JSONCodec.dumps({'error': 'Could not search users'})
|
||||
|
||||
|
||||
async def search_chats(
|
||||
query: str,
|
||||
count: int = 5,
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
"""The visualization tool validates source; only the isolated browser frame executes it."""
|
||||
|
||||
from typing import Literal
|
||||
|
||||
MAX_HTML_BYTES = 256 * 1024
|
||||
|
||||
DEFAULT_VISUALIZATION_PROMPT_TEMPLATE = """\
|
||||
Render an interactive chart, SVG diagram, calculator, or explainer inline in chat.
|
||||
|
||||
Use proactively when a visual helps the user understand or explore the answer,
|
||||
even when they have not explicitly asked for a visualization. Good uses include
|
||||
comparisons, trends, mechanisms, and exploring how inputs change an outcome.
|
||||
Prefer plain text for simple facts or short answers. Put the entire visualization
|
||||
in html; write explanation in normal messages. HTML/SVG previews
|
||||
appear progressively. Scripts run once, after the complete call is accepted.
|
||||
Default to a lean, compact, flat inline design: concise labels, restrained spacing,
|
||||
readable text, and only useful controls. Use regular font weight almost everywhere;
|
||||
use medium (500) sparingly and never heavier weights. Prefer flat layouts to cards.
|
||||
Inherit the default body text size (0.90625rem, matching chat) for normal text
|
||||
and labels; do not shrink body text to make a layout compact.
|
||||
Use rem for CSS typography, spacing, radii, and dimensions; use responsive widths.
|
||||
Prefer 0.25–0.5rem gaps and padding, with 0.75rem only between distinct sections.
|
||||
Keep labels close to controls and trim heading, paragraph, and list margins.
|
||||
Avoid fixed-pixel styling and empty space.
|
||||
The chat displays title above the visual; avoid repeating it in html. Avoid hero
|
||||
headers, introductory copy, decorative gradients/shadows, oversized typography,
|
||||
and nested cards unless requested.
|
||||
Let content determine height; use the chat's scrolling, not internal scroll areas.
|
||||
Emit a fragment: styles first, visible content next, classic inline scripts last.
|
||||
Use addEventListener, not onclick attributes or DOMContentLoaded. No external
|
||||
scripts, imports, fetch, frames, or parent-page access are available.
|
||||
Request libraries=["chartjs"] to get window.Chart (no script URL needed).
|
||||
Wrap each canvas in .chart-container; use responsive:true, maintainAspectRatio:false.
|
||||
Buttons, inputs, tables, and details have built-in styling. Use CSS variables
|
||||
--owui-background, --owui-surface, --owui-text, --owui-muted, --owui-border,
|
||||
--owui-accent. Include accessible labels and responsive layouts; avoid vh heights.
|
||||
window.openwebui.context supplies theme, language, direction, reducedMotion.
|
||||
Listen for openwebui:contextchange for custom canvas theme updates.
|
||||
await openwebui.sendMessage(text) requests a user-confirmed follow-up and returns
|
||||
{sent:boolean}. Never assume access to chat history, credentials, or storage."""
|
||||
|
||||
|
||||
async def render_visualization(
|
||||
title: str,
|
||||
html: str,
|
||||
libraries: list[Literal['chartjs']] | None = None,
|
||||
) -> dict:
|
||||
"""Render an interactive visualization inline in chat.
|
||||
|
||||
:param title: Short accessible title, 1–160 characters.
|
||||
:param html: Self-contained HTML/SVG/CSS/JavaScript fragment, at most 256 KiB UTF-8.
|
||||
:param libraries: Omit or use [] for native HTML/SVG, or ["chartjs"] for charts.
|
||||
"""
|
||||
if not isinstance(title, str) or not 1 <= len(title.strip()) <= 160:
|
||||
return {'error': 'title must contain 1–160 characters'}
|
||||
if not isinstance(html, str) or not html.strip():
|
||||
return {'error': 'html must be a nonempty string'}
|
||||
try:
|
||||
size = len(html.encode('utf-8'))
|
||||
except UnicodeEncodeError:
|
||||
return {'error': 'html must contain valid Unicode'}
|
||||
if size > MAX_HTML_BYTES:
|
||||
return {'error': 'html exceeds the 256 KiB limit'}
|
||||
if libraries is not None and libraries not in ([], ['chartjs']):
|
||||
return {'error': 'libraries must be [] or ["chartjs"]'}
|
||||
return {'status': 'accepted'}
|
||||
@@ -227,6 +227,7 @@ _SHARING_PERMISSION_KEYS = {
|
||||
'channel': (None, 'sharing.public_channels', None),
|
||||
'calendar': (None, 'sharing.public_calendars', None),
|
||||
'shared_chat': (None, 'sharing.public_chats', 'sharing.open_chats'),
|
||||
'terminal': (None, None, None),
|
||||
}
|
||||
|
||||
|
||||
@@ -296,6 +297,8 @@ async def validate_access_grants(
|
||||
) -> list:
|
||||
"""Reject unauthorized sharing changes before replacing any stored grants."""
|
||||
grants = normalize_access_grants(access_grants)
|
||||
if resource_type == 'terminal' and any(grant['permission'] != 'read' for grant in grants):
|
||||
raise HTTPException(400, 'Template access grants must be read-only')
|
||||
allowed = await filter_allowed_access_grants(default_permissions, user_id, user_role, grants, resource_type, db=db)
|
||||
if len(allowed) != len(grants):
|
||||
raise HTTPException(403, 'You do not have permission to share with the requested audience')
|
||||
|
||||
@@ -9,7 +9,7 @@ from open_webui.models.functions import Functions
|
||||
from open_webui.models.users import UserModel
|
||||
from open_webui.socket.main import get_event_call, get_event_emitter
|
||||
from open_webui.utils.middleware import process_tool_result
|
||||
from open_webui.utils.models import check_model_access, get_all_models
|
||||
from open_webui.utils.models import check_model_access, get_all_models, add_tether_model
|
||||
from open_webui.utils.plugin import get_function_module_from_cache
|
||||
|
||||
logging.basicConfig(stream=sys.stdout, level=GLOBAL_LOG_LEVEL)
|
||||
@@ -32,12 +32,7 @@ async def chat_action(request: Request, action_id: str, form_data: dict, user: A
|
||||
if not request.app.state.MODELS:
|
||||
await get_all_models(request, user=user)
|
||||
|
||||
if getattr(request.state, 'direct', False) and hasattr(request.state, 'model'):
|
||||
models = {
|
||||
request.state.model['id']: request.state.model,
|
||||
}
|
||||
else:
|
||||
models = request.app.state.MODELS
|
||||
models = await add_tether_model(request, user, form_data.get('model'))
|
||||
|
||||
data = form_data
|
||||
model_id = data['model']
|
||||
@@ -53,9 +48,8 @@ async def chat_action(request: Request, action_id: str, form_data: dict, user: A
|
||||
if action.type != 'action' or not action.is_active:
|
||||
raise Exception(f'Action not available: {action_id}')
|
||||
|
||||
# Direct connections carry a client-supplied model the caller already owns,
|
||||
# so scope the model-bound checks to server-resolved models.
|
||||
if not getattr(request.state, 'direct', False) and user.role != 'admin':
|
||||
# The checks apply to shared models; the caller's own models are theirs.
|
||||
if model.get('owner_id') != user.id and user.role != 'admin':
|
||||
await check_model_access(user, model)
|
||||
# model['actions'] entries are '<function_id>' or '<function_id>.<sub_id>';
|
||||
# the function id is always the prefix.
|
||||
|
||||
@@ -1 +1,8 @@
|
||||
"""Native coding agent support for Open Terminal environments."""
|
||||
|
||||
|
||||
def reasoning_effort(options):
|
||||
params = options.get('params') or {}
|
||||
params = {**params, **(params.get('custom_params') or {})}
|
||||
value = params.get('reasoningEffort') or params.get('reasoning_effort')
|
||||
return value.strip() if isinstance(value, str) and value.strip() else None
|
||||
@@ -4,6 +4,8 @@ import asyncio
|
||||
import contextlib
|
||||
import json
|
||||
|
||||
from . import reasoning_effort
|
||||
|
||||
|
||||
class Client:
|
||||
def __init__(self, transport, handle):
|
||||
@@ -34,7 +36,7 @@ def answer_value(value):
|
||||
return value
|
||||
|
||||
|
||||
async def elicit(output, params, native):
|
||||
async def elicit(output, params, request):
|
||||
"""Present ACP's flat form schema through the existing ask-user card."""
|
||||
if params.get('mode') != 'form':
|
||||
return {'action': 'decline'}
|
||||
@@ -63,7 +65,7 @@ async def elicit(output, params, native):
|
||||
)
|
||||
if not questions:
|
||||
return {'action': 'decline'}
|
||||
resolution = await output.approve('ask_user', {'questions': questions}, native)
|
||||
resolution = await output.approve('ask_user', {'questions': questions}, request)
|
||||
if resolution['action'] != 'answer' or resolution.get('timed_out'):
|
||||
return {'action': 'decline'}
|
||||
content = {}
|
||||
@@ -92,8 +94,10 @@ async def run(transport, output, prompt, images, options, *, auth_method=None):
|
||||
session_id = None
|
||||
streaming = False
|
||||
tools = {}
|
||||
config_options = []
|
||||
|
||||
async def handle(message):
|
||||
nonlocal config_options
|
||||
method, params = message.get('method'), message.get('params') or {}
|
||||
if params.get('sessionId') and session_id and params['sessionId'] != session_id:
|
||||
if 'id' in message:
|
||||
@@ -118,9 +122,13 @@ async def run(transport, output, prompt, images, options, *, auth_method=None):
|
||||
)
|
||||
return
|
||||
await client.send({'id': message['id'], 'result': result})
|
||||
elif method == 'session/update' and streaming:
|
||||
elif method == 'session/update':
|
||||
update = params.get('update') or {}
|
||||
kind = update.get('sessionUpdate')
|
||||
if kind == 'config_option_update':
|
||||
config_options = update.get('configOptions', [])
|
||||
if not streaming:
|
||||
return
|
||||
if kind in {'agent_message_chunk', 'agent_thought_chunk'}:
|
||||
content = update.get('content') or {}
|
||||
if content.get('type') == 'text':
|
||||
@@ -133,7 +141,7 @@ async def run(transport, output, prompt, images, options, *, auth_method=None):
|
||||
call_id,
|
||||
tool.get('title') or tool.get('kind', 'agent_tool'),
|
||||
tool.get('rawInput') or {},
|
||||
native=tool.copy(),
|
||||
provider_data=tool.copy(),
|
||||
result=tool.get('rawOutput', tool.get('content', [])),
|
||||
done=tool.get('status') in {'completed', 'failed'},
|
||||
)
|
||||
@@ -142,7 +150,7 @@ async def run(transport, output, prompt, images, options, *, auth_method=None):
|
||||
'agent_plan',
|
||||
'Plan',
|
||||
{'entries': update.get('entries', [])},
|
||||
native=update,
|
||||
provider_data=update,
|
||||
result=update.get('entries', []),
|
||||
done=True,
|
||||
)
|
||||
@@ -182,23 +190,39 @@ async def run(transport, output, prompt, images, options, *, auth_method=None):
|
||||
if capabilities.get('loadSession') or 'resume' in capabilities.get('sessionCapabilities', {}):
|
||||
output.state['session_id'] = session_id
|
||||
await output.flush(force=True)
|
||||
config_options = session.get('configOptions', config_options)
|
||||
config = next(
|
||||
(c for c in session.get('configOptions', []) if c.get('category') == 'model' or c.get('id') == 'model'),
|
||||
(c for c in config_options if c.get('category') == 'model' or c.get('id') == 'model'),
|
||||
None,
|
||||
)
|
||||
if not config and not session.get('models') and options.get('resume_state', {}).get('model_config'):
|
||||
config = {'id': options['resume_state']['model_config']}
|
||||
if config:
|
||||
output.state['model_config'] = config['id']
|
||||
await client.request(
|
||||
configured = await client.request(
|
||||
'session/set_config_option',
|
||||
{'sessionId': session_id, 'configId': config['id'], 'value': options['model']},
|
||||
)
|
||||
config_options = configured.get('configOptions', config_options)
|
||||
elif session.get('models') or options.get('resume'):
|
||||
await client.request('session/set_model', {'sessionId': session_id, 'modelId': options['model']})
|
||||
else:
|
||||
raise ValueError('Agent did not advertise model selection for this session')
|
||||
await output.flush(force=True)
|
||||
effort = reasoning_effort(options)
|
||||
if effort is not None:
|
||||
config = next((c for c in config_options if c.get('category') == 'thought_level'), None)
|
||||
values = [
|
||||
value['value']
|
||||
for group in (config or {}).get('options', [])
|
||||
for value in (group['options'] if 'group' in group else [group])
|
||||
]
|
||||
if not config or effort not in values:
|
||||
raise ValueError('Agent does not support the selected reasoning effort for this model')
|
||||
await client.request(
|
||||
'session/set_config_option',
|
||||
{'sessionId': session_id, 'configId': config['id'], 'value': effort},
|
||||
)
|
||||
await output.flush(force=True, persist=True)
|
||||
if images and not capabilities.get('promptCapabilities', {}).get('image'):
|
||||
raise ValueError('This agent does not support image prompts')
|
||||
content = []
|
||||
|
||||
@@ -5,23 +5,33 @@ import contextlib
|
||||
import json
|
||||
from uuid import uuid4
|
||||
|
||||
from . import reasoning_effort
|
||||
|
||||
|
||||
async def run(transport, output, prompt, images, options):
|
||||
async def send(message):
|
||||
await transport.write(json.dumps(message) + '\n')
|
||||
|
||||
initialize_id = uuid4().hex
|
||||
await send({'type': 'control_request', 'request_id': initialize_id, 'request': {'subtype': 'initialize'}})
|
||||
messages = transport.read_messages()
|
||||
async with asyncio.timeout(60):
|
||||
async for message in messages:
|
||||
if (
|
||||
message.get('type') == 'control_response'
|
||||
and message.get('response', {}).get('request_id') == initialize_id
|
||||
):
|
||||
if message['response'].get('subtype') == 'error':
|
||||
raise ValueError(message['response'].get('error', 'Claude initialization failed'))
|
||||
break
|
||||
|
||||
async def request(control):
|
||||
request_id = uuid4().hex
|
||||
await send({'type': 'control_request', 'request_id': request_id, 'request': control})
|
||||
async with asyncio.timeout(60):
|
||||
async for message in messages:
|
||||
if (
|
||||
message.get('type') == 'control_response'
|
||||
and message.get('response', {}).get('request_id') == request_id
|
||||
):
|
||||
if message['response'].get('subtype') == 'error':
|
||||
raise ValueError(message['response'].get('error', 'Claude request failed'))
|
||||
return
|
||||
raise ValueError('Claude ended before replying')
|
||||
|
||||
await request({'subtype': 'initialize'})
|
||||
effort = reasoning_effort(options)
|
||||
if effort is not None:
|
||||
await request({'subtype': 'apply_flag_settings', 'settings': {'effortLevel': effort}})
|
||||
content = [{'type': 'text', 'text': prompt}]
|
||||
for image in images:
|
||||
prefix, data = image.split(',', 1)
|
||||
@@ -42,7 +52,7 @@ async def run(transport, output, prompt, images, options):
|
||||
kind = message.get('type')
|
||||
if kind == 'system' and message.get('subtype') == 'init':
|
||||
output.state['session_id'] = message['session_id']
|
||||
await output.flush(force=True)
|
||||
await output.flush(force=True, persist=True)
|
||||
elif kind == 'control_request':
|
||||
request = message['request']
|
||||
if request.get('subtype') != 'can_use_tool':
|
||||
@@ -97,13 +107,16 @@ async def run(transport, output, prompt, images, options):
|
||||
streamed_thinking = True
|
||||
await output.text(delta.get('thinking', ''), reasoning=True)
|
||||
elif kind == 'assistant':
|
||||
if message.get('uuid') and not message.get('parent_tool_use_id'):
|
||||
# Later regenerations and edits resume the conversation at this turn's last reply.
|
||||
output.state['turn'] = message['uuid']
|
||||
for block in message.get('message', {}).get('content', []):
|
||||
if block['type'] == 'text' and not streamed_text:
|
||||
await output.text(block['text'])
|
||||
elif block['type'] == 'thinking' and not streamed_thinking:
|
||||
await output.text(block['thinking'], reasoning=True)
|
||||
elif block['type'] == 'tool_use':
|
||||
await output.tool(block['id'], block['name'], block['input'], native=block)
|
||||
await output.tool(block['id'], block['name'], block['input'], provider_data=block)
|
||||
elif kind == 'user':
|
||||
blocks = message.get('message', {}).get('content', [])
|
||||
for block in blocks if isinstance(blocks, list) else []:
|
||||
@@ -113,7 +126,8 @@ async def run(transport, output, prompt, images, options):
|
||||
block['tool_use_id'],
|
||||
previous.get('name', 'agent_tool'),
|
||||
json.loads(previous.get('arguments', '{}')),
|
||||
native=block,
|
||||
# The whole event: its tool_use_result has the edit's structuredPatch.
|
||||
provider_data=message,
|
||||
result=block.get('content'),
|
||||
done=True,
|
||||
)
|
||||
|
||||
@@ -73,14 +73,24 @@ async def run(transport, output, prompt, images, options):
|
||||
'approvalPolicy': 'untrusted',
|
||||
'sandbox': 'workspace-write',
|
||||
}
|
||||
if options.get('approval_mode') == 'auto':
|
||||
# Codex's own reviewer approves routine actions; only what it escalates reaches the user.
|
||||
params.update(approvalPolicy='on-request', approvalsReviewer='auto_review')
|
||||
if options.get('instructions'):
|
||||
params['developerInstructions'] = options['instructions']
|
||||
if options.get('resume'):
|
||||
params['threadId'] = options['resume']
|
||||
result = await client.request('thread/resume' if options.get('resume') else 'thread/start', params)
|
||||
if options.get('resume') and options.get('fork'):
|
||||
# A regenerated or edited message: copy the thread through the turn it follows.
|
||||
result = await client.request('thread/fork', {**params, 'lastTurnId': options['resume_at']})
|
||||
turns = result['thread'].get('turns') or []
|
||||
if options.get('resume_at') and (not turns or turns[-1].get('id') != options['resume_at']):
|
||||
raise ValueError('Update Codex to regenerate or edit earlier messages in this chat')
|
||||
else:
|
||||
result = await client.request('thread/resume' if options.get('resume') else 'thread/start', params)
|
||||
thread_id = result['thread']['id']
|
||||
output.state['session_id'] = thread_id
|
||||
await output.flush(force=True)
|
||||
await output.flush(force=True, persist=True)
|
||||
turn_options = {}
|
||||
chat_params = options.get('params') or {}
|
||||
chat_params = {**chat_params, **(chat_params.get('custom_params') or {})}
|
||||
@@ -100,6 +110,8 @@ async def run(transport, output, prompt, images, options):
|
||||
},
|
||||
)
|
||||
turn_id = result['turn']['id']
|
||||
# Later regenerations and edits fork the thread through this turn.
|
||||
output.state['turn'] = turn_id
|
||||
while True:
|
||||
event = await client.events.get()
|
||||
if isinstance(event, Exception):
|
||||
@@ -143,7 +155,7 @@ async def run(transport, output, prompt, images, options):
|
||||
item.get('id', params.get('itemId')),
|
||||
item.get('type', 'agent_tool'),
|
||||
item,
|
||||
native=item,
|
||||
provider_data=item,
|
||||
result=item.get('aggregatedOutput', item),
|
||||
done=method == 'item/completed',
|
||||
)
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
"""Models exposed by the selected Open Terminal environment."""
|
||||
|
||||
from urllib.parse import quote, urlencode
|
||||
from urllib.parse import urlencode
|
||||
|
||||
from open_webui.utils.terminals import get_terminal_json
|
||||
from open_webui.utils.agents.session import model_id
|
||||
from open_webui.utils.terminals import MissingTerminalContext, get_terminal_json
|
||||
|
||||
|
||||
def model_controls(model):
|
||||
@@ -13,7 +14,7 @@ def model_controls(model):
|
||||
'Reasoning effort',
|
||||
'supportedReasoningEfforts',
|
||||
'reasoningEffort',
|
||||
'reasoningEffort',
|
||||
'label',
|
||||
'defaultReasoningEffort',
|
||||
),
|
||||
('service_tier', 'Service tier', 'serviceTiers', 'id', 'name', 'defaultServiceTier'),
|
||||
@@ -36,19 +37,22 @@ async def get_models(request, user, metadata, *, provider=None, cwd=None):
|
||||
terminal_id = metadata.get('terminal_id')
|
||||
if not terminal_id:
|
||||
return []
|
||||
if not cwd:
|
||||
directory = await get_terminal_json(request, user, metadata, '/files/cwd')
|
||||
cwd = (directory or {}).get('cwd')
|
||||
params = {'provider': provider} if provider else {}
|
||||
if cwd:
|
||||
params['cwd'] = cwd
|
||||
path = '/agents' + ('?' + urlencode(params) if params else '')
|
||||
catalog = await get_terminal_json(request, user, metadata, path)
|
||||
try:
|
||||
if not cwd:
|
||||
directory = await get_terminal_json(request, user, metadata, '/files/cwd')
|
||||
cwd = (directory or {}).get('cwd')
|
||||
params = {'provider': provider} if provider else {}
|
||||
if cwd:
|
||||
params['cwd'] = cwd
|
||||
path = '/agents' + ('?' + urlencode(params) if params else '')
|
||||
catalog = await get_terminal_json(request, user, metadata, path)
|
||||
except MissingTerminalContext:
|
||||
return []
|
||||
if not catalog or catalog.get('protocol_version') != 1:
|
||||
return []
|
||||
models = [
|
||||
{
|
||||
'id': f'agent:{quote(terminal_id, safe="")}:{agent["id"]}:{quote(model["id"], safe="")}',
|
||||
'id': model_id({'terminal_id': terminal_id, 'provider': agent['id'], 'model': model['id']}),
|
||||
'name': f'{agent["id"]}/{model["id"]}',
|
||||
'owned_by': 'terminal',
|
||||
'object': 'model',
|
||||
@@ -61,6 +65,7 @@ async def get_models(request, user, metadata, *, provider=None, cwd=None):
|
||||
'file_upload': True,
|
||||
'web_search': False,
|
||||
'image_generation': False,
|
||||
'video_generation': False,
|
||||
'code_interpreter': False,
|
||||
'builtin_tools': False,
|
||||
}
|
||||
|
||||
@@ -8,12 +8,16 @@ from uuid import uuid4
|
||||
|
||||
from open_webui.models.chats import Chats
|
||||
from open_webui.socket.main import get_event_emitter
|
||||
from open_webui.tasks import clear_response_stream, save_response_stream
|
||||
from open_webui.utils.auth import create_token
|
||||
from open_webui.utils.misc import sanitize_data_for_db
|
||||
from open_webui.utils.redis import get_redis_client
|
||||
from open_webui.utils.tool_permissions import requires_tool_approval
|
||||
from redis.asyncio import Redis
|
||||
|
||||
|
||||
class Output:
|
||||
"""Use WebUI's persisted output cards; provider runners retain native item data."""
|
||||
"""Use WebUI's persisted output cards; each item keeps the provider's own event in provider_data."""
|
||||
|
||||
def __init__(self, metadata, user, check_connection, form_data):
|
||||
self.metadata, self.user = metadata, user
|
||||
@@ -26,19 +30,16 @@ class Output:
|
||||
self.emitter = None
|
||||
self.last_flush = 0
|
||||
self.last_save = 0
|
||||
self.save_task = None
|
||||
self.redis: Redis | None = get_redis_client(async_mode=True)
|
||||
self.lock = asyncio.Lock()
|
||||
|
||||
async def flush(self, done=False, force=False, persist=False):
|
||||
if self.save_task and self.save_task.done():
|
||||
self.save_task.result()
|
||||
if not force and not done and time.monotonic() - self.last_flush < 0.05:
|
||||
return
|
||||
if persist or done:
|
||||
# Approval cards must exist in the DB before users can answer them.
|
||||
if self.save_task:
|
||||
await asyncio.shield(self.save_task)
|
||||
await self.save(done=done)
|
||||
await clear_response_stream(self.redis, self.metadata.get('task_id'))
|
||||
if self.emitter is None:
|
||||
self.emitter = await get_event_emitter(self.metadata, update_db=False)
|
||||
await self.emitter(
|
||||
@@ -54,8 +55,14 @@ class Output:
|
||||
)
|
||||
self.last_flush = time.monotonic()
|
||||
if not (persist or done) and time.monotonic() - self.last_save >= 1:
|
||||
if self.save_task is None or self.save_task.done():
|
||||
self.save_task = asyncio.create_task(self.save())
|
||||
await save_response_stream(
|
||||
self.redis,
|
||||
self.metadata.get('task_id'),
|
||||
self.metadata['chat_id'],
|
||||
self.metadata['message_id'],
|
||||
sanitize_data_for_db(self.items),
|
||||
)
|
||||
self.last_save = time.monotonic()
|
||||
|
||||
async def save(self, done=False):
|
||||
async with self.lock:
|
||||
@@ -75,8 +82,9 @@ class Output:
|
||||
if self.usage is not None:
|
||||
message['usage'] = self.usage
|
||||
meta = dict(message.get('meta') or {})
|
||||
meta['model_name'] = f'{self.state["provider"]}/{self.state["model"]}'
|
||||
meta['agent'] = create_token(
|
||||
{'purpose': 'terminal-agent', 'user': self.user.id, 'chat': self.metadata['chat_id'], **self.state}
|
||||
{'typ': 'agent_session', 'user': self.user.id, 'chat': self.metadata['chat_id'], **self.state}
|
||||
)
|
||||
if done:
|
||||
meta['response_ended_at'] = time.time()
|
||||
@@ -102,13 +110,16 @@ class Output:
|
||||
self.content += text
|
||||
await self.flush()
|
||||
|
||||
async def tool(self, call_id, name, arguments, native=None, result=None, done=False):
|
||||
async def tool(self, call_id, name, arguments, provider_data=None, result=None, done=False):
|
||||
item = next((i for i in self.items if i.get('call_id') == call_id and i['type'] == 'function_call'), None)
|
||||
if item is None:
|
||||
item = {'type': 'function_call', 'id': call_id, 'call_id': call_id}
|
||||
self.items.append(item)
|
||||
item.update(
|
||||
name=name, arguments=json.dumps(arguments), status='completed' if done else 'in_progress', native=native
|
||||
name=name,
|
||||
arguments=json.dumps(arguments),
|
||||
status='completed' if done else 'in_progress',
|
||||
provider_data=provider_data,
|
||||
)
|
||||
if done:
|
||||
self.items[:] = [
|
||||
@@ -127,7 +138,7 @@ class Output:
|
||||
)
|
||||
await self.flush(force=True)
|
||||
|
||||
async def approve(self, name, arguments, native, timeout=None):
|
||||
async def approve(self, name, arguments, provider_data, timeout=None):
|
||||
call_id = f'approval_{uuid4().hex}'
|
||||
item = {
|
||||
'type': 'function_call',
|
||||
@@ -136,7 +147,7 @@ class Output:
|
||||
'name': name,
|
||||
'arguments': json.dumps(arguments),
|
||||
'status': 'pending',
|
||||
'native': native,
|
||||
'provider_data': provider_data,
|
||||
}
|
||||
resolution = None
|
||||
# Questions need an answer even when tool execution has Full access.
|
||||
@@ -156,6 +167,7 @@ class Output:
|
||||
):
|
||||
resolution = {'action': 'approve'}
|
||||
self.items.append(item)
|
||||
pending = resolution is None
|
||||
if resolution is None:
|
||||
await self.flush(force=True, persist=True)
|
||||
deadline = time.monotonic() + timeout if timeout is not None else None
|
||||
@@ -184,6 +196,6 @@ class Output:
|
||||
'status': 'completed',
|
||||
}
|
||||
)
|
||||
await self.flush(force=True, persist=True)
|
||||
await self.flush(force=True, persist=pending)
|
||||
return resolution
|
||||
await asyncio.sleep(0.5)
|
||||
@@ -5,6 +5,8 @@ import contextlib
|
||||
import json
|
||||
from uuid import uuid4
|
||||
|
||||
from . import reasoning_effort
|
||||
|
||||
|
||||
async def run(transport, output, prompt, images, options):
|
||||
messages = transport.read_messages()
|
||||
@@ -92,7 +94,7 @@ async def run(transport, output, prompt, images, options):
|
||||
call_id,
|
||||
tool.get('toolName', 'agent_tool'),
|
||||
tool.get('args', {}),
|
||||
native=tool.copy(),
|
||||
provider_data=tool.copy(),
|
||||
result=tool.get('result', tool.get('partialResult')),
|
||||
done=kind == 'tool_execution_end',
|
||||
)
|
||||
@@ -118,11 +120,14 @@ async def run(transport, output, prompt, images, options):
|
||||
if not separator or not model:
|
||||
raise ValueError('Pi models must include their provider')
|
||||
await request('set_model', {'provider': provider, 'modelId': model})
|
||||
effort = reasoning_effort(options)
|
||||
if effort is not None:
|
||||
await request('set_thinking_level', {'level': effort})
|
||||
state = await request('get_state')
|
||||
output.state['session_id'] = state['sessionId']
|
||||
if options.get('resume') and state['sessionId'] != options['resume']:
|
||||
raise ValueError('Pi resumed a different conversation')
|
||||
await output.flush(force=True)
|
||||
await output.flush(force=True, persist=True)
|
||||
content = []
|
||||
for image in images:
|
||||
prefix, data = image.split(',', 1)
|
||||
|
||||
@@ -3,10 +3,12 @@
|
||||
import copy
|
||||
|
||||
from open_webui.models.chats import Chats
|
||||
from open_webui.utils.auth import decode_token
|
||||
from open_webui.utils.chat_id import is_saved_chat_id
|
||||
from open_webui.utils.middleware import convert_url_images_to_base64
|
||||
from open_webui.utils.misc import get_message_list
|
||||
from open_webui.utils.terminals import get_terminal_json, upload_files_to_terminal
|
||||
|
||||
from .session import get_resume_point
|
||||
from .output import Output
|
||||
from .transport import TerminalTransport
|
||||
from . import acp, codex, claude_code, pi
|
||||
@@ -20,38 +22,70 @@ PROVIDERS = {
|
||||
'cline': acp.run,
|
||||
'gemini': acp.run,
|
||||
'pi': pi.run,
|
||||
'hermes': acp.run,
|
||||
'antigravity': acp.run,
|
||||
'copilot': acp.run,
|
||||
'goose': acp.run,
|
||||
'qwen': acp.run,
|
||||
}
|
||||
|
||||
|
||||
# Providers that can continue their native conversation from an earlier turn.
|
||||
RESUMABLE_AT = {'codex', 'claude-code'}
|
||||
|
||||
|
||||
def provider_runner(provider):
|
||||
# Agents configured in Open Terminal's OPEN_TERMINAL_ACP_AGENTS arrive as `acp-<id>`.
|
||||
return PROVIDERS.get(provider) or (acp.run if provider.startswith('acp-') else None)
|
||||
|
||||
|
||||
async def run(request, form_data, user, metadata, model):
|
||||
if not is_saved_chat_id(metadata.get('chat_id')):
|
||||
raise ValueError('Agent conversations require a saved chat')
|
||||
if metadata.get('regeneration_message_id') or metadata.get('assistant_message_id'):
|
||||
if metadata.get('assistant_message_id'):
|
||||
raise ValueError('Continue an agent conversation with a new message')
|
||||
agent = model['agent']
|
||||
if agent['provider'] not in PROVIDERS:
|
||||
run_provider = provider_runner(agent['provider'])
|
||||
if run_provider is None:
|
||||
raise ValueError('Unsupported terminal agent')
|
||||
chat = await Chats.get_accessible_chat_by_id(metadata['chat_id'], user, permission='write')
|
||||
if chat is None:
|
||||
raise ValueError('Chat reply access denied')
|
||||
parent = (metadata.get('user_message') or {}).get('parentId')
|
||||
previous, branched, copied = (
|
||||
await get_resume_point(chat, parent, user.id, exclude=metadata.get('message_id'))
|
||||
if parent
|
||||
else (None, False, False)
|
||||
)
|
||||
if previous and any(previous.get(key) != agent[key] for key in ('terminal_id', 'provider')):
|
||||
previous = None
|
||||
# Regenerated and edited messages branch off a reply whose native conversation went on without them;
|
||||
# a forked chat's first reply continues the conversation of the chat it was forked from.
|
||||
resume_at = None
|
||||
fork = False
|
||||
if previous and (branched or copied):
|
||||
if agent['provider'] in RESUMABLE_AT and (previous.get('turn') or not branched):
|
||||
resume_at = previous.get('turn') if branched or agent['provider'] == 'codex' else None
|
||||
# Codex copies the thread through that turn, keeping the original for the other branch. Claude
|
||||
# branches inside its own transcript, as T3 Code does, but copies it for a forked chat so the two
|
||||
# chats never write to one conversation.
|
||||
fork = agent['provider'] == 'codex' or copied
|
||||
else:
|
||||
# The agent can't continue from an earlier turn: start a new conversation from the transcript.
|
||||
previous = {key: value for key, value in previous.items() if key != 'session_id'}
|
||||
metadata['terminal_id'] = agent['terminal_id']
|
||||
transport = await TerminalTransport.resolve(request, user, metadata)
|
||||
output = Output(metadata, user, transport.raise_if_failed, form_data)
|
||||
output.state = {**agent}
|
||||
previous = None
|
||||
parent = (metadata.get('user_message') or {}).get('parentId')
|
||||
if parent:
|
||||
previous_message = await Chats.get_message_by_id_and_message_id(metadata['chat_id'], parent)
|
||||
token = ((previous_message or {}).get('meta') or {}).get('agent')
|
||||
previous = decode_token(token) if isinstance(token, str) else None
|
||||
if previous and not (
|
||||
previous.get('purpose') == 'terminal-agent'
|
||||
and previous.get('user') == user.id
|
||||
and previous.get('chat') == metadata['chat_id']
|
||||
and all(previous.get(k) == v for k, v in agent.items())
|
||||
):
|
||||
previous = None
|
||||
if previous and any(
|
||||
child != metadata.get('user_message_id') for child in (previous_message or {}).get('childrenIds', [])
|
||||
):
|
||||
raise ValueError('Agent history cannot be branched in place. Start a new chat instead.')
|
||||
output.state = {
|
||||
# A fork is a new native conversation, which records its own id once the agent reports it.
|
||||
**{
|
||||
key: previous[key]
|
||||
for key in ('model_config', *(() if fork else ('session_id',)))
|
||||
if previous and key in previous
|
||||
},
|
||||
**agent,
|
||||
'instance_user_id': (previous or {}).get('instance_user_id') or (previous or {}).get('user') or user.id,
|
||||
}
|
||||
# Browsing files must not move an existing agent conversation's workspace.
|
||||
cwd = (previous or {}).get('cwd') or metadata.get('initial_terminal_cwd')
|
||||
if not cwd:
|
||||
@@ -83,11 +117,26 @@ async def run(request, form_data, user, metadata, model):
|
||||
|
||||
prompt = text(user_message.get('content', ''))
|
||||
if not previous or not previous.get('session_id'):
|
||||
history = [m for m in messages if m.get('role') in {'user', 'assistant'}]
|
||||
# A new native conversation starts from this branch's transcript. Saved chats send only
|
||||
# the system prompt, so the branch is read from the stored messages.
|
||||
stored = get_message_list(await Chats.get_messages_map_by_chat_id(chat.id) or {}, parent) if parent else []
|
||||
history = [m for m in stored or messages if m.get('role') in {'user', 'assistant'}]
|
||||
if stored:
|
||||
history.append(user_message)
|
||||
elif metadata.get('regeneration_message_id') and history and history[-1].get('role') == 'assistant':
|
||||
history = history[:-1] # Guided regeneration sends the reply being revised; it's quoted below.
|
||||
if len(history) > 1:
|
||||
prompt = '\n\n'.join(f'{m["role"]}: {text(m.get("content", ""))}' for m in history)
|
||||
if metadata.get('regeneration_message_id') and form_data.get('regeneration_prompt'):
|
||||
# Guided regeneration: the agent revises a reply its branched conversation no longer holds.
|
||||
regenerated = await Chats.get_message_by_id_and_message_id(chat.id, metadata['regeneration_message_id'])
|
||||
earlier = text((regenerated or {}).get('content', ''))
|
||||
if earlier:
|
||||
prompt += f'\n\nYour previous reply to this was:\n<previous_reply>\n{earlier}\n</previous_reply>'
|
||||
prompt += f'\n\n{form_data["regeneration_prompt"]}'
|
||||
if paths:
|
||||
prompt += '\n\nAttached files in this environment:\n' + '\n'.join(paths)
|
||||
await convert_url_images_to_base64(form_data, user=user)
|
||||
images = [
|
||||
p['image_url']['url']
|
||||
for m in [user_message, *messages[-1:]]
|
||||
@@ -101,13 +150,24 @@ async def run(request, form_data, user, metadata, model):
|
||||
'cwd': cwd,
|
||||
'model': agent['model'],
|
||||
'resume': (previous or {}).get('session_id'),
|
||||
'resume_at': resume_at,
|
||||
'fork': fork,
|
||||
'instructions': instructions,
|
||||
# The chat's tool permission mode; agents with their own auto review use it for Auto.
|
||||
'approval_mode': (metadata.get('params') or {}).get('tool_approval_mode', 'full'),
|
||||
}
|
||||
succeeded = False
|
||||
try:
|
||||
await transport.start(agent['provider'], options)
|
||||
session = await transport.start(agent['provider'], options)
|
||||
if (
|
||||
agent['provider'] == 'claude-code'
|
||||
and (resume_at or fork)
|
||||
and (session.get('resume_at') != resume_at or bool(session.get('fork')) != fork)
|
||||
):
|
||||
# An older Open Terminal would resume the latest turn of the original conversation instead.
|
||||
raise ValueError('Update Open Terminal to regenerate or edit earlier messages in this chat')
|
||||
extra = {'auth_method': 'cursor_login'} if agent['provider'] == 'cursor' else {}
|
||||
await PROVIDERS[agent['provider']](
|
||||
await run_provider(
|
||||
transport,
|
||||
output,
|
||||
prompt,
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
"""Read native conversation state from signed, server-persisted chat messages."""
|
||||
|
||||
import hashlib
|
||||
import re
|
||||
from urllib.parse import quote
|
||||
|
||||
from open_webui.models.chats import ChatModel, Chats
|
||||
from open_webui.utils.auth import decode_token
|
||||
|
||||
|
||||
def model_id(state):
|
||||
model = re.sub(r'[^a-zA-Z0-9_-]+', '-', state['model']).strip('-')
|
||||
if model != state['model']:
|
||||
# Keeps CLI model names apart that only differ in the replaced characters.
|
||||
model = f'{model}-{hashlib.sha256(state["model"].encode()).hexdigest()[:8]}'
|
||||
return f'agent:{quote(state["terminal_id"], safe="")}:{state["provider"]}:{model}'
|
||||
|
||||
|
||||
async def ensure_chat_selections(chat):
|
||||
if all(key in (chat.chat or {}) for key in ('models', 'terminal_id', 'working_directory')):
|
||||
return chat
|
||||
state = await get_session(chat)
|
||||
if not state:
|
||||
return chat
|
||||
async with Chats._chat_transaction(chat.id) as (_, row):
|
||||
if row is None:
|
||||
return chat
|
||||
# Check missing fields under the lock so concurrent selection changes win.
|
||||
data = dict(row.chat or {})
|
||||
data.setdefault('models', [model_id(state)])
|
||||
data.setdefault('terminal_id', state['terminal_id'])
|
||||
if data['terminal_id'] == state['terminal_id']:
|
||||
data.setdefault('working_directory', state['cwd'])
|
||||
row.chat = data
|
||||
chat = ChatModel.model_validate(row)
|
||||
return chat
|
||||
|
||||
|
||||
def _state(message):
|
||||
token = (message.get('meta') or {}).get('agent')
|
||||
state = decode_token(token) if isinstance(token, str) else None
|
||||
return state if state and state.get('typ') == 'agent_session' else None
|
||||
|
||||
|
||||
def _find(chat, messages, message_id, user_id=None):
|
||||
"""The nearest saved native conversation above `message_id`.
|
||||
|
||||
A fork or clone copies its source's messages, and their conversations belong to that chat. With `user_id`,
|
||||
those owned by this user are returned for the fork to copy; otherwise the copied messages end the search.
|
||||
"""
|
||||
visited = set()
|
||||
while message_id and message_id not in visited:
|
||||
visited.add(message_id)
|
||||
message = messages.get(message_id)
|
||||
if not message:
|
||||
return None, None
|
||||
state = _state(message)
|
||||
if state:
|
||||
if state.get('chat') != chat.id and (
|
||||
not user_id or (state.get('instance_user_id') or state.get('user')) != user_id
|
||||
):
|
||||
return None, None
|
||||
if all(
|
||||
isinstance(state.get(key), str) and state[key]
|
||||
for key in ('terminal_id', 'provider', 'model', 'cwd', 'user')
|
||||
):
|
||||
return state, message_id
|
||||
message_id = message.get('parentId')
|
||||
return None, None
|
||||
|
||||
|
||||
async def get_session(chat, message_id=None):
|
||||
message_id = (
|
||||
message_id or getattr(chat, 'current_message_id', None) or (chat.chat or {}).get('history', {}).get('currentId')
|
||||
)
|
||||
if not message_id:
|
||||
return None
|
||||
messages = await Chats.get_messages_map_by_chat_id(chat.id) or {}
|
||||
return _find(chat, messages, message_id)[0]
|
||||
|
||||
|
||||
async def get_resume_point(chat, message_id, user_id, exclude=None):
|
||||
"""The native conversation to continue from `message_id`, whether later turns were added to it, and
|
||||
whether it belongs to the chat this one was forked or cloned from.
|
||||
|
||||
Regenerating or editing an earlier message reaches a reply whose native conversation already holds
|
||||
the turns that came after it; that conversation then continues from the reply instead of its latest turn.
|
||||
A forked chat continues from a copy, so the two chats never write to the same conversation.
|
||||
"""
|
||||
messages = await Chats.get_messages_map_by_chat_id(chat.id) or {}
|
||||
state, found_id = _find(chat, messages, message_id, user_id)
|
||||
if state is None or not state.get('session_id'):
|
||||
return state, False, False
|
||||
copied = state['chat'] != chat.id
|
||||
if copied:
|
||||
# Its later turns, if any, are in the source chat. A deleted source can't say, so assume there were.
|
||||
messages = await Chats.get_messages_map_by_chat_id(state['chat'])
|
||||
if not messages or found_id not in messages:
|
||||
return state, True, True
|
||||
timestamp = messages[found_id].get('timestamp') or 0
|
||||
for other_id, other in messages.items():
|
||||
if other_id in (found_id, exclude) or (other.get('timestamp') or 0) < timestamp:
|
||||
continue
|
||||
other_state = _state(other)
|
||||
if (
|
||||
other_state
|
||||
and other_state.get('chat') == state['chat']
|
||||
and other_state.get('session_id') == state['session_id']
|
||||
and other_state.get('provider') == state.get('provider')
|
||||
and other_state.get('terminal_id') == state.get('terminal_id')
|
||||
):
|
||||
return state, True, copied
|
||||
return state, False, copied
|
||||
@@ -16,6 +16,7 @@ from open_webui.utils.tether import get_terminal_client
|
||||
class TerminalTransport:
|
||||
def __init__(self, connection, headers, cookies, user_id):
|
||||
self.url = get_terminal_server_url(connection)
|
||||
self.service = connection.get('service', 'open_terminal')
|
||||
self.headers, self.cookies, self.user_id = headers, cookies, user_id
|
||||
self.session_id = None
|
||||
self.socket = None
|
||||
@@ -34,11 +35,11 @@ class TerminalTransport:
|
||||
resolved = await resolve_terminal_connection(request, user, metadata)
|
||||
if not resolved:
|
||||
raise ValueError('Select an accessible server or Tether terminal to use agents')
|
||||
return cls(*resolved, user.id)
|
||||
return cls(*resolved, resolved[0].get('instance_user_id', user.id))
|
||||
|
||||
async def request(self, method, path, body=None):
|
||||
async with get_terminal_client(
|
||||
self.url, self.user_id, timeout=aiohttp.ClientTimeout(total=30), trust_env=True
|
||||
self.url, self.user_id, service=self.service, timeout=aiohttp.ClientTimeout(total=30), trust_env=True
|
||||
) as client:
|
||||
async with client.request(
|
||||
method,
|
||||
@@ -51,7 +52,8 @@ class TerminalTransport:
|
||||
) as response:
|
||||
data = await response.json()
|
||||
if response.status >= 400:
|
||||
raise ValueError(data.get('detail', 'Agent environment request failed'))
|
||||
detail = data.get('detail')
|
||||
raise ValueError(detail if isinstance(detail, str) else 'Agent environment request failed')
|
||||
return data
|
||||
|
||||
async def start(self, provider, options):
|
||||
@@ -76,6 +78,7 @@ class TerminalTransport:
|
||||
async with get_terminal_client(
|
||||
self.url,
|
||||
self.user_id,
|
||||
service=self.service,
|
||||
timeout=aiohttp.ClientTimeout(total=None, connect=30),
|
||||
trust_env=True,
|
||||
cookies=self.cookies,
|
||||
|
||||
@@ -364,7 +364,7 @@ def convert_anthropic_payload_to_chat_completions(
|
||||
if openai_content:
|
||||
msg_dict['content'] = _finalize_chat_completions_content(openai_content)
|
||||
else:
|
||||
msg_dict['content'] = ''
|
||||
msg_dict['content'] = None
|
||||
msg_dict['tool_calls'] = tool_calls
|
||||
messages.append(msg_dict)
|
||||
elif openai_content or role == 'assistant':
|
||||
|
||||
@@ -174,13 +174,13 @@ def _serialize_json(value: Any) -> bytes:
|
||||
return json.dumps(value, separators=(',', ':'), ensure_ascii=False).encode()
|
||||
|
||||
|
||||
def create_app_context_token(app: AppModel, purpose: str, data: dict, expires_in: int = 900) -> str:
|
||||
def create_app_context_token(app: AppModel, typ: str, data: dict, expires_in: int = 900) -> str:
|
||||
payload = base64.urlsafe_b64encode(
|
||||
_serialize_json(
|
||||
{
|
||||
**data,
|
||||
'app_id': app.id,
|
||||
'purpose': purpose,
|
||||
'typ': typ,
|
||||
'exp': int(time.time()) + expires_in,
|
||||
'nonce': str(uuid.uuid4()),
|
||||
}
|
||||
@@ -190,7 +190,7 @@ def create_app_context_token(app: AppModel, purpose: str, data: dict, expires_in
|
||||
return payload + '.' + base64.urlsafe_b64encode(signature).decode()
|
||||
|
||||
|
||||
def decode_app_context_token(app: AppModel, purpose: str, token: str) -> dict:
|
||||
def decode_app_context_token(app: AppModel, typ: str, token: str) -> dict:
|
||||
try:
|
||||
payload, signature = token.split('.')
|
||||
decoded_signature = base64.b64decode(signature, altchars=b'-_', validate=True)
|
||||
@@ -203,7 +203,7 @@ def decode_app_context_token(app: AppModel, purpose: str, token: str) -> dict:
|
||||
if not hmac.compare_digest(decoded_signature, _sign_app_context(app, payload)):
|
||||
raise ValueError('Invalid context signature')
|
||||
data = json.loads(decoded_payload)
|
||||
if data['app_id'] != app.id or data['purpose'] != purpose or data['exp'] <= time.time():
|
||||
if data['app_id'] != app.id or data['typ'] != typ or data['exp'] <= time.time():
|
||||
raise ValueError('Expired context')
|
||||
return data
|
||||
except Exception:
|
||||
@@ -633,7 +633,7 @@ async def verify_app_event(form_data: AppTokenForm, app: AppModel, db: AsyncSess
|
||||
value = decode_app_context_token(app, 'event', form_data.token)
|
||||
await check_app_channel_membership(app, value['channel']['id'], db=db)
|
||||
require_scope(app, 'channels:messages:read')
|
||||
return {k: v for k, v in value.items() if k not in ('purpose', 'exp', 'nonce')}
|
||||
return {k: v for k, v in value.items() if k not in ('typ', 'exp', 'nonce')}
|
||||
|
||||
|
||||
async def get_app_channel_messages(
|
||||
|
||||
@@ -33,6 +33,7 @@ from open_webui.models.automations import AutomationModel, AutomationRuns, Autom
|
||||
from open_webui.models.chats import ChatForm, Chats
|
||||
from open_webui.models.config import Config
|
||||
from open_webui.models.folders import Folders
|
||||
from open_webui.utils.access_control.folders import has_folder_write_access
|
||||
from open_webui.models.messages import MessageForm
|
||||
from open_webui.models.users import Users
|
||||
from open_webui.utils.auth import create_token
|
||||
@@ -184,6 +185,7 @@ async def _resolve_model_defaults(app, model_id: str) -> dict:
|
||||
feature_checks = {
|
||||
'web_search': await Config.get('web.search.enable'),
|
||||
'image_generation': await Config.get('image_generation.enable'),
|
||||
'video_generation': await Config.get('video_generation.enable'),
|
||||
}
|
||||
|
||||
for feature_id in default_feature_ids:
|
||||
@@ -205,10 +207,19 @@ async def validate_automation_terminal(request, user, data: dict, automation_id:
|
||||
if is_agent:
|
||||
raise HTTPException(400, 'Select a terminal for the agent.')
|
||||
return
|
||||
metadata = {
|
||||
'terminal_id': terminal['server_id'],
|
||||
'automation_id': automation_id or f'preview:{user.id}',
|
||||
}
|
||||
if terminal['server_id'].startswith('template:'):
|
||||
from open_webui.utils.terminals import template_connection, require_model_access
|
||||
|
||||
_, template = await template_connection(user, terminal['server_id'])
|
||||
scope = (template.get('data') or {}).get('scope')
|
||||
if (data.get('target') or {}).get('type') == 'channel' and (is_agent or scope == 'chat'):
|
||||
raise HTTPException(400, 'This terminal requires a chat destination.')
|
||||
if scope == 'model':
|
||||
await require_model_access(user, model_id, terminal['server_id'], request)
|
||||
return
|
||||
metadata = {'terminal_id': terminal['server_id'], 'model_id': model_id}
|
||||
if automation_id:
|
||||
metadata['automation_id'] = automation_id
|
||||
if not await resolve_terminal_connection(request, user, metadata):
|
||||
raise HTTPException(400, 'The configured terminal is unavailable for this automation.')
|
||||
if is_agent:
|
||||
@@ -301,7 +312,7 @@ async def _execute_channel_automation(
|
||||
await initialize_terminal_directory(
|
||||
request,
|
||||
user,
|
||||
{'chat_id': form_data['chat_id'], 'automation_id': automation.id},
|
||||
{'chat_id': form_data['chat_id'], 'automation_id': automation.id, 'model_id': model_id},
|
||||
terminal['server_id'],
|
||||
terminal.get('cwd'),
|
||||
)
|
||||
@@ -384,8 +395,9 @@ async def execute_automation(app, automation: AutomationModel) -> None:
|
||||
await _execute_channel_automation(app, automation, user, prompt, model_id, token)
|
||||
return
|
||||
|
||||
# Runs land in the automation's folder while its creator can still write there.
|
||||
folder_id = automation.folder_id
|
||||
if folder_id and not await Folders.get_folder_by_id_and_user_id(folder_id, automation.user_id):
|
||||
if folder_id and not await has_folder_write_access(automation.user_id, folder_id):
|
||||
await Automations.clear_folder_ids(automation.user_id, [folder_id])
|
||||
folder_id = None
|
||||
|
||||
@@ -432,6 +444,7 @@ async def execute_automation(app, automation: AutomationModel) -> None:
|
||||
'meta': {'automation_id': automation.id},
|
||||
},
|
||||
),
|
||||
internal_meta={'automation_id': automation.id},
|
||||
)
|
||||
|
||||
if not chat:
|
||||
@@ -491,7 +504,7 @@ async def execute_automation(app, automation: AutomationModel) -> None:
|
||||
await initialize_terminal_directory(
|
||||
request,
|
||||
user,
|
||||
{'chat_id': chat.id, 'automation_id': automation.id},
|
||||
{'chat_id': chat.id, 'automation_id': automation.id, 'model_id': model_id},
|
||||
terminal['server_id'],
|
||||
terminal.get('cwd'),
|
||||
)
|
||||
|
||||
@@ -2,7 +2,9 @@ from fastapi import HTTPException
|
||||
from open_webui.utils.auth import create_token, decode_token, get_verified_user_by_id
|
||||
|
||||
|
||||
def browser_ticket(server_id, user_id, chat_id, session, headers=None, cookies=None):
|
||||
def create_browser_token(
|
||||
server_id, user_id, instance_user_id, chat_id, session, headers=None, cookies=None, *, resource='browser'
|
||||
):
|
||||
from open_webui.utils.oauth import encrypt_data
|
||||
|
||||
relay = encrypt_data(
|
||||
@@ -13,25 +15,23 @@ def browser_ticket(server_id, user_id, chat_id, session, headers=None, cookies=N
|
||||
)
|
||||
return create_token(
|
||||
{
|
||||
'purpose': 'terminal-browser',
|
||||
'typ': 'browser_view',
|
||||
'server': server_id,
|
||||
'user': user_id,
|
||||
'instance_user': instance_user_id,
|
||||
'chat': chat_id,
|
||||
'session': session['id'],
|
||||
'resource': resource,
|
||||
'model': (headers or {}).get('X-Terminal-Model-Id'),
|
||||
'capability': session['token'],
|
||||
'relay': relay,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
async def browser_access(server_id, sid, ticket):
|
||||
data = decode_token(ticket)
|
||||
if (
|
||||
not data
|
||||
or data.get('purpose') != 'terminal-browser'
|
||||
or data.get('server') != server_id
|
||||
or data.get('session') != sid
|
||||
):
|
||||
async def browser_access(server_id, sid, browser_token):
|
||||
data = decode_token(browser_token)
|
||||
if not data or data.get('typ') != 'browser_view' or data.get('server') != server_id or data.get('session') != sid:
|
||||
raise HTTPException(401, 'Browser session expired')
|
||||
user = await get_verified_user_by_id(data.get('user'))
|
||||
if user is None:
|
||||
|
||||
+114
-238
@@ -1,10 +1,8 @@
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
import random
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
from typing import Any, Optional
|
||||
|
||||
from aiocache import cached
|
||||
@@ -24,7 +22,6 @@ from open_webui.routers.pipelines import (
|
||||
process_pipeline_outlet_filter,
|
||||
)
|
||||
from open_webui.socket.main import (
|
||||
EVENT_QUEUES,
|
||||
get_event_call,
|
||||
get_event_emitter,
|
||||
)
|
||||
@@ -34,7 +31,7 @@ from open_webui.utils.filter import (
|
||||
process_filter_functions,
|
||||
)
|
||||
from open_webui.utils.json_codec import JSONCodec
|
||||
from open_webui.utils.models import check_model_access, get_all_models
|
||||
from open_webui.utils.models import check_model_access, get_all_models, add_tether_model
|
||||
from open_webui.utils.payload import apply_system_prompt_to_body, convert_chat_completions_payload_to_ollama
|
||||
from open_webui.utils.response import (
|
||||
convert_ollama_response_to_chat_completions,
|
||||
@@ -106,105 +103,6 @@ async def register_temporary_chat_session(redis, chat_id, user_id, session_id, s
|
||||
|
||||
# When the question has been asked, let silence not be the
|
||||
# answer. But if the answer must wait, let it come honest.
|
||||
async def generate_direct_chat_completion(
|
||||
request: Request,
|
||||
form_data: dict,
|
||||
user: Any,
|
||||
models: dict,
|
||||
):
|
||||
log.info('generate_direct_chat_completion')
|
||||
|
||||
metadata = form_data.pop('metadata', {})
|
||||
|
||||
user_id = metadata.get('user_id')
|
||||
session_id = metadata.get('session_id')
|
||||
request_id = str(uuid.uuid4()) # Generate a unique request ID
|
||||
|
||||
event_caller = await get_event_call(metadata)
|
||||
if event_caller is None:
|
||||
raise Exception(
|
||||
'Direct connection requires an active WebSocket session; '
|
||||
'cannot generate completion in this context (e.g. background task).'
|
||||
)
|
||||
|
||||
channel = f'{user_id}:{session_id}:{request_id}'
|
||||
logging.info('WebSocket channel: %s', channel)
|
||||
|
||||
if form_data.get('stream'):
|
||||
queue = asyncio.Queue()
|
||||
EVENT_QUEUES[channel] = queue
|
||||
|
||||
# Start processing chat completion in background
|
||||
try:
|
||||
res = await event_caller(
|
||||
{
|
||||
'type': 'request:chat:completion',
|
||||
'data': {
|
||||
'form_data': form_data,
|
||||
'model': models[form_data['model']],
|
||||
'channel': channel,
|
||||
'session_id': session_id,
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
log.info('res: %s', res)
|
||||
|
||||
status = res.get('status', False)
|
||||
except BaseException:
|
||||
EVENT_QUEUES.pop(channel, None)
|
||||
raise
|
||||
|
||||
if status:
|
||||
# Define a generator to stream responses
|
||||
async def event_generator():
|
||||
try:
|
||||
while True:
|
||||
data = await queue.get() # Wait for new messages
|
||||
if isinstance(data, dict):
|
||||
if 'done' in data and data['done']:
|
||||
break # Stop streaming when 'done' is received
|
||||
|
||||
yield f'data: {JSONCodec.dumps(data)}\n\n'
|
||||
elif isinstance(data, str):
|
||||
if 'data:' in data:
|
||||
yield f'{data}\n\n'
|
||||
else:
|
||||
yield f'data: {data}\n\n'
|
||||
except Exception as e:
|
||||
log.debug('Error in event generator: %s', e)
|
||||
pass
|
||||
finally:
|
||||
EVENT_QUEUES.pop(channel, None)
|
||||
|
||||
# Define a background task to run the event generator
|
||||
async def background():
|
||||
EVENT_QUEUES.pop(channel, None)
|
||||
|
||||
# Return the streaming response
|
||||
return StreamingResponse(event_generator(), media_type='text/event-stream', background=background)
|
||||
else:
|
||||
EVENT_QUEUES.pop(channel, None)
|
||||
raise Exception(str(res))
|
||||
else:
|
||||
res = await event_caller(
|
||||
{
|
||||
'type': 'request:chat:completion',
|
||||
'data': {
|
||||
'form_data': form_data,
|
||||
'model': models[form_data['model']],
|
||||
'channel': channel,
|
||||
'session_id': session_id,
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
if 'error' in res and res['error']:
|
||||
raise Exception(res['error'])
|
||||
|
||||
return res
|
||||
|
||||
|
||||
async def generate_chat_completion(
|
||||
request: Request,
|
||||
form_data: dict,
|
||||
@@ -231,146 +129,130 @@ async def generate_chat_completion(
|
||||
**request.state.metadata,
|
||||
}
|
||||
|
||||
if getattr(request.state, 'direct', False) and hasattr(request.state, 'model'):
|
||||
# Merge the direct connection model into server models so that
|
||||
# task functions (title, tags, etc.) can resolve a server-side
|
||||
# task model while still having the direct model available.
|
||||
# dict(...items()) is one HGETALL on a Redis-backed pool; ``{**pool}``
|
||||
# would issue HKEYS plus one HGET per model.
|
||||
models = {
|
||||
**dict(request.app.state.MODELS.items()),
|
||||
request.state.model['id']: request.state.model,
|
||||
}
|
||||
log.debug('direct connection to model: %s', request.state.model['id'])
|
||||
else:
|
||||
models = request.app.state.MODELS
|
||||
|
||||
model_id = form_data['model']
|
||||
models = await add_tether_model(request, user, model_id)
|
||||
# Single lookup — membership check plus getitem would be two Redis
|
||||
# round trips on a Redis-backed model pool.
|
||||
model = models.get(model_id)
|
||||
if model is None:
|
||||
raise Exception('Model not found')
|
||||
|
||||
if getattr(request.state, 'direct', False) and model_id == getattr(request.state, 'model', {}).get('id'):
|
||||
return await generate_direct_chat_completion(request, form_data, user=user, models=models)
|
||||
else:
|
||||
# Check if user has access to the model
|
||||
if not bypass_filter and user.role == 'user':
|
||||
try:
|
||||
await check_model_access(user, model)
|
||||
except Exception as e:
|
||||
raise e
|
||||
# Check if user has access to the model
|
||||
if not bypass_filter and user.role == 'user':
|
||||
try:
|
||||
await check_model_access(user, model)
|
||||
except Exception as e:
|
||||
raise e
|
||||
|
||||
# Arena model — sub-model was already resolved by process_chat_payload.
|
||||
# Inject selected_model_id into the response for the frontend.
|
||||
metadata = form_data.get('metadata', {})
|
||||
selected_model_id = metadata.pop('selected_model_id', None)
|
||||
# Also clear from request.state.metadata to prevent the merge at
|
||||
# lines 177-179 from re-adding it on the recursive call.
|
||||
if hasattr(request.state, 'metadata'):
|
||||
request.state.metadata.pop('selected_model_id', None)
|
||||
# Arena model — sub-model was already resolved by process_chat_payload.
|
||||
# Inject selected_model_id into the response for the frontend.
|
||||
metadata = form_data.get('metadata', {})
|
||||
selected_model_id = metadata.pop('selected_model_id', None)
|
||||
# Also clear from request.state.metadata to prevent the merge at
|
||||
# lines 177-179 from re-adding it on the recursive call.
|
||||
if hasattr(request.state, 'metadata'):
|
||||
request.state.metadata.pop('selected_model_id', None)
|
||||
|
||||
# Fallback: if generate_chat_completion is called with an arena model
|
||||
# from a path that did NOT go through process_chat_payload (e.g.,
|
||||
# background tasks for title/follow-up/tags generation), resolve now.
|
||||
if not selected_model_id and model.get('owned_by') == 'arena':
|
||||
model_ids = model.get('info', {}).get('meta', {}).get('model_ids')
|
||||
filter_mode = model.get('info', {}).get('meta', {}).get('filter_mode')
|
||||
if model_ids and filter_mode == 'exclude':
|
||||
model_ids = [
|
||||
available_model['id']
|
||||
for available_model in list(request.app.state.MODELS.values())
|
||||
if available_model.get('owned_by') != 'arena' and available_model['id'] not in model_ids
|
||||
]
|
||||
# Fallback: if generate_chat_completion is called with an arena model
|
||||
# from a path that did NOT go through process_chat_payload (e.g.,
|
||||
# background tasks for title/follow-up/tags generation), resolve now.
|
||||
if not selected_model_id and model.get('owned_by') == 'arena':
|
||||
model_ids = model.get('info', {}).get('meta', {}).get('model_ids')
|
||||
filter_mode = model.get('info', {}).get('meta', {}).get('filter_mode')
|
||||
if model_ids and filter_mode == 'exclude':
|
||||
model_ids = [
|
||||
available_model['id']
|
||||
for available_model in list(request.app.state.MODELS.values())
|
||||
if available_model.get('owned_by') != 'arena' and available_model['id'] not in model_ids
|
||||
]
|
||||
|
||||
if isinstance(model_ids, list) and model_ids:
|
||||
selected_model_id = random.choice(model_ids)
|
||||
else:
|
||||
model_ids = [
|
||||
available_model['id']
|
||||
for available_model in list(request.app.state.MODELS.values())
|
||||
if available_model.get('owned_by') != 'arena'
|
||||
]
|
||||
selected_model_id = random.choice(model_ids)
|
||||
|
||||
form_data['model'] = selected_model_id
|
||||
|
||||
# bypass_filter recursion below skips the line-200 check; gate the resolved model here.
|
||||
if not bypass_filter and user.role == 'user':
|
||||
selected_model = request.app.state.MODELS.get(selected_model_id)
|
||||
if selected_model:
|
||||
await check_model_access(user, selected_model)
|
||||
|
||||
if selected_model_id:
|
||||
if form_data.get('stream') == True:
|
||||
|
||||
async def stream_wrapper(stream):
|
||||
yield f'data: {JSONCodec.dumps({"selected_model_id": selected_model_id})}\n\n'
|
||||
async for chunk in stream:
|
||||
yield chunk
|
||||
|
||||
response = await generate_chat_completion(
|
||||
request,
|
||||
form_data,
|
||||
user,
|
||||
bypass_filter=True,
|
||||
bypass_system_prompt=bypass_system_prompt,
|
||||
)
|
||||
# Upstream errors come back as a response object.
|
||||
if not isinstance(response, StreamingResponse):
|
||||
return response
|
||||
return StreamingResponse(
|
||||
stream_wrapper(response.body_iterator),
|
||||
media_type='text/event-stream',
|
||||
background=response.background,
|
||||
)
|
||||
else:
|
||||
response = await generate_chat_completion(
|
||||
request,
|
||||
form_data,
|
||||
user,
|
||||
bypass_filter=True,
|
||||
bypass_system_prompt=bypass_system_prompt,
|
||||
)
|
||||
if not isinstance(response, dict):
|
||||
return response
|
||||
return {**response, 'selected_model_id': selected_model_id}
|
||||
|
||||
if model.get('pipe'):
|
||||
# Below does not require bypass_filter because this is the only route the uses this function and it is already bypassing the filter
|
||||
return await generate_function_chat_completion(request, form_data, user=user, models=models)
|
||||
if model.get('owned_by') == 'ollama':
|
||||
# Apply before Ollama conversion so tool follow-ups keep the model system prompt
|
||||
if not bypass_system_prompt:
|
||||
model_info = await Models.get_model_by_id(form_data['model'])
|
||||
if model_info:
|
||||
system = model_info.params.model_dump().get('system')
|
||||
form_data = await apply_system_prompt_to_body(system, form_data, metadata, user)
|
||||
request.state.bypass_system_prompt = True
|
||||
|
||||
# Using /ollama/api/chat endpoint
|
||||
form_data = convert_chat_completions_payload_to_ollama(form_data)
|
||||
response = await generate_ollama_chat_completion(
|
||||
request=request,
|
||||
form_data=form_data,
|
||||
user=user,
|
||||
)
|
||||
if form_data.get('stream'):
|
||||
response.headers['content-type'] = 'text/event-stream'
|
||||
return StreamingResponse(
|
||||
convert_ollama_stream_to_chat_completions(response),
|
||||
headers=dict(response.headers),
|
||||
background=response.background,
|
||||
)
|
||||
else:
|
||||
return convert_ollama_response_to_chat_completions(response)
|
||||
if isinstance(model_ids, list) and model_ids:
|
||||
selected_model_id = random.choice(model_ids)
|
||||
else:
|
||||
return await generate_openai_chat_completion(
|
||||
request=request,
|
||||
form_data=form_data,
|
||||
user=user,
|
||||
model_ids = [
|
||||
available_model['id']
|
||||
for available_model in list(request.app.state.MODELS.values())
|
||||
if available_model.get('owned_by') != 'arena'
|
||||
]
|
||||
selected_model_id = random.choice(model_ids)
|
||||
|
||||
form_data['model'] = selected_model_id
|
||||
|
||||
# bypass_filter recursion below skips the line-200 check; gate the resolved model here.
|
||||
if not bypass_filter and user.role == 'user':
|
||||
selected_model = request.app.state.MODELS.get(selected_model_id)
|
||||
if selected_model:
|
||||
await check_model_access(user, selected_model)
|
||||
|
||||
if selected_model_id:
|
||||
if form_data.get('stream') == True:
|
||||
|
||||
async def stream_wrapper(stream):
|
||||
yield f'data: {JSONCodec.dumps({"selected_model_id": selected_model_id})}\n\n'
|
||||
async for chunk in stream:
|
||||
yield chunk
|
||||
|
||||
response = await generate_chat_completion(
|
||||
request,
|
||||
form_data,
|
||||
user,
|
||||
bypass_filter=True,
|
||||
bypass_system_prompt=bypass_system_prompt,
|
||||
)
|
||||
# Upstream errors come back as a response object.
|
||||
if not isinstance(response, StreamingResponse):
|
||||
return response
|
||||
return StreamingResponse(
|
||||
stream_wrapper(response.body_iterator),
|
||||
media_type='text/event-stream',
|
||||
background=response.background,
|
||||
)
|
||||
else:
|
||||
response = await generate_chat_completion(
|
||||
request,
|
||||
form_data,
|
||||
user,
|
||||
bypass_filter=True,
|
||||
bypass_system_prompt=bypass_system_prompt,
|
||||
)
|
||||
if not isinstance(response, dict):
|
||||
return response
|
||||
return {**response, 'selected_model_id': selected_model_id}
|
||||
|
||||
if model.get('pipe'):
|
||||
# Below does not require bypass_filter because this is the only route the uses this function and it is already bypassing the filter
|
||||
return await generate_function_chat_completion(request, form_data, user=user, models=models)
|
||||
if model.get('owned_by') == 'ollama':
|
||||
# Apply before Ollama conversion so tool follow-ups keep the model system prompt
|
||||
if not bypass_system_prompt:
|
||||
model_info = await Models.get_model_by_id(form_data['model'])
|
||||
if model_info:
|
||||
system = model_info.params.model_dump().get('system')
|
||||
form_data = await apply_system_prompt_to_body(system, form_data, metadata, user)
|
||||
request.state.bypass_system_prompt = True
|
||||
|
||||
# Using /ollama/api/chat endpoint
|
||||
form_data = convert_chat_completions_payload_to_ollama(form_data)
|
||||
response = await generate_ollama_chat_completion(
|
||||
request=request,
|
||||
form_data=form_data,
|
||||
user=user,
|
||||
)
|
||||
if form_data.get('stream'):
|
||||
response.headers['content-type'] = 'text/event-stream'
|
||||
return StreamingResponse(
|
||||
convert_ollama_stream_to_chat_completions(response),
|
||||
headers=dict(response.headers),
|
||||
background=response.background,
|
||||
)
|
||||
else:
|
||||
return convert_ollama_response_to_chat_completions(response)
|
||||
else:
|
||||
return await generate_openai_chat_completion(
|
||||
request=request,
|
||||
form_data=form_data,
|
||||
user=user,
|
||||
)
|
||||
|
||||
|
||||
chat_completion = generate_chat_completion
|
||||
@@ -380,13 +262,7 @@ async def chat_completed(request: Request, form_data: dict, user: Any):
|
||||
if not request.app.state.MODELS:
|
||||
await get_all_models(request, user=user)
|
||||
|
||||
if getattr(request.state, 'direct', False) and hasattr(request.state, 'model'):
|
||||
models = {
|
||||
**dict(request.app.state.MODELS.items()),
|
||||
request.state.model['id']: request.state.model,
|
||||
}
|
||||
else:
|
||||
models = request.app.state.MODELS
|
||||
models = await add_tether_model(request, user, form_data.get('model'))
|
||||
|
||||
data = form_data
|
||||
|
||||
|
||||
@@ -3,6 +3,8 @@ from __future__ import annotations
|
||||
import copy
|
||||
import logging
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from itertools import takewhile
|
||||
from typing import Any
|
||||
|
||||
from fastapi.responses import JSONResponse
|
||||
@@ -10,7 +12,13 @@ from open_webui.models.chats import Chats
|
||||
from open_webui.models.config import Config
|
||||
from open_webui.utils.chat_id import is_saved_chat_id
|
||||
from open_webui.utils.json_codec import JSONCodec
|
||||
from open_webui.utils.misc import get_content_from_message, get_last_user_message, get_message_list
|
||||
from open_webui.utils.misc import (
|
||||
convert_output_to_messages,
|
||||
get_content_from_message,
|
||||
get_last_user_message,
|
||||
get_message_list,
|
||||
is_empty_reply,
|
||||
)
|
||||
from open_webui.utils.payload import apply_params_to_form_data
|
||||
from open_webui.utils.task import (
|
||||
prompt_template,
|
||||
@@ -43,92 +51,75 @@ Summarize the conversation history that will be compacted out of the active chat
|
||||
{{RECENT_MESSAGES}}"""
|
||||
|
||||
|
||||
async def compact_messages_for_request(
|
||||
request,
|
||||
form_data: dict | None,
|
||||
user,
|
||||
messages: list[dict],
|
||||
metadata: dict,
|
||||
model_id: str,
|
||||
models: dict,
|
||||
system_prompt: str = '',
|
||||
bypass_system_prompt: bool = False,
|
||||
) -> tuple[list[dict], str | None, list[dict]]:
|
||||
@dataclass(frozen=True)
|
||||
class MessageSplit:
|
||||
"""A request's messages divided at the compaction boundary."""
|
||||
|
||||
system_messages: list[dict]
|
||||
summary: str | None
|
||||
compacted: list[dict]
|
||||
messages: list[dict]
|
||||
|
||||
|
||||
async def split_messages(messages: list[dict], metadata: dict, system_prompt: str = '') -> MessageSplit:
|
||||
"""Divide messages at the compaction boundary; under the threshold nothing is compacted."""
|
||||
config = await _load_config()
|
||||
if not config['enable']:
|
||||
return messages, None, []
|
||||
return MessageSplit([], None, [], messages)
|
||||
|
||||
system_messages = [messages[0]] if messages and messages[0].get('role') == 'system' else []
|
||||
messages = messages[1:] if system_messages else messages
|
||||
|
||||
messages, previous_summary = _apply_latest_summary_checkpoint(messages)
|
||||
messages, summary = _apply_latest_summary_checkpoint(messages)
|
||||
system_prompt = system_prompt or (get_content_from_message(system_messages[0]) if system_messages else '')
|
||||
token_threshold = _resolve_token_threshold(config['token_threshold'], config['token_cap'], metadata)
|
||||
if not _exceeds_token_threshold(messages, system_prompt, previous_summary, token_threshold):
|
||||
return [*system_messages, *messages], previous_summary, []
|
||||
if token_threshold <= 0 or _estimate_request_tokens(messages, system_prompt, summary) <= token_threshold:
|
||||
return MessageSplit(system_messages, summary, [], messages)
|
||||
|
||||
# A tool loop's messages carry the turn's summary only in the system message.
|
||||
summary = summary or metadata.get('context_summary')
|
||||
boundary = _find_compaction_boundary(messages, config['retention_percentage'])
|
||||
compacted_messages = messages[:boundary]
|
||||
recent_messages = messages[boundary:]
|
||||
if not compacted_messages or not recent_messages:
|
||||
return [*system_messages, *messages], previous_summary, []
|
||||
if not messages[:boundary] or not messages[boundary:]:
|
||||
return MessageSplit(system_messages, summary, [], messages)
|
||||
return MessageSplit(system_messages, summary, messages[:boundary], messages[boundary:])
|
||||
|
||||
event_emitter = None
|
||||
if metadata.get('chat_id') and metadata.get('message_id'):
|
||||
from open_webui.socket.main import get_event_emitter
|
||||
|
||||
event_emitter = await get_event_emitter(metadata)
|
||||
async def compact_messages(
|
||||
request,
|
||||
form_data: dict | None,
|
||||
user,
|
||||
split: MessageSplit,
|
||||
metadata: dict,
|
||||
model_id: str,
|
||||
models: dict,
|
||||
bypass_system_prompt: bool = False,
|
||||
) -> tuple[list[dict], str | None, list[dict]]:
|
||||
"""Fold the split's compacted messages into its summary."""
|
||||
if not split.compacted:
|
||||
return [*split.system_messages, *split.messages], split.summary, []
|
||||
|
||||
if event_emitter:
|
||||
await event_emitter(
|
||||
{
|
||||
'type': 'context_compaction',
|
||||
'data': {
|
||||
'action': 'context_compaction',
|
||||
'description': 'Compacting context',
|
||||
'done': False,
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
try:
|
||||
summary = await _generate_summary(
|
||||
request,
|
||||
form_data,
|
||||
user,
|
||||
model_id,
|
||||
models,
|
||||
compacted_messages,
|
||||
recent_messages,
|
||||
previous_summary,
|
||||
config['prompt_template'],
|
||||
bypass_system_prompt,
|
||||
)
|
||||
except Exception:
|
||||
if event_emitter:
|
||||
await event_emitter(
|
||||
{
|
||||
'type': 'context_compaction',
|
||||
'data': {
|
||||
'action': 'context_compaction',
|
||||
'description': 'Context compaction failed',
|
||||
'done': True,
|
||||
'error': True,
|
||||
},
|
||||
}
|
||||
)
|
||||
raise
|
||||
new_summary = await _generate_summary(
|
||||
request,
|
||||
form_data,
|
||||
user,
|
||||
model_id,
|
||||
models,
|
||||
split.compacted,
|
||||
split.messages,
|
||||
split.summary,
|
||||
(await _load_config())['prompt_template'],
|
||||
bypass_system_prompt,
|
||||
)
|
||||
|
||||
chat_id = metadata.get('chat_id')
|
||||
checkpoint_message_id = (
|
||||
recent_messages[0].get('id') or metadata.get('user_message_id') or metadata.get('message_id')
|
||||
)
|
||||
checkpoint = split.messages[0]
|
||||
checkpoint_message_id = checkpoint.get('id') or metadata.get('user_message_id') or metadata.get('message_id')
|
||||
# Only whole-turn user boundaries correspond to persisted chat checkpoints.
|
||||
if recent_messages[0].get('role') == 'user' and is_saved_chat_id(chat_id) and checkpoint_message_id:
|
||||
if checkpoint.get('role') == 'user' and is_saved_chat_id(chat_id) and checkpoint_message_id:
|
||||
await Chats.upsert_message_to_chat_by_id_and_message_id(
|
||||
chat_id,
|
||||
checkpoint_message_id,
|
||||
{'contextSummary': summary},
|
||||
{'contextSummary': new_summary},
|
||||
touch=False,
|
||||
)
|
||||
|
||||
@@ -137,28 +128,23 @@ async def compact_messages_for_request(
|
||||
chat_id,
|
||||
checkpoint_message_id,
|
||||
metadata.get('message_id'),
|
||||
len(compacted_messages),
|
||||
len(recent_messages),
|
||||
len(summary),
|
||||
len(split.compacted),
|
||||
len(split.messages),
|
||||
len(new_summary),
|
||||
)
|
||||
|
||||
if event_emitter:
|
||||
if chat_id and metadata.get('message_id') and checkpoint.get('role') == 'user':
|
||||
from open_webui.socket.main import get_event_emitter
|
||||
|
||||
event_emitter = await get_event_emitter(metadata)
|
||||
await event_emitter(
|
||||
{
|
||||
'type': 'context_compaction',
|
||||
'data': {
|
||||
'action': 'context_compaction',
|
||||
'description': 'Context compacted',
|
||||
'done': True,
|
||||
'checkpoint_message_id': (
|
||||
recent_messages[0].get('id') if recent_messages[0].get('role') == 'user' else None
|
||||
),
|
||||
'context_summary': summary,
|
||||
},
|
||||
'data': {'checkpoint_message_id': checkpoint.get('id'), 'context_summary': new_summary},
|
||||
}
|
||||
)
|
||||
|
||||
return [*system_messages, *recent_messages], summary, compacted_messages
|
||||
return [*split.system_messages, *split.messages], new_summary, split.compacted
|
||||
|
||||
|
||||
async def apply_summary_checkpoint(messages: list[dict]) -> tuple[list[dict], str | None]:
|
||||
@@ -191,33 +177,38 @@ async def compact_chat_branch(request, user, chat: Any, model_id: str, models: d
|
||||
if not messages_map:
|
||||
messages_map = history.get('messages') or {}
|
||||
|
||||
messages, previous_summary = _apply_latest_summary_checkpoint(get_message_list(messages_map, current_id))
|
||||
compacted_messages = messages[:-1]
|
||||
recent_messages = messages[-1:]
|
||||
if not compacted_messages or not recent_messages:
|
||||
# A summary on an empty reply would be left out of the next request along with the reply.
|
||||
while current_id and is_empty_reply(messages_map.get(current_id) or {}):
|
||||
current_id = messages_map[current_id].get('parentId')
|
||||
if not current_id:
|
||||
return {'ok': True, 'compacted': False, 'reason': 'empty'}
|
||||
|
||||
history, summary = _apply_latest_summary_checkpoint(get_message_list(messages_map, current_id))
|
||||
compacted, messages = history[:-1], history[-1:]
|
||||
if not compacted:
|
||||
return {'ok': True, 'compacted': False, 'reason': 'too_short'}
|
||||
|
||||
summary = await _generate_summary(
|
||||
new_summary = await _generate_summary(
|
||||
request,
|
||||
None,
|
||||
user,
|
||||
model_id,
|
||||
models,
|
||||
compacted_messages,
|
||||
recent_messages,
|
||||
previous_summary,
|
||||
compacted,
|
||||
messages,
|
||||
summary,
|
||||
config['prompt_template'],
|
||||
)
|
||||
await Chats.upsert_message_to_chat_by_id_and_message_id(
|
||||
chat.id, current_id, {'contextSummary': summary}, touch=False
|
||||
chat.id, current_id, {'contextSummary': new_summary}, touch=False
|
||||
)
|
||||
|
||||
return {
|
||||
'ok': True,
|
||||
'compacted': True,
|
||||
'dropped_messages': len(compacted_messages),
|
||||
'kept_messages': len(recent_messages),
|
||||
'summary_chars': len(summary),
|
||||
'dropped_messages': len(compacted),
|
||||
'kept_messages': len(messages),
|
||||
'summary_chars': len(new_summary),
|
||||
}
|
||||
|
||||
|
||||
@@ -301,16 +292,8 @@ async def get_chat_context_usage(chat: Any, model_id: str | None = None) -> dict
|
||||
if model_id:
|
||||
params['model'] = model_id
|
||||
threshold = _resolve_token_threshold(config['token_threshold'], config['token_cap'], {'params': params})
|
||||
messages, previous_summary = _apply_latest_summary_checkpoint(messages)
|
||||
|
||||
for idx in range(len(messages) - 1, -1, -1):
|
||||
usage = messages[idx].get('usage') or (messages[idx].get('info') or {}).get('usage')
|
||||
if isinstance(usage, dict) and (tokens := _usage_token_count(usage)):
|
||||
tokens += _estimate_messages_tokens(messages[idx + 1 :])
|
||||
return _build_context_usage(tokens, threshold)
|
||||
|
||||
tokens = _estimate_tokens(previous_summary or '') + _estimate_messages_tokens(messages)
|
||||
return _build_context_usage(tokens, threshold)
|
||||
messages, summary = _apply_latest_summary_checkpoint(messages)
|
||||
return _build_context_usage(_estimate_request_tokens(messages, '', summary), threshold)
|
||||
|
||||
|
||||
def _build_context_usage(tokens: int, threshold: int) -> dict:
|
||||
@@ -323,11 +306,15 @@ def _build_context_usage(tokens: int, threshold: int) -> dict:
|
||||
}
|
||||
|
||||
|
||||
def _get_context_summary_from_message(message: dict) -> str | None:
|
||||
value = message.get('contextSummary') or message.get('context_summary')
|
||||
return value if isinstance(value, str) and value.strip() else None
|
||||
|
||||
|
||||
def _apply_latest_summary_checkpoint(messages: list[dict]) -> tuple[list[dict], str | None]:
|
||||
for idx in range(len(messages) - 1, -1, -1):
|
||||
message = messages[idx]
|
||||
value = message.get('contextSummary') or message.get('context_summary')
|
||||
if isinstance(value, str) and value.strip():
|
||||
if value := _get_context_summary_from_message(message):
|
||||
# Rerun without the summary so a tool-loop reply keeps its mid-turn trim.
|
||||
if message.get('output'):
|
||||
[trimmed_message], _ = _apply_latest_summary_checkpoint(
|
||||
@@ -340,7 +327,7 @@ def _apply_latest_summary_checkpoint(messages: list[dict]) -> tuple[list[dict],
|
||||
(
|
||||
item
|
||||
for item in reversed(message.get('output') or [])
|
||||
if item.get('type') == 'open_webui:context_compaction'
|
||||
if item.get('type') == 'open_webui:context_compaction' and item.get('summary')
|
||||
),
|
||||
None,
|
||||
)
|
||||
@@ -358,7 +345,11 @@ def _apply_latest_summary_checkpoint(messages: list[dict]) -> tuple[list[dict],
|
||||
),
|
||||
None,
|
||||
)
|
||||
if start is not None:
|
||||
if start is None:
|
||||
# A summary saved inside the retained rounds was written after this marker.
|
||||
if cut_idx < idx and _get_context_summary_from_message(messages[cut_idx]):
|
||||
break
|
||||
else:
|
||||
while start and output[start - 1].get('type') != 'function_call_output':
|
||||
start -= 1
|
||||
return [
|
||||
@@ -375,17 +366,22 @@ def _apply_latest_summary_checkpoint(messages: list[dict]) -> tuple[list[dict],
|
||||
return messages, None
|
||||
|
||||
|
||||
def _exceeds_token_threshold(messages: list[dict], system_prompt: str, summary: str | None, threshold: int) -> bool:
|
||||
if threshold <= 0:
|
||||
return False
|
||||
|
||||
def _estimate_request_tokens(messages: list[dict], system_prompt: str, summary: str | None) -> int:
|
||||
"""Tokens a request with these messages takes, counted from the latest reply that reports its usage."""
|
||||
for idx in range(len(messages) - 1, -1, -1):
|
||||
usage = messages[idx].get('usage') or (messages[idx].get('info') or {}).get('usage')
|
||||
if isinstance(usage, dict) and (tokens := _usage_token_count(usage)):
|
||||
return tokens + _estimate_messages_tokens(messages[idx + 1 :]) > threshold
|
||||
if tokens := _reported_tokens(messages[idx]):
|
||||
return tokens + _estimate_messages_tokens(messages[idx + 1 :])
|
||||
return _estimate_tokens(system_prompt) + _estimate_tokens(summary or '') + _estimate_messages_tokens(messages)
|
||||
|
||||
estimated = _estimate_tokens(system_prompt) + _estimate_tokens(summary or '') + _estimate_messages_tokens(messages)
|
||||
return estimated > threshold
|
||||
|
||||
def _reported_tokens(message: dict) -> int:
|
||||
"""Tokens the provider reported for this reply, or 0 when it reported none."""
|
||||
usage = message.get('usage') or (message.get('info') or {}).get('usage')
|
||||
if not isinstance(usage, dict) or not (tokens := _usage_token_count(usage)):
|
||||
return 0
|
||||
# Tool results that end the reply came back after the report, e.g. ones too long for the model to answer.
|
||||
outputs = takewhile(lambda item: item.get('type') == 'function_call_output', reversed(message.get('output') or []))
|
||||
return tokens + sum(_estimate_tokens(item) for item in outputs)
|
||||
|
||||
|
||||
def _find_compaction_boundary(messages: list[dict], retention_percentage: int = 40) -> int:
|
||||
@@ -412,16 +408,16 @@ async def _generate_summary(
|
||||
user,
|
||||
model_id: str,
|
||||
models: dict,
|
||||
compacted_messages: list[dict],
|
||||
recent_messages: list[dict],
|
||||
previous_summary: str | None,
|
||||
compacted: list[dict],
|
||||
messages: list[dict],
|
||||
summary: str | None,
|
||||
summary_prompt_template: str,
|
||||
bypass_system_prompt: bool = False,
|
||||
) -> str:
|
||||
from open_webui.utils.chat import generate_chat_completion
|
||||
from open_webui.utils.models import add_tether_model
|
||||
|
||||
if getattr(request.state, 'direct', False) and hasattr(request.state, 'model'):
|
||||
models = {**dict(models.items()), request.state.model['id']: request.state.model}
|
||||
models = await add_tether_model(request, user, model_id, models)
|
||||
|
||||
task_config = await Config.get_many(
|
||||
'task.model.params',
|
||||
@@ -433,31 +429,31 @@ async def _generate_summary(
|
||||
raise ValueError('No available model for context compaction')
|
||||
|
||||
summary_prompt_template = summary_prompt_template.strip() or DEFAULT_CONTEXT_COMPACTION_PROMPT
|
||||
recent_message_prefix = _message_prefix(recent_messages[0])
|
||||
boundary_prefix = _message_prefix(messages[0])
|
||||
has_unique_prefix = (
|
||||
recent_message_prefix
|
||||
and sum(
|
||||
_message_prefix(message) == recent_message_prefix for message in [*compacted_messages, *recent_messages]
|
||||
)
|
||||
== 1
|
||||
boundary_prefix and sum(_message_prefix(message) == boundary_prefix for message in [*compacted, *messages]) == 1
|
||||
)
|
||||
# The text-only prompt formatter otherwise omits tool names and arguments.
|
||||
compacted_messages, recent_messages = list(compacted_messages), list(recent_messages)
|
||||
for messages in (compacted_messages, recent_messages):
|
||||
for idx, message in enumerate(messages):
|
||||
if message.get('tool_calls'):
|
||||
messages[idx] = {
|
||||
compacted, messages = list(compacted), list(messages)
|
||||
for group in (compacted, messages):
|
||||
for idx, message in enumerate(group):
|
||||
# Saved replies keep their tool calls as output items.
|
||||
tool_calls = message.get('tool_calls') or [
|
||||
call for m in convert_output_to_messages(message.get('output')) for call in m.get('tool_calls', [])
|
||||
]
|
||||
if tool_calls:
|
||||
group[idx] = {
|
||||
**message,
|
||||
'content': f'{get_content_from_message(message) or ""}\n[TOOL CALLS] {JSONCodec.dumps(message["tool_calls"])}',
|
||||
'content': f'{get_content_from_message(message) or ""}\n[TOOL CALLS] {JSONCodec.dumps(tool_calls)}',
|
||||
}
|
||||
|
||||
async def render_prompt(template: str) -> str:
|
||||
all_messages = [*compacted_messages, *recent_messages]
|
||||
all_messages = [*compacted, *messages]
|
||||
prompt = replace_prompt_variable(template, get_last_user_message(all_messages) or '')
|
||||
prompt = replace_messages_variable(prompt, all_messages)
|
||||
prompt = replace_messages_variable(prompt, compacted_messages, 'COMPACTED_MESSAGES')
|
||||
prompt = replace_messages_variable(prompt, recent_messages, 'RECENT_MESSAGES')
|
||||
prompt = prompt_variables_template(prompt, {'{{PREVIOUS_SUMMARY}}': previous_summary or ''})
|
||||
prompt = replace_messages_variable(prompt, compacted, 'COMPACTED_MESSAGES')
|
||||
prompt = replace_messages_variable(prompt, messages, 'RECENT_MESSAGES')
|
||||
prompt = prompt_variables_template(prompt, {'{{PREVIOUS_SUMMARY}}': summary or ''})
|
||||
return await prompt_template(prompt, user)
|
||||
|
||||
task_model_params = task_config.get('task.model.params') or {}
|
||||
@@ -476,7 +472,7 @@ async def _generate_summary(
|
||||
form_data
|
||||
and task_model_id == model_id
|
||||
and has_unique_prefix
|
||||
and sum(_message_prefix(message) == recent_message_prefix for message in form_data['messages']) == 1
|
||||
and sum(_message_prefix(message) == boundary_prefix for message in form_data['messages']) == 1
|
||||
):
|
||||
prompt = await render_prompt(
|
||||
prompt_variables_template(
|
||||
@@ -484,10 +480,10 @@ async def _generate_summary(
|
||||
{
|
||||
'{{COMPACTED_MESSAGES}}': (
|
||||
'Every non-system message above before (excluding) the message beginning with '
|
||||
f'"{recent_message_prefix}".'
|
||||
f'"{boundary_prefix}".'
|
||||
),
|
||||
'{{RECENT_MESSAGES}}': (
|
||||
f'The message above beginning with "{recent_message_prefix}" and every message after it.'
|
||||
f'The message above beginning with "{boundary_prefix}" and every message after it.'
|
||||
),
|
||||
},
|
||||
)
|
||||
@@ -509,9 +505,9 @@ async def _generate_summary(
|
||||
)
|
||||
except Exception:
|
||||
response = None
|
||||
summary = _response_text(response).strip()
|
||||
if summary:
|
||||
return summary
|
||||
text = _response_text(response).strip()
|
||||
if text:
|
||||
return text
|
||||
|
||||
prompt = await render_prompt(summary_prompt_template)
|
||||
payload = {
|
||||
@@ -523,12 +519,12 @@ async def _generate_summary(
|
||||
|
||||
payload = apply_params_to_form_data(payload, models[task_model_id], task_model_params)
|
||||
response = await generate_chat_completion(request, form_data=payload, user=user)
|
||||
summary = _response_text(response).strip()
|
||||
if summary:
|
||||
return summary
|
||||
text = _response_text(response).strip()
|
||||
if text:
|
||||
return text
|
||||
|
||||
parts = [previous_summary] if previous_summary else []
|
||||
for message in compacted_messages:
|
||||
parts = [summary] if summary else []
|
||||
for message in compacted:
|
||||
content = get_content_from_message(message)
|
||||
if content:
|
||||
parts.append(f'- {message.get("role", "unknown")}: {content[:500]}')
|
||||
|
||||
@@ -13,7 +13,7 @@ from open_webui.routers.ollama import (
|
||||
embed as ollama_embed,
|
||||
)
|
||||
from open_webui.routers.openai import embeddings as openai_embeddings
|
||||
from open_webui.utils.models import check_model_access
|
||||
from open_webui.utils.models import check_model_access, add_tether_model
|
||||
from open_webui.utils.payload import convert_embed_payload_openai_to_ollama
|
||||
from open_webui.utils.response import convert_embedding_response_ollama_to_openai
|
||||
|
||||
@@ -52,13 +52,7 @@ async def generate_embeddings(
|
||||
**request.state.metadata,
|
||||
}
|
||||
|
||||
# If "direct" flag present, use only that model
|
||||
if getattr(request.state, 'direct', False) and hasattr(request.state, 'model'):
|
||||
models = {
|
||||
request.state.model['id']: request.state.model,
|
||||
}
|
||||
else:
|
||||
models = request.app.state.MODELS
|
||||
models = await add_tether_model(request, user, form_data.get('model'))
|
||||
|
||||
model_id = form_data.get('model')
|
||||
if model_id not in models:
|
||||
@@ -66,9 +60,8 @@ async def generate_embeddings(
|
||||
model = models[model_id]
|
||||
|
||||
# Access filtering
|
||||
if not getattr(request.state, 'direct', False):
|
||||
if not bypass_filter and user.role == 'user':
|
||||
await check_model_access(user, model)
|
||||
if not bypass_filter and user.role == 'user':
|
||||
await check_model_access(user, model)
|
||||
|
||||
# Ollama backend — use /api/embed which supports batch input natively
|
||||
if model.get('owned_by') == 'ollama':
|
||||
|
||||
@@ -0,0 +1,564 @@
|
||||
"""Image connections: the configured backends that built-in image generation and editing run on.
|
||||
|
||||
A connection is one backend (an OpenAI-compatible endpoint such as LiteLLM, Gemini, ComfyUI or
|
||||
AUTOMATIC1111) with the image models it exposes. Users pick a model by its reference,
|
||||
``{connection_id}:{model_id}``, and only see models their access grants allow.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import uuid
|
||||
from typing import Any, Literal
|
||||
|
||||
from aiocache import cached
|
||||
from fastapi import HTTPException, Request
|
||||
from open_webui.constants import ERROR_MESSAGES
|
||||
from open_webui.env import AIOHTTP_CLIENT_SESSION_SSL, MODELS_CACHE_TTL
|
||||
from open_webui.models.config import Config
|
||||
from open_webui.models.groups import Groups
|
||||
from open_webui.models.users import UserModel
|
||||
from open_webui.utils.access_control import has_connection_access
|
||||
from open_webui.utils.headers import get_headers_and_cookies
|
||||
from open_webui.utils.json_codec import JSONCodec
|
||||
from open_webui.utils.session_pool import get_session
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
IMAGE_CONNECTIONS_CONFIG_KEY = 'images.connections'
|
||||
IMAGE_GENERATION_DEFAULT_MODEL_CONFIG_KEY = 'image_generation.default_model'
|
||||
IMAGE_EDIT_DEFAULT_MODEL_CONFIG_KEY = 'images.edit.default_model'
|
||||
|
||||
IMAGE_CONNECTION_TYPES = ('openai', 'gemini', 'comfyui', 'automatic1111')
|
||||
|
||||
# The auth types chat model connections offer; only OpenAI compatible image connections use more than a key.
|
||||
IMAGE_CONNECTION_AUTH_TYPES = ('none', 'bearer', 'session', 'system_oauth', 'microsoft_entra_id')
|
||||
|
||||
DEFAULT_OPENAI_IMAGE_MODEL = 'gpt-image-2'
|
||||
DEFAULT_GEMINI_IMAGE_MODEL = 'imagen-3.0-generate-002'
|
||||
|
||||
ImageCapability = Literal['image_generation', 'image_edit']
|
||||
|
||||
IMAGE_CAPABILITIES: tuple[ImageCapability, ...] = ('image_generation', 'image_edit')
|
||||
|
||||
PUBLIC_ACCESS_GRANTS = [{'principal_type': 'user', 'principal_id': '*', 'permission': 'read'}]
|
||||
|
||||
|
||||
def get_image_model_ref(connection_id: str, model_id: str) -> str:
|
||||
return f'{connection_id}:{model_id}'
|
||||
|
||||
|
||||
def _json_object(value: Any, label: str) -> dict:
|
||||
if value in (None, ''):
|
||||
return {}
|
||||
if isinstance(value, str):
|
||||
try:
|
||||
value = JSONCodec.loads(value)
|
||||
except JSONCodec.JSONDecodeError:
|
||||
raise ValueError(f'Invalid JSON for {label}')
|
||||
if not isinstance(value, dict):
|
||||
raise ValueError(f'Invalid JSON for {label}')
|
||||
return value
|
||||
|
||||
|
||||
def _workflow(value: Any, label: str) -> str:
|
||||
if value in (None, ''):
|
||||
return ''
|
||||
if isinstance(value, dict):
|
||||
return JSONCodec.dumps(value)
|
||||
_json_object(value, label)
|
||||
return str(value)
|
||||
|
||||
|
||||
def _size(value: Any) -> str:
|
||||
size = str(value or '').strip()
|
||||
if size and size != 'auto':
|
||||
width, _, height = size.partition('x')
|
||||
if not (width.isdigit() and height.isdigit()):
|
||||
raise ValueError(f'Invalid image size: {size} (e.g. 512x512)')
|
||||
return size
|
||||
|
||||
|
||||
def _workflow_nodes(nodes: Any) -> list[dict]:
|
||||
normalized = []
|
||||
for node in nodes or []:
|
||||
if not isinstance(node, dict):
|
||||
continue
|
||||
node_ids = node.get('node_ids') or []
|
||||
if isinstance(node_ids, str):
|
||||
node_ids = [node_id.strip() for node_id in node_ids.split(',') if node_id.strip()]
|
||||
normalized.append(
|
||||
{
|
||||
'type': str(node.get('type') or ''),
|
||||
'key': str(node.get('key') or ''),
|
||||
'node_ids': [str(node_id) for node_id in node_ids],
|
||||
}
|
||||
)
|
||||
return normalized
|
||||
|
||||
|
||||
def normalize_image_connection(connection: dict[str, Any]) -> dict[str, Any]:
|
||||
"""Validate an image connection and fill in defaults. Raises ValueError on invalid input."""
|
||||
connection_type = str(connection.get('type') or 'openai')
|
||||
if connection_type not in IMAGE_CONNECTION_TYPES:
|
||||
raise ValueError(f'Unsupported image connection type: {connection_type}')
|
||||
|
||||
connection_id = str(connection.get('id') or uuid.uuid4())
|
||||
if ':' in connection_id:
|
||||
raise ValueError('Image connection IDs cannot contain ":"')
|
||||
|
||||
config = connection.get('config') or {}
|
||||
|
||||
model_ids = []
|
||||
for model_id in config.get('model_ids') or []:
|
||||
model_id = str(model_id).strip()
|
||||
if model_id and model_id not in model_ids:
|
||||
model_ids.append(model_id)
|
||||
|
||||
auth_type = str(config.get('auth_type') or 'bearer')
|
||||
if auth_type not in IMAGE_CONNECTION_AUTH_TYPES:
|
||||
raise ValueError(f'Unsupported auth type: {auth_type}')
|
||||
if connection_type != 'openai' and auth_type not in ('none', 'bearer'):
|
||||
raise ValueError(f'{connection_type} connections support no auth or a key')
|
||||
|
||||
steps = config.get('steps')
|
||||
if steps not in (None, ''):
|
||||
steps = int(steps)
|
||||
if steps < 0:
|
||||
raise ValueError('Steps must be a positive number (e.g. 50)')
|
||||
else:
|
||||
steps = None
|
||||
|
||||
return {
|
||||
'id': connection_id,
|
||||
'name': str(connection.get('name') or '').strip() or connection_type,
|
||||
'type': connection_type,
|
||||
'url': str(connection.get('url') or '').strip().rstrip('/'),
|
||||
'key': str(connection.get('key') or ''),
|
||||
'config': {
|
||||
'enable': bool(config.get('enable', True)),
|
||||
'capabilities': {
|
||||
capability: bool((config.get('capabilities') or {}).get(capability, True))
|
||||
for capability in IMAGE_CAPABILITIES
|
||||
},
|
||||
'model_ids': model_ids,
|
||||
'access_grants': list(config.get('access_grants') or []),
|
||||
'auth_type': auth_type,
|
||||
'headers': _json_object(config.get('headers'), 'headers'),
|
||||
'size': _size(config.get('size')),
|
||||
'edit_size': _size(config.get('edit_size')),
|
||||
'steps': steps,
|
||||
'api_version': str(config.get('api_version') or ''),
|
||||
'params': _json_object(config.get('params'), 'additional parameters'),
|
||||
'endpoint_method': str(config.get('endpoint_method') or ''),
|
||||
'workflow': _workflow(config.get('workflow'), 'ComfyUI workflow'),
|
||||
'nodes': _workflow_nodes(config.get('nodes')),
|
||||
'edit_workflow': _workflow(config.get('edit_workflow'), 'ComfyUI edit workflow'),
|
||||
'edit_nodes': _workflow_nodes(config.get('edit_nodes')),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def get_image_connection_capabilities(connection: dict) -> dict[str, bool]:
|
||||
"""What a connection's models can do: what its type supports (ComfyUI needs the matching
|
||||
workflow, AUTOMATIC1111 cannot edit), narrowed by the capabilities the admin turned on."""
|
||||
config = connection.get('config') or {}
|
||||
if connection.get('type') == 'automatic1111':
|
||||
supported = {'image_generation': True, 'image_edit': False}
|
||||
elif connection.get('type') == 'comfyui':
|
||||
supported = {'image_generation': bool(config.get('workflow')), 'image_edit': bool(config.get('edit_workflow'))}
|
||||
else:
|
||||
supported = {'image_generation': True, 'image_edit': True}
|
||||
|
||||
enabled = config.get('capabilities') or {}
|
||||
return {capability: supported[capability] and bool(enabled.get(capability, True)) for capability in supported}
|
||||
|
||||
|
||||
async def get_openai_connection_models(request: Request, connection: dict, user: UserModel | None = None) -> list[dict]:
|
||||
"""The models an OpenAI compatible connection serves. LiteLLM also reports each one's mode and endpoints,
|
||||
which mark its image models (``image``) and what they can do, and its video models (``video``)."""
|
||||
from open_webui.routers.images import raise_for_provider_status
|
||||
|
||||
headers, cookies = await get_headers_and_cookies(
|
||||
request, connection['url'], connection.get('key'), connection.get('config') or {}, user=user
|
||||
)
|
||||
session = await get_session()
|
||||
async with session.get(
|
||||
url=f'{connection["url"]}/models', headers=headers, cookies=cookies, ssl=AIOHTTP_CLIENT_SESSION_SSL
|
||||
) as r:
|
||||
await raise_for_provider_status(r)
|
||||
res = await r.json(content_type=None)
|
||||
|
||||
models = [
|
||||
{'id': model['id'], 'name': model['id']}
|
||||
for model in (res.get('data') or [])
|
||||
if isinstance(model, dict) and model.get('id')
|
||||
]
|
||||
|
||||
try:
|
||||
async with session.get(
|
||||
url=f'{connection["url"]}/model/info', headers=headers, cookies=cookies, ssl=AIOHTTP_CLIENT_SESSION_SSL
|
||||
) as r:
|
||||
info = await r.json(content_type=None) if r.ok else {}
|
||||
except Exception as e:
|
||||
log.debug('No model info at %s: %s', connection['url'], e)
|
||||
return models
|
||||
|
||||
model_infos = {
|
||||
entry.get('model_name'): entry.get('model_info') or {}
|
||||
for entry in (info.get('data') or [])
|
||||
if isinstance(entry, dict)
|
||||
}
|
||||
if not any(model_info.get('mode') for model_info in model_infos.values()):
|
||||
return models
|
||||
|
||||
for model in models:
|
||||
model_info = model_infos.get(model['id']) or {}
|
||||
endpoints = [str(endpoint) for endpoint in model_info.get('supported_endpoints') or []]
|
||||
if endpoints:
|
||||
capabilities = {
|
||||
'image_generation': any(endpoint.endswith('/images/generations') for endpoint in endpoints),
|
||||
'image_edit': any(endpoint.endswith('/images/edits') for endpoint in endpoints),
|
||||
}
|
||||
model['video'] = any(endpoint.endswith('/videos') for endpoint in endpoints)
|
||||
else:
|
||||
capabilities = {capability: model_info.get('mode') == capability for capability in IMAGE_CAPABILITIES}
|
||||
model['video'] = model_info.get('mode') == 'video_generation'
|
||||
model['image'] = any(capabilities.values())
|
||||
if model['image']:
|
||||
model.update(capabilities)
|
||||
return models
|
||||
|
||||
|
||||
@cached(
|
||||
ttl=MODELS_CACHE_TTL,
|
||||
key_builder=lambda _func, request, connection, user=None: (
|
||||
f'image_connection_models_{connection["id"]}_{user.id}'
|
||||
if user
|
||||
else f'image_connection_models_{connection["id"]}'
|
||||
),
|
||||
)
|
||||
async def get_synced_image_models(request: Request, connection: dict, user: UserModel | None = None) -> list[dict]:
|
||||
"""The image models an OpenAI compatible connection with no model IDs offers, listed live so new ones
|
||||
appear on their own. Servers that do not label image models (plain OpenAI, Azure) offer the default model."""
|
||||
try:
|
||||
models = await get_openai_connection_models(request, connection, user)
|
||||
except Exception as e:
|
||||
log.warning('Could not list image models from %s: %s', connection.get('url'), e)
|
||||
return []
|
||||
|
||||
if not any('image' in model for model in models):
|
||||
return [{'id': ''}]
|
||||
return [model for model in models if model['image']]
|
||||
|
||||
|
||||
async def get_image_models(request: Request, user: UserModel, *, bypass_access: bool = False) -> list[dict]:
|
||||
"""Image models the user may use, across enabled connections. Each carries its connection for internal use.
|
||||
|
||||
A connection without model IDs offers its default: every image model an OpenAI compatible server
|
||||
labels (LiteLLM), else the engine's default model, the model a ComfyUI workflow sets, or the
|
||||
checkpoint AUTOMATIC1111 has loaded.
|
||||
"""
|
||||
connections = await Config.get(IMAGE_CONNECTIONS_CONFIG_KEY) or []
|
||||
user_group_ids = {group.id for group in await Groups.get_groups_by_member_id(user.id, include_inherited=True)}
|
||||
|
||||
models = []
|
||||
for connection in connections:
|
||||
config = connection.get('config') or {}
|
||||
if not config.get('enable', True):
|
||||
continue
|
||||
if not bypass_access and not await has_connection_access(user, connection, user_group_ids):
|
||||
continue
|
||||
capabilities = get_image_connection_capabilities(connection)
|
||||
|
||||
if config.get('model_ids'):
|
||||
entries = [{'id': model_id} for model_id in config['model_ids']]
|
||||
elif connection.get('type') == 'openai':
|
||||
entries = await get_synced_image_models(request, connection, user)
|
||||
else:
|
||||
entries = [{'id': ''}]
|
||||
|
||||
for entry in entries:
|
||||
model_id = entry['id']
|
||||
models.append(
|
||||
{
|
||||
'id': get_image_model_ref(connection['id'], model_id),
|
||||
'name': model_id or connection.get('name') or connection['id'],
|
||||
'model': model_id,
|
||||
'connection_id': connection['id'],
|
||||
'connection_name': connection.get('name') or connection['id'],
|
||||
# A synced model can do only what both the connection allows and the server says it does.
|
||||
**{
|
||||
capability: capabilities[capability] and entry.get(capability, True)
|
||||
for capability in IMAGE_CAPABILITIES
|
||||
},
|
||||
'connection': connection,
|
||||
}
|
||||
)
|
||||
return models
|
||||
|
||||
|
||||
def get_requested_model(metadata: dict | None, feature: str, meta_key: str) -> str | None:
|
||||
"""The model a chat asked for: the user's pick, else the chat model's default.
|
||||
|
||||
The pick rides on the feature itself, ``features.<feature> = {'model': ref}``; plain ``true`` means no pick.
|
||||
"""
|
||||
metadata = metadata or {}
|
||||
requested = (metadata.get('features') or {}).get(feature)
|
||||
if isinstance(requested, dict) and isinstance(requested.get('model'), str) and requested['model']:
|
||||
return requested['model']
|
||||
model = metadata.get('model') or {}
|
||||
return ((model.get('info') or {}).get('meta') or {}).get(meta_key) or None
|
||||
|
||||
|
||||
def get_requested_image_model(metadata: dict | None) -> str | None:
|
||||
return get_requested_model(metadata, 'image_generation', 'imageModelId')
|
||||
|
||||
|
||||
async def resolve_image_model(
|
||||
request: Request,
|
||||
user: UserModel,
|
||||
capability: ImageCapability,
|
||||
model: str | None = None,
|
||||
*,
|
||||
strict: bool = False,
|
||||
) -> tuple[dict, str]:
|
||||
"""Pick the connection and model to run a request on.
|
||||
|
||||
Order: the requested model (a reference or a bare model id), then the admin's default for
|
||||
the capability, then the first model the user can use for it. A requested model the user
|
||||
cannot use, or one that cannot do the capability (an edit sent to a generation-only model),
|
||||
falls back to the default unless ``strict`` is set, as on the direct API routes.
|
||||
"""
|
||||
models = await get_image_models(request, user)
|
||||
|
||||
def find(value: str | None) -> dict | None:
|
||||
if not value:
|
||||
return None
|
||||
return next((m for m in models if m['id'] == value), None) or next(
|
||||
(m for m in models if m['model'] == value), None
|
||||
)
|
||||
|
||||
if model:
|
||||
requested = find(model)
|
||||
if requested and requested[capability]:
|
||||
return requested['connection'], requested['model']
|
||||
if strict:
|
||||
detail = (
|
||||
f'Image model "{model}" cannot be used for {capability.replace("_", " ")}'
|
||||
if requested
|
||||
else f'Image model "{model}" was not found'
|
||||
)
|
||||
raise HTTPException(status_code=400, detail=detail)
|
||||
log.debug('Image model %s is not available to %s for %s; using the default', model, user.id, capability)
|
||||
|
||||
default_key = (
|
||||
IMAGE_GENERATION_DEFAULT_MODEL_CONFIG_KEY
|
||||
if capability == 'image_generation'
|
||||
else IMAGE_EDIT_DEFAULT_MODEL_CONFIG_KEY
|
||||
)
|
||||
default = find(await Config.get(default_key))
|
||||
if default and default[capability]:
|
||||
return default['connection'], default['model']
|
||||
|
||||
fallback = next((m for m in models if m[capability]), None)
|
||||
if fallback:
|
||||
return fallback['connection'], fallback['model']
|
||||
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=ERROR_MESSAGES.DEFAULT(
|
||||
'No image model is available'
|
||||
if capability == 'image_generation'
|
||||
else 'No image model that can edit images is available'
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
# Migration from the single-engine settings
|
||||
|
||||
|
||||
def _legacy_generation_connection(values: dict) -> dict | None:
|
||||
connection_type = values.get('image_generation.engine') or 'automatic1111'
|
||||
enabled = bool(values.get('image_generation.enable'))
|
||||
model = values.get('image_generation.model') or ''
|
||||
config: dict[str, Any] = {
|
||||
'size': values.get('image_generation.size') or '',
|
||||
'steps': values.get('image_generation.steps'),
|
||||
}
|
||||
|
||||
if connection_type == 'openai':
|
||||
url = values.get('image_generation.openai.api_base_url') or ''
|
||||
key = values.get('image_generation.openai.api_key') or ''
|
||||
config.update(
|
||||
api_version=values.get('image_generation.openai.api_version') or '',
|
||||
params=values.get('image_generation.openai.params') or {},
|
||||
)
|
||||
model = model or DEFAULT_OPENAI_IMAGE_MODEL
|
||||
configured = bool(url) and (bool(key) or enabled)
|
||||
elif connection_type == 'gemini':
|
||||
url = values.get('image_generation.gemini.api_base_url') or ''
|
||||
key = values.get('image_generation.gemini.api_key') or ''
|
||||
config.update(endpoint_method=values.get('image_generation.gemini.endpoint_method') or '')
|
||||
model = model or DEFAULT_GEMINI_IMAGE_MODEL
|
||||
configured = bool(url) and (bool(key) or enabled)
|
||||
elif connection_type == 'comfyui':
|
||||
url = values.get('image_generation.comfyui.base_url') or ''
|
||||
key = values.get('image_generation.comfyui.api_key') or ''
|
||||
config.update(
|
||||
workflow=values.get('image_generation.comfyui.workflow') or '',
|
||||
nodes=values.get('image_generation.comfyui.nodes') or [],
|
||||
)
|
||||
configured = bool(url)
|
||||
else:
|
||||
connection_type = 'automatic1111'
|
||||
url = values.get('image_generation.automatic1111.base_url') or ''
|
||||
key = values.get('image_generation.automatic1111.api_auth') or ''
|
||||
config.update(params=values.get('image_generation.automatic1111.api_params') or {})
|
||||
configured = bool(url)
|
||||
|
||||
if not configured:
|
||||
return None
|
||||
|
||||
config.update(model_ids=[model], capabilities={'image_generation': True, 'image_edit': False})
|
||||
return {'type': connection_type, 'url': url, 'key': key, 'config': config}
|
||||
|
||||
|
||||
def _legacy_edit_connection(values: dict) -> dict | None:
|
||||
connection_type = values.get('images.edit.engine') or 'openai'
|
||||
enabled = bool(values.get('images.edit.enable'))
|
||||
model = values.get('images.edit.model') or ''
|
||||
config: dict[str, Any] = {'edit_size': values.get('images.edit.size') or ''}
|
||||
|
||||
if connection_type == 'openai':
|
||||
url = values.get('images.edit.openai.api_base_url') or ''
|
||||
key = values.get('images.edit.openai.api_key') or ''
|
||||
config.update(api_version=values.get('images.edit.openai.api_version') or '')
|
||||
model = model or DEFAULT_OPENAI_IMAGE_MODEL
|
||||
configured = bool(url) and (bool(key) or enabled)
|
||||
elif connection_type == 'gemini':
|
||||
url = values.get('images.edit.gemini.api_base_url') or ''
|
||||
key = values.get('images.edit.gemini.api_key') or ''
|
||||
# The edit route builds models/{model}:generateContent, so it never worked without a model.
|
||||
configured = bool(url) and bool(model) and (bool(key) or enabled)
|
||||
elif connection_type == 'comfyui':
|
||||
url = values.get('images.edit.comfyui.base_url') or ''
|
||||
key = values.get('images.edit.comfyui.api_key') or ''
|
||||
config.update(
|
||||
edit_workflow=values.get('images.edit.comfyui.workflow') or '',
|
||||
edit_nodes=values.get('images.edit.comfyui.nodes') or [],
|
||||
)
|
||||
configured = bool(url)
|
||||
else:
|
||||
return None
|
||||
|
||||
if not configured:
|
||||
return None
|
||||
|
||||
config.update(model_ids=[model], capabilities={'image_generation': False, 'image_edit': True})
|
||||
return {'type': connection_type, 'url': url, 'key': key, 'config': config}
|
||||
|
||||
|
||||
LEGACY_IMAGE_CONFIG_KEYS = (
|
||||
'image_generation.enable',
|
||||
'image_generation.engine',
|
||||
'image_generation.model',
|
||||
'image_generation.size',
|
||||
'image_generation.steps',
|
||||
'image_generation.openai.api_base_url',
|
||||
'image_generation.openai.api_key',
|
||||
'image_generation.openai.api_version',
|
||||
'image_generation.openai.params',
|
||||
'image_generation.gemini.api_base_url',
|
||||
'image_generation.gemini.api_key',
|
||||
'image_generation.gemini.endpoint_method',
|
||||
'image_generation.comfyui.base_url',
|
||||
'image_generation.comfyui.api_key',
|
||||
'image_generation.comfyui.workflow',
|
||||
'image_generation.comfyui.nodes',
|
||||
'image_generation.automatic1111.base_url',
|
||||
'image_generation.automatic1111.api_auth',
|
||||
'image_generation.automatic1111.api_params',
|
||||
'images.edit.enable',
|
||||
'images.edit.engine',
|
||||
'images.edit.model',
|
||||
'images.edit.size',
|
||||
'images.edit.openai.api_base_url',
|
||||
'images.edit.openai.api_key',
|
||||
'images.edit.openai.api_version',
|
||||
'images.edit.gemini.api_base_url',
|
||||
'images.edit.gemini.api_key',
|
||||
'images.edit.comfyui.base_url',
|
||||
'images.edit.comfyui.api_key',
|
||||
'images.edit.comfyui.workflow',
|
||||
'images.edit.comfyui.nodes',
|
||||
)
|
||||
|
||||
LEGACY_IMAGE_CONNECTION_NAMES = {
|
||||
'openai': 'OpenAI',
|
||||
'gemini': 'Gemini',
|
||||
'comfyui': 'ComfyUI',
|
||||
'automatic1111': 'AUTOMATIC1111',
|
||||
}
|
||||
|
||||
|
||||
async def migrate_legacy_image_config() -> list[dict]:
|
||||
"""Turn the single generation and edit engine settings into image connections, once.
|
||||
|
||||
The connections key is only written here or by an admin, so its absence marks a deployment
|
||||
that has not been migrated. Both old engines keep working, with everyone who could use them
|
||||
before keeping access.
|
||||
"""
|
||||
connections = await Config.get(IMAGE_CONNECTIONS_CONFIG_KEY)
|
||||
if connections is not None:
|
||||
return connections
|
||||
|
||||
values = await Config.get_many(*LEGACY_IMAGE_CONFIG_KEYS)
|
||||
generation = _legacy_generation_connection(values)
|
||||
edit = _legacy_edit_connection(values)
|
||||
|
||||
folded_edit_model = None
|
||||
if (
|
||||
generation
|
||||
and edit
|
||||
and (generation['type'], generation['url'], generation['key'])
|
||||
== (
|
||||
edit['type'],
|
||||
edit['url'],
|
||||
edit['key'],
|
||||
)
|
||||
):
|
||||
# Same backend for both: one connection, with the edit model and settings folded in.
|
||||
generation_model = generation['config']['model_ids'][0]
|
||||
folded_edit_model = edit['config']['model_ids'][0]
|
||||
for key, value in edit['config'].items():
|
||||
if key not in ('model_ids', 'capabilities'):
|
||||
generation['config'].setdefault(key, value)
|
||||
generation['config']['capabilities'] = {'image_generation': True, 'image_edit': True}
|
||||
if folded_edit_model != generation_model:
|
||||
generation['config']['model_ids'].append(folded_edit_model)
|
||||
edit = None
|
||||
|
||||
connections = []
|
||||
defaults = {IMAGE_GENERATION_DEFAULT_MODEL_CONFIG_KEY: '', IMAGE_EDIT_DEFAULT_MODEL_CONFIG_KEY: ''}
|
||||
for legacy, default_key, suffix in (
|
||||
(generation, IMAGE_GENERATION_DEFAULT_MODEL_CONFIG_KEY, ''),
|
||||
(edit, IMAGE_EDIT_DEFAULT_MODEL_CONFIG_KEY, ' (edit)'),
|
||||
):
|
||||
if legacy is None:
|
||||
continue
|
||||
legacy['config']['access_grants'] = PUBLIC_ACCESS_GRANTS
|
||||
connection = normalize_image_connection(
|
||||
{**legacy, 'name': f'{LEGACY_IMAGE_CONNECTION_NAMES[legacy["type"]]}{suffix}'}
|
||||
)
|
||||
connections.append(connection)
|
||||
# An empty legacy model (ComfyUI, AUTOMATIC1111) becomes the connection's default model.
|
||||
defaults[default_key] = get_image_model_ref(connection['id'], legacy['config']['model_ids'][0])
|
||||
|
||||
if folded_edit_model is not None:
|
||||
defaults[IMAGE_EDIT_DEFAULT_MODEL_CONFIG_KEY] = get_image_model_ref(connections[0]['id'], folded_edit_model)
|
||||
|
||||
await Config.upsert({IMAGE_CONNECTIONS_CONFIG_KEY: connections, **defaults})
|
||||
if connections:
|
||||
log.info('Migrated image generation settings to %d image connection(s)', len(connections))
|
||||
return connections
|
||||
@@ -2,19 +2,19 @@
|
||||
|
||||
from collections import defaultdict
|
||||
|
||||
from open_webui.models.notifications import Notification, insert_notifications
|
||||
from sqlalchemy import and_, false, or_, select, true
|
||||
from sqlalchemy.orm import load_only
|
||||
|
||||
from open_webui.models.notifications import Notification, insert_notifications
|
||||
|
||||
|
||||
def source_models():
|
||||
from open_webui.utils.comments import resource_models
|
||||
from open_webui.models.automations import Automation, AutomationRun
|
||||
from open_webui.models.calendar import Calendar, CalendarEvent
|
||||
from open_webui.models.channels import Channel
|
||||
from open_webui.models.chat_messages import ChatMessage
|
||||
from open_webui.models.comments import Comment
|
||||
from open_webui.models.messages import Message
|
||||
from open_webui.utils.comments import resource_models
|
||||
|
||||
return {
|
||||
**resource_models(),
|
||||
@@ -23,6 +23,7 @@ def source_models():
|
||||
'calendar': Calendar,
|
||||
'calendar_event': CalendarEvent,
|
||||
'channel': Channel,
|
||||
'chat_message': ChatMessage,
|
||||
'comment': Comment,
|
||||
'message': Message,
|
||||
}
|
||||
@@ -52,6 +53,15 @@ async def validate_source(event_type, resource_type, resource_id, object_type, o
|
||||
)
|
||||
elif event_type.startswith('channel.'):
|
||||
valid = object_type == 'message' and resource_type == 'channel' and obj.channel_id == resource_id
|
||||
elif event_type == 'chat.mentioned':
|
||||
valid = (
|
||||
object_type == 'chat_message'
|
||||
and resource_type == 'chat'
|
||||
and obj.chat_id == resource_id
|
||||
and obj.role == 'assistant'
|
||||
and obj.done
|
||||
and not obj.error
|
||||
)
|
||||
elif event_type == 'automation.run_failed':
|
||||
valid = (
|
||||
object_type == 'automation_run'
|
||||
@@ -92,6 +102,7 @@ async def resource_queries(user, db):
|
||||
'calendar.enable',
|
||||
'automations.enable',
|
||||
'user.permissions',
|
||||
db=db,
|
||||
)
|
||||
admin = user.role == 'admin'
|
||||
|
||||
@@ -115,27 +126,26 @@ async def resource_queries(user, db):
|
||||
else or_(model.user_id == user.id, grant(kind, model.id))
|
||||
)
|
||||
queries[kind] = select(model.id).where(allowed)
|
||||
if config.get('comments.enable'):
|
||||
chat = models['chat']
|
||||
# UNION (not UNION ALL) terminates even if legacy folder data contains a cycle.
|
||||
folders = (
|
||||
select(Folder.id)
|
||||
.where(or_(Folder.user_id == user.id, grant('folder', Folder.id)))
|
||||
.cte('inbox_folders', recursive=True)
|
||||
)
|
||||
folders = folders.union(select(Folder.id).join(folders, Folder.parent_id == folders.c.id))
|
||||
shared = select(SharedChat.chat_id).where(
|
||||
SharedChat.chat['share_mode'].as_string() == 'continue', grant('shared_chat', SharedChat.chat_id)
|
||||
)
|
||||
queries['chat'] = select(chat.id).where(
|
||||
or_(
|
||||
chat.user_id == user.id,
|
||||
true() if admin and ENABLE_ADMIN_CHAT_ACCESS else false(),
|
||||
and_(true() if admin else false(), chat.meta['internal'].as_boolean().is_(True)),
|
||||
chat.id.in_(shared),
|
||||
chat.folder_id.in_(select(folders.c.id)),
|
||||
)
|
||||
chat = models['chat']
|
||||
# UNION (not UNION ALL) terminates even if legacy folder data contains a cycle.
|
||||
folders = (
|
||||
select(Folder.id)
|
||||
.where(or_(Folder.user_id == user.id, grant('folder', Folder.id)))
|
||||
.cte('inbox_folders', recursive=True)
|
||||
)
|
||||
folders = folders.union(select(Folder.id).join(folders, Folder.parent_id == folders.c.id))
|
||||
shared = select(SharedChat.chat_id).where(
|
||||
SharedChat.chat['share_mode'].as_string() == 'continue', grant('shared_chat', SharedChat.chat_id)
|
||||
)
|
||||
queries['chat'] = select(chat.id).where(
|
||||
or_(
|
||||
chat.user_id == user.id,
|
||||
true() if admin and ENABLE_ADMIN_CHAT_ACCESS else false(),
|
||||
and_(true() if admin else false(), chat.meta['internal'].as_boolean().is_(True)),
|
||||
chat.id.in_(shared),
|
||||
chat.folder_id.in_(select(folders.c.id)),
|
||||
)
|
||||
)
|
||||
if await enabled('channels'):
|
||||
channel = models['channel']
|
||||
member = (
|
||||
@@ -169,14 +179,22 @@ async def resource_queries(user, db):
|
||||
|
||||
|
||||
async def eligible_recipients(recipients, resource_type, resource_id, actor_id, db):
|
||||
from open_webui.models.chats import Chats
|
||||
from open_webui.models.config import Config
|
||||
from open_webui.models.users import User, UserModel
|
||||
|
||||
if not await Config.get('comments.enable'):
|
||||
recipients = {id: kind for id, kind in recipients.items() if not kind.startswith('comment.')}
|
||||
users = (await db.scalars(select(User).where(User.id.in_(recipients), User.role.in_(['user', 'admin'])))).all()
|
||||
eligible = {}
|
||||
for row in users:
|
||||
kind = recipients[row.id]
|
||||
if row.id == actor_id and kind.startswith(('comment.', 'channel.')):
|
||||
continue
|
||||
if kind == 'chat.mentioned':
|
||||
if await Chats.has_chat_access(resource_id, UserModel.model_validate(row), permission='read', db=db):
|
||||
eligible[row.id] = kind
|
||||
continue
|
||||
if resource_type is not None:
|
||||
queries = await resource_queries(UserModel.model_validate(row), db=db)
|
||||
query = queries.get(resource_type)
|
||||
@@ -189,7 +207,10 @@ async def eligible_recipients(recipients, resource_type, resource_id, actor_id,
|
||||
|
||||
|
||||
async def visible_clause(user, db):
|
||||
from open_webui.models.config import Config
|
||||
|
||||
queries = await resource_queries(user, db=db)
|
||||
comments_enabled = await Config.get('comments.enable', db=db)
|
||||
models = source_models()
|
||||
resources = or_(
|
||||
*[
|
||||
@@ -201,13 +222,18 @@ async def visible_clause(user, db):
|
||||
for kind, parent_column, events in (
|
||||
('comment', 'resource_id', ['comment.created', 'comment.replied', 'comment.mentioned']),
|
||||
('message', 'channel_id', ['channel.mentioned', 'channel.replied']),
|
||||
('chat_message', 'chat_id', ['chat.mentioned']),
|
||||
('automation_run', 'automation_id', ['automation.run_failed']),
|
||||
('calendar_event', 'calendar_id', ['calendar.alert']),
|
||||
):
|
||||
model = models[kind]
|
||||
conditions = [model.id == Notification.object_id, getattr(model, parent_column) == Notification.resource_id]
|
||||
if kind == 'comment':
|
||||
conditions += [model.resource_type == Notification.resource_type, model.deleted_at.is_(None)]
|
||||
conditions += [
|
||||
true() if comments_enabled else false(),
|
||||
model.resource_type == Notification.resource_type,
|
||||
model.deleted_at.is_(None),
|
||||
]
|
||||
if kind == 'calendar_event':
|
||||
conditions.append(model.is_cancelled.is_(False))
|
||||
objects.append(
|
||||
@@ -234,6 +260,20 @@ async def visible_clause(user, db):
|
||||
)
|
||||
|
||||
|
||||
def chat_message_text(message):
|
||||
from open_webui.utils.misc import get_output_text
|
||||
|
||||
if isinstance(message.output, list):
|
||||
return get_output_text(message.output)
|
||||
if isinstance(message.content, str):
|
||||
return message.content
|
||||
return ''.join(
|
||||
part.get('text', '')
|
||||
for part in message.content or []
|
||||
if isinstance(part, dict) and part.get('type') in {'text', 'output_text'}
|
||||
)
|
||||
|
||||
|
||||
async def hydrate(rows, db):
|
||||
"""Fetch each actor/resource/object type once, never once per notification."""
|
||||
from open_webui.models.users import User
|
||||
@@ -252,19 +292,20 @@ async def hydrate(rows, db):
|
||||
fields = ['id', 'title', 'name']
|
||||
if kind in {'comment', 'message'}:
|
||||
fields += ['content', 'target_type', 'target_id', 'parent_id']
|
||||
elif kind == 'chat_message':
|
||||
fields += ['content', 'output', 'chat_id']
|
||||
columns = [getattr(model, field) for field in fields if hasattr(model, field)]
|
||||
objects[kind] = {
|
||||
obj.id: obj
|
||||
for obj in (await db.scalars(select(model).options(load_only(*columns)).where(model.id.in_(values)))).all()
|
||||
}
|
||||
actors = {
|
||||
user_ids = {r.actor_id for r in rows if r.actor_id}
|
||||
for message in objects.get('chat_message', {}).values():
|
||||
user_ids.update(mentioned_users(chat_message_text(message)))
|
||||
users = {
|
||||
u.id: {'id': u.id, 'name': u.name}
|
||||
for u in (
|
||||
await db.scalars(
|
||||
select(User)
|
||||
.options(load_only(User.id, User.name))
|
||||
.where(User.id.in_({r.actor_id for r in rows if r.actor_id}))
|
||||
)
|
||||
await db.scalars(select(User).options(load_only(User.id, User.name)).where(User.id.in_(user_ids)))
|
||||
).all()
|
||||
}
|
||||
result = []
|
||||
@@ -282,12 +323,19 @@ async def hydrate(rows, db):
|
||||
data.update(target_type=obj.target_type, target_id=obj.target_id, parent_id=obj.parent_id)
|
||||
elif row.object_type == 'message':
|
||||
data['parent_id'] = obj.parent_id
|
||||
elif row.object_type == 'chat_message':
|
||||
content = chat_message_text(obj)
|
||||
for id in mentioned_users(content):
|
||||
if id in users:
|
||||
content = content.replace(f'<@U:{id}>', f'@{users[id]["name"]}')
|
||||
preview = replace_mentions(content)[:300]
|
||||
data['message_id'] = obj.id.removeprefix(f'{obj.chat_id}-')
|
||||
elif row.object_type == 'calendar_event':
|
||||
title = obj.title
|
||||
result.append(
|
||||
{
|
||||
**{c.name: getattr(row, c.name) for c in Notification.__table__.columns},
|
||||
'actor': actors.get(row.actor_id),
|
||||
'actor': users.get(row.actor_id),
|
||||
'title': title,
|
||||
'preview': preview,
|
||||
'data': data,
|
||||
@@ -382,7 +430,32 @@ async def consume_event(event, db):
|
||||
|
||||
subject_id = (event.subject or {}).get('id')
|
||||
models = source_models()
|
||||
if event.event in {EVENTS.COMMENT_CREATED.name, EVENTS.COMMENT_UPDATED.name}:
|
||||
if event.event == EVENTS.CHAT_FINISHED.name:
|
||||
from open_webui.utils.chat_id import is_saved_chat_id
|
||||
|
||||
message_id = event.data.get('message_id')
|
||||
if not is_saved_chat_id(subject_id) or not message_id:
|
||||
return set()
|
||||
message = await db.get(models['chat_message'], f'{subject_id}-{message_id}')
|
||||
if (
|
||||
not message
|
||||
or message.chat_id != subject_id
|
||||
or message.role != 'assistant'
|
||||
or not message.done
|
||||
or message.error
|
||||
):
|
||||
return set()
|
||||
return await insert_notifications(
|
||||
recipients={id: 'chat.mentioned' for id in mentioned_users(chat_message_text(message))},
|
||||
event_key=f'chat:{subject_id}:message:{message_id}:mentioned',
|
||||
resource_type='chat',
|
||||
resource_id=subject_id,
|
||||
object_type='chat_message',
|
||||
object_id=message.id,
|
||||
data={'model_name': event.data.get('model_name') or message.model_id or 'Assistant'},
|
||||
db=db,
|
||||
)
|
||||
elif event.event in {EVENTS.COMMENT_CREATED.name, EVENTS.COMMENT_UPDATED.name}:
|
||||
comment = await db.get(models['comment'], subject_id)
|
||||
if not comment or comment.deleted_at:
|
||||
raise ValueError('Comment event references an unavailable comment')
|
||||
|
||||
@@ -2,6 +2,7 @@ import asyncio
|
||||
import base64
|
||||
import logging
|
||||
import math
|
||||
from contextlib import AsyncExitStack
|
||||
from typing import Optional
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
@@ -77,6 +78,7 @@ class MCPClient:
|
||||
def __init__(self, event_caller=None, server_name=''):
|
||||
self.client: Optional[Client] = None
|
||||
self.session_task: Optional[asyncio.Task] = None
|
||||
self.connect_kwargs: Optional[dict] = None
|
||||
self.event_caller = event_caller
|
||||
self.server_name = server_name
|
||||
self.instructions: Optional[str] = None
|
||||
@@ -117,27 +119,47 @@ class MCPClient:
|
||||
log.warning('MCP elicitation failed: %s', type(e).__name__)
|
||||
return ElicitResult(action='cancel')
|
||||
|
||||
async def connect(self, url: str, headers: Optional[dict] = None, auth: Optional[httpx2.Auth] = None):
|
||||
async def connect(
|
||||
self,
|
||||
url: str,
|
||||
headers: Optional[dict] = None,
|
||||
auth: Optional[httpx2.Auth] = None,
|
||||
tether: Optional[dict] = None,
|
||||
):
|
||||
self.connect_kwargs = {'url': url, 'headers': headers, 'auth': auth, 'tether': tether}
|
||||
# A failed request makes the SDK cancel the task that opened the session, so it gets its own task.
|
||||
connected = asyncio.get_running_loop().create_future()
|
||||
self.session_task = asyncio.create_task(self.run_session(url, headers, auth, connected))
|
||||
self.session_task = asyncio.create_task(self.run_session(url, headers, auth, connected, tether))
|
||||
try:
|
||||
await connected
|
||||
except BaseException:
|
||||
await self.disconnect()
|
||||
# Keep connect_kwargs so the next tool call can try again.
|
||||
await self.close_session()
|
||||
raise
|
||||
|
||||
async def run_session(
|
||||
self, url: str, headers: Optional[dict], auth: Optional[httpx2.Auth], connected: asyncio.Future
|
||||
self,
|
||||
url: str,
|
||||
headers: Optional[dict],
|
||||
auth: Optional[httpx2.Auth],
|
||||
connected: asyncio.Future,
|
||||
tether: Optional[dict] = None,
|
||||
) -> None:
|
||||
try:
|
||||
async with create_httpx_client(headers=headers, auth=auth) as http_client:
|
||||
async with AsyncExitStack() as stack:
|
||||
if tether:
|
||||
from open_webui.utils.mcp.tether import tether_transport
|
||||
|
||||
transport = tether_transport(**tether)
|
||||
else:
|
||||
http_client = await stack.enter_async_context(create_httpx_client(headers=headers, auth=auth))
|
||||
transport = streamable_http_client(url, http_client=http_client, max_sse_event_size=None)
|
||||
# mode='auto' (the default) probes server/discover for the stateless
|
||||
# 2026-07-28 protocol and falls back to the initialize handshake on
|
||||
# legacy servers. The read timeout bounds that handshake and every
|
||||
# later request that does not set its own; the SDK caps the probe itself.
|
||||
async with Client(
|
||||
streamable_http_client(url, http_client=http_client),
|
||||
transport,
|
||||
extensions=[advertise('io.modelcontextprotocol/ui', {'mimeTypes': ['text/html;profile=mcp-app']})],
|
||||
read_timeout_seconds=MCP_INITIALIZE_TIMEOUT,
|
||||
elicitation_callback=self.elicit if self.event_caller else None,
|
||||
@@ -188,6 +210,9 @@ class MCPClient:
|
||||
return tool_specs
|
||||
|
||||
async def call_tool_raw(self, function_name: str, function_args: dict) -> dict:
|
||||
if not self.client and self.connect_kwargs:
|
||||
# The session ends for good when the server drops it, e.g. on a restart.
|
||||
await self.connect(**self.connect_kwargs)
|
||||
if not self.client:
|
||||
raise RuntimeError('MCP client is not connected.')
|
||||
|
||||
@@ -322,11 +347,15 @@ class MCPClient:
|
||||
return result_dict
|
||||
|
||||
async def disconnect(self):
|
||||
"""Clean up and close the session.
|
||||
"""Clean up and close the session, and stop later tool calls from reconnecting.
|
||||
|
||||
This method is idempotent — calling it multiple times or on a
|
||||
client that was never connected is safe.
|
||||
"""
|
||||
self.connect_kwargs = None
|
||||
await self.close_session()
|
||||
|
||||
async def close_session(self):
|
||||
session_task = self.session_task
|
||||
if session_task is None:
|
||||
return
|
||||
|
||||
@@ -0,0 +1,187 @@
|
||||
"""MCP transports over Tether. Commands, endpoints and credentials stay on the device."""
|
||||
|
||||
import time
|
||||
from contextlib import asynccontextmanager
|
||||
|
||||
import aiohttp
|
||||
import anyio
|
||||
import httpx2
|
||||
import mcp_types
|
||||
from mcp.client.streamable_http import streamable_http_client
|
||||
from mcp.shared.message import SessionMessage
|
||||
from open_webui.models.auth_sessions import AuthSessions
|
||||
from open_webui.utils.tether import CHUNK, MAX_MESSAGE, RelayClient, RelayInterrupted, hub
|
||||
|
||||
|
||||
class Target:
|
||||
def __init__(self, user_id, device_id, service, transport):
|
||||
self.user_id, self.device_id, self.service, self.transport = user_id, device_id, service, transport
|
||||
self.connection = None
|
||||
self.revision = None
|
||||
|
||||
async def check(self):
|
||||
presence = await hub.presence(self.user_id, self.device_id)
|
||||
if not presence or presence['user'] != self.user_id or self.service not in presence.get('services', []):
|
||||
raise RelayInterrupted('MCP service unavailable')
|
||||
item = next(
|
||||
(
|
||||
item
|
||||
for item in presence.get('connections', [])
|
||||
if item['service'] == self.service and item['type'] == 'mcp' and item.get('transport') == self.transport
|
||||
),
|
||||
None,
|
||||
)
|
||||
if item is None:
|
||||
raise RelayInterrupted('MCP service unavailable')
|
||||
revision = item.get('revision', '')
|
||||
if self.revision is not None and self.revision != revision:
|
||||
raise RelayInterrupted('MCP configuration changed; reconnect before making another call')
|
||||
self.revision = revision
|
||||
row = await AuthSessions.get(presence['session'])
|
||||
if not row or row.user_id != self.user_id or row.refresh_token_id is None or row.expires_at <= time.time():
|
||||
raise RelayInterrupted('MCP sign-in expired')
|
||||
if self.connection is not None and self.connection != presence['connection']:
|
||||
raise RelayInterrupted('MCP connection changed; reconnect before making another call')
|
||||
self.connection = presence['connection']
|
||||
|
||||
|
||||
class ResponseStream(httpx2.AsyncByteStream):
|
||||
def __init__(self, response):
|
||||
self.response = response
|
||||
|
||||
async def __aiter__(self):
|
||||
try:
|
||||
async for data in self.response.iter_any():
|
||||
yield data
|
||||
except RelayInterrupted as error:
|
||||
raise httpx2.ReadError(str(error)) from error
|
||||
|
||||
async def aclose(self):
|
||||
await self.response.close()
|
||||
|
||||
|
||||
class MCPRelayClient(RelayClient):
|
||||
def __init__(self, target):
|
||||
super().__init__(target.user_id, target.service)
|
||||
self.target = target
|
||||
|
||||
async def _open(self, device):
|
||||
stream = await super()._open(device)
|
||||
if stream.presence['connection'] != self.target.connection:
|
||||
await stream.close()
|
||||
raise RelayInterrupted('MCP connection changed before the request was sent')
|
||||
return stream
|
||||
|
||||
|
||||
class TetherHTTPTransport(httpx2.AsyncBaseTransport):
|
||||
def __init__(self, target):
|
||||
self.target = target
|
||||
self.relay = MCPRelayClient(target)
|
||||
|
||||
async def handle_async_request(self, request):
|
||||
# A synthetic endpoint keeps local URLs out of the backend. Reject redirects
|
||||
# and alternate paths even when the MCP SDK follows them itself.
|
||||
if str(request.url) != 'http://tether.invalid/':
|
||||
raise httpx2.RequestError('Only the configured MCP endpoint is available', request=request)
|
||||
await self.target.check()
|
||||
timeout = request.extensions.get('timeout', {})
|
||||
try:
|
||||
response = await self.relay.request(
|
||||
request.method,
|
||||
f'tether://{self.target.device_id}/',
|
||||
headers=dict(request.headers),
|
||||
data=request.stream,
|
||||
idempotent=False,
|
||||
revision=self.target.revision,
|
||||
timeout=aiohttp.ClientTimeout(total=None, sock_read=timeout.get('read', 300)),
|
||||
)
|
||||
except RelayInterrupted as error:
|
||||
raise httpx2.ReadError(str(error), request=request) from error
|
||||
return httpx2.Response(response.status, headers=dict(response.headers), stream=ResponseStream(response))
|
||||
|
||||
async def aclose(self):
|
||||
await self.relay.close()
|
||||
|
||||
|
||||
async def read_stdio(stream, incoming_writer):
|
||||
buffer = bytearray()
|
||||
async with incoming_writer:
|
||||
while True:
|
||||
header, data = await stream.receive()
|
||||
if header['type'] == 'end':
|
||||
if buffer:
|
||||
raise ValueError('Incomplete MCP message')
|
||||
return
|
||||
if header['type'] != 'data':
|
||||
raise ValueError('Invalid MCP stream')
|
||||
buffer.extend(data)
|
||||
if len(buffer) > MAX_MESSAGE:
|
||||
raise ValueError('MCP message too large')
|
||||
# Replenish credit before waiting for a complete line: messages may
|
||||
# exceed the relay window, but never the separate framing limit.
|
||||
await stream.consumed(len(data))
|
||||
while b'\n' in buffer:
|
||||
line, _, rest = buffer.partition(b'\n')
|
||||
buffer = bytearray(rest)
|
||||
message = mcp_types.jsonrpc_message_adapter.validate_json(line, by_name=False)
|
||||
await incoming_writer.send(SessionMessage(message))
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def stdio_transport(target):
|
||||
await target.check()
|
||||
stream = await hub.open(target.user_id, target.device_id, target.service)
|
||||
if stream.presence['connection'] != target.connection:
|
||||
await stream.close()
|
||||
raise RelayInterrupted('Connection changed before the process was started')
|
||||
incoming_writer, incoming = anyio.create_memory_object_stream(0)
|
||||
outgoing, outgoing_reader = anyio.create_memory_object_stream(0)
|
||||
|
||||
async def write():
|
||||
async with outgoing_reader:
|
||||
async for message in outgoing_reader:
|
||||
await target.check()
|
||||
data = (message.message.model_dump_json(by_alias=True, exclude_unset=True) + '\n').encode()
|
||||
if len(data) > MAX_MESSAGE:
|
||||
raise ValueError('MCP message too large')
|
||||
for offset in range(0, len(data), CHUNK):
|
||||
await stream.send('data', data[offset : offset + CHUNK])
|
||||
|
||||
try:
|
||||
with anyio.fail_after(15):
|
||||
await stream.send('stdio-open', service=target.service, revision=target.revision)
|
||||
header, _ = await stream.receive()
|
||||
if header['type'] != 'stdio-ready':
|
||||
raise ValueError('MCP process did not start')
|
||||
async with anyio.create_task_group() as tasks:
|
||||
tasks.start_soon(read_stdio, stream, incoming_writer)
|
||||
tasks.start_soon(write)
|
||||
try:
|
||||
yield incoming, outgoing
|
||||
finally:
|
||||
tasks.cancel_scope.cancel()
|
||||
finally:
|
||||
with anyio.CancelScope(shield=True):
|
||||
await stream.close()
|
||||
await incoming.aclose()
|
||||
await incoming_writer.aclose()
|
||||
await outgoing.aclose()
|
||||
await outgoing_reader.aclose()
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def tether_transport(user_id, device_id, service, transport):
|
||||
target = Target(user_id, device_id, service, transport)
|
||||
if transport == 'stdio':
|
||||
async with stdio_transport(target) as streams:
|
||||
yield streams
|
||||
elif transport == 'streamable-http':
|
||||
async with httpx2.AsyncClient(
|
||||
transport=TetherHTTPTransport(target), timeout=httpx2.Timeout(30, read=300)
|
||||
) as http:
|
||||
async with streamable_http_client(
|
||||
'http://tether.invalid/', http_client=http, max_sse_event_size=None
|
||||
) as streams:
|
||||
yield streams
|
||||
else:
|
||||
raise ValueError('Unsupported MCP transport')
|
||||
@@ -287,7 +287,24 @@ def model_allows_memory(model: dict | None) -> bool:
|
||||
return ((model or {}).get('info', {}).get('meta', {}).get('capabilities') or {}).get('memory', True)
|
||||
|
||||
|
||||
async def recall_memories(request, messages: list[dict], user, model: dict | None = None) -> str:
|
||||
async def memory_context_enabled(user, features: dict) -> bool:
|
||||
"""Whether this request asked for memory context and the user may have it."""
|
||||
if not (
|
||||
features.get('memory')
|
||||
and await Config.get('memories.enable')
|
||||
and await Config.get('memories.system_context.enable')
|
||||
):
|
||||
return False
|
||||
# features is client-supplied; re-check the permission the native FC path enforces.
|
||||
return getattr(user, 'role', None) == 'admin' or await has_permission(
|
||||
getattr(user, 'id', ''),
|
||||
'features.memories',
|
||||
await Config.get('user.permissions'),
|
||||
)
|
||||
|
||||
|
||||
async def recall_memories(request, messages: list[dict], user, model: dict | None = None, sent: str = '') -> str:
|
||||
"""Recall memories for the latest turn, leaving out any whose line is already in the earlier recall text `sent`."""
|
||||
if not model_allows_memory(model):
|
||||
return ''
|
||||
|
||||
@@ -371,7 +388,12 @@ async def recall_memories(request, messages: list[dict], user, model: dict | Non
|
||||
('Relevant Context', 'context'),
|
||||
):
|
||||
if sections[key]:
|
||||
ordered = sorted(sections[key], key=lambda memory: (memory.casefold(), memory))
|
||||
ordered = sorted(
|
||||
(memory for memory in sections[key] if f'- {memory}\n' not in sent),
|
||||
key=lambda memory: (memory.casefold(), memory),
|
||||
)
|
||||
if not ordered:
|
||||
continue
|
||||
parts.append(f'[{title}]\n' + '\n'.join(f'- {memory}' for memory in ordered))
|
||||
if not parts:
|
||||
return ''
|
||||
@@ -500,7 +522,7 @@ async def _review_memory(
|
||||
role = message.get('role', '')
|
||||
content = message.get('content', '')
|
||||
if not isinstance(content, str):
|
||||
content = get_content_from_message(message)
|
||||
content = get_content_from_message(message) or ''
|
||||
content = content.strip()
|
||||
if role not in {'user', 'assistant'} or not content:
|
||||
continue
|
||||
|
||||
@@ -45,8 +45,9 @@ from open_webui.env import (
|
||||
GLOBAL_LOG_LEVEL,
|
||||
RAG_SYSTEM_CONTEXT,
|
||||
)
|
||||
from open_webui.events import EVENTS, publish_event
|
||||
from open_webui.events import EVENTS, build_event, publish_event
|
||||
from open_webui.models.access_grants import AccessGrants
|
||||
from open_webui.models.chat_messages import ChatMessages
|
||||
from open_webui.models.chats import Chats
|
||||
from open_webui.models.config import Config
|
||||
from open_webui.models.folders import Folders
|
||||
@@ -89,7 +90,7 @@ from open_webui.utils.auth import get_verified_user_by_id
|
||||
from open_webui.utils.chat import generate_chat_completion
|
||||
from open_webui.utils.chat_id import is_saved_chat_id, is_temporary_chat_id
|
||||
from open_webui.utils.code_interpreter import execute_code_jupyter
|
||||
from open_webui.utils.context_compaction import apply_summary_checkpoint, compact_messages_for_request
|
||||
from open_webui.utils.context_compaction import apply_summary_checkpoint, compact_messages, split_messages
|
||||
from open_webui.utils.files import (
|
||||
convert_markdown_base64_images,
|
||||
get_file_url_from_base64,
|
||||
@@ -102,9 +103,15 @@ from open_webui.utils.filter import (
|
||||
get_filter_functions,
|
||||
process_filter_functions,
|
||||
)
|
||||
from open_webui.utils.images.connections import get_requested_image_model
|
||||
from open_webui.utils.json_codec import JSONCodec, dumps_bytes
|
||||
from open_webui.utils.mcp.apps import MCPAppResult
|
||||
from open_webui.utils.memory import add_memory_context, recall_memories, review_memory_after_turn
|
||||
from open_webui.utils.memory import (
|
||||
add_memory_context,
|
||||
memory_context_enabled,
|
||||
recall_memories,
|
||||
review_memory_after_turn,
|
||||
)
|
||||
from open_webui.utils.misc import (
|
||||
add_or_update_system_message,
|
||||
add_or_update_user_message,
|
||||
@@ -112,6 +119,7 @@ from open_webui.utils.misc import (
|
||||
extract_urls,
|
||||
get_content_from_message,
|
||||
get_last_assistant_message,
|
||||
get_last_tool_result,
|
||||
get_last_user_message,
|
||||
get_last_user_message_item,
|
||||
get_message_list,
|
||||
@@ -120,6 +128,8 @@ from open_webui.utils.misc import (
|
||||
get_reasoning_details,
|
||||
get_response_error_detail,
|
||||
get_system_message,
|
||||
get_tool_results,
|
||||
is_empty_reply,
|
||||
is_raster_image_content_type,
|
||||
merge_system_messages,
|
||||
prepend_to_first_user_message_content,
|
||||
@@ -151,7 +161,6 @@ from open_webui.utils.task import (
|
||||
rag_template,
|
||||
tools_function_calling_generation_template,
|
||||
)
|
||||
from open_webui.utils.tether import get_terminal_connections
|
||||
from open_webui.utils.terminals import filter_user_terminal_tools, upload_files_to_terminal
|
||||
from open_webui.utils.tool_approval import complete_tool_call, pending_tool_calls
|
||||
from open_webui.utils.tool_permissions import (
|
||||
@@ -166,7 +175,7 @@ from open_webui.utils.tool_calling import (
|
||||
final_answer_payload,
|
||||
prepare_tool_call,
|
||||
recover_tool_calls,
|
||||
set_tool_call_visibility,
|
||||
set_tool_call_metadata,
|
||||
split_tool_calls,
|
||||
tool_repetition_error,
|
||||
)
|
||||
@@ -245,7 +254,8 @@ async def publish_chat_finished_event(
|
||||
|
||||
content = content or get_output_text(output)
|
||||
webui_url = await Config.get('webui.url')
|
||||
await publish_event(
|
||||
model = (getattr(request.app.state, 'MODELS', {}) or {}).get(metadata.get('model_id'), {})
|
||||
event = build_event(
|
||||
request,
|
||||
EVENTS.CHAT_FINISHED,
|
||||
actor=user,
|
||||
@@ -256,12 +266,25 @@ async def publish_chat_finished_event(
|
||||
'chat_id': chat_id,
|
||||
'message_id': metadata.get('message_id'),
|
||||
'model_id': metadata.get('model_id'),
|
||||
'model_name': model.get('name'),
|
||||
'title': title,
|
||||
'url': f'{webui_url}/c/{chat_id}' if webui_url else f'/c/{chat_id}',
|
||||
'message': content,
|
||||
},
|
||||
message=title or 'Chat finished',
|
||||
)
|
||||
try:
|
||||
from open_webui.internal.db import get_async_db_context
|
||||
from open_webui.models.notifications import emit_changes
|
||||
from open_webui.utils.inbox import consume_event
|
||||
|
||||
async with get_async_db_context() as db:
|
||||
recipients = await consume_event(event, db=db)
|
||||
await db.commit()
|
||||
await emit_changes(recipients)
|
||||
except Exception:
|
||||
log.exception('Chat mention notification failed for %s', chat_id)
|
||||
await publish_event(request, event)
|
||||
event_emitter = await get_event_emitter(metadata, update_db=False)
|
||||
if event_emitter:
|
||||
folder_id = metadata.get('folder_id') or await Chats.get_chat_folder_id(chat_id, metadata.get('user_id'))
|
||||
@@ -714,7 +737,6 @@ async def process_tool_result(
|
||||
tool_function_name,
|
||||
tool_result,
|
||||
tool_type,
|
||||
direct_tool=False,
|
||||
metadata=None,
|
||||
user=None,
|
||||
):
|
||||
@@ -767,9 +789,7 @@ async def process_tool_result(
|
||||
else:
|
||||
tool_result = tool_result.body.decode('utf-8', 'replace')
|
||||
|
||||
elif (tool_type in EXTERNAL_TOOL_TYPES and isinstance(tool_result, tuple)) or (
|
||||
direct_tool and isinstance(tool_result, list) and len(tool_result) == 2
|
||||
):
|
||||
elif tool_type in EXTERNAL_TOOL_TYPES and isinstance(tool_result, tuple):
|
||||
tool_result, tool_response_headers = tool_result
|
||||
|
||||
try:
|
||||
@@ -1019,7 +1039,7 @@ async def chat_completion_tools_handler(
|
||||
|
||||
recent_messages = messages[-4:] if len(messages) > 4 else messages
|
||||
chat_history = '\n'.join(
|
||||
f'{message["role"].upper()}: """{get_content_from_message(message)}"""' for message in recent_messages
|
||||
f'{message["role"].upper()}: """{get_content_from_message(message) or ""}"""' for message in recent_messages
|
||||
)
|
||||
|
||||
prompt = f'History:\n{chat_history}\nQuery: {user_message}' if chat_history else f'Query: {user_message}'
|
||||
@@ -1096,10 +1116,9 @@ async def chat_completion_tools_handler(
|
||||
|
||||
tool = None
|
||||
tool_type = ''
|
||||
direct_tool = False
|
||||
|
||||
try:
|
||||
tool_function_params, tool_result, tool, tool_type, direct_tool = await execute_tool_call(
|
||||
tool_function_params, tool_result, tool, tool_type = await execute_tool_call(
|
||||
body,
|
||||
{**metadata, 'tools': tools},
|
||||
event_caller,
|
||||
@@ -1114,7 +1133,6 @@ async def chat_completion_tools_handler(
|
||||
tool_function_name,
|
||||
tool_result,
|
||||
tool_type,
|
||||
direct_tool,
|
||||
metadata,
|
||||
user,
|
||||
)
|
||||
@@ -1510,7 +1528,7 @@ async def chat_image_generation_handler(request: Request, form_data: dict, extra
|
||||
try:
|
||||
images = await image_edits(
|
||||
request=request,
|
||||
form_data=EditImageForm(**{'prompt': prompt, 'image': input_images}),
|
||||
form_data=EditImageForm(prompt=prompt, image=input_images, model=get_requested_image_model(metadata)),
|
||||
metadata=image_metadata,
|
||||
user=user,
|
||||
)
|
||||
@@ -1622,7 +1640,7 @@ async def chat_image_generation_handler(request: Request, form_data: dict, extra
|
||||
try:
|
||||
images = await image_generations(
|
||||
request=request,
|
||||
form_data=CreateImageForm(**{'prompt': prompt}),
|
||||
form_data=CreateImageForm(prompt=prompt, model=get_requested_image_model(metadata)),
|
||||
metadata=image_metadata,
|
||||
user=user,
|
||||
)
|
||||
@@ -1877,9 +1895,7 @@ async def load_messages_from_db(chat_id: str, message_id: str) -> Optional[list[
|
||||
set_last_user_message_content(skills_create['expanded_text'], [msg])
|
||||
|
||||
return [
|
||||
{k: v for k, v in msg.items() if k in MESSAGE_REPLAY_KEYS}
|
||||
for msg in db_messages
|
||||
if not (msg.get('role') == 'assistant' and not msg.get('content') and not msg.get('output'))
|
||||
{k: v for k, v in msg.items() if k in MESSAGE_REPLAY_KEYS} for msg in db_messages if not is_empty_reply(msg)
|
||||
]
|
||||
|
||||
|
||||
@@ -2141,6 +2157,38 @@ async def process_chat_payload(request, form_data, user, metadata, model):
|
||||
filter_functions = (
|
||||
await get_filter_functions(request, model, metadata.get('filter_ids', [])) if ENABLE_FUNCTIONS else []
|
||||
)
|
||||
event_emitter = await get_event_emitter(metadata)
|
||||
initial_output = []
|
||||
# What the model is told is available, by the hidden tool that reports it; added after compaction, and only
|
||||
# when the history the model sees does not already end with the same manifest.
|
||||
manifests: dict[str, str] = {}
|
||||
|
||||
async def emit_initial_output():
|
||||
await event_emitter({'type': 'chat:completion', 'data': {'output': initial_output}})
|
||||
|
||||
async def compact_history(messages: list[dict], summary_form_data: dict | None):
|
||||
"""Compact the history, shown in this response's output while it runs; only a failure stays."""
|
||||
split = await split_messages(messages, metadata, chat_system_prompt)
|
||||
item = None
|
||||
# A continued reply keeps its own output, so only a new one shows the compaction.
|
||||
if split.compacted and not metadata.get('assistant_message_id'):
|
||||
item = {'type': 'open_webui:context_compaction', 'id': output_id('cc'), 'status': 'in_progress'}
|
||||
initial_output.append(item)
|
||||
await emit_initial_output()
|
||||
try:
|
||||
result = await compact_messages(
|
||||
request, summary_form_data, user, split, metadata, form_data['model'], request.app.state.MODELS
|
||||
)
|
||||
except Exception:
|
||||
if item:
|
||||
item['status'] = 'failed'
|
||||
await emit_initial_output()
|
||||
raise
|
||||
if item:
|
||||
initial_output.remove(item)
|
||||
await emit_initial_output()
|
||||
return result
|
||||
|
||||
compaction_messages = None
|
||||
context_summary = None
|
||||
if (is_saved_chat_id(chat_id) or is_temporary_chat_id(chat_id)) and user_message_id:
|
||||
@@ -2157,16 +2205,7 @@ async def process_chat_payload(request, form_data, user, metadata, model):
|
||||
or pending_assistant_message is not None
|
||||
or metadata.get('params', {}).get('function_calling') == 'legacy'
|
||||
):
|
||||
form_data['messages'], context_summary, _ = await compact_messages_for_request(
|
||||
request,
|
||||
None,
|
||||
user,
|
||||
form_data.get('messages', []),
|
||||
metadata,
|
||||
form_data['model'],
|
||||
request.app.state.MODELS,
|
||||
chat_system_prompt,
|
||||
)
|
||||
form_data['messages'], context_summary, _ = await compact_history(form_data.get('messages', []), None)
|
||||
if context_summary:
|
||||
form_data['messages'] = add_or_update_system_message(
|
||||
f'[CONVERSATION SUMMARY]\n{context_summary}', form_data['messages'], append=True
|
||||
@@ -2213,7 +2252,6 @@ async def process_chat_payload(request, form_data, user, metadata, model):
|
||||
|
||||
form_data = await convert_url_images_to_base64(form_data, user=user)
|
||||
|
||||
event_emitter = await get_event_emitter(metadata)
|
||||
event_caller = await get_event_call(metadata)
|
||||
|
||||
extra_params = {
|
||||
@@ -2229,12 +2267,9 @@ async def process_chat_payload(request, form_data, user, metadata, model):
|
||||
}
|
||||
# Initialize events to store additional event to be sent to the client
|
||||
# Initialize contexts and citation
|
||||
if getattr(request.state, 'direct', False) and hasattr(request.state, 'model'):
|
||||
models = {
|
||||
request.state.model['id']: request.state.model,
|
||||
}
|
||||
else:
|
||||
models = request.app.state.MODELS
|
||||
from open_webui.utils.models import add_tether_model
|
||||
|
||||
models = await add_tether_model(request, user, form_data.get('model'))
|
||||
|
||||
task_model_id = get_task_model_id(
|
||||
form_data['model'],
|
||||
@@ -2341,7 +2376,6 @@ async def process_chat_payload(request, form_data, user, metadata, model):
|
||||
except Exception as e:
|
||||
raise Exception(f'{e}')
|
||||
|
||||
initial_output = []
|
||||
features = form_data.pop('features', None) or {}
|
||||
extra_params['__features__'] = features
|
||||
if features:
|
||||
@@ -2356,23 +2390,8 @@ async def process_chat_payload(request, form_data, user, metadata, model):
|
||||
form_data['messages'],
|
||||
)
|
||||
|
||||
if (
|
||||
'memory' in features
|
||||
and features['memory']
|
||||
and await Config.get('memories.enable')
|
||||
and await Config.get('memories.system_context.enable')
|
||||
):
|
||||
# features is client-supplied; re-check the permission the native FC path enforces.
|
||||
if getattr(user, 'role', None) == 'admin' or await has_permission(
|
||||
getattr(user, 'id', ''),
|
||||
'features.memories',
|
||||
await Config.get('user.permissions'),
|
||||
):
|
||||
if use_builtin_tools:
|
||||
if not metadata.get('assistant_message_id'):
|
||||
initial_output.extend(await preload_memory(request, form_data['messages'], user, model))
|
||||
else:
|
||||
form_data = await add_memory_context(request, form_data, user, model)
|
||||
if not use_builtin_tools and await memory_context_enabled(user, features):
|
||||
form_data = await add_memory_context(request, form_data, user, model)
|
||||
|
||||
if 'web_search' in features and features['web_search'] and await Config.get('web.search.enable'):
|
||||
# features is client-supplied; re-check the permission the native FC path enforces.
|
||||
@@ -2426,10 +2445,9 @@ async def process_chat_payload(request, form_data, user, metadata, model):
|
||||
tool_ids = form_data.pop('tool_ids', None)
|
||||
terminal_id = form_data.pop('terminal_id', None)
|
||||
if not ENABLE_TOOL_SERVERS:
|
||||
if terminal_id or metadata.get('tool_servers'):
|
||||
if terminal_id:
|
||||
log.debug('Excluded external plugins disabled by plugin configuration')
|
||||
terminal_id = None
|
||||
metadata['tool_servers'] = None
|
||||
files = form_data.pop('files', None)
|
||||
form_data.pop('folder_id', None)
|
||||
metadata['terminal_id'] = terminal_id
|
||||
@@ -2603,11 +2621,7 @@ async def process_chat_payload(request, form_data, user, metadata, model):
|
||||
|
||||
if skill_tools_enabled and skill_manifest:
|
||||
if not metadata.get('assistant_message_id'):
|
||||
initial_output.extend(
|
||||
hidden_tool_result(
|
||||
'list_available_skills', f'<available_skills>\n{skill_manifest}</available_skills>'
|
||||
)
|
||||
)
|
||||
manifests['list_available_skills'] = f'<available_skills>\n{skill_manifest}</available_skills>'
|
||||
elif skill_manifest:
|
||||
form_data['messages'] = add_or_update_system_message(
|
||||
f'<available_skills>\n{skill_manifest}</available_skills>',
|
||||
@@ -2655,13 +2669,8 @@ async def process_chat_payload(request, form_data, user, metadata, model):
|
||||
# skip all server-side tool resolution and pass the caller's tools through
|
||||
# unchanged. Sending `tools: []` explicitly opts out of builtin injection.
|
||||
if payload_tools is None:
|
||||
# Server side tools
|
||||
tool_ids = metadata.get('tool_ids', None)
|
||||
# Client side tools
|
||||
direct_tool_servers = metadata.get('tool_servers', None)
|
||||
|
||||
log.debug('tool_ids=%r', tool_ids)
|
||||
log.debug('direct_tool_servers=%r', direct_tool_servers)
|
||||
|
||||
tools_dict = {}
|
||||
|
||||
@@ -2720,7 +2729,6 @@ async def process_chat_payload(request, form_data, user, metadata, model):
|
||||
'callable': tool_function,
|
||||
'type': 'mcp',
|
||||
'client': client,
|
||||
'direct': False,
|
||||
}
|
||||
except Exception:
|
||||
log.exception("Failed to connect to MCP server '%s'", server_id)
|
||||
@@ -2757,10 +2765,10 @@ async def process_chat_payload(request, form_data, user, metadata, model):
|
||||
tools_dict = {**tools_dict, **mcp_tools_dict}
|
||||
|
||||
# Resolve terminal tools if terminal_id is set (outside tool_ids check
|
||||
# so system terminals work even when no other tools are selected)
|
||||
# so system terminals work even when no other tools are selected).
|
||||
# get_terminal_tools does the access check, including a shared chat's owner pick.
|
||||
terminal_capability = (model.get('info', {}).get('meta', {}).get('capabilities') or {}).get('terminal', True)
|
||||
terminal_connection_ids = {connection.get('id') for connection in await get_terminal_connections(user)}
|
||||
if terminal_id and terminal_capability and terminal_id in terminal_connection_ids:
|
||||
if terminal_id and terminal_capability:
|
||||
try:
|
||||
terminal_result = await get_terminal_tools(
|
||||
request,
|
||||
@@ -2785,33 +2793,6 @@ async def process_chat_payload(request, form_data, user, metadata, model):
|
||||
log.exception(e)
|
||||
raise HTTPException(status_code=503, detail=f'Terminal unavailable: {e}') from e
|
||||
|
||||
if direct_tool_servers:
|
||||
for tool_server in direct_tool_servers:
|
||||
if tool_server.get('is_terminal') is True and not terminal_capability:
|
||||
continue
|
||||
# Copy so the pops below keep metadata intact for sub-agents and approval resumes
|
||||
tool_server = dict(tool_server)
|
||||
tool_server_system_prompt = tool_server.pop('system_prompt', None)
|
||||
if tool_server_system_prompt:
|
||||
form_data['messages'] = add_or_update_system_message(
|
||||
tool_server_system_prompt,
|
||||
form_data['messages'],
|
||||
append=True,
|
||||
)
|
||||
|
||||
tool_specs = tool_server.pop('specs', [])
|
||||
|
||||
for tool in tool_specs:
|
||||
tools_dict[tool['name']] = {
|
||||
'spec': (
|
||||
get_builtin_tool_spec(display_file)
|
||||
if tool_server.get('is_terminal') and tool['name'] == 'display_file'
|
||||
else tool
|
||||
),
|
||||
'direct': True,
|
||||
'server': tool_server,
|
||||
}
|
||||
|
||||
if terminal_id and terminal_capability:
|
||||
from open_webui.utils.terminals import add_terminal_agents_md, get_terminal_agents_md
|
||||
|
||||
@@ -2844,11 +2825,8 @@ async def process_chat_payload(request, form_data, user, metadata, model):
|
||||
knowledge_tags.append(f'<knowledge {attrs}/>')
|
||||
|
||||
if knowledge_tags and not metadata.get('assistant_message_id'):
|
||||
initial_output.extend(
|
||||
hidden_tool_result(
|
||||
'list_attached_knowledge',
|
||||
'<attached_knowledge>\n' + '\n'.join(knowledge_tags) + '\n</attached_knowledge>',
|
||||
)
|
||||
manifests['list_attached_knowledge'] = (
|
||||
'<attached_knowledge>\n' + '\n'.join(knowledge_tags) + '\n</attached_knowledge>'
|
||||
)
|
||||
|
||||
builtin_tools = await get_builtin_tools(
|
||||
@@ -2865,10 +2843,7 @@ async def process_chat_payload(request, form_data, user, metadata, model):
|
||||
for name, tool_dict in builtin_tools.items():
|
||||
if name not in tools_dict:
|
||||
tools_dict[name] = tool_dict
|
||||
elif name == 'display_file' and (
|
||||
tools_dict[name].get('type') == 'terminal'
|
||||
or tools_dict[name].get('server', {}).get('is_terminal') is True
|
||||
):
|
||||
elif name == 'display_file' and tools_dict[name].get('type') == 'terminal':
|
||||
tools_dict[name] = {**tools_dict[name], 'file_tool': tool_dict}
|
||||
|
||||
await filter_user_terminal_tools(request, user, tools_dict, metadata, extra_params)
|
||||
@@ -2990,20 +2965,6 @@ async def process_chat_payload(request, form_data, user, metadata, model):
|
||||
raise Exception(f'{e}')
|
||||
|
||||
metadata.pop('initial_output', None)
|
||||
if skill_tools_enabled and not metadata.get('assistant_message_id'):
|
||||
initial_output.extend(
|
||||
await preload_skills(
|
||||
form_data['messages'],
|
||||
activated_skill_ids & resolved_skill_ids,
|
||||
metadata.get('tools', {}).get('view_skill'),
|
||||
)
|
||||
)
|
||||
if initial_output:
|
||||
form_data['messages'].extend(
|
||||
convert_output_to_messages(initial_output, raw=True, reasoning_format=get_reasoning_format(model))
|
||||
)
|
||||
metadata['initial_output'] = initial_output
|
||||
|
||||
form_data = normalize_messages_for_model(form_data)
|
||||
|
||||
if compaction_messages is not None:
|
||||
@@ -3015,16 +2976,7 @@ async def process_chat_payload(request, form_data, user, metadata, model):
|
||||
append=True,
|
||||
)
|
||||
try:
|
||||
_, context_summary, compacted = await compact_messages_for_request(
|
||||
request,
|
||||
summary_form_data,
|
||||
user,
|
||||
compaction_messages,
|
||||
metadata,
|
||||
form_data['model'],
|
||||
request.app.state.MODELS,
|
||||
chat_system_prompt,
|
||||
)
|
||||
_, context_summary, compacted = await compact_history(compaction_messages, summary_form_data)
|
||||
if compacted:
|
||||
# Compacted messages lead the history this request was built from.
|
||||
compacted_count = len(
|
||||
@@ -3047,12 +2999,39 @@ async def process_chat_payload(request, form_data, user, metadata, model):
|
||||
summary_content = f'[CONVERSATION SUMMARY]\n{context_summary}'
|
||||
form_data['messages'] = add_or_update_system_message(summary_content, form_data['messages'], append=True)
|
||||
|
||||
metadata['context_summary'] = context_summary
|
||||
|
||||
# Added after compaction: it can summarize away the copy the model had, and it should not summarize this turn's.
|
||||
if use_builtin_tools and not metadata.get('assistant_message_id') and await memory_context_enabled(user, features):
|
||||
initial_output.extend(await preload_memory(request, form_data['messages'], user, model))
|
||||
for name, manifest in manifests.items():
|
||||
if get_last_tool_result(form_data['messages'], name) != manifest:
|
||||
initial_output.extend(hidden_tool_result(name, manifest))
|
||||
if skill_tools_enabled and not metadata.get('assistant_message_id'):
|
||||
initial_output.extend(
|
||||
await preload_skills(
|
||||
form_data['messages'],
|
||||
activated_skill_ids & resolved_skill_ids,
|
||||
metadata.get('tools', {}).get('view_skill'),
|
||||
)
|
||||
)
|
||||
if initial_output:
|
||||
form_data['messages'].extend(
|
||||
convert_output_to_messages(initial_output, raw=True, reasoning_format=get_reasoning_format(model))
|
||||
)
|
||||
metadata['initial_output'] = initial_output
|
||||
|
||||
return form_data, metadata, events, False
|
||||
|
||||
|
||||
async def preload_memory(request, messages: list[dict], user, model: dict) -> list[dict]:
|
||||
"""Keep automatic recall in ordinary tool history so later turns replay it unchanged."""
|
||||
result = await recall_memories(request, messages, user, model)
|
||||
"""Keep automatic recall in ordinary tool history so later turns replay it unchanged.
|
||||
|
||||
Memories whose line is still in an earlier recall are left out, so each is sent again only once
|
||||
it changes, was cut off by the character limit, or its earlier copy was compacted away.
|
||||
"""
|
||||
sent = ''.join(f'{result}\n' for result in get_tool_results(messages, 'recall_memories'))
|
||||
result = await recall_memories(request, messages, user, model, sent=sent)
|
||||
return hidden_tool_result('recall_memories', result) if result else []
|
||||
|
||||
|
||||
@@ -3187,7 +3166,7 @@ async def execute_tool_call(form_data, metadata, event_caller, tool_call, histor
|
||||
history.append(tool_call)
|
||||
tool_call['status'] = 'failed' if error else 'in_progress'
|
||||
if error:
|
||||
return {}, error, None, None, False
|
||||
return {}, error, None, None
|
||||
params = JSONCodec.loads(tool_call['arguments'])
|
||||
if name == 'display_file' and (
|
||||
str(params.get('path', '')).startswith('/api/v1/files/')
|
||||
@@ -3195,11 +3174,10 @@ async def execute_tool_call(form_data, metadata, event_caller, tool_call, histor
|
||||
):
|
||||
if tool.get('file_tool'):
|
||||
tool = tool['file_tool']
|
||||
elif tool.get('type') == 'terminal' or tool.get('server', {}).get('is_terminal') is True:
|
||||
elif tool.get('type') == 'terminal':
|
||||
tool_call['status'] = 'failed'
|
||||
return params, 'Error: Uploaded file display is not available.', None, None, False
|
||||
return params, 'Error: Uploaded file display is not available.', None, None
|
||||
tool_type = tool.get('type', '')
|
||||
direct_tool = tool.get('direct', False)
|
||||
if tool_type != 'mcp':
|
||||
allowed_params = tool.get('spec', {}).get('parameters', {}).get('properties', {})
|
||||
params = {key: value for key, value in params.items() if key in allowed_params}
|
||||
@@ -3224,43 +3202,26 @@ async def execute_tool_call(form_data, metadata, event_caller, tool_call, histor
|
||||
is not True
|
||||
):
|
||||
tool_call['status'] = 'failed'
|
||||
return params, 'Error: tool call was not approved.', tool, tool_type, direct_tool
|
||||
return params, 'Error: tool call was not approved.', tool, tool_type
|
||||
|
||||
tool_call['started_at'] = time.time()
|
||||
started = time.perf_counter()
|
||||
try:
|
||||
if direct_tool:
|
||||
if not event_caller:
|
||||
result = 'Error: Browser session is not connected for this direct tool.'
|
||||
else:
|
||||
result = await event_caller(
|
||||
{
|
||||
'type': 'execute:tool',
|
||||
'data': {
|
||||
'id': str(uuid4()),
|
||||
'name': name,
|
||||
'params': params,
|
||||
'server': tool.get('server', {}),
|
||||
'session_id': metadata.get('session_id'),
|
||||
},
|
||||
}
|
||||
)
|
||||
else:
|
||||
function = await get_updated_tool_function(
|
||||
function=tool['callable'],
|
||||
extra_params={
|
||||
'__messages__': form_data.get('messages', []),
|
||||
'__files__': metadata.get('files') or [],
|
||||
},
|
||||
)
|
||||
result = await function(**params)
|
||||
function = await get_updated_tool_function(
|
||||
function=tool['callable'],
|
||||
extra_params={
|
||||
'__messages__': form_data.get('messages', []),
|
||||
'__files__': metadata.get('files') or [],
|
||||
},
|
||||
)
|
||||
result = await function(**params)
|
||||
finally:
|
||||
tool_call['ended_at'] = time.time()
|
||||
tool_call['duration'] = time.perf_counter() - started
|
||||
except Exception as e:
|
||||
result = {'error': str(e)}
|
||||
tool_call['status'] = 'failed' if _is_tool_result_error(result) else 'completed'
|
||||
return params, result, tool, tool_type, direct_tool
|
||||
return params, result, tool, tool_type
|
||||
|
||||
|
||||
async def resume_tool_calls(request, form_data, user, model, metadata, message) -> bool:
|
||||
@@ -3348,9 +3309,7 @@ async def resume_tool_calls(request, form_data, user, model, metadata, message)
|
||||
try:
|
||||
history = [call for call in output if call.get('type') == 'function_call']
|
||||
history = history[: next(i for i, call in enumerate(history) if call.get('call_id') == item['call_id'])]
|
||||
params, result, tool, tool_type, direct_tool = await execute_tool_call(
|
||||
form_data, metadata, event_caller, item, history
|
||||
)
|
||||
params, result, tool, tool_type = await execute_tool_call(form_data, metadata, event_caller, item, history)
|
||||
files, embeds = [], []
|
||||
if result is None and tool is None:
|
||||
result = (
|
||||
@@ -3361,9 +3320,7 @@ async def resume_tool_calls(request, form_data, user, model, metadata, message)
|
||||
terminal_file_result = build_terminal_file_tool_result(name, params, result, tool, metadata)
|
||||
if terminal_file_result:
|
||||
result = terminal_file_result
|
||||
result, files, embeds = await process_tool_result(
|
||||
request, name, result, tool_type, direct_tool, metadata, user
|
||||
)
|
||||
result, files, embeds = await process_tool_result(request, name, result, tool_type, metadata, user)
|
||||
await terminal_event_handler(name, params, result, event_emitter)
|
||||
content = await tool_result_with_citations(
|
||||
item.get('name', ''),
|
||||
@@ -3483,7 +3440,6 @@ async def pause_for_tool_approval(chat_id: str, message_id: str, output: list[di
|
||||
'tool_ids': metadata.get('tool_ids') or [],
|
||||
'skill_ids': metadata.get('skill_ids') or [],
|
||||
'terminal_id': metadata.get('terminal_id'),
|
||||
'tool_servers': metadata.get('tool_servers'),
|
||||
'filter_ids': metadata.get('filter_ids') or [],
|
||||
'features': metadata.get('features') or {},
|
||||
'variables': metadata.get('variables') or {},
|
||||
@@ -3656,6 +3612,22 @@ async def background_tasks_handler(ctx):
|
||||
if not await get_verified_user_by_id(user.id):
|
||||
return
|
||||
|
||||
# Messages the user sent while this reply ran are answered now; follow-ups for it would go unused.
|
||||
if (
|
||||
is_saved_chat_id(metadata.get('chat_id'))
|
||||
and not metadata.get('internal')
|
||||
and await ChatMessages.has_queued_message(metadata['chat_id'], metadata['message_id'])
|
||||
):
|
||||
from open_webui.utils.subagents import get_pending_run, process_pending_internal_messages
|
||||
|
||||
tasks = {key: value for key, value in (tasks or {}).items() if key != TASKS.FOLLOW_UP_GENERATION}
|
||||
try:
|
||||
await process_pending_internal_messages(
|
||||
request, metadata['chat_id'], user.id, get_pending_run(metadata), reply_id=metadata['message_id']
|
||||
)
|
||||
except Exception:
|
||||
log.exception('Failed to answer queued messages for chat %s', metadata['chat_id'])
|
||||
|
||||
message = None
|
||||
messages = []
|
||||
|
||||
@@ -3882,7 +3854,7 @@ async def background_tasks_handler(ctx):
|
||||
except Exception as e:
|
||||
pass
|
||||
|
||||
if messages:
|
||||
if messages and not is_temporary_chat_id(metadata.get('chat_id')):
|
||||
await review_memory_after_turn(
|
||||
request=request,
|
||||
user=user,
|
||||
@@ -4690,7 +4662,7 @@ async def streaming_chat_response_handler(response, ctx):
|
||||
|
||||
def full_output():
|
||||
for item in output:
|
||||
set_tool_call_visibility(item, metadata.get('tools', {}))
|
||||
set_tool_call_metadata(item, metadata.get('tools', {}))
|
||||
if is_message_continuation():
|
||||
return [
|
||||
*prior_output[:-1],
|
||||
@@ -4910,7 +4882,7 @@ async def streaming_chat_response_handler(response, ctx):
|
||||
response_data.get('item') or {},
|
||||
*((response_data.get('response') or {}).get('output') or []),
|
||||
]:
|
||||
set_tool_call_visibility(item, metadata.get('tools', {}))
|
||||
set_tool_call_metadata(item, metadata.get('tools', {}))
|
||||
if response_data.get('type', '').endswith('.delta'):
|
||||
await queue_pending_delta_data(
|
||||
response_data,
|
||||
@@ -4982,7 +4954,7 @@ async def streaming_chat_response_handler(response, ctx):
|
||||
)
|
||||
|
||||
if data:
|
||||
if 'event' in data and not getattr(request.state, 'direct', False):
|
||||
if 'event' in data:
|
||||
await event_emitter(data.get('event', {}))
|
||||
|
||||
if 'selected_model_id' in data:
|
||||
@@ -5244,6 +5216,7 @@ async def streaming_chat_response_handler(response, ctx):
|
||||
if item.get('type') == 'function_call'
|
||||
}
|
||||
|
||||
tool_name_changed = False
|
||||
for tc in response_tool_calls:
|
||||
call_id = tc.get('id') or output_id('fc')
|
||||
tc['id'] = call_id
|
||||
@@ -5252,6 +5225,7 @@ async def streaming_chat_response_handler(response, ctx):
|
||||
output_index, item = output_by_call_id[call_id]
|
||||
if func.get('name', item.get('name', '')) != item.get('name'):
|
||||
stream_size = 0
|
||||
tool_name_changed = True
|
||||
item['name'] = func.get('name', item.get('name', ''))
|
||||
item['arguments'] = func.get('arguments', item.get('arguments', ''))
|
||||
item['status'] = 'in_progress'
|
||||
@@ -5303,6 +5277,17 @@ async def streaming_chat_response_handler(response, ctx):
|
||||
}
|
||||
)
|
||||
|
||||
if tool_name_changed:
|
||||
# A late tool name can select a native renderer. Flush deltas
|
||||
# before the full snapshot so arguments are not appended twice.
|
||||
await flush_pending_delta_data()
|
||||
await event_emitter(
|
||||
{
|
||||
'type': 'chat:completion',
|
||||
'data': {'output': full_output(), 'flush': True},
|
||||
}
|
||||
)
|
||||
|
||||
data = None
|
||||
delta_type = 'tool_call'
|
||||
|
||||
@@ -6007,9 +5992,7 @@ async def streaming_chat_response_handler(response, ctx):
|
||||
)
|
||||
except ToolApprovalRequired:
|
||||
break
|
||||
tool_function_params, tool_result, tool, tool_type, direct_tool = tool_results[
|
||||
tool_call['call_id']
|
||||
]
|
||||
tool_function_params, tool_result, tool, tool_type = tool_results[tool_call['call_id']]
|
||||
if tool_result is None:
|
||||
results.append(
|
||||
{
|
||||
@@ -6037,7 +6020,6 @@ async def streaming_chat_response_handler(response, ctx):
|
||||
tool_function_name,
|
||||
tool_result,
|
||||
tool_type,
|
||||
direct_tool,
|
||||
metadata,
|
||||
user,
|
||||
)
|
||||
@@ -6115,6 +6097,11 @@ async def streaming_chat_response_handler(response, ctx):
|
||||
if final_answer_requested:
|
||||
await emit_message_error(round_error or 'The provider requested tools after tool use stopped.')
|
||||
break
|
||||
# The user sent a message meanwhile: stop here, and it is answered next with these results.
|
||||
if is_saved_chat_id(metadata.get('chat_id')) and await ChatMessages.has_queued_message(
|
||||
metadata['chat_id'], metadata['message_id']
|
||||
):
|
||||
break
|
||||
|
||||
try:
|
||||
new_form_data = {
|
||||
@@ -6191,6 +6178,7 @@ async def streaming_chat_response_handler(response, ctx):
|
||||
return request_messages
|
||||
|
||||
new_form_data['messages'] = get_request_messages(messages)
|
||||
item = None
|
||||
try:
|
||||
user_messages = [
|
||||
(message, message.get('content'))
|
||||
@@ -6211,11 +6199,20 @@ async def streaming_chat_response_handler(response, ctx):
|
||||
set_last_user_message_content(
|
||||
metadata.get('base_user_prompt') or user_message, [message]
|
||||
)
|
||||
messages, context_summary, compacted = await compact_messages_for_request(
|
||||
split = await split_messages(messages, metadata)
|
||||
if split.compacted:
|
||||
item = {
|
||||
'type': 'open_webui:context_compaction',
|
||||
'id': output_id('cc'),
|
||||
'status': 'in_progress',
|
||||
}
|
||||
output.append(item)
|
||||
await emit_output()
|
||||
messages, context_summary, compacted = await compact_messages(
|
||||
request,
|
||||
summary_form_data,
|
||||
user,
|
||||
messages,
|
||||
split,
|
||||
metadata,
|
||||
form_data['model'],
|
||||
request.app.state.MODELS,
|
||||
@@ -6236,20 +6233,21 @@ async def streaming_chat_response_handler(response, ctx):
|
||||
)
|
||||
messages[checkpoint] = {**messages[checkpoint], 'contextSummary': context_summary}
|
||||
new_form_data['messages'] = get_request_messages(messages)
|
||||
output.append(
|
||||
{
|
||||
'type': 'open_webui:context_compaction',
|
||||
'id': output_id('cc'),
|
||||
'call_id': next(
|
||||
message['tool_calls'][0]['id']
|
||||
for message in messages
|
||||
if message.get('tool_calls')
|
||||
),
|
||||
'summary': context_summary,
|
||||
}
|
||||
# The progress item becomes the checkpoint later turns resume from.
|
||||
item.update(
|
||||
status='completed',
|
||||
call_id=next(
|
||||
message['tool_calls'][0]['id']
|
||||
for message in messages
|
||||
if message.get('tool_calls')
|
||||
),
|
||||
summary=context_summary,
|
||||
)
|
||||
await emit_output()
|
||||
except Exception:
|
||||
if item:
|
||||
item['status'] = 'failed'
|
||||
await emit_output()
|
||||
log.exception('Tool loop context compaction failed; keeping the current context')
|
||||
|
||||
new_form_data = await convert_url_images_to_base64(new_form_data, user=user)
|
||||
|
||||
@@ -187,6 +187,11 @@ def is_host_blocked(host: Union[str, Sequence[str]], filter_list: list[str] | No
|
||||
return any(_host_matches_pattern(h, blocked) for h in hosts for blocked in block_list)
|
||||
|
||||
|
||||
def is_empty_reply(message: dict) -> bool:
|
||||
"""An assistant reply with nothing in it, such as a failed one. Requests leave these out."""
|
||||
return message.get('role') == 'assistant' and not message.get('content') and not message.get('output')
|
||||
|
||||
|
||||
def get_message_list(messages_map, message_id):
|
||||
"""
|
||||
Reconstructs a list of messages in order up to the specified message_id.
|
||||
@@ -223,7 +228,7 @@ def get_message_list(messages_map, message_id):
|
||||
|
||||
|
||||
def get_messages_content(messages: list[dict]) -> str:
|
||||
return '\n'.join([f'{message["role"].upper()}: {get_content_from_message(message)}' for message in messages])
|
||||
return '\n'.join([f'{message["role"].upper()}: {get_content_from_message(message) or ""}' for message in messages])
|
||||
|
||||
|
||||
def get_last_user_message_item(messages: list[dict]) -> dict | None:
|
||||
@@ -289,6 +294,27 @@ def get_paired_tool_call_ids(messages: list[dict]) -> list[set[str]]:
|
||||
return paired_ids_by_message
|
||||
|
||||
|
||||
def get_tool_results(messages: list[dict], name: str) -> list[str]:
|
||||
"""Everything the named tool returned in these messages, oldest first."""
|
||||
call_ids = {
|
||||
tool_call.get('id')
|
||||
for message in messages
|
||||
for tool_call in message.get('tool_calls') or []
|
||||
if (tool_call.get('function') or {}).get('name') == name
|
||||
}
|
||||
return [
|
||||
get_content_from_message(message) or ''
|
||||
for message in messages
|
||||
if message.get('role') == 'tool' and message.get('tool_call_id') in call_ids
|
||||
]
|
||||
|
||||
|
||||
def get_last_tool_result(messages: list[dict], name: str) -> str | None:
|
||||
"""What the named tool last returned in these messages, or None if it never did."""
|
||||
results = get_tool_results(messages, name)
|
||||
return results[-1] if results else None
|
||||
|
||||
|
||||
def reconcile_tool_pairs(messages: list[dict]) -> list[dict]:
|
||||
"""Drop unpaired tool_use / tool_result from a reconstructed conversation.
|
||||
|
||||
@@ -477,7 +503,7 @@ def convert_output_to_messages(
|
||||
|
||||
message = {
|
||||
'role': 'assistant',
|
||||
'content': '\n'.join(pending_content) if pending_content else '',
|
||||
'content': '\n'.join(pending_content) if pending_content else (None if pending_tool_calls else ''),
|
||||
**({'tool_calls': pending_tool_calls} if pending_tool_calls else {}),
|
||||
}
|
||||
|
||||
|
||||
@@ -238,7 +238,7 @@ async def get_all_models(request, refresh: bool = False, user: UserModel = None)
|
||||
if custom_model.is_active:
|
||||
arena_meta = model['info']['meta'] if model.get('arena') else None
|
||||
model['name'] = custom_model.name
|
||||
model['info'] = custom_model.model_dump()
|
||||
model['info'] = custom_model.model_dump(exclude={'meta': {'profile_image_url'}})
|
||||
if arena_meta:
|
||||
# Evaluation config owns arena access grants and model_ids
|
||||
model['info']['meta'].update(
|
||||
@@ -300,7 +300,7 @@ async def get_all_models(request, refresh: bool = False, user: UserModel = None)
|
||||
**({'loaded': base_model.get('loaded')} if base_model and base_model.get('loaded') is not None else {}),
|
||||
}
|
||||
|
||||
info = custom_model.model_dump()
|
||||
info = custom_model.model_dump(exclude={'meta': {'profile_image_url'}})
|
||||
schema = get_chat_variables_schema(custom_model.params.model_dump().get('system'))
|
||||
if schema:
|
||||
info.setdefault('meta', {})['chat_variables_schema'] = schema
|
||||
@@ -524,7 +524,18 @@ async def get_all_models(request, refresh: bool = False, user: UserModel = None)
|
||||
return models
|
||||
|
||||
|
||||
async def add_tether_model(request: Request, user, model_id, models=None):
|
||||
"""`models` (default: the shared models), plus the user's own model `model_id` when it is one."""
|
||||
models = request.app.state.MODELS if models is None else models
|
||||
tether_model = await openai.get_tether_model(request, user, model_id)
|
||||
# dict(...items()) is one HGETALL on a Redis-backed pool.
|
||||
return {**dict(models.items()), model_id: tether_model} if tether_model else models
|
||||
|
||||
|
||||
async def check_model_access(user, model, model_info=None, db=None):
|
||||
if model.get('owner_id') is not None and model.get('owner_id') == getattr(user, 'id', None):
|
||||
# The caller's own connection, resolved from their settings.
|
||||
return
|
||||
if model.get('arena'):
|
||||
meta = model.get('info', {}).get('meta', {})
|
||||
access_grants = meta.get('access_grants', [])
|
||||
|
||||
@@ -7,6 +7,7 @@ import re
|
||||
import sys
|
||||
import urllib
|
||||
import uuid
|
||||
import weakref
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime, timedelta
|
||||
from functools import partialmethod
|
||||
@@ -247,6 +248,9 @@ async def get_oauth_runtime_config() -> SimpleNamespace:
|
||||
DEFAULT_TOKEN_EXPIRY_SECONDS = 3600
|
||||
NON_EXPIRING_TOKEN_EXPIRES_AT = 253402300799 # 9999-12-31 23:59:59 UTC
|
||||
|
||||
# Some OAuth servers send single headers larger than aiohttp's default limit (#34078)
|
||||
OAUTH_MAX_FIELD_SIZE = 64 * 1024
|
||||
|
||||
|
||||
def _normalize_token_expiry(token: dict) -> dict:
|
||||
"""Ensure a token dict always has a numeric access-token ``expires_at``.
|
||||
@@ -438,7 +442,7 @@ async def get_protected_resource_metadata(server_url: str) -> ProtectedResourceM
|
||||
resource = None
|
||||
scopes = []
|
||||
try:
|
||||
async with aiohttp.ClientSession(trust_env=True) as session:
|
||||
async with aiohttp.ClientSession(trust_env=True, max_field_size=OAUTH_MAX_FIELD_SIZE) as session:
|
||||
async with session.post(
|
||||
server_url,
|
||||
json={'jsonrpc': '2.0', 'method': 'initialize', 'params': {}, 'id': 1},
|
||||
@@ -538,7 +542,7 @@ async def get_discovery_urls(server_url) -> list[str]:
|
||||
async def _get_oauth_server_metadata(
|
||||
server_url: str, resource_metadata: ProtectedResourceMetadata
|
||||
) -> tuple[OAuthMetadata, str | None]:
|
||||
async with aiohttp.ClientSession(trust_env=True) as session:
|
||||
async with aiohttp.ClientSession(trust_env=True, max_field_size=OAUTH_MAX_FIELD_SIZE) as session:
|
||||
for url in resource_metadata.get_discovery_urls(server_url):
|
||||
async with session.get(url, ssl=AIOHTTP_CLIENT_SESSION_SSL) as response:
|
||||
if response.status != 200:
|
||||
@@ -626,7 +630,7 @@ async def get_oauth_client_info_with_dynamic_client_registration(
|
||||
)
|
||||
|
||||
# Perform dynamic client registration and return client info
|
||||
async with aiohttp.ClientSession(trust_env=True) as session:
|
||||
async with aiohttp.ClientSession(trust_env=True, max_field_size=OAUTH_MAX_FIELD_SIZE) as session:
|
||||
async with session.post(
|
||||
registration_url, json=registration_data, ssl=AIOHTTP_CLIENT_SESSION_SSL
|
||||
) as oauth_client_registration_response:
|
||||
@@ -855,7 +859,61 @@ async def recover_oauth_client_metadata(connection: dict, oauth_client_info: dic
|
||||
return recovered
|
||||
|
||||
|
||||
class OAuthClientManager:
|
||||
OAUTH_REFRESH_LOCK_TIMEOUT = 60
|
||||
OAUTH_REFRESH_LOCKS: weakref.WeakValueDictionary[str, asyncio.Lock] = weakref.WeakValueDictionary()
|
||||
|
||||
|
||||
class OAuthSessionRefresher:
|
||||
async def _refresh_token(self, session) -> dict:
|
||||
"""
|
||||
Refresh an OAuth token if needed, with concurrency protection.
|
||||
|
||||
Args:
|
||||
session: The OAuth session object
|
||||
|
||||
Returns:
|
||||
dict: Refreshed token data, or None if refresh failed
|
||||
"""
|
||||
redis = self.app.state.redis
|
||||
if redis:
|
||||
# Shared across workers and replicas
|
||||
refresh_lock = redis.lock(
|
||||
f'{REDIS_KEY_PREFIX}:oauth:refresh_lock:{session.id}',
|
||||
timeout=OAUTH_REFRESH_LOCK_TIMEOUT,
|
||||
blocking_timeout=OAUTH_REFRESH_LOCK_TIMEOUT,
|
||||
)
|
||||
else:
|
||||
refresh_lock = OAUTH_REFRESH_LOCKS.setdefault(session.id, asyncio.Lock())
|
||||
|
||||
# Cancel a stalled refresh before another worker can acquire the expired lease
|
||||
async with refresh_lock, asyncio.timeout(OAUTH_REFRESH_LOCK_TIMEOUT / 2):
|
||||
# Another request may have refreshed while we waited; its refresh token is now spent
|
||||
current_session = await OAuthSessions.get_session_by_id(session.id)
|
||||
if current_session and current_session.token != session.token:
|
||||
return current_session.token
|
||||
|
||||
try:
|
||||
# Perform the actual refresh
|
||||
refreshed_token = await self._perform_token_refresh(session)
|
||||
|
||||
if refreshed_token:
|
||||
# Update the session with new token data
|
||||
session = await OAuthSessions.update_session_by_id(session.id, refreshed_token)
|
||||
log.info('Successfully refreshed token for session %s', session.id)
|
||||
return session.token
|
||||
else:
|
||||
log.error(f'Failed to refresh token for session {session.id}')
|
||||
return None
|
||||
|
||||
except (aiohttp.ClientError, asyncio.TimeoutError):
|
||||
# Transient provider failure: the grant is still valid, keep the session
|
||||
raise
|
||||
except Exception as e:
|
||||
log.error(f'Error refreshing token for session {session.id}: {e}')
|
||||
return None
|
||||
|
||||
|
||||
class OAuthClientManager(OAuthSessionRefresher):
|
||||
def __init__(self, app):
|
||||
self.oauth = OAuth()
|
||||
self.app = app
|
||||
@@ -1124,36 +1182,6 @@ class OAuthClientManager:
|
||||
log.error(f'Error getting OAuth token for user {user_id}: {e}')
|
||||
return None
|
||||
|
||||
async def _refresh_token(self, session) -> dict:
|
||||
"""
|
||||
Refresh an OAuth token if needed, with concurrency protection.
|
||||
|
||||
Args:
|
||||
session: The OAuth session object
|
||||
|
||||
Returns:
|
||||
dict: Refreshed token data, or None if refresh failed
|
||||
"""
|
||||
try:
|
||||
# Perform the actual refresh
|
||||
refreshed_token = await self._perform_token_refresh(session)
|
||||
|
||||
if refreshed_token:
|
||||
# Update the session with new token data
|
||||
session = await OAuthSessions.update_session_by_id(session.id, refreshed_token)
|
||||
log.info('Successfully refreshed token for session %s', session.id)
|
||||
return session.token
|
||||
else:
|
||||
log.error(f'Failed to refresh token for session {session.id}')
|
||||
return None
|
||||
|
||||
except (aiohttp.ClientError, asyncio.TimeoutError):
|
||||
# Transient provider failure: the grant is still valid, keep the session
|
||||
raise
|
||||
except Exception as e:
|
||||
log.error(f'Error refreshing token for session {session.id}: {e}')
|
||||
return None
|
||||
|
||||
async def _perform_token_refresh(self, session) -> dict:
|
||||
"""
|
||||
Perform the actual OAuth token refresh.
|
||||
@@ -1214,7 +1242,7 @@ class OAuthClientManager:
|
||||
refresh_data['scope'] = client.client_kwargs['scope']
|
||||
|
||||
# Make refresh request
|
||||
async with aiohttp.ClientSession(trust_env=True) as session_http:
|
||||
async with aiohttp.ClientSession(trust_env=True, max_field_size=OAUTH_MAX_FIELD_SIZE) as session_http:
|
||||
async with session_http.post(
|
||||
token_endpoint,
|
||||
data=refresh_data,
|
||||
@@ -1269,6 +1297,8 @@ class OAuthClientManager:
|
||||
)
|
||||
# Keep the URL out of the session cookie; long scope lists push it past the browser size limit
|
||||
authorization_url = auth_data.pop('url')
|
||||
# Without a stored nonce authlib skips verifying the id_token, which MCP never uses (#34504)
|
||||
auth_data.pop('nonce', None)
|
||||
auth_data['user_id'] = user_id
|
||||
await client.save_authorize_data(request, redirect_uri=redirect_uri_str, **auth_data)
|
||||
return RedirectResponse(authorization_url, status_code=302)
|
||||
@@ -1343,6 +1373,12 @@ class OAuthClientManager:
|
||||
sessions = await OAuthSessions.get_sessions_by_user_id(user_id)
|
||||
for session in sessions:
|
||||
if session.provider == client_id:
|
||||
log.warning(
|
||||
'Reconnect for user %s, client_id %s, deleting session %s',
|
||||
user_id,
|
||||
client_id,
|
||||
session.id,
|
||||
)
|
||||
await OAuthSessions.delete_session_by_id(session.id)
|
||||
|
||||
session = await OAuthSessions.create_session(
|
||||
@@ -1383,13 +1419,12 @@ class OAuthClientManager:
|
||||
return response
|
||||
|
||||
|
||||
class OAuthManager:
|
||||
class OAuthManager(OAuthSessionRefresher):
|
||||
def __init__(self, app):
|
||||
self.oauth = OAuth()
|
||||
self.app = app
|
||||
|
||||
self._clients = {}
|
||||
self._refresh_locks: dict[str, asyncio.Lock] = {}
|
||||
|
||||
async def initialize(self):
|
||||
# Provider connections are fixed for this worker's lifetime.
|
||||
@@ -1484,46 +1519,6 @@ class OAuthManager:
|
||||
log.error(f'Error getting OAuth token for user {user_id}: {e}')
|
||||
return None
|
||||
|
||||
async def _refresh_token(self, session) -> dict:
|
||||
"""
|
||||
Refresh an OAuth token if needed, with concurrency protection.
|
||||
|
||||
Args:
|
||||
session: The OAuth session object
|
||||
|
||||
Returns:
|
||||
dict: Refreshed token data, or None if refresh failed
|
||||
"""
|
||||
redis = self.app.state.redis
|
||||
if redis:
|
||||
# Shared across workers and replicas
|
||||
refresh_lock = redis.lock(f'{REDIS_KEY_PREFIX}:oauth:refresh_lock:{session.id}', timeout=60)
|
||||
else:
|
||||
refresh_lock = self._refresh_locks.setdefault(session.id, asyncio.Lock())
|
||||
|
||||
async with refresh_lock:
|
||||
# Another request may have refreshed while we waited; its refresh token is now spent
|
||||
current_session = await OAuthSessions.get_session_by_id(session.id)
|
||||
if current_session and current_session.token != session.token:
|
||||
return current_session.token
|
||||
|
||||
try:
|
||||
# Perform the actual refresh
|
||||
refreshed_token = await self._perform_token_refresh(session)
|
||||
|
||||
if refreshed_token:
|
||||
# Update the session with new token data
|
||||
session = await OAuthSessions.update_session_by_id(session.id, refreshed_token)
|
||||
log.info('Successfully refreshed token for session %s', session.id)
|
||||
return session.token
|
||||
else:
|
||||
log.error(f'Failed to refresh token for session {session.id}')
|
||||
return None
|
||||
|
||||
except Exception as e:
|
||||
log.error(f'Error refreshing token for session {session.id}: {e}')
|
||||
return None
|
||||
|
||||
async def _perform_token_refresh(self, session) -> dict:
|
||||
"""
|
||||
Perform the actual OAuth token refresh.
|
||||
@@ -1557,6 +1552,8 @@ class OAuthManager:
|
||||
token_endpoint = openid_data.get('token_endpoint')
|
||||
else:
|
||||
log.error(f'Failed to fetch OpenID configuration for provider {provider}')
|
||||
if r.status == 429 or r.status >= 500:
|
||||
r.raise_for_status()
|
||||
if not token_endpoint:
|
||||
log.error(f'No token endpoint found for provider {provider}')
|
||||
return None
|
||||
@@ -1609,8 +1606,12 @@ class OAuthManager:
|
||||
else:
|
||||
error_text = await r.text()
|
||||
log.error(f'Token refresh failed for provider {provider}: {r.status} - {error_text}')
|
||||
if r.status == 429 or r.status >= 500:
|
||||
r.raise_for_status()
|
||||
return None
|
||||
|
||||
except (aiohttp.ClientError, asyncio.TimeoutError):
|
||||
raise
|
||||
except Exception as e:
|
||||
log.error(f'Exception during token refresh for provider {provider}: {e}')
|
||||
return None
|
||||
@@ -2276,12 +2277,18 @@ class OAuthManager:
|
||||
sessions = await OAuthSessions.get_sessions_by_user_id(user.id, db=db)
|
||||
provider_sessions = sorted(
|
||||
[session for session in sessions if session.provider == provider],
|
||||
key=lambda session: session.created_at,
|
||||
key=lambda session: session.updated_at,
|
||||
reverse=True,
|
||||
)
|
||||
# Keep the newest sessions up to the limit, prune the rest
|
||||
if len(provider_sessions) >= OAUTH_MAX_SESSIONS_PER_USER:
|
||||
for old_session in provider_sessions[OAUTH_MAX_SESSIONS_PER_USER - 1 :]:
|
||||
log.warning(
|
||||
'Session limit reached for user %s, provider %s, deleting session %s',
|
||||
user.id,
|
||||
provider,
|
||||
old_session.id,
|
||||
)
|
||||
await OAuthSessions.delete_session_by_id(old_session.id, db=db)
|
||||
|
||||
session = await OAuthSessions.create_session(
|
||||
@@ -2514,6 +2521,12 @@ class OAuthManager:
|
||||
for user in users_to_logout:
|
||||
sessions = await OAuthSessions.get_sessions_by_user_id(user.id, db=db)
|
||||
for oauth_session in sessions:
|
||||
log.warning(
|
||||
'Back-channel logout: user %s, provider %s, deleting session %s',
|
||||
user.id,
|
||||
oauth_session.provider,
|
||||
oauth_session.id,
|
||||
)
|
||||
await OAuthSessions.delete_session_by_id(oauth_session.id, db=db)
|
||||
|
||||
if redis:
|
||||
|
||||
@@ -405,7 +405,7 @@ def convert_chat_completions_payload_to_ollama(openai_payload: dict) -> dict:
|
||||
ollama_payload['model'] = openai_payload.get('model')
|
||||
ollama_payload['messages'] = convert_chat_completions_messages_to_ollama(openai_payload.get('messages'))
|
||||
ollama_payload['stream'] = openai_payload.get('stream', False)
|
||||
if 'tools' in openai_payload:
|
||||
if 'tools' in openai_payload and openai_payload.get('tool_choice') != 'none':
|
||||
ollama_payload['tools'] = openai_payload['tools']
|
||||
|
||||
# If there are advanced parameters in the payload, format them in Ollama's options field
|
||||
|
||||
@@ -91,18 +91,87 @@ async def _build_request(source: Request, user_id: str, *, internal: bool) -> Re
|
||||
return request
|
||||
|
||||
|
||||
async def queue_user_message(
|
||||
request: Request, chat_id: str, user: UserModel, user_message: dict, parent_id: str
|
||||
) -> bool:
|
||||
"""Hold a message sent while its reply is running. The reply ends at its next step and this is answered next."""
|
||||
if not user_message.get('id') or not await has_active_tasks(request.app.state.redis, chat_id):
|
||||
return False
|
||||
# Only a reply still being written holds messages. Checked before locking: the turn that answers
|
||||
# held messages is started under this lock, and its own reply is already finished.
|
||||
reply = await Chats.get_message_by_id_and_message_id(chat_id, parent_id)
|
||||
if not reply or reply.get('role') != 'assistant' or reply.get('done') is not False:
|
||||
return False
|
||||
async with _parent_locks.setdefault(chat_id, asyncio.Lock()):
|
||||
# Checked under the lock the reply's own cleanup takes, so the message can't be left unanswered.
|
||||
if not await has_active_tasks(request.app.state.redis, chat_id):
|
||||
return False
|
||||
async with Chats._chat_transaction(chat_id) as (_, chat):
|
||||
if not chat or chat.user_id != user.id:
|
||||
return False
|
||||
history = copy.deepcopy((chat.chat or {}).get('history') or {})
|
||||
messages = history.get('messages') or {}
|
||||
reply = messages.get(parent_id)
|
||||
if not reply:
|
||||
return False
|
||||
message = {
|
||||
'id': user_message['id'],
|
||||
'parentId': parent_id,
|
||||
'childrenIds': [],
|
||||
'role': 'user',
|
||||
'content': user_message.get('content', ''),
|
||||
**({'files': user_message['files']} if user_message.get('files') else {}),
|
||||
'model': reply.get('model'),
|
||||
'user_id': user.id,
|
||||
'user': {'id': user.id, 'name': user.name},
|
||||
'meta': {'status': 'pending'},
|
||||
'timestamp': int(time.time()),
|
||||
}
|
||||
messages[message['id']] = message
|
||||
reply.setdefault('childrenIds', []).append(message['id'])
|
||||
history['messages'] = messages
|
||||
chat.chat = {**(chat.chat or {}), 'history': history}
|
||||
chat.updated_at = int(time.time())
|
||||
await ChatMessages.upsert_message(message['id'], chat_id, user.id, message)
|
||||
return True
|
||||
|
||||
|
||||
def get_pending_run(metadata: dict, model_id: str | None = None) -> dict:
|
||||
"""The settings a turn started for pending messages takes from the turn before it."""
|
||||
return {
|
||||
'model_id': metadata.get('model_id') or model_id,
|
||||
'session_id': metadata.get('session_id'),
|
||||
'tool_ids': metadata.get('tool_ids') or [],
|
||||
'skill_ids': metadata.get('skill_ids') or [],
|
||||
'chat_context': metadata.get('chat_context'),
|
||||
'filter_ids': metadata.get('filter_ids') or [],
|
||||
'terminal_id': metadata.get('terminal_id'),
|
||||
'features': metadata.get('features') or {},
|
||||
'variables': metadata.get('variables') or {},
|
||||
}
|
||||
|
||||
|
||||
async def process_pending_internal_messages(
|
||||
source_request: Request,
|
||||
parent_chat_id: str,
|
||||
user_id: str,
|
||||
run: dict,
|
||||
reply_id: str | None = None,
|
||||
) -> None:
|
||||
"""Answer pending messages once the chat is idle. With reply_id, answer only the messages queued under that
|
||||
reply as soon as it is saved, without waiting for its follow-ups, title and other background work."""
|
||||
lock = _parent_locks.setdefault(parent_chat_id, asyncio.Lock())
|
||||
while await has_active_tasks(source_request.app.state.redis, parent_chat_id):
|
||||
await asyncio.sleep(0.25)
|
||||
if reply_id is None:
|
||||
while await has_active_tasks(source_request.app.state.redis, parent_chat_id):
|
||||
await asyncio.sleep(0.25)
|
||||
else:
|
||||
# The turn started below asks whether its parent reply is still running, without taking this lock.
|
||||
reply = await Chats.get_message_by_id_and_message_id(parent_chat_id, reply_id)
|
||||
if not reply or reply.get('done') is not True:
|
||||
return
|
||||
|
||||
async with lock:
|
||||
if await has_active_tasks(source_request.app.state.redis, parent_chat_id):
|
||||
if reply_id is None and await has_active_tasks(source_request.app.state.redis, parent_chat_id):
|
||||
return
|
||||
|
||||
user = await Users.get_user_by_id(user_id)
|
||||
@@ -128,14 +197,28 @@ async def process_pending_internal_messages(
|
||||
and meta.get('status') in (None, 'pending')
|
||||
)
|
||||
or (meta.get('internal') is True and meta.get('type') == 'timer')
|
||||
# The user's own message, held while its reply was running.
|
||||
or (meta.get('internal') is not True and meta.get('status') == 'pending')
|
||||
)
|
||||
]
|
||||
if reply_id is not None:
|
||||
pending = [
|
||||
message
|
||||
for message in pending
|
||||
if message.get('parentId') == reply_id and (message.get('meta') or {}).get('internal') is not True
|
||||
]
|
||||
if not pending:
|
||||
return
|
||||
|
||||
first = pending[0]
|
||||
first_meta = first.get('meta') or {}
|
||||
kind = 'timer' if first_meta.get('internal') is True and first_meta.get('type') == 'timer' else 'subagent'
|
||||
kind = (
|
||||
'timer'
|
||||
if first_meta.get('internal') is True and first_meta.get('type') == 'timer'
|
||||
else 'queued'
|
||||
if first_meta.get('internal') is not True
|
||||
else 'subagent'
|
||||
)
|
||||
parent_id = first.get('parentId')
|
||||
if kind == 'timer' and first_meta.get('timer_id'):
|
||||
timer = await Chats.get_chat_by_id(first_meta['timer_id'])
|
||||
@@ -145,6 +228,12 @@ async def process_pending_internal_messages(
|
||||
model_id = first.get('model') or run['model_id']
|
||||
if kind == 'timer':
|
||||
batch = [first]
|
||||
elif kind == 'queued':
|
||||
batch = [
|
||||
message
|
||||
for message in pending
|
||||
if message.get('parentId') == parent_id and (message.get('meta') or {}).get('internal') is not True
|
||||
]
|
||||
else:
|
||||
batch = [
|
||||
message
|
||||
@@ -168,6 +257,9 @@ async def process_pending_internal_messages(
|
||||
combined_meta['timer_id'] = timer_ids[0]
|
||||
elif timer_ids:
|
||||
combined_meta['timer_ids'] = timer_ids
|
||||
elif kind == 'queued':
|
||||
# The user's own words, answered as an ordinary message.
|
||||
combined_meta = {}
|
||||
else:
|
||||
delegation_ids = [
|
||||
message['meta']['delegation_id']
|
||||
@@ -215,6 +307,11 @@ async def process_pending_internal_messages(
|
||||
'meta': combined_meta,
|
||||
'timestamp': int(time.time()),
|
||||
}
|
||||
if kind == 'queued':
|
||||
user_message.update(user_id=user.id, user={'id': user.id, 'name': user.name})
|
||||
held_files = [file for message in batch for file in message.get('files') or []]
|
||||
if held_files:
|
||||
user_message['files'] = held_files
|
||||
assistant_message = {
|
||||
'id': assistant_message_id,
|
||||
'parentId': user_message_id,
|
||||
@@ -285,7 +382,16 @@ async def process_pending_internal_messages(
|
||||
'skill_ids': run.get('skill_ids') or [],
|
||||
'filter_ids': run.get('filter_ids') or [],
|
||||
'features': run.get('features') or {},
|
||||
'files': run.get('files') or [],
|
||||
'files': [
|
||||
*(run.get('files') or []),
|
||||
# Documents attached to held messages; their images reach the model with the message itself.
|
||||
*[
|
||||
file
|
||||
for file in user_message.get('files') or []
|
||||
if file.get('type') in ('doc', 'text', 'note', 'chat', 'collection', 'folder')
|
||||
or (file.get('type') == 'file' and not is_raster_image_content_type(file.get('content_type')))
|
||||
],
|
||||
],
|
||||
'variables': run.get('variables') or {},
|
||||
'chat_variables': chat_context.get('chat_variables'),
|
||||
}
|
||||
@@ -360,19 +466,15 @@ async def delegate(
|
||||
'tool_ids': copy.deepcopy(metadata.get('tool_ids') or []),
|
||||
'skill_ids': copy.deepcopy(metadata.get('skill_ids') or []),
|
||||
'chat_context': copy.deepcopy(metadata.get('chat_context') or {}),
|
||||
'tool_servers': [] if background else copy.deepcopy(metadata.get('tool_servers') or []),
|
||||
'filter_ids': copy.deepcopy(metadata.get('filter_ids') or []),
|
||||
'terminal_id': metadata.get('terminal_id'),
|
||||
'features': features,
|
||||
'files': copy.deepcopy(metadata.get('files') or []),
|
||||
'variables': copy.deepcopy(metadata.get('variables') or {}),
|
||||
'direct': bool(metadata.get('direct')),
|
||||
'folder_id': folder_id,
|
||||
}
|
||||
if not run.get('model_id'):
|
||||
return 'Error: model context is required.'
|
||||
if run.get('direct'):
|
||||
return 'Error: sub-agents are unavailable for direct connections.'
|
||||
if model_id:
|
||||
available_models = await get_subagent_models(request, UserModel(**user_data), metadata.get('model') or {})
|
||||
available_ids = [model['id'] for model in available_models]
|
||||
@@ -537,8 +639,6 @@ async def delegate(
|
||||
}
|
||||
if run.get('terminal_id'):
|
||||
form_data['terminal_id'] = run['terminal_id']
|
||||
if run.get('tool_servers'):
|
||||
form_data['tool_servers'] = run['tool_servers']
|
||||
await request.app.state.CHAT_COMPLETION_HANDLER(child_request, form_data, user=user)
|
||||
message = await Chats.get_message_by_id_and_message_id(chat_id, assistant_message_id)
|
||||
if not message:
|
||||
@@ -667,23 +767,24 @@ async def delegate(
|
||||
updated_history = updated_chat.setdefault('history', {})
|
||||
updated_messages = updated_history.setdefault('messages', {})
|
||||
parent_message = updated_messages.get(parent_message_id)
|
||||
done_assistants = [
|
||||
is_active = await has_active_tasks(request.app.state.redis, parent_chat_id)
|
||||
assistants = [
|
||||
message
|
||||
for message_id, message in updated_messages.items()
|
||||
if message.get('role') == 'assistant'
|
||||
and message.get('done') is not False
|
||||
and (is_active or message.get('done') is not False)
|
||||
and (
|
||||
parent_message is None
|
||||
or any(entry is parent_message for entry in get_message_list(updated_messages, message_id))
|
||||
)
|
||||
]
|
||||
result_parent_id = (
|
||||
max(done_assistants, key=lambda message: message.get('timestamp', 0)).get('id')
|
||||
if done_assistants
|
||||
max(assistants, key=lambda message: message.get('timestamp', 0)).get('id')
|
||||
if assistants
|
||||
else parent_message_id
|
||||
)
|
||||
pending_message['parentId'] = result_parent_id
|
||||
if await has_active_tasks(request.app.state.redis, parent_chat_id):
|
||||
if is_active:
|
||||
pending_message['meta']['status'] = 'pending'
|
||||
updated_messages[pending_message_id] = pending_message
|
||||
if result_parent_id and result_parent_id in updated_messages:
|
||||
|
||||
@@ -6,9 +6,14 @@ import logging
|
||||
import ntpath
|
||||
import posixpath
|
||||
from pathlib import Path
|
||||
from urllib.parse import quote
|
||||
from urllib.parse import quote, unquote
|
||||
|
||||
from open_webui.env import AIOHTTP_CLIENT_TIMEOUT_TERMINAL, ENABLE_TOOL_SERVERS
|
||||
import aiohttp
|
||||
|
||||
from fastapi import HTTPException
|
||||
|
||||
from open_webui.env import AIOHTTP_CLIENT_SESSION_SSL, AIOHTTP_CLIENT_TIMEOUT_TERMINAL, ENABLE_TOOL_SERVERS
|
||||
from open_webui.utils.headers import bearer_auth_header
|
||||
from open_webui.utils.chat_id import is_saved_chat_id
|
||||
from open_webui.utils.skill_files import (
|
||||
SKILL_CONTENT_MAX_CHARS,
|
||||
@@ -18,10 +23,6 @@ from open_webui.utils.skill_files import (
|
||||
skill_overview,
|
||||
)
|
||||
|
||||
TERMINAL_CONTEXT_HEADER = 'X-Terminal-Context-Id'
|
||||
TERMINAL_CONTEXT_DEFAULT = 'default'
|
||||
TERMINAL_CONTEXT_TYPES = {'chat', 'automation'}
|
||||
TERMINAL_CONTEXT_ID_SOURCES = {'chat': 'chat_id', 'automation': 'automation_id'}
|
||||
TERMINAL_CHAT_UPLOAD_MODES = {'default', 'filesystem'}
|
||||
MAX_AGENTS_MD_BYTES = 32 * 1024
|
||||
|
||||
@@ -29,99 +30,11 @@ log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def is_terminal_orchestrator(connection: dict) -> bool:
|
||||
"""Return whether this connection points at Terminals, not raw Open Terminal."""
|
||||
return connection.get('server_type') == 'orchestrator' or bool(connection.get('policy_id'))
|
||||
return connection.get('server_type') == 'orchestrator'
|
||||
|
||||
|
||||
def get_terminal_server_url(connection: dict) -> str:
|
||||
"""Return the upstream base URL for a terminal connection.
|
||||
|
||||
An explicit policy uses the named-policy route. Connections without one
|
||||
keep their existing root route.
|
||||
"""
|
||||
base_url = str(connection.get('url') or '').rstrip('/')
|
||||
policy_id = str(connection.get('policy_id') or '').strip()
|
||||
if policy_id:
|
||||
return f'{base_url}/p/{quote(policy_id, safe="")}'
|
||||
return base_url
|
||||
|
||||
|
||||
def terminal_context_config(connection: dict, context: str) -> dict | bool:
|
||||
"""Return config for an OpenWebUI terminal context.
|
||||
|
||||
Missing config is legacy behavior: available, shared default terminal.
|
||||
"""
|
||||
if not is_terminal_orchestrator(connection):
|
||||
return {}
|
||||
|
||||
contexts = (connection.get('config') or {}).get('contexts')
|
||||
if not isinstance(contexts, dict):
|
||||
return {}
|
||||
|
||||
value = contexts.get(context, {})
|
||||
if value is False:
|
||||
return False
|
||||
return value if isinstance(value, dict) else {}
|
||||
|
||||
|
||||
def terminal_context_available(connection: dict, context: str) -> bool:
|
||||
"""Return whether this terminal is exposed in an OpenWebUI context."""
|
||||
if context not in TERMINAL_CONTEXT_TYPES:
|
||||
return False
|
||||
return terminal_context_config(connection, context) is not False
|
||||
|
||||
|
||||
def terminal_context_id(
|
||||
connection: dict,
|
||||
metadata: dict | None = None,
|
||||
context: str = 'chat',
|
||||
) -> str | None:
|
||||
"""Return the terminal runtime context for trusted request metadata."""
|
||||
if not is_terminal_orchestrator(connection) or not terminal_context_available(connection, context):
|
||||
return None
|
||||
|
||||
config = terminal_context_config(connection, context)
|
||||
context_id_source = config.get('context_id') if isinstance(config, dict) else None
|
||||
if not context_id_source or context_id_source == TERMINAL_CONTEXT_DEFAULT:
|
||||
return None
|
||||
|
||||
if context_id_source != TERMINAL_CONTEXT_ID_SOURCES.get(context):
|
||||
return None
|
||||
|
||||
metadata = metadata or {}
|
||||
|
||||
if context == 'automation':
|
||||
automation_id = metadata.get('automation_id')
|
||||
return f'automation:{automation_id}' if automation_id else None
|
||||
|
||||
chat_id = metadata.get('chat_id')
|
||||
if context == 'chat' and chat_id and is_saved_chat_id(chat_id):
|
||||
return f'chat:{chat_id}'
|
||||
return None
|
||||
|
||||
|
||||
def terminal_contexts(connection: dict) -> dict:
|
||||
"""Return normalized sparse context config for clients."""
|
||||
if not is_terminal_orchestrator(connection):
|
||||
return {}
|
||||
|
||||
contexts = (connection.get('config') or {}).get('contexts')
|
||||
if not isinstance(contexts, dict):
|
||||
return {}
|
||||
|
||||
result = {}
|
||||
for context, value in contexts.items():
|
||||
if context not in TERMINAL_CONTEXT_TYPES:
|
||||
continue
|
||||
if value is False:
|
||||
result[context] = False
|
||||
elif isinstance(value, dict):
|
||||
context_id_source = value.get('context_id')
|
||||
if context_id_source in {TERMINAL_CONTEXT_DEFAULT, TERMINAL_CONTEXT_ID_SOURCES[context]}:
|
||||
result[context] = {'context_id': context_id_source}
|
||||
else:
|
||||
result[context] = {}
|
||||
return result
|
||||
return str(connection.get('url') or '').rstrip('/')
|
||||
|
||||
|
||||
def terminal_chat_uploads(connection: dict) -> str:
|
||||
@@ -130,49 +43,371 @@ def terminal_chat_uploads(connection: dict) -> str:
|
||||
return value if value in TERMINAL_CHAT_UPLOAD_MODES else 'default'
|
||||
|
||||
|
||||
async def resolve_terminal_connection(request, user, metadata):
|
||||
"""Resolve an authorized backend connection and trusted runtime headers."""
|
||||
terminal_id = metadata.get('terminal_id')
|
||||
if not ENABLE_TOOL_SERVERS or not terminal_id:
|
||||
return None
|
||||
from open_webui.utils.tether import get_terminal_connections
|
||||
async def server_request(connection, path, *, method='GET', body=None, params=None):
|
||||
if not connection.get('key'):
|
||||
raise HTTPException(503, 'A Terminals server key is required')
|
||||
url = connection['url'].rstrip('/') + '/' + path.lstrip('/')
|
||||
try:
|
||||
async with aiohttp.ClientSession(trust_env=True, timeout=aiohttp.ClientTimeout(total=180)) as session:
|
||||
async with session.request(
|
||||
method,
|
||||
url,
|
||||
headers=bearer_auth_header(connection['key']),
|
||||
json=body,
|
||||
params=params,
|
||||
ssl=AIOHTTP_CLIENT_SESSION_SSL,
|
||||
allow_redirects=False,
|
||||
) as response:
|
||||
if response.status >= 300:
|
||||
try:
|
||||
detail = (await response.json()).get('detail', 'Terminals request failed')
|
||||
except Exception:
|
||||
detail = 'Terminals request failed'
|
||||
raise HTTPException(response.status if response.status >= 400 else 502, detail)
|
||||
return await response.json()
|
||||
except (aiohttp.ClientError, asyncio.TimeoutError):
|
||||
raise HTTPException(503, 'Terminals is unavailable')
|
||||
|
||||
|
||||
async def get_connection(user, connection_id):
|
||||
from open_webui.models.config import Config
|
||||
from open_webui.utils.access_control import has_connection_access
|
||||
|
||||
if not ENABLE_TOOL_SERVERS:
|
||||
raise HTTPException(403, 'Tool servers are disabled')
|
||||
connections = await Config.get('terminal_server.connections', []) or []
|
||||
connection = next((c for c in connections if c.get('id') == connection_id), None)
|
||||
if not connection or not connection.get('enabled', True) or connection.get('server_type') != 'orchestrator':
|
||||
raise HTTPException(404, 'Managed terminal connection not found')
|
||||
if not await has_connection_access(user, connection) and not await has_connection_write_access(user, connection):
|
||||
raise HTTPException(403, 'Terminal connection access denied')
|
||||
return connection
|
||||
|
||||
|
||||
async def has_connection_write_access(user, connection, user_group_ids=None):
|
||||
from open_webui.models.groups import Groups
|
||||
from open_webui.utils.access_control import has_access
|
||||
|
||||
from open_webui.config import BYPASS_ADMIN_ACCESS_CONTROL
|
||||
|
||||
if user.role == 'admin' and (
|
||||
BYPASS_ADMIN_ACCESS_CONTROL or not (connection.get('config') or {}).get('access_grants')
|
||||
):
|
||||
return True
|
||||
if user_group_ids is None:
|
||||
user_group_ids = {g.id for g in await Groups.get_groups_by_member_id(user.id, include_inherited=True)}
|
||||
return await has_access(user.id, 'write', (connection.get('config') or {}).get('access_grants', []), user_group_ids)
|
||||
|
||||
|
||||
def template_terminal_id(connection_id, template_id):
|
||||
return f'template:{connection_id}:{quote(template_id, safe="")}'
|
||||
|
||||
|
||||
async def has_terminal_write_access(user, terminal_id):
|
||||
"""Write access to a terminal's connection, the right that lists, restarts and deletes its instances."""
|
||||
if not terminal_id.startswith('template:'):
|
||||
return False
|
||||
connection_id, _ = split_template_id(terminal_id)
|
||||
return await has_connection_write_access(user, await get_connection(user, connection_id))
|
||||
|
||||
|
||||
def split_template_id(terminal_id):
|
||||
if not terminal_id.startswith('template:'):
|
||||
raise HTTPException(400, 'Invalid template terminal ID')
|
||||
connection_id, separator, encoded = terminal_id.removeprefix('template:').rpartition(':')
|
||||
template_id = unquote(encoded)
|
||||
if (
|
||||
not separator
|
||||
or not connection_id
|
||||
or not template_id
|
||||
or template_terminal_id(connection_id, template_id) != terminal_id
|
||||
):
|
||||
raise HTTPException(400, 'Invalid template terminal ID')
|
||||
return connection_id, template_id
|
||||
|
||||
|
||||
async def require_terminal_access(user, terminal_id):
|
||||
from open_webui.models.access_grants import AccessGrants
|
||||
from open_webui.config import BYPASS_ADMIN_ACCESS_CONTROL
|
||||
|
||||
if user.role == 'admin' and BYPASS_ADMIN_ACCESS_CONTROL:
|
||||
return
|
||||
if await AccessGrants.has_access(user.id, 'terminal', terminal_id, 'read'):
|
||||
return
|
||||
raise HTTPException(403, 'Terminal access denied')
|
||||
|
||||
|
||||
async def template_connection(user, terminal_id, permission='read'):
|
||||
connection_id, template_id = split_template_id(terminal_id)
|
||||
connection = await get_connection(user, connection_id)
|
||||
if not await has_connection_write_access(user, connection):
|
||||
if permission == 'write':
|
||||
raise HTTPException(403, 'Terminal connection write access required')
|
||||
await require_terminal_access(user, terminal_id)
|
||||
template = await server_request(connection, f'api/v1/terminals/templates/{quote(template_id, safe="")}')
|
||||
return connection, template
|
||||
|
||||
|
||||
async def list_template_connections(user, connections):
|
||||
from open_webui.models.access_grants import AccessGrants
|
||||
from open_webui.models.groups import Groups
|
||||
from open_webui.models.users import UserModel
|
||||
from open_webui.utils.access_control import has_connection_access
|
||||
|
||||
if not isinstance(user, UserModel):
|
||||
user = UserModel(**user)
|
||||
group_ids = {group.id for group in await Groups.get_groups_by_member_id(user.id, include_inherited=True)}
|
||||
result = []
|
||||
for connection in connections:
|
||||
if connection.get('server_type') != 'orchestrator' or not connection.get('enabled', True):
|
||||
continue
|
||||
writable = await has_connection_write_access(user, connection, group_ids)
|
||||
if not writable and not await has_connection_access(user, connection, group_ids):
|
||||
continue
|
||||
try:
|
||||
templates = await server_request(connection, 'api/v1/terminals/templates')
|
||||
except HTTPException as exc:
|
||||
log.warning('Cannot list templates for connection %s: HTTP %s', connection['id'], exc.status_code)
|
||||
continue
|
||||
selectors = [template_terminal_id(connection['id'], template['id']) for template in templates]
|
||||
readable = (
|
||||
set(selectors)
|
||||
if writable
|
||||
else await AccessGrants.get_accessible_resource_ids(
|
||||
user_id=user.id,
|
||||
resource_type='terminal',
|
||||
resource_ids=selectors,
|
||||
permission='read',
|
||||
user_group_ids=group_ids,
|
||||
)
|
||||
)
|
||||
for template, selector in zip(templates, selectors):
|
||||
if selector not in readable:
|
||||
continue
|
||||
data = template.get('data') or {}
|
||||
result.append(
|
||||
{
|
||||
**connection,
|
||||
'id': selector,
|
||||
'name': data.get('name') or template['id'],
|
||||
'template_id': template['id'],
|
||||
'scope': data.get('scope'),
|
||||
'auth_type': 'bearer',
|
||||
}
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
class MissingTerminalContext(HTTPException):
|
||||
def __init__(self, scope):
|
||||
detail = 'This terminal requires a saved chat' if scope == 'chat' else f'This terminal requires a {scope}'
|
||||
super().__init__(409, detail)
|
||||
|
||||
|
||||
def get_terminal_context(template, user_id, metadata=None):
|
||||
"""Validate a template's scope and return context for its environment."""
|
||||
metadata = metadata or {}
|
||||
scope = (template.get('data') or {}).get('scope')
|
||||
if scope not in (None, 'user', 'chat', 'model'):
|
||||
raise HTTPException(422, 'Invalid template scope')
|
||||
chat_id = metadata.get('chat_id')
|
||||
model_id = metadata.get('model_id') or metadata.get('model')
|
||||
if scope == 'chat' and not is_saved_chat_id(chat_id):
|
||||
raise MissingTerminalContext(scope)
|
||||
if scope == 'model' and not model_id:
|
||||
raise MissingTerminalContext(scope)
|
||||
return {
|
||||
'user_id': user_id,
|
||||
'chat_id': chat_id if is_saved_chat_id(chat_id) else None,
|
||||
'model_id': model_id if scope == 'model' else None,
|
||||
}
|
||||
|
||||
|
||||
async def require_model_access(user, model_id, terminal_id, request=None):
|
||||
if not model_id:
|
||||
raise MissingTerminalContext('model')
|
||||
if model_id.startswith('agent:'):
|
||||
parts = model_id.split(':', 3)
|
||||
if len(parts) != 4 or unquote(parts[1]) != terminal_id or not all(parts[1:]):
|
||||
raise HTTPException(403, 'Agent model does not belong to this terminal')
|
||||
# Agent access follows its terminal. Execution still validates the live agent catalog.
|
||||
return
|
||||
from open_webui.models.models import Models
|
||||
from open_webui.utils.models import check_model_access, get_all_models, get_filtered_models
|
||||
|
||||
if request is not None:
|
||||
models = await get_all_models(request, user=user)
|
||||
permitted = await get_filtered_models(models, user)
|
||||
if not any(model['id'] == model_id for model in permitted):
|
||||
raise HTTPException(403, 'Model access denied')
|
||||
else:
|
||||
row = await Models.get_model_by_id(model_id)
|
||||
if row is None:
|
||||
raise HTTPException(403, 'Model not found')
|
||||
try:
|
||||
await check_model_access(user, {'id': model_id}, row)
|
||||
except Exception as exc:
|
||||
raise HTTPException(403, 'Model access denied') from exc
|
||||
|
||||
|
||||
def terminal_headers(connection):
|
||||
"""Only consumes context produced by find_terminal_connection, never browser headers."""
|
||||
if not connection.get('template_id'):
|
||||
return {'X-User-Id': connection['instance_user_id']} if connection.get('instance_user_id') else {}
|
||||
context = connection['terminal_context']
|
||||
headers = {
|
||||
'X-Terminal-Template-Id': connection['template_id'],
|
||||
'X-User-Id': context['user_id'],
|
||||
}
|
||||
if context.get('chat_id'):
|
||||
headers['X-Terminal-Chat-Id'] = context['chat_id']
|
||||
if context.get('model_id'):
|
||||
headers['X-Terminal-Model-Id'] = context['model_id']
|
||||
return headers
|
||||
|
||||
|
||||
async def find_terminal_connection(user, terminal_id, metadata=None, request=None):
|
||||
from open_webui.models.chats import Chats
|
||||
from open_webui.models.users import UserModel, Users
|
||||
from open_webui.utils.access_control import has_connection_access
|
||||
from open_webui.utils.tether import get_terminal_connections
|
||||
|
||||
if not ENABLE_TOOL_SERVERS:
|
||||
raise HTTPException(403, 'Tool servers are disabled')
|
||||
if not isinstance(user, UserModel):
|
||||
user = UserModel(**user)
|
||||
metadata = dict(metadata or {})
|
||||
|
||||
async def find_instance_user_connection(instance_user_id):
|
||||
# Another person's instance is reached as they would reach it, by whoever manages the terminal.
|
||||
instance_user = (
|
||||
await Users.get_user_by_id(instance_user_id) if await has_terminal_write_access(user, terminal_id) else None
|
||||
)
|
||||
if instance_user is None:
|
||||
raise HTTPException(403, 'Instance access denied')
|
||||
connection = await find_terminal_connection(instance_user, terminal_id, metadata, request=request)
|
||||
return connection and {'instance_user_id': instance_user.id, **connection}
|
||||
|
||||
instance_user_id = metadata.pop('instance_user_id', None)
|
||||
if instance_user_id and instance_user_id != user.id:
|
||||
return await find_instance_user_connection(instance_user_id)
|
||||
chat = None
|
||||
shared_session = None
|
||||
instance_user = user
|
||||
chat_id = metadata.get('chat_id')
|
||||
if chat_id and is_saved_chat_id(chat_id):
|
||||
chat = await Chats.get_accessible_chat_by_id(chat_id, user, permission='write')
|
||||
if chat is None:
|
||||
other = await Chats.get_chat_by_id(chat_id)
|
||||
if other is None or not await has_terminal_write_access(user, terminal_id):
|
||||
raise HTTPException(403, 'Chat access denied')
|
||||
return await find_instance_user_connection(other.user_id)
|
||||
if chat.meta.get('internal') is True and chat.meta.get('type') == 'subagent':
|
||||
# A sub-agent shares the instance and files of its parent chat.
|
||||
metadata['chat_id'] = chat.meta.get('parent_chat_id')
|
||||
return await find_terminal_connection(user, terminal_id, metadata, request=request)
|
||||
from open_webui.utils.agents.session import get_session, model_id
|
||||
|
||||
shared_session = await get_session(chat)
|
||||
if shared_session and shared_session['terminal_id'] != terminal_id:
|
||||
shared_session = None
|
||||
if shared_session:
|
||||
metadata['model_id'] = model_id(shared_session)
|
||||
instance_user_id = shared_session.get('instance_user_id') or shared_session['user']
|
||||
instance_user = user if instance_user_id == user.id else await Users.get_user_by_id(instance_user_id)
|
||||
if instance_user is None:
|
||||
raise HTTPException(403, 'Agent terminal owner is unavailable')
|
||||
|
||||
def authorized_connection(connection):
|
||||
if shared_session:
|
||||
connection = {**connection, 'instance_user_id': instance_user.id}
|
||||
return connection
|
||||
|
||||
if not terminal_id.startswith('template:'):
|
||||
connections = await get_terminal_connections(instance_user, include_templates=False)
|
||||
connection = next((c for c in connections if c.get('id') == terminal_id), None)
|
||||
if (
|
||||
not connection
|
||||
or not connection.get('enabled', True)
|
||||
or not await has_connection_access(instance_user, connection)
|
||||
):
|
||||
return None
|
||||
if is_terminal_orchestrator(connection):
|
||||
raise HTTPException(409, 'Select a terminal template')
|
||||
return authorized_connection(connection)
|
||||
|
||||
connection_id, template_id = split_template_id(terminal_id)
|
||||
connection = await get_connection(instance_user, connection_id)
|
||||
template = await server_request(connection, f'api/v1/terminals/templates/{quote(template_id, safe="")}')
|
||||
scope = (template.get('data') or {}).get('scope')
|
||||
|
||||
if chat and not shared_session:
|
||||
stored = (chat.chat or {}).get('terminal_id')
|
||||
if chat.user_id != user.id and stored != terminal_id:
|
||||
raise HTTPException(403, 'Use the terminal selected by the chat owner')
|
||||
if stored and stored != terminal_id:
|
||||
raise HTTPException(409, 'Chat terminal selection changed; refresh the chat')
|
||||
|
||||
principal = instance_user
|
||||
if not shared_session and scope == 'chat' and chat:
|
||||
owner = user if chat.user_id == user.id else await Users.get_user_by_id(chat.user_id)
|
||||
if owner is None:
|
||||
raise HTTPException(403, 'Chat owner is unavailable')
|
||||
if (
|
||||
owner.id != instance_user.id
|
||||
and not await has_connection_access(owner, connection)
|
||||
and not await has_connection_write_access(owner, connection)
|
||||
):
|
||||
raise HTTPException(403, 'Terminal connection access denied')
|
||||
principal = owner
|
||||
if not await has_connection_write_access(principal, connection):
|
||||
await require_terminal_access(principal, terminal_id)
|
||||
|
||||
context = get_terminal_context(template, instance_user.id, metadata)
|
||||
if scope == 'model':
|
||||
await require_model_access(instance_user, context['model_id'], terminal_id, request)
|
||||
if metadata.get('automation_id'):
|
||||
from open_webui.models.automations import Automations
|
||||
|
||||
automation = await Automations.get_by_id(metadata['automation_id'])
|
||||
if not automation or automation.user_id != user.id:
|
||||
raise HTTPException(403, 'Automation terminal access denied')
|
||||
return authorized_connection(
|
||||
{
|
||||
**connection,
|
||||
'id': terminal_id,
|
||||
'name': (template.get('data') or {}).get('name') or template_id,
|
||||
'template_id': template_id,
|
||||
'scope': scope,
|
||||
'auth_type': 'bearer',
|
||||
'terminal_context': context,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
async def resolve_terminal_connection(request, user, metadata):
|
||||
"""Resolve an authorized backend connection and trusted instance headers."""
|
||||
terminal_id = metadata.get('terminal_id')
|
||||
if not ENABLE_TOOL_SERVERS or not terminal_id:
|
||||
return None
|
||||
from open_webui.models.users import UserModel
|
||||
from open_webui.utils.tools import build_tool_server_headers
|
||||
|
||||
user_model = user if isinstance(user, UserModel) else UserModel(**user)
|
||||
connections = await get_terminal_connections(user_model)
|
||||
connection = next((item for item in connections if item.get('id') == terminal_id), None)
|
||||
connection = await find_terminal_connection(user_model, terminal_id, metadata, request=request)
|
||||
|
||||
if connection:
|
||||
terminal_context = 'automation' if metadata.get('automation_id') else 'chat'
|
||||
context_id = terminal_context_id(connection, metadata, terminal_context)
|
||||
config = terminal_context_config(connection, terminal_context)
|
||||
if (
|
||||
not connection.get('enabled', True)
|
||||
or not terminal_context_available(connection, terminal_context)
|
||||
or (config.get('context_id') in {'chat_id', 'automation_id'} and not context_id)
|
||||
):
|
||||
return None
|
||||
user_group_ids = {
|
||||
group.id for group in await Groups.get_groups_by_member_id(user_model.id, include_inherited=True)
|
||||
}
|
||||
if not await has_connection_access(user_model, connection, user_group_ids):
|
||||
return None
|
||||
|
||||
headers, cookies = await build_tool_server_headers(
|
||||
connection,
|
||||
request,
|
||||
user_model,
|
||||
metadata=metadata,
|
||||
)
|
||||
headers.update(terminal_headers(connection))
|
||||
headers['Accept'] = 'application/json'
|
||||
headers['X-User-Id'] = user_model.id
|
||||
headers['X-User-Id'] = connection.get('instance_user_id', user_model.id)
|
||||
if metadata.get('chat_id'):
|
||||
headers['X-Session-Id'] = metadata['chat_id']
|
||||
if context_id:
|
||||
headers[TERMINAL_CONTEXT_HEADER] = context_id
|
||||
return connection, headers, cookies
|
||||
return None
|
||||
|
||||
@@ -188,7 +423,7 @@ async def get_terminal_json(
|
||||
method: str = 'GET',
|
||||
body: dict | None = None,
|
||||
):
|
||||
"""Read JSON or upload a file through an admin terminal or a personal terminal's browser."""
|
||||
"""Read JSON or upload a file through the chat's terminal connection."""
|
||||
metadata = metadata or {}
|
||||
terminal_id = metadata.get('terminal_id')
|
||||
if not ENABLE_TOOL_SERVERS or not terminal_id:
|
||||
@@ -208,7 +443,7 @@ async def get_terminal_json(
|
||||
from open_webui.storage.provider import Storage
|
||||
|
||||
source = await Files.get_file_by_id(file['id'])
|
||||
if not source or source.user_id != headers['X-User-Id'] or not source.path:
|
||||
if not source or source.user_id != (user.id if hasattr(user, 'id') else user['id']) or not source.path:
|
||||
return None
|
||||
local_path = await asyncio.to_thread(Storage.get_file, source.path)
|
||||
body = aiohttp.FormData()
|
||||
@@ -223,7 +458,8 @@ async def get_terminal_json(
|
||||
try:
|
||||
async with get_terminal_client(
|
||||
get_terminal_server_url(connection),
|
||||
user.id if hasattr(user, 'id') else user['id'],
|
||||
connection.get('instance_user_id') or (user.id if hasattr(user, 'id') else user['id']),
|
||||
service=connection.get('service', 'open_terminal'),
|
||||
timeout=timeout,
|
||||
trust_env=True,
|
||||
) as session:
|
||||
@@ -243,21 +479,6 @@ async def get_terminal_json(
|
||||
f"Terminal '{connection.get('name') or terminal_id}' timed out. "
|
||||
'It may still be starting. Please try again.'
|
||||
) from error
|
||||
|
||||
event_caller = (extra_params or {}).get('__event_call__')
|
||||
if event_caller:
|
||||
result = await event_caller(
|
||||
{
|
||||
'type': 'request:terminal',
|
||||
'data': {
|
||||
'terminal_id': terminal_id,
|
||||
'path': path,
|
||||
'session_id': metadata.get('session_id'),
|
||||
**({'file': file} if file else {}),
|
||||
},
|
||||
}
|
||||
)
|
||||
return result.get('data') if isinstance(result, dict) else None
|
||||
return None
|
||||
|
||||
|
||||
@@ -308,25 +529,16 @@ async def filter_user_terminal_tools(request, user, tools: dict, metadata: dict,
|
||||
shell_tools = {
|
||||
name: tool
|
||||
for name, tool in tools.items()
|
||||
if name in {'read_user_terminal', 'send_user_terminal_input'}
|
||||
and (tool.get('type') == 'terminal' or tool.get('server', {}).get('is_terminal') is True)
|
||||
if name in {'read_user_terminal', 'send_user_terminal_input'} and tool.get('type') == 'terminal'
|
||||
}
|
||||
selected = {
|
||||
name: tool
|
||||
for name, tool in shell_tools.items()
|
||||
if terminal_id
|
||||
and (
|
||||
tool.get('tool_id') == f'terminal:{terminal_id}'
|
||||
or (tool.get('direct') and tool.get('server', {}).get('url') == terminal_id)
|
||||
)
|
||||
if terminal_id and tool.get('tool_id') == f'terminal:{terminal_id}'
|
||||
}
|
||||
available = False
|
||||
if selected and not metadata.get('automation_id') and not metadata.get('internal'):
|
||||
available = any(
|
||||
tool.get('user_shell_tools') == 'always'
|
||||
or (tool.get('direct') and (tool.get('server', {}).get('config') or {}).get('user_shell_tools') == 'always')
|
||||
for tool in selected.values()
|
||||
)
|
||||
available = any(tool.get('user_shell_tools') == 'always' for tool in selected.values())
|
||||
if not available and metadata.get('chat_id'):
|
||||
try:
|
||||
# This endpoint checks ownership, a live process, and a connected shell.
|
||||
@@ -400,7 +612,8 @@ async def get_terminal_file(request, user, metadata: dict, path: str, *, max_byt
|
||||
base_url = get_terminal_server_url(connection)
|
||||
async with get_terminal_client(
|
||||
base_url,
|
||||
user.id if hasattr(user, 'id') else user['id'],
|
||||
connection.get('instance_user_id') or (user.id if hasattr(user, 'id') else user['id']),
|
||||
service=connection.get('service', 'open_terminal'),
|
||||
timeout=aiohttp.ClientTimeout(total=AIOHTTP_CLIENT_TIMEOUT_TERMINAL),
|
||||
trust_env=True,
|
||||
) as session:
|
||||
|
||||
@@ -18,16 +18,33 @@ from open_webui.models.auth_sessions import AuthSessions
|
||||
from open_webui.models.config import Config
|
||||
|
||||
CHUNK = 65536
|
||||
WINDOW = 2 * 1024 * 1024
|
||||
# ~40 MB/s per stream at 100 ms round trip. Buffers fill only while a reader falls behind.
|
||||
WINDOW = 4 * 1024 * 1024
|
||||
MAX_MESSAGE = 16 * 1024 * 1024
|
||||
# Used when Tether does not state its own limit.
|
||||
DEFAULT_CONCURRENT_STREAMS = 16
|
||||
MAX_CONCURRENT_STREAMS = 64
|
||||
# Both ends may buffer one window per open stream, so streams × window stays within this.
|
||||
BUFFER_BUDGET = MAX_CONCURRENT_STREAMS * WINDOW
|
||||
# The receive window bounds bytes; frames are counted only to bound floods of tiny ones.
|
||||
MIN_FRAME_COST = 64
|
||||
SAFE_METHODS = ('GET', 'HEAD', 'OPTIONS')
|
||||
# One default for every service: long streams stay open while data flows; silence ends them.
|
||||
TIMEOUT = aiohttp.ClientTimeout(total=None, sock_read=300)
|
||||
|
||||
|
||||
class RelayInterrupted(ConnectionError):
|
||||
def __init__(self, reason='Connection lost'):
|
||||
def __init__(self, reason='Connection lost', disconnected=False):
|
||||
super().__init__(
|
||||
f'Tether connection interrupted: {reason}. '
|
||||
'The operation may have completed. Check its result before trying again; do not automatically repeat it.'
|
||||
)
|
||||
# Set when Tether's socket dropped, as opposed to a timeout or a rejected operation.
|
||||
self.disconnected = disconnected
|
||||
# Set when no response header arrived; with a safe method the request can be repeated once.
|
||||
self.before_response = False
|
||||
self.connection = None
|
||||
self.device = None
|
||||
|
||||
def result(self):
|
||||
return {'error': str(self), 'code': 'tether_interrupted', 'outcome': 'unknown', 'retryable': False}
|
||||
@@ -43,6 +60,53 @@ def get_services(value):
|
||||
return list(dict.fromkeys(value))
|
||||
|
||||
|
||||
def get_max_concurrent_streams(hello, window):
|
||||
"""Tether's stated stream limit, bounded so each open stream can hold a full window."""
|
||||
value = hello.get('max_concurrent_streams', DEFAULT_CONCURRENT_STREAMS)
|
||||
if type(value) is not int or value < 1:
|
||||
raise ValueError('Invalid stream limit')
|
||||
return min(value, MAX_CONCURRENT_STREAMS, BUFFER_BUDGET // window)
|
||||
|
||||
|
||||
def get_connections(value):
|
||||
"""Connections the user added in Tether. Each is a relay service of its own, like `open_terminal`;
|
||||
URLs and keys stay on the device."""
|
||||
if value is None:
|
||||
return []
|
||||
if not isinstance(value, list) or len(value) > 16:
|
||||
raise ValueError('Invalid Tether connections')
|
||||
connections = []
|
||||
for item in value:
|
||||
if (
|
||||
not isinstance(item, dict)
|
||||
or item.get('type') not in ('openai', 'openapi', 'terminal', 'mcp')
|
||||
or not isinstance(item.get('name'), str)
|
||||
):
|
||||
raise ValueError('Invalid Tether connection')
|
||||
service = get_services([item.get('service')])[0]
|
||||
connection = {'service': service, 'name': item['name'].strip()[:100] or service, 'type': item['type']}
|
||||
if item['type'] == 'mcp':
|
||||
if item.get('transport') not in ('stdio', 'streamable-http'):
|
||||
raise ValueError('Invalid MCP transport')
|
||||
connection['transport'] = item['transport']
|
||||
revision = item.get('revision', '')
|
||||
if not isinstance(revision, str) or len(revision) > 64:
|
||||
raise ValueError('Invalid MCP revision')
|
||||
connection['revision'] = revision
|
||||
connections.append(connection)
|
||||
return connections
|
||||
|
||||
|
||||
async def get_tether_connections(user_id, type):
|
||||
"""(presence, connection) pairs of this type across the user's online devices."""
|
||||
return [
|
||||
(presence, item)
|
||||
for presence in await hub.presences(user_id)
|
||||
for item in presence.get('connections', [])
|
||||
if item['type'] == type and item['service'] in presence.get('services', [])
|
||||
]
|
||||
|
||||
|
||||
def encode(header, data=b''):
|
||||
raw = json.dumps(header, separators=(',', ':')).encode()
|
||||
if len(raw) > 4096 or len(data) > CHUNK:
|
||||
@@ -76,7 +140,8 @@ class Stream:
|
||||
self.window = presence.get('window', 256 * 1024)
|
||||
self.credit = self.receive_credit = self.window
|
||||
self.wake = asyncio.Event()
|
||||
self.queue = asyncio.Queue(maxsize=64)
|
||||
# Model output arrives as many tiny frames; a count of 64 failed streams far inside their window.
|
||||
self.queue = asyncio.Queue(maxsize=self.window // MIN_FRAME_COST)
|
||||
self.closed = False
|
||||
self.lock = asyncio.Lock()
|
||||
self.error = None
|
||||
@@ -108,14 +173,18 @@ class Stream:
|
||||
try:
|
||||
await self.owner.send(self.presence, header, data)
|
||||
except (OSError, TimeoutError) as error:
|
||||
self.fail(str(error) or 'Send failed')
|
||||
self.fail(str(error) or 'Send failed', disconnected=isinstance(error, ConnectionError))
|
||||
raise self.error from error
|
||||
|
||||
def feed(self, header, data):
|
||||
if self.closed:
|
||||
return
|
||||
if header['sequence'] != self.incoming:
|
||||
self.fail('Missing relay packet')
|
||||
if header['type'] == 'error':
|
||||
# Failures sent on another's behalf (a dropped socket, a full device) carry sequence 0.
|
||||
self.fail(str(header.get('message', 'Response interrupted'))[:500], header.get('disconnected') is True)
|
||||
else:
|
||||
self.fail('Missing relay packet')
|
||||
return
|
||||
self.incoming += 1
|
||||
if header['type'] == 'window':
|
||||
@@ -135,13 +204,15 @@ class Stream:
|
||||
except asyncio.QueueFull:
|
||||
self.fail('Relay consumer too slow')
|
||||
|
||||
def fail(self, message):
|
||||
self.error = RelayInterrupted(message)
|
||||
def fail(self, message, disconnected=False):
|
||||
if self.error:
|
||||
return
|
||||
self.error = RelayInterrupted(message, disconnected)
|
||||
self.closed = True
|
||||
self.wake.set()
|
||||
while not self.queue.empty():
|
||||
self.queue.get_nowait()
|
||||
self.queue.put_nowait(({'type': 'error', 'message': message}, b''))
|
||||
self.queue.put_nowait(({'type': 'error', 'message': message, 'disconnected': disconnected}, b''))
|
||||
|
||||
async def receive(self):
|
||||
if self.error:
|
||||
@@ -152,7 +223,7 @@ class Stream:
|
||||
self.fail('Response timed out')
|
||||
raise self.error from error
|
||||
if header['type'] == 'error':
|
||||
self.fail(header.get('message', 'Response interrupted'))
|
||||
self.fail(str(header.get('message', 'Response interrupted'))[:500], header.get('disconnected') is True)
|
||||
raise self.error
|
||||
return header, data
|
||||
|
||||
@@ -184,6 +255,65 @@ class Stream:
|
||||
self.owner.streams.pop(self.id, None)
|
||||
|
||||
|
||||
class Connection:
|
||||
"""A Tether socket held by this worker."""
|
||||
|
||||
def __init__(self, ws, presence):
|
||||
self.ws, self.presence = ws, presence
|
||||
# Stream id -> worker awaiting the replies.
|
||||
self.routes = {}
|
||||
self.lock = asyncio.Lock()
|
||||
# Frames from other workers go through one ordered queue, so a slow socket never blocks the
|
||||
# worker's Redis listener and the other devices it serves.
|
||||
self.outbox = asyncio.Queue()
|
||||
self.queued = 0
|
||||
self.closing = None
|
||||
self.forwarder = asyncio.create_task(self._forward())
|
||||
|
||||
def full(self):
|
||||
return len(self.routes) >= self.presence.get('max_concurrent_streams', DEFAULT_CONCURRENT_STREAMS)
|
||||
|
||||
async def send(self, header, data):
|
||||
# Lock waiters are FIFO; each stream yields after one chunk.
|
||||
async with self.lock:
|
||||
try:
|
||||
await asyncio.wait_for(self.ws.send_bytes(encode(header, data)), 10)
|
||||
except TimeoutError as error:
|
||||
# A socket that cannot drain fails every stream at once, not each after its own timeout.
|
||||
await self.disconnect()
|
||||
raise ConnectionError('Tether is not receiving') from error
|
||||
|
||||
def forward(self, header, data):
|
||||
if self.closing:
|
||||
return
|
||||
if self.queued + len(data) > BUFFER_BUDGET:
|
||||
# Never block the listener on a stuck socket: drop the connection in the background.
|
||||
self.closing = asyncio.create_task(self.disconnect())
|
||||
return
|
||||
self.queued += len(data)
|
||||
self.outbox.put_nowait((header, data))
|
||||
|
||||
async def _forward(self):
|
||||
while True:
|
||||
header, data = await self.outbox.get()
|
||||
self.queued -= len(data)
|
||||
try:
|
||||
await self.send(header, data)
|
||||
except Exception:
|
||||
# The router's cleanup fails the affected streams on every worker.
|
||||
await self.disconnect()
|
||||
return
|
||||
|
||||
async def disconnect(self):
|
||||
with suppress(Exception):
|
||||
async with asyncio.timeout(5):
|
||||
await self.ws.close(code=1011)
|
||||
|
||||
async def close(self):
|
||||
self.forwarder.cancel()
|
||||
await asyncio.gather(self.forwarder, return_exceptions=True)
|
||||
|
||||
|
||||
class Hub:
|
||||
def __init__(self):
|
||||
self.worker = str(uuid4())
|
||||
@@ -229,26 +359,15 @@ class Hub:
|
||||
async for message in pubsub.listen():
|
||||
if message['type'] != 'message':
|
||||
continue
|
||||
header, data = decode(message['data'])
|
||||
try:
|
||||
header, data = decode(message['data'])
|
||||
except ValueError:
|
||||
# One malformed frame must not drop every relay this worker holds.
|
||||
continue
|
||||
if header.pop('route', None) == 'connection':
|
||||
connection = self.connections.get(header.pop('connection', ''))
|
||||
if not connection:
|
||||
continue
|
||||
if header['type'] == 'notification':
|
||||
await connection.send(header, data)
|
||||
continue
|
||||
reply = header.pop('reply', '')
|
||||
if header['type'] in ('http-open', 'ws-open'):
|
||||
if len(connection.routes) >= 16:
|
||||
continue
|
||||
connection.routes[header['stream']] = reply
|
||||
elif connection.routes.get(header['stream']) != reply:
|
||||
continue
|
||||
try:
|
||||
await connection.send(header, data)
|
||||
finally:
|
||||
if header['type'] == 'cancel':
|
||||
connection.routes.pop(header['stream'], None)
|
||||
if connection:
|
||||
await self.deliver(connection, header.pop('reply', ''), header, data)
|
||||
else:
|
||||
stream = self.streams.get(header['stream'])
|
||||
if stream and header.pop('connection', None) == stream.presence['connection']:
|
||||
@@ -262,6 +381,41 @@ class Hub:
|
||||
finally:
|
||||
await pubsub.aclose()
|
||||
|
||||
async def deliver(self, connection, reply, header, data):
|
||||
"""Accept a frame another worker sent to a Tether socket held here."""
|
||||
stream_id = header['stream']
|
||||
if header['type'] in ('http-open', 'ws-open', 'stdio-open'):
|
||||
# This worker holds the socket, so its count is the device's true count.
|
||||
if connection.full():
|
||||
await self.reject(reply, connection, stream_id, 'Tether has too many active operations.')
|
||||
return
|
||||
connection.routes[stream_id] = reply
|
||||
elif header['type'] != 'notification':
|
||||
if connection.routes.get(stream_id) != reply:
|
||||
return
|
||||
if header['type'] == 'cancel':
|
||||
connection.routes.pop(stream_id, None)
|
||||
connection.forward(header, data)
|
||||
|
||||
async def reject(self, worker, connection, stream_id, message, disconnected=False):
|
||||
"""Fail a remote stream at once instead of leaving it to time out."""
|
||||
with suppress(Exception):
|
||||
await self.redis.publish(
|
||||
self.channel(worker),
|
||||
encode(
|
||||
{
|
||||
'type': 'error',
|
||||
'stream': stream_id,
|
||||
'sequence': 0,
|
||||
'route': 'stream',
|
||||
'connection': connection.presence['connection'],
|
||||
'message': message,
|
||||
'disconnected': disconnected,
|
||||
},
|
||||
b'',
|
||||
),
|
||||
)
|
||||
|
||||
async def presence(self, user_id, connection_id):
|
||||
await self.start()
|
||||
if self.redis:
|
||||
@@ -298,19 +452,32 @@ class Hub:
|
||||
raise HTTPException(403, 'Tether session is no longer available.')
|
||||
if service not in presence.get('services', []):
|
||||
raise HTTPException(503, 'Tether service is unavailable.')
|
||||
if sum(s.presence['connection'] == presence['connection'] for s in self.streams.values()) >= 16:
|
||||
# Only this worker's streams are visible here; the socket's worker enforces the device total.
|
||||
active = sum(s.presence['connection'] == presence['connection'] for s in self.streams.values())
|
||||
if active >= presence.get('max_concurrent_streams', DEFAULT_CONCURRENT_STREAMS):
|
||||
raise HTTPException(429, 'Tether has too many active operations.')
|
||||
stream = Stream(self, presence)
|
||||
self.streams[stream.id] = stream
|
||||
return stream
|
||||
|
||||
async def wait_for_presence(self, user_id, connection_id, service, previous, timeout=20):
|
||||
"""Wait for a reconnected Tether, not the socket that just dropped, to offer `service` again."""
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
with suppress(Exception):
|
||||
presence = await self.presence(user_id, connection_id)
|
||||
if presence and presence['connection'] != previous and service in presence.get('services', []):
|
||||
return True
|
||||
await asyncio.sleep(1)
|
||||
return False
|
||||
|
||||
async def send(self, presence, header, data):
|
||||
connection = self.connections.get(presence['connection'])
|
||||
if presence['worker'] == self.worker:
|
||||
if not connection:
|
||||
raise ConnectionError('Tether disconnected')
|
||||
if header['type'] in ('http-open', 'ws-open'):
|
||||
if len(connection.routes) >= 16:
|
||||
if header['type'] in ('http-open', 'ws-open', 'stdio-open'):
|
||||
if connection.full():
|
||||
raise HTTPException(429, 'Tether has too many active operations.')
|
||||
connection.routes[header['stream']] = self.worker
|
||||
try:
|
||||
@@ -388,7 +555,7 @@ async def notify(user_id, notification_id, title, body, path):
|
||||
)
|
||||
|
||||
|
||||
async def get_terminal_connections(user):
|
||||
async def get_terminal_connections(user, include_templates=True):
|
||||
"""Resolve personal targets alongside existing configured servers."""
|
||||
user_id = user['id'] if isinstance(user, dict) else user.id
|
||||
connections = list(await Config.get('terminal_server.connections', []) or [])
|
||||
@@ -408,10 +575,34 @@ async def get_terminal_connections(user):
|
||||
'enabled': True,
|
||||
'owner_id': user_id,
|
||||
'config': {
|
||||
'access_grants': [{'principal_type': 'user', 'principal_id': user_id, 'permission': 'read'}]
|
||||
'chat_uploads': 'filesystem',
|
||||
'access_grants': [{'principal_type': 'user', 'principal_id': user_id, 'permission': 'read'}],
|
||||
},
|
||||
}
|
||||
)
|
||||
# Terminals the user added in Tether: like the built-in one, but each under its own service.
|
||||
for presence, item in await get_tether_connections(user_id, 'terminal'):
|
||||
connections.append(
|
||||
{
|
||||
'id': f'tether:{presence["connection_id"]}:{item["service"]}',
|
||||
'name': f'{presence["name"]} · {item["name"]}',
|
||||
'url': f'tether://{presence["connection_id"]}',
|
||||
'service': item['service'],
|
||||
'auth_type': 'none',
|
||||
'enabled': True,
|
||||
'owner_id': user_id,
|
||||
'config': {
|
||||
'chat_uploads': 'filesystem',
|
||||
'access_grants': [{'principal_type': 'user', 'principal_id': user_id, 'permission': 'read'}],
|
||||
},
|
||||
}
|
||||
)
|
||||
if include_templates:
|
||||
from open_webui.utils.terminals import list_template_connections
|
||||
|
||||
managed = [c for c in connections if c.get('server_type') == 'orchestrator']
|
||||
connections = [c for c in connections if c.get('server_type') != 'orchestrator']
|
||||
connections.extend(await list_template_connections(user, managed))
|
||||
return connections
|
||||
|
||||
|
||||
@@ -439,6 +630,7 @@ class RelayResponse:
|
||||
self.content_type = self.headers.get('Content-Type', '').split(';')[0]
|
||||
self.content = self
|
||||
self.cached = None
|
||||
self.closed = False
|
||||
|
||||
async def iter_any(self):
|
||||
while True:
|
||||
@@ -453,6 +645,11 @@ class RelayResponse:
|
||||
def iter_chunked(self, size):
|
||||
return self.iter_any()
|
||||
|
||||
async def iter_chunks(self):
|
||||
# aiohttp yields (data, end_of_http_chunk); the relay has no HTTP chunk boundaries.
|
||||
async for data in self.iter_any():
|
||||
yield data, False
|
||||
|
||||
async def read(self):
|
||||
if self.cached is None:
|
||||
parts, size = [], 0
|
||||
@@ -468,10 +665,11 @@ class RelayResponse:
|
||||
async def text(self):
|
||||
return (await self.read()).decode('utf-8', errors='replace')
|
||||
|
||||
async def json(self):
|
||||
return json.loads(await self.read())
|
||||
async def json(self, loads=json.loads, **_):
|
||||
return loads(await self.read())
|
||||
|
||||
async def close(self):
|
||||
self.closed = True
|
||||
self.upload.cancel()
|
||||
await asyncio.gather(self.upload, return_exceptions=True)
|
||||
await self.stream.close()
|
||||
@@ -529,13 +727,16 @@ class RelaySocket:
|
||||
|
||||
|
||||
class RelayClient:
|
||||
"""aiohttp-like client for `tether://<device>/<path>` URLs, served by one of the device's services."""
|
||||
|
||||
def __init__(self, user_id, service, timeout=None):
|
||||
if not user_id:
|
||||
raise HTTPException(403, 'A user is required for Tether.')
|
||||
self.user_id = user_id
|
||||
self.service = get_services([service])[0]
|
||||
self.operations = []
|
||||
self.timeout = timeout if timeout is not None else aiohttp.ClientTimeout(total=300)
|
||||
self.timeout = timeout if timeout is not None else TIMEOUT
|
||||
self.closed = False
|
||||
|
||||
async def __aenter__(self):
|
||||
return self
|
||||
@@ -544,29 +745,51 @@ class RelayClient:
|
||||
await self.close()
|
||||
|
||||
async def close(self):
|
||||
self.closed = True
|
||||
await asyncio.gather(*(operation.close() for operation in self.operations), return_exceptions=True)
|
||||
|
||||
def request(self, method, url, **kwargs):
|
||||
return Operation(self._request(method, url, **kwargs))
|
||||
return Operation(self._retrying(method, url, **kwargs))
|
||||
|
||||
def ws_connect(self, url, **kwargs):
|
||||
return Operation(self._request(None, url, **kwargs))
|
||||
|
||||
async def _open(self, device):
|
||||
return await hub.open(self.user_id, device, self.service)
|
||||
|
||||
def __getattr__(self, name):
|
||||
if name in ('get', 'post', 'put', 'patch', 'delete', 'head', 'options'):
|
||||
return lambda url, **kwargs: self.request(name.upper(), url, **kwargs)
|
||||
raise AttributeError(name)
|
||||
|
||||
async def _retrying(self, method, url, idempotent=None, **kwargs):
|
||||
"""Repeat a safe request once when Tether dropped before any response arrived."""
|
||||
if idempotent is None:
|
||||
idempotent = method in SAFE_METHODS
|
||||
body = kwargs.get('data')
|
||||
replayable = idempotent and (body is None or isinstance(body, (bytes, bytearray, str)))
|
||||
try:
|
||||
return await self._request(method, url, **kwargs)
|
||||
except RelayInterrupted as error:
|
||||
if not (replayable and error.disconnected and error.before_response and error.connection):
|
||||
raise
|
||||
if not await hub.wait_for_presence(self.user_id, error.device, self.service, error.connection):
|
||||
raise
|
||||
return await self._request(method, url, **kwargs)
|
||||
|
||||
async def _request(self, method, url, **kwargs):
|
||||
parsed = urlsplit(str(url))
|
||||
if parsed.scheme != 'tether' or not parsed.hostname:
|
||||
raise ValueError('Invalid Tether URL')
|
||||
device, path = parsed.hostname, parsed.path or '/'
|
||||
headers = dict(kwargs.get('headers') or {})
|
||||
headers['X-User-Id'] = self.user_id
|
||||
if self.service == 'open_terminal':
|
||||
# Only the built-in terminal reads this; never send it to the user's own servers.
|
||||
headers['X-User-Id'] = self.user_id
|
||||
query = parsed.query
|
||||
if kwargs.get('params'):
|
||||
query += ('&' if query else '') + urlencode(kwargs['params'], doseq=True)
|
||||
stream = await hub.open(self.user_id, parsed.hostname, self.service)
|
||||
stream = await self._open(device)
|
||||
body = kwargs.get('data')
|
||||
if kwargs.get('json') is not None:
|
||||
body = json.dumps(kwargs['json']).encode()
|
||||
@@ -585,9 +808,10 @@ class RelayClient:
|
||||
'http-open' if method else 'ws-open',
|
||||
service=self.service,
|
||||
method=method,
|
||||
path=parsed.path or '/',
|
||||
path=path,
|
||||
query=query,
|
||||
headers=headers,
|
||||
**({'revision': kwargs['revision']} if 'revision' in kwargs else {}),
|
||||
)
|
||||
if method:
|
||||
|
||||
@@ -629,12 +853,22 @@ class RelayClient:
|
||||
upload.cancel()
|
||||
await asyncio.gather(upload, return_exceptions=True)
|
||||
await stream.close()
|
||||
if isinstance(error, (OSError, TimeoutError)) and not isinstance(error, RelayInterrupted):
|
||||
raise RelayInterrupted(str(error) or 'Response timed out') from error
|
||||
raise
|
||||
if isinstance(error, RelayInterrupted):
|
||||
interrupted = error
|
||||
elif isinstance(error, (OSError, TimeoutError)):
|
||||
interrupted = RelayInterrupted(str(error) or 'Response timed out')
|
||||
else:
|
||||
raise
|
||||
# Everything in this block precedes the response header.
|
||||
interrupted.before_response = True
|
||||
interrupted.connection = stream.presence['connection']
|
||||
interrupted.device = device
|
||||
if interrupted is error:
|
||||
raise
|
||||
raise interrupted from error
|
||||
|
||||
|
||||
def get_terminal_client(url, user_id=None, **kwargs):
|
||||
def get_terminal_client(url, user_id=None, service='open_terminal', **kwargs):
|
||||
if str(url).startswith('tether://'):
|
||||
return RelayClient(user_id, service='open_terminal', timeout=kwargs.get('timeout'))
|
||||
return RelayClient(user_id, service=service, timeout=kwargs.get('timeout'))
|
||||
return aiohttp.ClientSession(**kwargs)
|
||||
@@ -99,8 +99,6 @@ async def create_timer(
|
||||
model_id = metadata.get('model_id') or (metadata.get('model') or {}).get('id')
|
||||
if not model_id:
|
||||
return 'Error: model context is required.'
|
||||
if metadata.get('direct'):
|
||||
return 'Error: timers are unavailable for direct connections.'
|
||||
|
||||
chat_id = str(uuid4())
|
||||
user_message_id = str(uuid4())
|
||||
|
||||
@@ -102,14 +102,15 @@ async def resolve_tool_call_output(
|
||||
function_call.setdefault('call_id', form_data.call_id)
|
||||
tool_name = function_call.get('name')
|
||||
|
||||
if function_call.get('native') is not None:
|
||||
# Terminal agent requests carry the provider's event; older saved messages call it 'native'.
|
||||
if function_call.get('provider_data') is not None or function_call.get('native') is not None:
|
||||
from open_webui.utils.auth import decode_token
|
||||
|
||||
token = (message.get('meta') or {}).get('agent')
|
||||
binding = decode_token(token) if isinstance(token, str) else None
|
||||
if (
|
||||
not binding
|
||||
or binding.get('purpose') != 'terminal-agent'
|
||||
or binding.get('typ') != 'agent_session'
|
||||
or binding.get('user') != user.id
|
||||
or binding.get('chat') != chat_id
|
||||
):
|
||||
@@ -122,7 +123,7 @@ async def resolve_tool_call_output(
|
||||
raise HTTPException(400, 'Answers must be keyed by question')
|
||||
function_call['agent_resolution'] = form_data.model_dump()
|
||||
function_call['status'] = 'queued'
|
||||
# The running native client consumes this persisted response. Do not start a model/tool loop.
|
||||
# The running agent client consumes this persisted response. Do not start a model/tool loop.
|
||||
return {'chat': chat, 'output': output, 'resume': None}
|
||||
|
||||
if (
|
||||
@@ -269,7 +270,6 @@ async def build_tool_approval_resume_payload(chat_id: str, message_id: str, chat
|
||||
'tool_ids': message_meta.get('tool_ids') or None,
|
||||
'skill_ids': message_meta.get('skill_ids') or None,
|
||||
'terminal_id': message_meta.get('terminal_id') or None,
|
||||
'tool_servers': message_meta.get('tool_servers') or None,
|
||||
'features': message_meta.get('features') or {},
|
||||
'variables': message_meta.get('variables') or {},
|
||||
'chat_variables': chat.variables if (assistant_message.get('user_id') or chat.user_id) == chat.user_id else {},
|
||||
|
||||
@@ -93,9 +93,23 @@ def strip_tool_approval_prompt(prompt):
|
||||
return _TOOL_APPROVAL_PROMPT_RE.sub('', prompt) if prompt else prompt
|
||||
|
||||
|
||||
def set_tool_call_visibility(item, tools):
|
||||
"""Copy trusted tool visibility metadata onto display output, without changing execution."""
|
||||
if item.get('type') == 'function_call' and tools.get(item.get('name'), {}).get('hidden') is True:
|
||||
def set_tool_call_metadata(item, tools):
|
||||
"""Copy application-owned display metadata, never trusting provider annotations."""
|
||||
if item.get('type') != 'function_call':
|
||||
return
|
||||
tool = tools.get(item.get('name'), {})
|
||||
for field, source in (('tool_id', 'tool_id'), ('tool_type', 'type')):
|
||||
item.pop(field, None)
|
||||
if tool.get(source):
|
||||
item[field] = tool[source]
|
||||
item.pop('tool_targets', None)
|
||||
if tool.get('type') == 'builtin' and tool.get('tool_id') == 'builtin:call_tool':
|
||||
item['tool_targets'] = {
|
||||
name: {'tool_id': target['tool_id'], 'tool_type': target['type']}
|
||||
for name, target in tools.items()
|
||||
if target.get('type') == 'builtin' and target.get('tool_id') and not target.get('hidden')
|
||||
}
|
||||
if tool.get('hidden') is True:
|
||||
item['hidden'] = True
|
||||
|
||||
|
||||
@@ -319,10 +333,9 @@ def prepare_tool_call(call, schema=None, *, display_labels=False, approval_revie
|
||||
|
||||
|
||||
def final_answer_payload(payload):
|
||||
"""Make one OpenAI-compatible continuation request with tools disabled."""
|
||||
"""Make one OpenAI-compatible continuation request with tool calls turned off."""
|
||||
return {
|
||||
**payload,
|
||||
'tools': [],
|
||||
'tool_choice': 'none',
|
||||
'messages': [*payload.get('messages', []), {'role': 'system', 'content': FINAL_ANSWER_PROMPT}],
|
||||
}
|
||||
@@ -181,7 +181,7 @@ def split_tool_call_batches(calls: list[dict], tools: dict[str, dict]) -> list[d
|
||||
expanded.append(
|
||||
{
|
||||
**call,
|
||||
'id': call_id if index == 0 else f'call_{uuid4().hex[:24]}',
|
||||
'id': call_id if index == 0 else f'{call_id}:{index}',
|
||||
'function': {'name': CALL_TOOL_NAME, 'arguments': JSONCodec.dumps(entry)},
|
||||
'provider_batch': {**batch, 'tool_name': entry['tool_name']},
|
||||
}
|
||||
|
||||
+213
-103
@@ -62,6 +62,7 @@ from open_webui.tools.builtin import (
|
||||
execute_code,
|
||||
fetch_url,
|
||||
generate_image,
|
||||
generate_video,
|
||||
get_current_timestamp,
|
||||
grep_chat_files,
|
||||
grep_knowledge_files,
|
||||
@@ -79,6 +80,7 @@ from open_webui.tools.builtin import (
|
||||
read_memory_path,
|
||||
replace_memory_content,
|
||||
replace_note_content,
|
||||
render_visualization,
|
||||
search_calendar_events,
|
||||
search_channel_messages,
|
||||
search_channels,
|
||||
@@ -87,6 +89,7 @@ from open_webui.tools.builtin import (
|
||||
search_knowledge_files,
|
||||
search_memories,
|
||||
search_notes,
|
||||
search_users,
|
||||
search_web,
|
||||
timer,
|
||||
toggle_automation,
|
||||
@@ -107,6 +110,7 @@ from open_webui.tools.builtin import (
|
||||
update_skill_files,
|
||||
write_note,
|
||||
)
|
||||
from open_webui.tools.visualizations import DEFAULT_VISUALIZATION_PROMPT_TEMPLATE
|
||||
from open_webui.utils.access_control import has_access, has_connection_access, has_permission
|
||||
from open_webui.utils.chat_id import is_saved_chat_id, is_temporary_chat_id
|
||||
from open_webui.utils.headers import (
|
||||
@@ -125,13 +129,9 @@ from open_webui.utils.plugin import (
|
||||
load_tool_module_by_id,
|
||||
set_tool_module_in_cache,
|
||||
)
|
||||
from open_webui.utils.tether import RelayInterrupted, get_terminal_connections, get_terminal_client
|
||||
from open_webui.utils.tether import RelayInterrupted, get_tether_connections, get_terminal_client
|
||||
from open_webui.utils.terminals import (
|
||||
TERMINAL_CONTEXT_HEADER,
|
||||
get_terminal_server_url,
|
||||
terminal_context_available,
|
||||
terminal_context_config,
|
||||
terminal_context_id,
|
||||
)
|
||||
from open_webui.utils.voice_avatar import avatar_animation_tools
|
||||
from pydantic import BaseModel, Field, create_model
|
||||
@@ -214,10 +214,32 @@ async def connect_mcp_server(
|
||||
return None
|
||||
|
||||
mcp_server_connection = None
|
||||
for server_connection in await Config.get('tool_server.connections', []):
|
||||
if server_connection.get('type', '') == 'mcp' and (server_connection.get('info') or {}).get('id') == server_id:
|
||||
mcp_server_connection = server_connection
|
||||
break
|
||||
if server_id.startswith('tether:'):
|
||||
server = next(
|
||||
(item for item in await get_tether_tool_servers(user, 'mcp') if 'tether:' + item['id'] == server_id), None
|
||||
)
|
||||
if server:
|
||||
mcp_server_connection = {
|
||||
'auth_type': 'none',
|
||||
'config': {
|
||||
'enable': True,
|
||||
'access_grants': [{'principal_type': 'user', 'principal_id': user.id, 'permission': 'read'}],
|
||||
},
|
||||
'tether': {
|
||||
'user_id': user.id,
|
||||
'device_id': server['device_id'],
|
||||
'service': server['service'],
|
||||
'transport': server['transport'],
|
||||
},
|
||||
}
|
||||
else:
|
||||
for server_connection in await Config.get('tool_server.connections', []):
|
||||
if (
|
||||
server_connection.get('type', '') == 'mcp'
|
||||
and (server_connection.get('info') or {}).get('id') == server_id
|
||||
):
|
||||
mcp_server_connection = server_connection
|
||||
break
|
||||
|
||||
if not mcp_server_connection or not (mcp_server_connection.get('config') or {}).get('enable'):
|
||||
log.error(f'MCP server with id {server_id} not found')
|
||||
@@ -250,6 +272,7 @@ async def connect_mcp_server(
|
||||
url=mcp_server_connection.get('url', ''),
|
||||
headers=headers if headers else None,
|
||||
auth=auth,
|
||||
**({'tether': mcp_server_connection['tether']} if mcp_server_connection.get('tether') else {}),
|
||||
)
|
||||
function_name_filter_list = (mcp_server_connection.get('config') or {}).get('function_name_filter_list', '')
|
||||
if isinstance(function_name_filter_list, str):
|
||||
@@ -484,16 +507,23 @@ async def get_tools(request: Request, tool_ids: list[str], user: UserModel, extr
|
||||
if len(splits) == 2:
|
||||
type = 'openapi'
|
||||
server_id = splits[1]
|
||||
elif len(splits) == 3:
|
||||
elif len(splits) >= 3:
|
||||
type = splits[1]
|
||||
server_id = splits[2]
|
||||
server_id = ':'.join(splits[2:])
|
||||
|
||||
server_id_splits = server_id.split('|')
|
||||
if len(server_id_splits) == 2:
|
||||
server_id = server_id_splits[0]
|
||||
function_names = server_id_splits[1].split(',')
|
||||
|
||||
if type == 'openapi':
|
||||
if type == 'tether':
|
||||
# A tool server the user added in Tether, reached through it.
|
||||
loaded = await get_tether_tool_server(user, server_id)
|
||||
if loaded is None:
|
||||
log.warning(f"Tool server {server_id} is not offered by any of the user's devices")
|
||||
continue
|
||||
tool_server_data, tool_server_connection = loaded
|
||||
elif type == 'openapi':
|
||||
tool_server_data = None
|
||||
for server in await get_tool_servers(request):
|
||||
if server['id'] == server_id:
|
||||
@@ -519,69 +549,69 @@ async def get_tools(request: Request, tool_ids: list[str], user: UserModel, extr
|
||||
log.warning(f'Access denied to tool server {server_id} for user {user.id}')
|
||||
continue
|
||||
|
||||
specs = tool_server_data.get('specs', [])
|
||||
function_name_filter_list = tool_server_connection.get('config', {}).get(
|
||||
'function_name_filter_list', ''
|
||||
)
|
||||
|
||||
if isinstance(function_name_filter_list, str):
|
||||
function_name_filter_list = function_name_filter_list.split(',')
|
||||
|
||||
for spec in specs:
|
||||
function_name = spec['name']
|
||||
if function_name_filter_list:
|
||||
if not is_string_allowed(function_name, function_name_filter_list):
|
||||
# Skip this function
|
||||
continue
|
||||
|
||||
metadata = extra_params.get('__metadata__', {})
|
||||
|
||||
async def make_tool_function(function_name, tool_server_data, connection, server_id, metadata):
|
||||
async def tool_function(**kwargs):
|
||||
headers, cookies = await build_tool_server_headers(
|
||||
connection, request, user, server_id=server_id, metadata=metadata
|
||||
)
|
||||
headers.setdefault('Content-Type', 'application/json')
|
||||
return await execute_tool_server(
|
||||
url=tool_server_data['url'],
|
||||
headers=headers,
|
||||
cookies=cookies,
|
||||
name=function_name,
|
||||
params=kwargs,
|
||||
server_data=tool_server_data,
|
||||
)
|
||||
|
||||
return tool_function
|
||||
|
||||
tool_function = await make_tool_function(
|
||||
function_name, tool_server_data, tool_server_connection, server_id, metadata
|
||||
)
|
||||
|
||||
callable = await get_async_tool_function_and_apply_extra_params(
|
||||
tool_function,
|
||||
{},
|
||||
)
|
||||
|
||||
tool_dict = {
|
||||
'tool_id': tool_id,
|
||||
'callable': callable,
|
||||
'spec': clean_openai_tool_schema(spec),
|
||||
# Misc info
|
||||
'type': 'external',
|
||||
}
|
||||
|
||||
# Handle function name collisions
|
||||
while function_name in tools_dict:
|
||||
log.warning(f'Tool {function_name} already exists in another tools!')
|
||||
# Prepend server ID to function name
|
||||
function_name = f'{server_id}_{function_name}'
|
||||
|
||||
tool_dict['spec'] = {**tool_dict['spec'], 'name': function_name}
|
||||
tools_dict[function_name] = tool_dict
|
||||
|
||||
else:
|
||||
continue
|
||||
|
||||
specs = tool_server_data.get('specs', [])
|
||||
function_name_filter_list = tool_server_connection.get('config', {}).get(
|
||||
'function_name_filter_list', ''
|
||||
)
|
||||
|
||||
if isinstance(function_name_filter_list, str):
|
||||
function_name_filter_list = function_name_filter_list.split(',')
|
||||
|
||||
for spec in specs:
|
||||
function_name = spec['name']
|
||||
if function_name_filter_list:
|
||||
if not is_string_allowed(function_name, function_name_filter_list):
|
||||
# Skip this function
|
||||
continue
|
||||
|
||||
metadata = extra_params.get('__metadata__', {})
|
||||
|
||||
async def make_tool_function(function_name, tool_server_data, connection, server_id, metadata):
|
||||
async def tool_function(**kwargs):
|
||||
headers, cookies = await build_tool_server_headers(
|
||||
connection, request, user, server_id=server_id, metadata=metadata
|
||||
)
|
||||
headers.setdefault('Content-Type', 'application/json')
|
||||
return await execute_tool_server(
|
||||
url=tool_server_data['url'],
|
||||
headers=headers,
|
||||
cookies=cookies,
|
||||
name=function_name,
|
||||
params=kwargs,
|
||||
server_data=tool_server_data,
|
||||
)
|
||||
|
||||
return tool_function
|
||||
|
||||
tool_function = await make_tool_function(
|
||||
function_name, tool_server_data, tool_server_connection, server_id, metadata
|
||||
)
|
||||
|
||||
callable = await get_async_tool_function_and_apply_extra_params(
|
||||
tool_function,
|
||||
{},
|
||||
)
|
||||
|
||||
tool_dict = {
|
||||
'tool_id': tool_id,
|
||||
'callable': callable,
|
||||
'spec': clean_openai_tool_schema(spec),
|
||||
# Misc info
|
||||
'type': 'external',
|
||||
}
|
||||
|
||||
# Handle function name collisions
|
||||
while function_name in tools_dict:
|
||||
log.warning(f'Tool {function_name} already exists in another tools!')
|
||||
# Prepend server ID to function name
|
||||
function_name = f'{server_id}_{function_name}'
|
||||
|
||||
tool_dict['spec'] = {**tool_dict['spec'], 'name': function_name}
|
||||
tools_dict[function_name] = tool_dict
|
||||
|
||||
return tools_dict
|
||||
|
||||
|
||||
@@ -660,6 +690,7 @@ async def get_builtin_tools(
|
||||
'web.search.enable',
|
||||
'image_generation.enable',
|
||||
'images.edit.enable',
|
||||
'video_generation.enable',
|
||||
'code_interpreter.enable',
|
||||
'notes.enable',
|
||||
'channels.enable',
|
||||
@@ -668,6 +699,7 @@ async def get_builtin_tools(
|
||||
'ui.enable_user_webhooks',
|
||||
'subagents.enable',
|
||||
'subagents.background_enabled',
|
||||
'chat.visualizations.prompt_template',
|
||||
)
|
||||
|
||||
async def has_user_permission(feature_key: str) -> bool:
|
||||
@@ -723,6 +755,9 @@ async def get_builtin_tools(
|
||||
'type': 'builtin',
|
||||
}
|
||||
|
||||
if is_builtin_tool_enabled('visualizations', False):
|
||||
builtin_functions.append(render_visualization)
|
||||
|
||||
# Time utilities - available for date calculations
|
||||
if is_builtin_tool_enabled('time'):
|
||||
builtin_functions.extend([get_current_timestamp, calculate_timestamp])
|
||||
@@ -792,16 +827,16 @@ async def get_builtin_tools(
|
||||
]
|
||||
)
|
||||
|
||||
# Chats tools - search and fetch user's chat history
|
||||
# Chats tools - search chat history and the user directory
|
||||
if is_builtin_tool_enabled('chats'):
|
||||
builtin_functions.extend([search_chats, view_chat])
|
||||
builtin_functions.extend([search_chats, view_chat, search_users])
|
||||
|
||||
if (
|
||||
is_builtin_tool_enabled('subagents')
|
||||
and config.get('subagents.enable')
|
||||
and getattr(request.state, 'internal', False) is not True
|
||||
and getattr(request.state, 'direct', False) is not True
|
||||
and not is_temporary_chat_id(metadata.get('chat_id'))
|
||||
and await has_user_permission('subagents')
|
||||
):
|
||||
builtin_functions.extend([delegate_task, timer])
|
||||
|
||||
@@ -855,6 +890,17 @@ async def get_builtin_tools(
|
||||
):
|
||||
builtin_functions.append(edit_image)
|
||||
|
||||
# Add video generation tool if builtin category enabled,
|
||||
# globally enabled, and allowed by model capability.
|
||||
if (
|
||||
is_builtin_tool_enabled('video_generation')
|
||||
and config.get('video_generation.enable')
|
||||
and get_model_capability('video_generation')
|
||||
and features.get('video_generation')
|
||||
and await has_user_permission('video_generation')
|
||||
):
|
||||
builtin_functions.append(generate_video)
|
||||
|
||||
# Add code interpreter tool if builtin category enabled,
|
||||
# globally enabled, and allowed by model capability.
|
||||
if (
|
||||
@@ -953,6 +999,9 @@ async def get_builtin_tools(
|
||||
)
|
||||
|
||||
spec = get_builtin_tool_spec(func)
|
||||
if func.__name__ == 'render_visualization':
|
||||
prompt = config.get('chat.visualizations.prompt_template') or ''
|
||||
spec['description'] = prompt if prompt.strip() else DEFAULT_VISUALIZATION_PROMPT_TEMPLATE
|
||||
if func.__name__ == 'delegate_task':
|
||||
from open_webui.utils.subagents import get_subagent_models
|
||||
|
||||
@@ -1374,6 +1423,7 @@ async def get_terminal_cwd(
|
||||
base_url: str,
|
||||
headers: dict,
|
||||
cookies: dict | None = None,
|
||||
service: str = 'open_terminal',
|
||||
) -> str | None:
|
||||
"""Fetch the current working directory from a terminal server."""
|
||||
try:
|
||||
@@ -1381,6 +1431,7 @@ async def get_terminal_cwd(
|
||||
async with get_terminal_client(
|
||||
base_url,
|
||||
headers.get('X-User-Id'),
|
||||
service=service,
|
||||
timeout=aiohttp.ClientTimeout(total=5),
|
||||
trust_env=True,
|
||||
) as session:
|
||||
@@ -1399,6 +1450,7 @@ async def get_terminal_system_prompt(
|
||||
base_url: str,
|
||||
headers: dict,
|
||||
cookies: dict | None = None,
|
||||
service: str = 'open_terminal',
|
||||
) -> str | None:
|
||||
"""Fetch the system prompt from a terminal server.
|
||||
|
||||
@@ -1411,6 +1463,7 @@ async def get_terminal_system_prompt(
|
||||
async with get_terminal_client(
|
||||
base_url,
|
||||
headers.get('X-User-Id'),
|
||||
service=service,
|
||||
timeout=aiohttp.ClientTimeout(total=3),
|
||||
trust_env=True,
|
||||
) as session:
|
||||
@@ -1447,7 +1500,7 @@ async def set_terminal_servers(request: Request):
|
||||
# Terminal connections store id/name at top level; translate to info dict
|
||||
server_configs = []
|
||||
for connection in connections:
|
||||
if not connection.get('url'):
|
||||
if not connection.get('url') or connection.get('server_type') == 'orchestrator':
|
||||
continue
|
||||
|
||||
enabled = connection.get('enabled', True)
|
||||
@@ -1487,8 +1540,6 @@ async def set_terminal_servers(request: Request):
|
||||
headers = {}
|
||||
if connection.get('auth_type', 'bearer') == 'bearer':
|
||||
headers.update(bearer_auth_header(connection.get('key', '')))
|
||||
if connection.get('policy_id'):
|
||||
headers['X-User-Id'] = 'system'
|
||||
prompt = await get_terminal_system_prompt(server['url'], headers)
|
||||
if prompt:
|
||||
server['system_prompt'] = prompt
|
||||
@@ -1549,10 +1600,10 @@ async def get_terminal_tools(
|
||||
if not ENABLE_TOOL_SERVERS:
|
||||
return {}
|
||||
|
||||
connections = await get_terminal_connections(user)
|
||||
connection = next(
|
||||
(terminal_connection for terminal_connection in connections if terminal_connection.get('id') == terminal_id),
|
||||
None,
|
||||
from open_webui.utils.terminals import find_terminal_connection, terminal_headers
|
||||
|
||||
connection = await find_terminal_connection(
|
||||
user, terminal_id, extra_params.get('__metadata__', {}), request=request
|
||||
)
|
||||
if connection is None:
|
||||
raise RuntimeError(f"Terminal server '{terminal_id}' not found")
|
||||
@@ -1564,15 +1615,27 @@ async def get_terminal_tools(
|
||||
raise RuntimeError(f'Access denied to terminal {terminal_id}')
|
||||
|
||||
# Find the cached spec data for this terminal
|
||||
if connection.get('owner_id') == user.id:
|
||||
url = connection['url']
|
||||
openapi = await get_tool_server_data(url + '/openapi.json', {'X-User-Id': user.id})
|
||||
if connection.get('template_id'):
|
||||
url = get_terminal_server_url(connection)
|
||||
discovery_headers = {**bearer_auth_header(connection['key']), **terminal_headers(connection)}
|
||||
openapi = await get_tool_server_data(url + '/openapi.json', discovery_headers)
|
||||
server_data = {
|
||||
'id': terminal_id,
|
||||
'url': url,
|
||||
'openapi': openapi,
|
||||
'specs': convert_openapi_to_tool_payload(openapi),
|
||||
}
|
||||
elif connection.get('owner_id') == user.id:
|
||||
url = connection['url']
|
||||
service = connection.get('service', 'open_terminal')
|
||||
openapi = await get_tool_server_data(url + '/openapi.json', {'X-User-Id': user.id}, service=service)
|
||||
server_data = {
|
||||
'id': terminal_id,
|
||||
'url': url,
|
||||
'openapi': openapi,
|
||||
'specs': convert_openapi_to_tool_payload(openapi),
|
||||
'service': service,
|
||||
}
|
||||
else:
|
||||
terminal_servers = await get_terminal_servers(request)
|
||||
server_data = next((server for server in terminal_servers if server.get('id') == terminal_id), None)
|
||||
@@ -1600,31 +1663,25 @@ async def get_terminal_tools(
|
||||
|
||||
# Use chat_id as the per-session key for cwd tracking
|
||||
metadata = extra_params.get('__metadata__', {})
|
||||
terminal_context = 'automation' if metadata.get('automation_id') else 'chat'
|
||||
if not terminal_context_available(connection, terminal_context):
|
||||
raise RuntimeError(f"Terminal server '{terminal_id}' is not available for {terminal_context}")
|
||||
|
||||
session_id = metadata.get('chat_id')
|
||||
if session_id:
|
||||
headers['X-Session-Id'] = session_id
|
||||
|
||||
context_id = terminal_context_id(connection, metadata, terminal_context)
|
||||
config = terminal_context_config(connection, terminal_context)
|
||||
if isinstance(config, dict) and config.get('context_id') in {'chat_id', 'automation_id'} and not context_id:
|
||||
raise RuntimeError(f"Terminal server '{terminal_id}' requires a saved {terminal_context} context")
|
||||
if context_id:
|
||||
headers[TERMINAL_CONTEXT_HEADER] = context_id
|
||||
headers.update(terminal_headers(connection))
|
||||
|
||||
# Fetch live with the user's credentials so prompt changes apply without a restart
|
||||
connection_config = connection.get('config') or {}
|
||||
terminal_cwd = None
|
||||
if connection_config.get('working_directory_context', True):
|
||||
service = server_data.get('service', 'open_terminal')
|
||||
terminal_cwd, system_prompt = await asyncio.gather(
|
||||
get_terminal_cwd(server_data['url'], headers, cookies),
|
||||
get_terminal_system_prompt(server_data['url'], headers, cookies),
|
||||
get_terminal_cwd(server_data['url'], headers, cookies, service),
|
||||
get_terminal_system_prompt(server_data['url'], headers, cookies, service),
|
||||
)
|
||||
else:
|
||||
system_prompt = await get_terminal_system_prompt(server_data['url'], headers, cookies)
|
||||
system_prompt = await get_terminal_system_prompt(
|
||||
server_data['url'], headers, cookies, server_data.get('service', 'open_terminal')
|
||||
)
|
||||
if not system_prompt:
|
||||
system_prompt = server_data.get('system_prompt')
|
||||
|
||||
@@ -1642,12 +1699,20 @@ async def get_terminal_tools(
|
||||
|
||||
async def make_tool_function(fn_name, srv_data, hdrs, cks):
|
||||
async def tool_function(**kwargs):
|
||||
call_headers = dict(hdrs)
|
||||
if connection.get('template_id'):
|
||||
current = await find_terminal_connection(
|
||||
user, terminal_id, {**metadata, 'scope': connection.get('scope')}, request=request
|
||||
)
|
||||
if current is None:
|
||||
raise HTTPException(403, 'Terminal access revoked')
|
||||
call_headers.update(terminal_headers(current))
|
||||
params = dict(kwargs)
|
||||
if fn_name == 'display_file':
|
||||
params.pop('page', None)
|
||||
return await execute_tool_server(
|
||||
url=srv_data['url'],
|
||||
headers=hdrs,
|
||||
headers=call_headers,
|
||||
cookies=cks,
|
||||
name=fn_name,
|
||||
params=params,
|
||||
@@ -1670,7 +1735,9 @@ async def get_terminal_tools(
|
||||
return tools_dict, system_prompt
|
||||
|
||||
|
||||
async def get_tool_server_data(url: str, headers: dict | None) -> dict[str, Any]:
|
||||
async def get_tool_server_data(
|
||||
url: str, headers: dict | None, service: str = 'open_terminal', user_id: str | None = None
|
||||
) -> dict[str, Any]:
|
||||
if not ENABLE_TOOL_SERVERS:
|
||||
raise RuntimeError('Tool servers are disabled')
|
||||
|
||||
@@ -1685,7 +1752,9 @@ async def get_tool_server_data(url: str, headers: dict | None) -> dict[str, Any]
|
||||
error = None
|
||||
try:
|
||||
timeout = aiohttp.ClientTimeout(total=AIOHTTP_CLIENT_TIMEOUT_TOOL_SERVER_DATA)
|
||||
async with get_terminal_client(url, _headers.get('X-User-Id'), timeout=timeout, trust_env=True) as session:
|
||||
async with get_terminal_client(
|
||||
url, user_id or _headers.get('X-User-Id'), service=service, timeout=timeout, trust_env=True
|
||||
) as session:
|
||||
async with session.get(url, headers=_headers, ssl=AIOHTTP_CLIENT_SESSION_TOOL_SERVER_SSL) as response:
|
||||
if response.status != 200:
|
||||
error_body = await response.json()
|
||||
@@ -1719,6 +1788,42 @@ async def get_tool_server_data(url: str, headers: dict | None) -> dict[str, Any]
|
||||
return res
|
||||
|
||||
|
||||
async def get_tether_tool_servers(user, type='openapi') -> list[dict]:
|
||||
"""Personal tool servers, scoped to the requesting user and device."""
|
||||
if not ENABLE_TOOL_SERVERS:
|
||||
return []
|
||||
return [
|
||||
{
|
||||
'id': f'{presence["connection_id"]}:{item["service"]}',
|
||||
'name': f'{presence["name"]} · {item["name"]}',
|
||||
'url': f'tether://{presence["connection_id"]}',
|
||||
'service': item['service'],
|
||||
'device_id': presence['connection_id'],
|
||||
'transport': item.get('transport'),
|
||||
}
|
||||
for presence, item in await get_tether_connections(user.id, type)
|
||||
]
|
||||
|
||||
|
||||
async def get_tether_tool_server(user, server_id: str) -> tuple[dict, dict] | None:
|
||||
"""Spec data and connection for a tool server the user added in Tether. Tether adds the key."""
|
||||
server = next((s for s in await get_tether_tool_servers(user) if s['id'] == server_id), None)
|
||||
if server is None:
|
||||
return None
|
||||
grant = {'principal_type': 'user', 'principal_id': user.id, 'permission': 'read'}
|
||||
connection = {
|
||||
'url': server['url'],
|
||||
'path': 'openapi.json',
|
||||
'auth_type': 'none',
|
||||
'info': {'id': server_id, 'name': server['name']},
|
||||
'service': server['service'],
|
||||
'user_id': user.id,
|
||||
'config': {'enable': True, 'access_grants': [grant]},
|
||||
}
|
||||
data = await get_tool_servers_data([connection])
|
||||
return (data[0], connection) if data else None
|
||||
|
||||
|
||||
async def get_tool_servers_data(servers: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
# Prepare list of enabled servers along with their original index
|
||||
|
||||
@@ -1757,6 +1862,8 @@ async def get_tool_servers_data(servers: list[dict[str, Any]]) -> list[dict[str,
|
||||
task = get_tool_server_data(
|
||||
spec_url,
|
||||
{'Authorization': f'Bearer {token}'} if token else None,
|
||||
service=server.get('service', 'open_terminal'),
|
||||
user_id=server.get('user_id'),
|
||||
)
|
||||
elif spec_type == 'json' and server.get('spec', ''):
|
||||
# Use provided JSON spec
|
||||
@@ -1815,6 +1922,8 @@ async def get_tool_servers_data(servers: list[dict[str, Any]]) -> list[dict[str,
|
||||
'openapi': openapi_data,
|
||||
'info': response.get('info'),
|
||||
'specs': response.get('specs'),
|
||||
# A tool server the user added in Tether is reached through it.
|
||||
**({'service': server['service'], 'user_id': server.get('user_id')} if server.get('service') else {}),
|
||||
}
|
||||
)
|
||||
|
||||
@@ -1928,7 +2037,8 @@ async def execute_tool_server(
|
||||
|
||||
async with get_terminal_client(
|
||||
url,
|
||||
(headers or {}).get('X-User-Id'),
|
||||
server_data.get('user_id') or (headers or {}).get('X-User-Id'),
|
||||
service=server_data.get('service', 'open_terminal'),
|
||||
trust_env=True,
|
||||
timeout=aiohttp.ClientTimeout(total=AIOHTTP_CLIENT_TIMEOUT_TOOL_SERVER),
|
||||
) as session:
|
||||
@@ -1989,7 +2099,7 @@ async def execute_tool_server(
|
||||
except RelayInterrupted as err:
|
||||
return (err.result(), None)
|
||||
except Exception as err:
|
||||
error = str(err)
|
||||
error = str(err) or type(err).__name__
|
||||
log.warning(f'API Request Error: {error}')
|
||||
return ({'error': error}, None)
|
||||
|
||||
|
||||
@@ -0,0 +1,234 @@
|
||||
"""Video connections: the configured backends that built-in video generation runs on.
|
||||
|
||||
A connection is one OpenAI compatible server with a video API (``/videos``), such as LiteLLM,
|
||||
OpenAI or OpenRouter, with the video models it exposes. Users pick a model by its reference,
|
||||
``{connection_id}:{model_id}``, and only see models their access grants allow.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import uuid
|
||||
from typing import Any
|
||||
|
||||
from aiocache import cached
|
||||
from fastapi import HTTPException, Request
|
||||
from open_webui.constants import ERROR_MESSAGES
|
||||
from open_webui.env import AIOHTTP_CLIENT_SESSION_SSL, MODELS_CACHE_TTL
|
||||
from open_webui.models.config import Config
|
||||
from open_webui.models.groups import Groups
|
||||
from open_webui.models.users import UserModel
|
||||
from open_webui.utils.access_control import has_connection_access
|
||||
from open_webui.utils.headers import get_headers_and_cookies
|
||||
from open_webui.utils.images.connections import (
|
||||
IMAGE_CONNECTION_AUTH_TYPES,
|
||||
_json_object,
|
||||
_size,
|
||||
get_image_model_ref,
|
||||
get_openai_connection_models,
|
||||
get_requested_model,
|
||||
)
|
||||
from open_webui.utils.session_pool import get_session
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
VIDEO_CONNECTIONS_CONFIG_KEY = 'videos.connections'
|
||||
VIDEO_GENERATION_DEFAULT_MODEL_CONFIG_KEY = 'video_generation.default_model'
|
||||
|
||||
VIDEO_CONNECTION_TYPES = ('openai',)
|
||||
VIDEO_CONNECTION_AUTH_TYPES = IMAGE_CONNECTION_AUTH_TYPES
|
||||
|
||||
# Like chat model connections: '' is the OpenAI video API (OpenAI, LiteLLM); OpenRouter has its own.
|
||||
VIDEO_CONNECTION_PROVIDERS = ('', 'openrouter')
|
||||
|
||||
|
||||
def get_video_connection_provider(connection: dict) -> str:
|
||||
"""The API a connection speaks: the admin's choice, else OpenRouter when the URL is OpenRouter's."""
|
||||
provider = (connection.get('config') or {}).get('provider') or ''
|
||||
if not provider and 'openrouter.ai' in (connection.get('url') or ''):
|
||||
return 'openrouter'
|
||||
return provider
|
||||
|
||||
|
||||
def normalize_video_connection(connection: dict[str, Any]) -> dict[str, Any]:
|
||||
"""Validate a video connection and fill in defaults. Raises ValueError on invalid input."""
|
||||
connection_type = str(connection.get('type') or 'openai')
|
||||
if connection_type not in VIDEO_CONNECTION_TYPES:
|
||||
raise ValueError(f'Unsupported video connection type: {connection_type}')
|
||||
|
||||
connection_id = str(connection.get('id') or uuid.uuid4())
|
||||
if ':' in connection_id:
|
||||
raise ValueError('Video connection IDs cannot contain ":"')
|
||||
|
||||
config = connection.get('config') or {}
|
||||
|
||||
model_ids = []
|
||||
for model_id in config.get('model_ids') or []:
|
||||
model_id = str(model_id).strip()
|
||||
if model_id and model_id not in model_ids:
|
||||
model_ids.append(model_id)
|
||||
|
||||
auth_type = str(config.get('auth_type') or 'bearer')
|
||||
if auth_type not in VIDEO_CONNECTION_AUTH_TYPES:
|
||||
raise ValueError(f'Unsupported auth type: {auth_type}')
|
||||
|
||||
provider = str(config.get('provider') or '')
|
||||
if provider not in VIDEO_CONNECTION_PROVIDERS:
|
||||
raise ValueError(f'Unsupported video provider: {provider}')
|
||||
|
||||
seconds = config.get('seconds')
|
||||
if seconds not in (None, ''):
|
||||
seconds = int(seconds)
|
||||
if seconds <= 0:
|
||||
raise ValueError('Video length must be a positive number of seconds (e.g. 8)')
|
||||
else:
|
||||
seconds = None
|
||||
|
||||
return {
|
||||
'id': connection_id,
|
||||
'name': str(connection.get('name') or '').strip() or connection_type,
|
||||
'type': connection_type,
|
||||
'url': str(connection.get('url') or '').strip().rstrip('/'),
|
||||
'key': str(connection.get('key') or ''),
|
||||
'config': {
|
||||
'enable': bool(config.get('enable', True)),
|
||||
'model_ids': model_ids,
|
||||
'access_grants': list(config.get('access_grants') or []),
|
||||
'provider': provider,
|
||||
'auth_type': auth_type,
|
||||
'headers': _json_object(config.get('headers'), 'headers'),
|
||||
'size': _size(config.get('size')),
|
||||
'seconds': seconds,
|
||||
'api_version': str(config.get('api_version') or ''),
|
||||
'params': _json_object(config.get('params'), 'additional parameters'),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
async def get_video_connection_models(request: Request, connection: dict, user: UserModel | None = None) -> list[dict]:
|
||||
"""The models a connection serves, with video models marked (``video``). OpenRouter lists its video
|
||||
models on their own at ``/videos/models``; other servers list everything at ``/models``, and LiteLLM
|
||||
marks which ones make video."""
|
||||
if get_video_connection_provider(connection) != 'openrouter':
|
||||
return await get_openai_connection_models(request, connection, user)
|
||||
|
||||
from open_webui.routers.images import raise_for_provider_status
|
||||
|
||||
headers, cookies = await get_headers_and_cookies(
|
||||
request, connection['url'], connection.get('key'), connection.get('config') or {}, user=user
|
||||
)
|
||||
session = await get_session()
|
||||
async with session.get(
|
||||
url=f'{connection["url"]}/videos/models', headers=headers, cookies=cookies, ssl=AIOHTTP_CLIENT_SESSION_SSL
|
||||
) as r:
|
||||
await raise_for_provider_status(r)
|
||||
res = await r.json(content_type=None)
|
||||
|
||||
entries = res.get('data') if isinstance(res, dict) else res
|
||||
return [
|
||||
{'id': entry['id'], 'name': entry.get('name') or entry['id'], 'video': True}
|
||||
for entry in entries or []
|
||||
if isinstance(entry, dict) and entry.get('id')
|
||||
]
|
||||
|
||||
|
||||
@cached(
|
||||
ttl=MODELS_CACHE_TTL,
|
||||
key_builder=lambda _func, request, connection, user=None: (
|
||||
f'video_connection_models_{connection["id"]}_{user.id}'
|
||||
if user
|
||||
else f'video_connection_models_{connection["id"]}'
|
||||
),
|
||||
)
|
||||
async def get_synced_video_models(request: Request, connection: dict, user: UserModel | None = None) -> list[dict]:
|
||||
"""The video models a connection with no model IDs offers, listed live so new ones appear on their own.
|
||||
Servers that do not label video models (plain OpenAI) offer their default model."""
|
||||
try:
|
||||
models = await get_video_connection_models(request, connection, user)
|
||||
except Exception as e:
|
||||
log.warning('Could not list video models from %s: %s', connection.get('url'), e)
|
||||
return []
|
||||
|
||||
if not any('video' in model for model in models):
|
||||
return [{'id': ''}]
|
||||
return [model for model in models if model['video']]
|
||||
|
||||
|
||||
async def get_video_models(request: Request, user: UserModel, *, bypass_access: bool = False) -> list[dict]:
|
||||
"""Video models the user may use, across enabled connections. Each carries its connection for internal use.
|
||||
|
||||
A connection without model IDs offers every video model the server labels (LiteLLM), else its default model.
|
||||
"""
|
||||
connections = await Config.get(VIDEO_CONNECTIONS_CONFIG_KEY) or []
|
||||
user_group_ids = {group.id for group in await Groups.get_groups_by_member_id(user.id, include_inherited=True)}
|
||||
|
||||
models = []
|
||||
for connection in connections:
|
||||
config = connection.get('config') or {}
|
||||
if not config.get('enable', True):
|
||||
continue
|
||||
if not bypass_access and not await has_connection_access(user, connection, user_group_ids):
|
||||
continue
|
||||
|
||||
if config.get('model_ids'):
|
||||
entries = [{'id': model_id} for model_id in config['model_ids']]
|
||||
else:
|
||||
entries = await get_synced_video_models(request, connection, user)
|
||||
|
||||
for entry in entries:
|
||||
model_id = entry['id']
|
||||
models.append(
|
||||
{
|
||||
'id': get_image_model_ref(connection['id'], model_id),
|
||||
'name': model_id or connection.get('name') or connection['id'],
|
||||
'model': model_id,
|
||||
'connection_id': connection['id'],
|
||||
'connection_name': connection.get('name') or connection['id'],
|
||||
'connection': connection,
|
||||
}
|
||||
)
|
||||
return models
|
||||
|
||||
|
||||
def get_requested_video_model(metadata: dict | None) -> str | None:
|
||||
return get_requested_model(metadata, 'video_generation', 'videoModelId')
|
||||
|
||||
|
||||
async def resolve_video_model(
|
||||
request: Request,
|
||||
user: UserModel,
|
||||
model: str | None = None,
|
||||
*,
|
||||
strict: bool = False,
|
||||
) -> tuple[dict, str]:
|
||||
"""Pick the connection and model to run a request on.
|
||||
|
||||
Order: the requested model (a reference or a bare model id), then the admin's default, then the
|
||||
first model the user can use. A requested model the user cannot use falls back to the default
|
||||
unless ``strict`` is set, as on the direct API route.
|
||||
"""
|
||||
models = await get_video_models(request, user)
|
||||
|
||||
def find(value: str | None) -> dict | None:
|
||||
if not value:
|
||||
return None
|
||||
return next((m for m in models if m['id'] == value), None) or next(
|
||||
(m for m in models if m['model'] == value), None
|
||||
)
|
||||
|
||||
if model:
|
||||
requested = find(model)
|
||||
if requested:
|
||||
return requested['connection'], requested['model']
|
||||
if strict:
|
||||
raise HTTPException(status_code=400, detail=f'Video model "{model}" was not found')
|
||||
log.debug('Video model %s is not available to %s; using the default', model, user.id)
|
||||
|
||||
default = find(await Config.get(VIDEO_GENERATION_DEFAULT_MODEL_CONFIG_KEY))
|
||||
if default:
|
||||
return default['connection'], default['model']
|
||||
|
||||
if models:
|
||||
return models[0]['connection'], models[0]['model']
|
||||
|
||||
raise HTTPException(status_code=400, detail=ERROR_MESSAGES.DEFAULT('No video model is available'))
|
||||
File diff suppressed because it is too large.
Load diff
Loaded 100 of 518 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user