Skip to content

Commit 5822c6d

Browse files
committed
perf: batch DB fetch for tools in get_tools
1 parent 2255736 commit 5822c6d

2 files changed

Lines changed: 18 additions & 1 deletion

File tree

backend/open_webui/models/tools.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -151,6 +151,19 @@ async def get_tool_by_id(self, id: str, db: AsyncSession | None = None) -> ToolM
151151
except Exception:
152152
return None
153153

154+
async def get_tools_by_ids(self, ids: list[str], db: AsyncSession | None = None) -> dict[str, ToolModel]:
155+
if not ids:
156+
return {}
157+
async with get_async_db_context(db) as db:
158+
result = await db.execute(select(Tool).where(Tool.id.in_(ids)))
159+
tools = result.scalars().all()
160+
tool_ids = [t.id for t in tools]
161+
grants_map = await AccessGrants.get_grants_by_resources('tool', tool_ids, db=db)
162+
return {
163+
t.id: await self._to_tool_model(t, access_grants=grants_map.get(t.id, []), db=db)
164+
for t in tools
165+
}
166+
154167
async def get_tools(self, defer_content: bool = False, db: AsyncSession | None = None) -> list[ToolUserModel]:
155168
async with get_async_db_context(db) as db:
156169
stmt = select(Tool).order_by(Tool.updated_at.desc())

backend/open_webui/utils/tools.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -166,8 +166,12 @@ async def get_tools(request: Request, tool_ids: list[str], user: UserModel, extr
166166
# Get user's group memberships for access control checks
167167
user_group_ids = {group.id for group in await Groups.get_groups_by_member_id(user.id)}
168168

169+
# Single query for all local tools instead of one per tool_id
170+
local_tool_ids = [tid for tid in tool_ids if not tid.startswith('server:')]
171+
tools_by_id = await Tools.get_tools_by_ids(local_tool_ids)
172+
169173
for tool_id in tool_ids:
170-
tool = await Tools.get_tool_by_id(tool_id)
174+
tool = tools_by_id.get(tool_id)
171175
if tool:
172176
# Check access control for local tools
173177
if (

0 commit comments

Comments
 (0)