2024-06-14 10:33:59 +08:00
|
|
|
#
|
|
|
|
|
# Copyright 2024 The InfiniFlow Authors. All Rights Reserved.
|
|
|
|
|
#
|
|
|
|
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
|
|
|
# you may not use this file except in compliance with the License.
|
|
|
|
|
# You may obtain a copy of the License at
|
|
|
|
|
#
|
|
|
|
|
# http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
|
#
|
|
|
|
|
# Unless required by applicable law or agreed to in writing, software
|
|
|
|
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
|
|
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
|
|
|
# See the License for the specific language governing permissions and
|
|
|
|
|
# limitations under the License.
|
|
|
|
|
#
|
2024-12-09 12:38:04 +08:00
|
|
|
import json
|
2025-07-30 19:41:09 +08:00
|
|
|
import logging
|
2025-01-24 11:07:55 +08:00
|
|
|
import time
|
feat: add tag management for Agents with filtering and sorting (#14774) (#14799)
## Summary
Closes #14774.
Adds free-form tags on agents (UserCanvas) with full UI + API:
- Stored as comma-separated `tags` column on `UserCanvas` with online
migration.
- New endpoints: `GET /v1/agents/tags` (aggregate counts) and `PUT
/v1/agent/<id>/tags` (write). `GET /v1/agents` accepts a `tags=` query.
- "Edit tags" item in agent dropdown opens a chip-style editor dialog;
tags render as badges on each agent card.
- New "Tags" facet in the agents filter bar, with counts.
## Implementation notes
- **Tag matching is exact-token**: the SQL filter wraps stored tags as
`,…,` and matches `,ml,` so `ml` doesn't match `ml-ops`.
- **Server-side normalization** in `UserCanvasService.update_tags`:
dedup (case-insensitive), per-tag cap of 64 chars, total length capped
at 512 chars to fit the column, commas inside tag values are replaced
with spaces.
- **Tenant authorization**: `PUT /v1/agent/<id>/tags` gates on
`UserCanvasService.accessible(canvas_id, tenant_id)`.
- **Tag listing scope**: `UserCanvasService.list_tags` follows the same
own + team-shared rule as `get_by_tenant_ids`.
- **i18n**: keys added to `en.ts` and `zh.ts` only (per project
convention; other locales fall back).
- **`HomeCard`** gets a non-breaking `extra?: ReactNode` slot for the
chip row; no `src/components/ui/` files modified.
## Test plan
- [ ] Backend boot runs `migrate_db` → confirm `user_canvas.tags` column
exists (`DESCRIBE user_canvas`).
- [ ] Agents page renders cards normally (no console error from missing
field).
- [ ] `⋯ → Edit tags` opens a dialog that stays open (regression: dialog
was unmounting with the dropdown).
- [ ] Typing a tag without pressing Enter and clicking Save persists it
(regression: last typed tag was being dropped).
- [ ] Chip input supports Enter/comma to commit, Backspace on empty to
remove, `×` to remove individual chip.
- [ ] Tag containing a comma sent via API is stored with the comma
replaced by a space.
- [ ] 20 long tags sent via API does not error (length cap silently
truncates).
- [ ] "Tags" filter in the filter bar shows counts and narrows the list.
- [ ] Filtering by `ml` does **not** return agents tagged `ml-ops`.
- [ ] UI in Chinese shows 编辑标签 / 添加标签以整理和筛选你的智能体 etc.
- [ ] `PUT /v1/agent/<other-tenant-id>/tags` returns `Agent not found or
no permission.`
2026-05-13 06:41:32 -07:00
|
|
|
from functools import reduce
|
|
|
|
|
from operator import or_
|
2024-12-09 12:38:04 +08:00
|
|
|
from uuid import uuid4
|
|
|
|
|
from agent.canvas import Canvas
|
2025-09-03 14:55:24 +08:00
|
|
|
from api.db import CanvasCategory, TenantPermission
|
2026-03-10 14:25:27 +08:00
|
|
|
from api.db.db_models import DB, CanvasTemplate, User, UserCanvas, API4Conversation, UserCanvasVersion
|
2024-12-09 12:38:04 +08:00
|
|
|
from api.db.services.api_service import API4ConversationService
|
2024-06-14 10:33:59 +08:00
|
|
|
from api.db.services.common_service import CommonService
|
2026-03-13 16:31:17 +08:00
|
|
|
from api.db.services.user_canvas_version import UserCanvasVersionService
|
fix: offload blocking DB/Redis calls to thread pool for high-concurrency support (#13825) (#13941)
### What problem does this PR solve?
Addresses event-loop blocking under high concurrency reported in #13825.
When multiple requests hit the API simultaneously, synchronous DB/Redis
calls block the async event loop, preventing Quart from handling other
requests and causing cascading 502/504 timeouts.
This PR wraps all remaining blocking DB/Redis calls in `canvas_app.py`,
`chat_api.py`, `session.py`, and `canvas_service.py` with `await
thread_pool_exec()`
- Offload all synchronous `Service.*`, `REDIS_CONN.*`, and
`APIToken.query` calls to the thread pool
- Convert sync endpoint handlers (`list_chats`, `get_chat`, `templates`,
`sessions`, etc.) to `async def`
- Convert sync helper functions (`_ensure_owned_chat`,
`_validate_llm_id`, `_validate_dataset_ids`, etc.) to async - no
duplicate sync/async pairs
- Wrap `CanvasReplicaService` Redis IO calls (`bootstrap`,
`replace_for_set`, `commit_after_run`)
- Use `asyncio.gather()` for concurrent file uploads and chat response
building
**Note:** This fixes the code-level event-loop blocking, which is a
prerequisite for handling concurrent requests. For the full "30
concurrent requests without 502/504" goal described in the issue, users
should also tune deployment config:
- `WS=4` or higher (HTTP worker processes, default 1)
- `MAX_CONCURRENT_CHATS=50` (default 10)
- `SANDBOX_EXECUTOR_MANAGER_POOL_SIZE` for workflow-heavy workloads
### Performance verification
Reviewer asked for a before-vs-after comparison
([comment](https://github.com/infiniflow/ragflow/pull/13941#issuecomment-4393667231)).
I built a self-contained microbenchmark that reproduces the exact
failure mode this PR targets: an async handler that performs blocking
DB/Redis-style calls (50 ms each, 3 per request, 30 concurrent requests)
is run twice — once with the pre-PR pattern (sync call directly inside
the async handler) and once with the post-PR pattern (`await
thread_pool_exec(...)`). The benchmark imports nothing from RAGFlow
except `thread_pool_exec` itself, so it is hermetic and reproducible
(`THREAD_POOL_MAX_WORKERS=128`, Python 3.13.12).
**Throughput — wall-clock for 30 concurrent requests (lower is better)**
| flavour | wall(s) | p50(s) | p95(s) | max(s) |
|---|---:|---:|---:|---:|
| before | 4.986 | 0.158 | 0.207 | 0.269 |
| after | 0.248 | 0.181 | 0.230 | 0.231 |
The pre-PR handler serializes the entire load on the event-loop thread,
so 30 × 3 × 50 ms ≈ 4.5 s shows up as the wall time. The post-PR handler
parallelizes the blocking work across the thread pool and finishes the
same load in 248 ms — a **~20× speedup** on this workload.
**Event-loop responsiveness — latency of an unrelated probe coroutine
while the 30 slow requests are running (lower is better)**
| flavour | samples | probe p50 (ms) | probe p95 (ms) | probe max (ms) |
|---|---:|---:|---:|---:|
| before | 1 | 5442.26 | 5442.26 | 5442.26 |
| after | 28 | 0.88 | 11.53 | 98.02 |
This is the metric that maps directly to "the API still answers other
requests while one is busy". A 5 ms-interval probe was scheduled while
the 30 slow handlers ran. With the pre-PR code the event loop was frozen
for the entire duration of the blocking work, so only one probe sample
was ever picked up and it waited **5,442 ms**. After the PR, 28 probe
samples landed with **p50 0.88 ms / p95 11.53 ms**, meaning unrelated
requests are no longer starved by the slow ones. That is the regression
mode behind the cascading 502/504s reported in #13825.
<details>
<summary>Raw benchmark output</summary>
```
config: 30 concurrent requests, 3 blocking calls of 50ms each per request, THREAD_POOL_MAX_WORKERS=128
=== Throughput (lower wall is better) ===
flavour wall(s) p50(s) p95(s) max(s)
before 4.986 0.158 0.207 0.269
after 0.248 0.181 0.230 0.231
=== Event-loop responsiveness (lower probe latency is better) ===
flavour samples probe p50(ms) probe p95(ms) probe max(ms)
before 1 5442.26 5442.26 5442.26
after 28 0.88 11.53 98.02
```
</details>
The benchmark script is included as a comment on the PR for
reproducibility.
### Type of change
- [x] Bug Fix (non-breaking change which fixes an issue)
- [x] Performance Improvement
Closes [#13825](https://github.com/infiniflow/ragflow/issues/13825)
---------
Co-authored-by: tmimmanuel <tmimmanuel@users.noreply.github.com>
Co-authored-by: Kevin Hu <kevinhu.sh@gmail.com>
2026-05-10 21:08:55 -10:00
|
|
|
from common.misc_utils import get_uuid, thread_pool_exec
|
2025-04-03 15:51:37 +07:00
|
|
|
from api.utils.api_utils import get_data_openai
|
|
|
|
|
import tiktoken
|
2025-03-19 18:04:13 +07:00
|
|
|
from peewee import fn
|
2025-07-30 19:41:09 +08:00
|
|
|
|
|
|
|
|
|
2024-06-14 10:33:59 +08:00
|
|
|
class CanvasTemplateService(CommonService):
|
|
|
|
|
model = CanvasTemplate
|
|
|
|
|
|
2025-09-03 14:55:24 +08:00
|
|
|
class DataFlowTemplateService(CommonService):
|
|
|
|
|
"""
|
|
|
|
|
Alias of CanvasTemplateService
|
|
|
|
|
"""
|
|
|
|
|
model = CanvasTemplate
|
|
|
|
|
|
2024-11-04 17:20:16 +08:00
|
|
|
|
2024-06-14 10:33:59 +08:00
|
|
|
class UserCanvasService(CommonService):
|
|
|
|
|
model = UserCanvas
|
2024-12-03 19:03:16 +08:00
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
|
@DB.connection_context()
|
|
|
|
|
def get_list(cls, tenant_id,
|
2025-09-03 14:55:24 +08:00
|
|
|
page_number, items_per_page, orderby, desc, id, title, canvas_category=CanvasCategory.Agent):
|
2024-12-03 19:03:16 +08:00
|
|
|
agents = cls.model.select()
|
|
|
|
|
if id:
|
|
|
|
|
agents = agents.where(cls.model.id == id)
|
|
|
|
|
if title:
|
|
|
|
|
agents = agents.where(cls.model.title == title)
|
|
|
|
|
agents = agents.where(cls.model.user_id == tenant_id)
|
2025-09-03 14:55:24 +08:00
|
|
|
agents = agents.where(cls.model.canvas_category == canvas_category)
|
2024-12-03 19:03:16 +08:00
|
|
|
if desc:
|
|
|
|
|
agents = agents.order_by(cls.model.getter_by(orderby).desc())
|
|
|
|
|
else:
|
|
|
|
|
agents = agents.order_by(cls.model.getter_by(orderby).asc())
|
|
|
|
|
|
|
|
|
|
agents = agents.paginate(page_number, items_per_page)
|
|
|
|
|
|
|
|
|
|
return list(agents.dicts())
|
2025-08-05 17:47:25 +08:00
|
|
|
|
2025-09-25 16:15:15 +08:00
|
|
|
@classmethod
|
|
|
|
|
@DB.connection_context()
|
|
|
|
|
def get_all_agents_by_tenant_ids(cls, tenant_ids, user_id):
|
|
|
|
|
# will get all permitted agents, be cautious
|
|
|
|
|
fields = [
|
2025-09-29 10:16:13 +08:00
|
|
|
cls.model.id,
|
2025-11-07 09:27:31 +08:00
|
|
|
cls.model.avatar,
|
2025-09-25 16:15:15 +08:00
|
|
|
cls.model.title,
|
|
|
|
|
cls.model.permission,
|
|
|
|
|
cls.model.canvas_type,
|
|
|
|
|
cls.model.canvas_category
|
|
|
|
|
]
|
|
|
|
|
# find team agents and owned agents
|
|
|
|
|
agents = cls.model.select(*fields).where(
|
|
|
|
|
(cls.model.user_id.in_(tenant_ids) & (cls.model.permission == TenantPermission.TEAM.value)) | (
|
|
|
|
|
cls.model.user_id == user_id
|
|
|
|
|
)
|
|
|
|
|
)
|
|
|
|
|
# sort by create_time, asc
|
|
|
|
|
agents.order_by(cls.model.create_time.asc())
|
|
|
|
|
# maybe cause slow query by deep paginate, optimize later
|
|
|
|
|
offset, limit = 0, 50
|
|
|
|
|
res = []
|
|
|
|
|
while True:
|
|
|
|
|
ag_batch = agents.offset(offset).limit(limit)
|
|
|
|
|
_temp = list(ag_batch.dicts())
|
|
|
|
|
if not _temp:
|
|
|
|
|
break
|
|
|
|
|
res.extend(_temp)
|
|
|
|
|
offset += limit
|
|
|
|
|
return res
|
|
|
|
|
|
2025-03-19 18:04:13 +07:00
|
|
|
@classmethod
|
|
|
|
|
@DB.connection_context()
|
2025-09-29 10:16:13 +08:00
|
|
|
def get_by_canvas_id(cls, pid):
|
2025-03-19 18:04:13 +07:00
|
|
|
try:
|
2025-08-05 17:47:25 +08:00
|
|
|
|
2025-03-19 18:04:13 +07:00
|
|
|
fields = [
|
|
|
|
|
cls.model.id,
|
|
|
|
|
cls.model.avatar,
|
|
|
|
|
cls.model.title,
|
|
|
|
|
cls.model.dsl,
|
|
|
|
|
cls.model.description,
|
|
|
|
|
cls.model.permission,
|
|
|
|
|
cls.model.update_time,
|
|
|
|
|
cls.model.user_id,
|
|
|
|
|
cls.model.create_time,
|
|
|
|
|
cls.model.create_date,
|
|
|
|
|
cls.model.update_date,
|
2025-09-03 14:55:24 +08:00
|
|
|
cls.model.canvas_category,
|
2025-03-19 18:04:13 +07:00
|
|
|
User.nickname,
|
|
|
|
|
User.avatar.alias('tenant_avatar'),
|
|
|
|
|
]
|
2025-06-18 09:41:09 +08:00
|
|
|
agents = cls.model.select(*fields) \
|
2025-03-19 18:04:13 +07:00
|
|
|
.join(User, on=(cls.model.user_id == User.id)) \
|
|
|
|
|
.where(cls.model.id == pid)
|
|
|
|
|
# obj = cls.model.query(id=pid)[0]
|
2025-06-18 09:41:09 +08:00
|
|
|
return True, agents.dicts()[0]
|
2025-03-19 18:04:13 +07:00
|
|
|
except Exception as e:
|
2025-07-30 19:41:09 +08:00
|
|
|
logging.exception(e)
|
2025-03-19 18:04:13 +07:00
|
|
|
return False, None
|
2025-08-05 17:47:25 +08:00
|
|
|
|
2025-12-25 21:18:13 +08:00
|
|
|
@classmethod
|
|
|
|
|
@DB.connection_context()
|
|
|
|
|
def get_basic_info_by_canvas_ids(cls, canvas_id):
|
|
|
|
|
fields = [
|
|
|
|
|
cls.model.id,
|
|
|
|
|
cls.model.avatar,
|
|
|
|
|
cls.model.user_id,
|
|
|
|
|
cls.model.title,
|
|
|
|
|
cls.model.permission,
|
|
|
|
|
cls.model.canvas_category
|
|
|
|
|
]
|
|
|
|
|
return cls.model.select(*fields).where(cls.model.id.in_(canvas_id)).dicts()
|
|
|
|
|
|
2025-03-19 18:04:13 +07:00
|
|
|
@classmethod
|
|
|
|
|
@DB.connection_context()
|
2026-04-24 10:02:22 +08:00
|
|
|
def get_by_tenant_ids(
|
|
|
|
|
cls,
|
|
|
|
|
joined_tenant_ids,
|
|
|
|
|
user_id,
|
|
|
|
|
page_number,
|
|
|
|
|
items_per_page,
|
|
|
|
|
orderby,
|
|
|
|
|
desc,
|
|
|
|
|
keywords,
|
|
|
|
|
canvas_category=None,
|
feat: add tag management for Agents with filtering and sorting (#14774) (#14799)
## Summary
Closes #14774.
Adds free-form tags on agents (UserCanvas) with full UI + API:
- Stored as comma-separated `tags` column on `UserCanvas` with online
migration.
- New endpoints: `GET /v1/agents/tags` (aggregate counts) and `PUT
/v1/agent/<id>/tags` (write). `GET /v1/agents` accepts a `tags=` query.
- "Edit tags" item in agent dropdown opens a chip-style editor dialog;
tags render as badges on each agent card.
- New "Tags" facet in the agents filter bar, with counts.
## Implementation notes
- **Tag matching is exact-token**: the SQL filter wraps stored tags as
`,…,` and matches `,ml,` so `ml` doesn't match `ml-ops`.
- **Server-side normalization** in `UserCanvasService.update_tags`:
dedup (case-insensitive), per-tag cap of 64 chars, total length capped
at 512 chars to fit the column, commas inside tag values are replaced
with spaces.
- **Tenant authorization**: `PUT /v1/agent/<id>/tags` gates on
`UserCanvasService.accessible(canvas_id, tenant_id)`.
- **Tag listing scope**: `UserCanvasService.list_tags` follows the same
own + team-shared rule as `get_by_tenant_ids`.
- **i18n**: keys added to `en.ts` and `zh.ts` only (per project
convention; other locales fall back).
- **`HomeCard`** gets a non-breaking `extra?: ReactNode` slot for the
chip row; no `src/components/ui/` files modified.
## Test plan
- [ ] Backend boot runs `migrate_db` → confirm `user_canvas.tags` column
exists (`DESCRIBE user_canvas`).
- [ ] Agents page renders cards normally (no console error from missing
field).
- [ ] `⋯ → Edit tags` opens a dialog that stays open (regression: dialog
was unmounting with the dropdown).
- [ ] Typing a tag without pressing Enter and clicking Save persists it
(regression: last typed tag was being dropped).
- [ ] Chip input supports Enter/comma to commit, Backspace on empty to
remove, `×` to remove individual chip.
- [ ] Tag containing a comma sent via API is stored with the comma
replaced by a space.
- [ ] 20 long tags sent via API does not error (length cap silently
truncates).
- [ ] "Tags" filter in the filter bar shows counts and narrows the list.
- [ ] Filtering by `ml` does **not** return agents tagged `ml-ops`.
- [ ] UI in Chinese shows 编辑标签 / 添加标签以整理和筛选你的智能体 etc.
- [ ] `PUT /v1/agent/<other-tenant-id>/tags` returns `Agent not found or
no permission.`
2026-05-13 06:41:32 -07:00
|
|
|
tags=None,
|
2026-04-24 10:02:22 +08:00
|
|
|
):
|
2025-03-19 18:04:13 +07:00
|
|
|
fields = [
|
|
|
|
|
cls.model.id,
|
|
|
|
|
cls.model.avatar,
|
|
|
|
|
cls.model.title,
|
|
|
|
|
cls.model.description,
|
|
|
|
|
cls.model.permission,
|
2025-10-09 12:36:19 +08:00
|
|
|
cls.model.user_id.alias("tenant_id"),
|
2025-03-19 18:04:13 +07:00
|
|
|
User.nickname,
|
|
|
|
|
User.avatar.alias('tenant_avatar'),
|
2025-09-03 14:55:24 +08:00
|
|
|
cls.model.update_time,
|
|
|
|
|
cls.model.canvas_category,
|
feat: add tag management for Agents with filtering and sorting (#14774) (#14799)
## Summary
Closes #14774.
Adds free-form tags on agents (UserCanvas) with full UI + API:
- Stored as comma-separated `tags` column on `UserCanvas` with online
migration.
- New endpoints: `GET /v1/agents/tags` (aggregate counts) and `PUT
/v1/agent/<id>/tags` (write). `GET /v1/agents` accepts a `tags=` query.
- "Edit tags" item in agent dropdown opens a chip-style editor dialog;
tags render as badges on each agent card.
- New "Tags" facet in the agents filter bar, with counts.
## Implementation notes
- **Tag matching is exact-token**: the SQL filter wraps stored tags as
`,…,` and matches `,ml,` so `ml` doesn't match `ml-ops`.
- **Server-side normalization** in `UserCanvasService.update_tags`:
dedup (case-insensitive), per-tag cap of 64 chars, total length capped
at 512 chars to fit the column, commas inside tag values are replaced
with spaces.
- **Tenant authorization**: `PUT /v1/agent/<id>/tags` gates on
`UserCanvasService.accessible(canvas_id, tenant_id)`.
- **Tag listing scope**: `UserCanvasService.list_tags` follows the same
own + team-shared rule as `get_by_tenant_ids`.
- **i18n**: keys added to `en.ts` and `zh.ts` only (per project
convention; other locales fall back).
- **`HomeCard`** gets a non-breaking `extra?: ReactNode` slot for the
chip row; no `src/components/ui/` files modified.
## Test plan
- [ ] Backend boot runs `migrate_db` → confirm `user_canvas.tags` column
exists (`DESCRIBE user_canvas`).
- [ ] Agents page renders cards normally (no console error from missing
field).
- [ ] `⋯ → Edit tags` opens a dialog that stays open (regression: dialog
was unmounting with the dropdown).
- [ ] Typing a tag without pressing Enter and clicking Save persists it
(regression: last typed tag was being dropped).
- [ ] Chip input supports Enter/comma to commit, Backspace on empty to
remove, `×` to remove individual chip.
- [ ] Tag containing a comma sent via API is stored with the comma
replaced by a space.
- [ ] 20 long tags sent via API does not error (length cap silently
truncates).
- [ ] "Tags" filter in the filter bar shows counts and narrows the list.
- [ ] Filtering by `ml` does **not** return agents tagged `ml-ops`.
- [ ] UI in Chinese shows 编辑标签 / 添加标签以整理和筛选你的智能体 etc.
- [ ] `PUT /v1/agent/<other-tenant-id>/tags` returns `Agent not found or
no permission.`
2026-05-13 06:41:32 -07:00
|
|
|
cls.model.tags,
|
2025-03-19 18:04:13 +07:00
|
|
|
]
|
|
|
|
|
if keywords:
|
2025-06-18 09:41:09 +08:00
|
|
|
agents = cls.model.select(*fields).join(User, on=(cls.model.user_id == User.id)).where(
|
2025-10-14 19:38:54 +08:00
|
|
|
(((cls.model.user_id.in_(joined_tenant_ids)) & (cls.model.permission == TenantPermission.TEAM.value)) | (cls.model.user_id == user_id)),
|
|
|
|
|
(fn.LOWER(cls.model.title).contains(keywords.lower()))
|
2025-03-19 18:04:13 +07:00
|
|
|
)
|
|
|
|
|
else:
|
2025-06-18 09:41:09 +08:00
|
|
|
agents = cls.model.select(*fields).join(User, on=(cls.model.user_id == User.id)).where(
|
2025-10-14 19:38:54 +08:00
|
|
|
(((cls.model.user_id.in_(joined_tenant_ids)) & (cls.model.permission == TenantPermission.TEAM.value)) | (cls.model.user_id == user_id))
|
2025-03-19 18:04:13 +07:00
|
|
|
)
|
2025-10-09 12:36:19 +08:00
|
|
|
if canvas_category:
|
|
|
|
|
agents = agents.where(cls.model.canvas_category == canvas_category)
|
feat: add tag management for Agents with filtering and sorting (#14774) (#14799)
## Summary
Closes #14774.
Adds free-form tags on agents (UserCanvas) with full UI + API:
- Stored as comma-separated `tags` column on `UserCanvas` with online
migration.
- New endpoints: `GET /v1/agents/tags` (aggregate counts) and `PUT
/v1/agent/<id>/tags` (write). `GET /v1/agents` accepts a `tags=` query.
- "Edit tags" item in agent dropdown opens a chip-style editor dialog;
tags render as badges on each agent card.
- New "Tags" facet in the agents filter bar, with counts.
## Implementation notes
- **Tag matching is exact-token**: the SQL filter wraps stored tags as
`,…,` and matches `,ml,` so `ml` doesn't match `ml-ops`.
- **Server-side normalization** in `UserCanvasService.update_tags`:
dedup (case-insensitive), per-tag cap of 64 chars, total length capped
at 512 chars to fit the column, commas inside tag values are replaced
with spaces.
- **Tenant authorization**: `PUT /v1/agent/<id>/tags` gates on
`UserCanvasService.accessible(canvas_id, tenant_id)`.
- **Tag listing scope**: `UserCanvasService.list_tags` follows the same
own + team-shared rule as `get_by_tenant_ids`.
- **i18n**: keys added to `en.ts` and `zh.ts` only (per project
convention; other locales fall back).
- **`HomeCard`** gets a non-breaking `extra?: ReactNode` slot for the
chip row; no `src/components/ui/` files modified.
## Test plan
- [ ] Backend boot runs `migrate_db` → confirm `user_canvas.tags` column
exists (`DESCRIBE user_canvas`).
- [ ] Agents page renders cards normally (no console error from missing
field).
- [ ] `⋯ → Edit tags` opens a dialog that stays open (regression: dialog
was unmounting with the dropdown).
- [ ] Typing a tag without pressing Enter and clicking Save persists it
(regression: last typed tag was being dropped).
- [ ] Chip input supports Enter/comma to commit, Backspace on empty to
remove, `×` to remove individual chip.
- [ ] Tag containing a comma sent via API is stored with the comma
replaced by a space.
- [ ] 20 long tags sent via API does not error (length cap silently
truncates).
- [ ] "Tags" filter in the filter bar shows counts and narrows the list.
- [ ] Filtering by `ml` does **not** return agents tagged `ml-ops`.
- [ ] UI in Chinese shows 编辑标签 / 添加标签以整理和筛选你的智能体 etc.
- [ ] `PUT /v1/agent/<other-tenant-id>/tags` returns `Agent not found or
no permission.`
2026-05-13 06:41:32 -07:00
|
|
|
if tags:
|
|
|
|
|
tag_list = [t.strip() for t in tags if t and t.strip()] if isinstance(tags, (list, tuple)) else [t.strip() for t in str(tags).split(",") if t.strip()]
|
|
|
|
|
if tag_list:
|
|
|
|
|
# Wrap value with commas so 'ml' doesn't match 'ml-ops'.
|
|
|
|
|
wrapped = fn.CONCAT(",", cls.model.tags, ",")
|
|
|
|
|
clauses = [wrapped.contains(f",{t},") for t in tag_list]
|
|
|
|
|
agents = agents.where(reduce(or_, clauses))
|
2025-03-19 18:04:13 +07:00
|
|
|
if desc:
|
2025-06-18 09:41:09 +08:00
|
|
|
agents = agents.order_by(cls.model.getter_by(orderby).desc())
|
2025-03-19 18:04:13 +07:00
|
|
|
else:
|
2025-06-18 09:41:09 +08:00
|
|
|
agents = agents.order_by(cls.model.getter_by(orderby).asc())
|
2025-10-09 12:36:19 +08:00
|
|
|
|
2025-06-18 09:41:09 +08:00
|
|
|
count = agents.count()
|
2025-10-09 12:36:19 +08:00
|
|
|
if page_number and items_per_page:
|
|
|
|
|
agents = agents.paginate(page_number, items_per_page)
|
2026-03-10 14:25:27 +08:00
|
|
|
|
|
|
|
|
agents_list = list(agents.dicts())
|
|
|
|
|
|
|
|
|
|
# Get latest release time for each canvas
|
|
|
|
|
if agents_list:
|
|
|
|
|
canvas_ids = [a['id'] for a in agents_list]
|
|
|
|
|
release_times = (
|
|
|
|
|
UserCanvasVersion.select(UserCanvasVersion.user_canvas_id, fn.MAX(UserCanvasVersion.create_time).alias("release_time"))
|
|
|
|
|
.where((UserCanvasVersion.user_canvas_id.in_(canvas_ids)) & (UserCanvasVersion.release))
|
|
|
|
|
.group_by(UserCanvasVersion.user_canvas_id)
|
|
|
|
|
)
|
|
|
|
|
release_time_map = {r.user_canvas_id: r.release_time for r in release_times}
|
|
|
|
|
|
|
|
|
|
for agent in agents_list:
|
|
|
|
|
agent['release_time'] = release_time_map.get(agent['id'])
|
|
|
|
|
|
|
|
|
|
return agents_list, count
|
2024-12-09 12:38:04 +08:00
|
|
|
|
feat: add tag management for Agents with filtering and sorting (#14774) (#14799)
## Summary
Closes #14774.
Adds free-form tags on agents (UserCanvas) with full UI + API:
- Stored as comma-separated `tags` column on `UserCanvas` with online
migration.
- New endpoints: `GET /v1/agents/tags` (aggregate counts) and `PUT
/v1/agent/<id>/tags` (write). `GET /v1/agents` accepts a `tags=` query.
- "Edit tags" item in agent dropdown opens a chip-style editor dialog;
tags render as badges on each agent card.
- New "Tags" facet in the agents filter bar, with counts.
## Implementation notes
- **Tag matching is exact-token**: the SQL filter wraps stored tags as
`,…,` and matches `,ml,` so `ml` doesn't match `ml-ops`.
- **Server-side normalization** in `UserCanvasService.update_tags`:
dedup (case-insensitive), per-tag cap of 64 chars, total length capped
at 512 chars to fit the column, commas inside tag values are replaced
with spaces.
- **Tenant authorization**: `PUT /v1/agent/<id>/tags` gates on
`UserCanvasService.accessible(canvas_id, tenant_id)`.
- **Tag listing scope**: `UserCanvasService.list_tags` follows the same
own + team-shared rule as `get_by_tenant_ids`.
- **i18n**: keys added to `en.ts` and `zh.ts` only (per project
convention; other locales fall back).
- **`HomeCard`** gets a non-breaking `extra?: ReactNode` slot for the
chip row; no `src/components/ui/` files modified.
## Test plan
- [ ] Backend boot runs `migrate_db` → confirm `user_canvas.tags` column
exists (`DESCRIBE user_canvas`).
- [ ] Agents page renders cards normally (no console error from missing
field).
- [ ] `⋯ → Edit tags` opens a dialog that stays open (regression: dialog
was unmounting with the dropdown).
- [ ] Typing a tag without pressing Enter and clicking Save persists it
(regression: last typed tag was being dropped).
- [ ] Chip input supports Enter/comma to commit, Backspace on empty to
remove, `×` to remove individual chip.
- [ ] Tag containing a comma sent via API is stored with the comma
replaced by a space.
- [ ] 20 long tags sent via API does not error (length cap silently
truncates).
- [ ] "Tags" filter in the filter bar shows counts and narrows the list.
- [ ] Filtering by `ml` does **not** return agents tagged `ml-ops`.
- [ ] UI in Chinese shows 编辑标签 / 添加标签以整理和筛选你的智能体 etc.
- [ ] `PUT /v1/agent/<other-tenant-id>/tags` returns `Agent not found or
no permission.`
2026-05-13 06:41:32 -07:00
|
|
|
@classmethod
|
|
|
|
|
@DB.connection_context()
|
|
|
|
|
def list_tags(cls, joined_tenant_ids, user_id, canvas_category=None):
|
|
|
|
|
"""Return {tag: agent_count} aggregated across agents visible to the user."""
|
|
|
|
|
query = cls.model.select(cls.model.tags).where(
|
|
|
|
|
((cls.model.user_id.in_(joined_tenant_ids)) & (cls.model.permission == TenantPermission.TEAM.value)) | (cls.model.user_id == user_id)
|
|
|
|
|
)
|
|
|
|
|
if canvas_category:
|
|
|
|
|
query = query.where(cls.model.canvas_category == canvas_category)
|
|
|
|
|
|
|
|
|
|
counts: dict[str, int] = {}
|
|
|
|
|
for row in query.dicts():
|
|
|
|
|
for t in (row.get("tags") or "").split(","):
|
|
|
|
|
t = t.strip()
|
|
|
|
|
if t:
|
|
|
|
|
counts[t] = counts.get(t, 0) + 1
|
|
|
|
|
logging.info(
|
|
|
|
|
"UserCanvasService.list_tags user=%s canvas_category=%s tags_count=%d",
|
|
|
|
|
user_id,
|
|
|
|
|
canvas_category,
|
|
|
|
|
len(counts),
|
|
|
|
|
)
|
|
|
|
|
return counts
|
|
|
|
|
|
|
|
|
|
# Tag storage is a single comma-separated CharField(max_length=512);
|
|
|
|
|
# commas inside a tag would corrupt the encoding, so strip them on write.
|
|
|
|
|
TAGS_FIELD_MAX = 512
|
|
|
|
|
TAG_MAX_LEN = 64
|
|
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
|
@DB.connection_context()
|
|
|
|
|
def update_tags(cls, canvas_id, tags):
|
|
|
|
|
"""Persist a normalized comma-separated tag string for the given canvas."""
|
|
|
|
|
if isinstance(tags, (list, tuple)):
|
|
|
|
|
cleaned = [str(t).replace(",", " ").strip() for t in tags if t and str(t).strip()]
|
|
|
|
|
else:
|
|
|
|
|
cleaned = [t.strip() for t in str(tags or "").split(",") if t.strip()]
|
|
|
|
|
# Dedupe (case-insensitive, preserve order), cap individual tag length,
|
|
|
|
|
# then truncate the joined value so it always fits the column.
|
|
|
|
|
seen = set()
|
|
|
|
|
normalized = []
|
|
|
|
|
used = 0
|
|
|
|
|
for t in cleaned:
|
|
|
|
|
t = t[: cls.TAG_MAX_LEN]
|
|
|
|
|
key = t.lower()
|
|
|
|
|
if key in seen:
|
|
|
|
|
continue
|
|
|
|
|
extra = len(t) + (1 if normalized else 0)
|
|
|
|
|
if used + extra > cls.TAGS_FIELD_MAX:
|
|
|
|
|
break
|
|
|
|
|
seen.add(key)
|
|
|
|
|
normalized.append(t)
|
|
|
|
|
used += extra
|
|
|
|
|
value = ",".join(normalized)
|
|
|
|
|
rows_affected = cls.model.update(tags=value).where(cls.model.id == canvas_id).execute()
|
|
|
|
|
logging.info(
|
|
|
|
|
"UserCanvasService.update_tags canvas_id=%s tags_count=%d rows=%d",
|
|
|
|
|
canvas_id,
|
|
|
|
|
len(normalized),
|
|
|
|
|
rows_affected,
|
|
|
|
|
)
|
|
|
|
|
return rows_affected
|
|
|
|
|
|
2025-08-08 18:31:51 +08:00
|
|
|
@classmethod
|
|
|
|
|
@DB.connection_context()
|
|
|
|
|
def accessible(cls, canvas_id, tenant_id):
|
|
|
|
|
from api.db.services.user_service import UserTenantService
|
2025-09-29 10:16:13 +08:00
|
|
|
e, c = UserCanvasService.get_by_canvas_id(canvas_id)
|
2025-08-08 18:31:51 +08:00
|
|
|
if not e:
|
|
|
|
|
return False
|
|
|
|
|
|
|
|
|
|
tids = [t.tenant_id for t in UserTenantService.query(user_id=tenant_id)]
|
2026-04-24 10:02:22 +08:00
|
|
|
if c["user_id"] == tenant_id:
|
|
|
|
|
return True
|
|
|
|
|
if c["user_id"] not in tids:
|
|
|
|
|
return False
|
|
|
|
|
if c["permission"] != TenantPermission.TEAM.value:
|
2025-08-08 18:31:51 +08:00
|
|
|
return False
|
|
|
|
|
return True
|
2025-07-30 19:41:09 +08:00
|
|
|
|
2026-03-13 16:31:17 +08:00
|
|
|
@classmethod
|
|
|
|
|
def get_agent_dsl_with_release(cls, agent_id, release_mode=False, tenant_id=None):
|
|
|
|
|
e, cvs = cls.get_by_id(agent_id)
|
|
|
|
|
if not e:
|
|
|
|
|
raise LookupError("Agent not found.")
|
|
|
|
|
|
|
|
|
|
if release_mode:
|
|
|
|
|
released_version = UserCanvasVersionService.get_latest_released(agent_id)
|
|
|
|
|
if not released_version:
|
|
|
|
|
raise PermissionError("No available published version")
|
|
|
|
|
dsl = released_version.dsl
|
|
|
|
|
else:
|
|
|
|
|
dsl = cvs.dsl
|
|
|
|
|
|
|
|
|
|
if not isinstance(dsl, str):
|
|
|
|
|
dsl = json.dumps(dsl, ensure_ascii=False)
|
|
|
|
|
|
|
|
|
|
return cvs, dsl
|
|
|
|
|
|
2025-08-22 12:04:15 +08:00
|
|
|
|
2025-11-20 14:31:12 +08:00
|
|
|
async def completion(tenant_id, agent_id, session_id=None, **kwargs):
|
2025-08-08 10:00:16 +08:00
|
|
|
query = kwargs.get("query", "") or kwargs.get("question", "")
|
2025-07-30 19:41:09 +08:00
|
|
|
files = kwargs.get("files", [])
|
|
|
|
|
inputs = kwargs.get("inputs", {})
|
|
|
|
|
user_id = kwargs.get("user_id", "")
|
2026-05-22 02:15:49 -05:00
|
|
|
chat_template_kwargs = kwargs.get("chat_template_kwargs")
|
2026-02-03 11:01:18 +08:00
|
|
|
custom_header = kwargs.get("custom_header", "")
|
2026-03-05 17:26:39 +08:00
|
|
|
release_mode = str(kwargs.get("release", "")).strip().lower()
|
2025-07-30 19:41:09 +08:00
|
|
|
|
|
|
|
|
if session_id:
|
fix: offload blocking DB/Redis calls to thread pool for high-concurrency support (#13825) (#13941)
### What problem does this PR solve?
Addresses event-loop blocking under high concurrency reported in #13825.
When multiple requests hit the API simultaneously, synchronous DB/Redis
calls block the async event loop, preventing Quart from handling other
requests and causing cascading 502/504 timeouts.
This PR wraps all remaining blocking DB/Redis calls in `canvas_app.py`,
`chat_api.py`, `session.py`, and `canvas_service.py` with `await
thread_pool_exec()`
- Offload all synchronous `Service.*`, `REDIS_CONN.*`, and
`APIToken.query` calls to the thread pool
- Convert sync endpoint handlers (`list_chats`, `get_chat`, `templates`,
`sessions`, etc.) to `async def`
- Convert sync helper functions (`_ensure_owned_chat`,
`_validate_llm_id`, `_validate_dataset_ids`, etc.) to async - no
duplicate sync/async pairs
- Wrap `CanvasReplicaService` Redis IO calls (`bootstrap`,
`replace_for_set`, `commit_after_run`)
- Use `asyncio.gather()` for concurrent file uploads and chat response
building
**Note:** This fixes the code-level event-loop blocking, which is a
prerequisite for handling concurrent requests. For the full "30
concurrent requests without 502/504" goal described in the issue, users
should also tune deployment config:
- `WS=4` or higher (HTTP worker processes, default 1)
- `MAX_CONCURRENT_CHATS=50` (default 10)
- `SANDBOX_EXECUTOR_MANAGER_POOL_SIZE` for workflow-heavy workloads
### Performance verification
Reviewer asked for a before-vs-after comparison
([comment](https://github.com/infiniflow/ragflow/pull/13941#issuecomment-4393667231)).
I built a self-contained microbenchmark that reproduces the exact
failure mode this PR targets: an async handler that performs blocking
DB/Redis-style calls (50 ms each, 3 per request, 30 concurrent requests)
is run twice — once with the pre-PR pattern (sync call directly inside
the async handler) and once with the post-PR pattern (`await
thread_pool_exec(...)`). The benchmark imports nothing from RAGFlow
except `thread_pool_exec` itself, so it is hermetic and reproducible
(`THREAD_POOL_MAX_WORKERS=128`, Python 3.13.12).
**Throughput — wall-clock for 30 concurrent requests (lower is better)**
| flavour | wall(s) | p50(s) | p95(s) | max(s) |
|---|---:|---:|---:|---:|
| before | 4.986 | 0.158 | 0.207 | 0.269 |
| after | 0.248 | 0.181 | 0.230 | 0.231 |
The pre-PR handler serializes the entire load on the event-loop thread,
so 30 × 3 × 50 ms ≈ 4.5 s shows up as the wall time. The post-PR handler
parallelizes the blocking work across the thread pool and finishes the
same load in 248 ms — a **~20× speedup** on this workload.
**Event-loop responsiveness — latency of an unrelated probe coroutine
while the 30 slow requests are running (lower is better)**
| flavour | samples | probe p50 (ms) | probe p95 (ms) | probe max (ms) |
|---|---:|---:|---:|---:|
| before | 1 | 5442.26 | 5442.26 | 5442.26 |
| after | 28 | 0.88 | 11.53 | 98.02 |
This is the metric that maps directly to "the API still answers other
requests while one is busy". A 5 ms-interval probe was scheduled while
the 30 slow handlers ran. With the pre-PR code the event loop was frozen
for the entire duration of the blocking work, so only one probe sample
was ever picked up and it waited **5,442 ms**. After the PR, 28 probe
samples landed with **p50 0.88 ms / p95 11.53 ms**, meaning unrelated
requests are no longer starved by the slow ones. That is the regression
mode behind the cascading 502/504s reported in #13825.
<details>
<summary>Raw benchmark output</summary>
```
config: 30 concurrent requests, 3 blocking calls of 50ms each per request, THREAD_POOL_MAX_WORKERS=128
=== Throughput (lower wall is better) ===
flavour wall(s) p50(s) p95(s) max(s)
before 4.986 0.158 0.207 0.269
after 0.248 0.181 0.230 0.231
=== Event-loop responsiveness (lower probe latency is better) ===
flavour samples probe p50(ms) probe p95(ms) probe max(ms)
before 1 5442.26 5442.26 5442.26
after 28 0.88 11.53 98.02
```
</details>
The benchmark script is included as a comment on the PR for
reproducibility.
### Type of change
- [x] Bug Fix (non-breaking change which fixes an issue)
- [x] Performance Improvement
Closes [#13825](https://github.com/infiniflow/ragflow/issues/13825)
---------
Co-authored-by: tmimmanuel <tmimmanuel@users.noreply.github.com>
Co-authored-by: Kevin Hu <kevinhu.sh@gmail.com>
2026-05-10 21:08:55 -10:00
|
|
|
e, conv = await thread_pool_exec(API4ConversationService.get_by_id, session_id)
|
2026-03-05 17:26:39 +08:00
|
|
|
if not e:
|
|
|
|
|
raise LookupError("Session not found!")
|
2025-07-30 19:41:09 +08:00
|
|
|
if not conv.message:
|
|
|
|
|
conv.message = []
|
2025-08-01 21:49:39 +08:00
|
|
|
if not isinstance(conv.dsl, str):
|
|
|
|
|
conv.dsl = json.dumps(conv.dsl, ensure_ascii=False)
|
2026-02-10 17:04:45 +08:00
|
|
|
canvas = Canvas(conv.dsl, tenant_id, agent_id, canvas_id=agent_id, custom_header=custom_header)
|
2025-07-30 19:41:09 +08:00
|
|
|
else:
|
fix: offload blocking DB/Redis calls to thread pool for high-concurrency support (#13825) (#13941)
### What problem does this PR solve?
Addresses event-loop blocking under high concurrency reported in #13825.
When multiple requests hit the API simultaneously, synchronous DB/Redis
calls block the async event loop, preventing Quart from handling other
requests and causing cascading 502/504 timeouts.
This PR wraps all remaining blocking DB/Redis calls in `canvas_app.py`,
`chat_api.py`, `session.py`, and `canvas_service.py` with `await
thread_pool_exec()`
- Offload all synchronous `Service.*`, `REDIS_CONN.*`, and
`APIToken.query` calls to the thread pool
- Convert sync endpoint handlers (`list_chats`, `get_chat`, `templates`,
`sessions`, etc.) to `async def`
- Convert sync helper functions (`_ensure_owned_chat`,
`_validate_llm_id`, `_validate_dataset_ids`, etc.) to async - no
duplicate sync/async pairs
- Wrap `CanvasReplicaService` Redis IO calls (`bootstrap`,
`replace_for_set`, `commit_after_run`)
- Use `asyncio.gather()` for concurrent file uploads and chat response
building
**Note:** This fixes the code-level event-loop blocking, which is a
prerequisite for handling concurrent requests. For the full "30
concurrent requests without 502/504" goal described in the issue, users
should also tune deployment config:
- `WS=4` or higher (HTTP worker processes, default 1)
- `MAX_CONCURRENT_CHATS=50` (default 10)
- `SANDBOX_EXECUTOR_MANAGER_POOL_SIZE` for workflow-heavy workloads
### Performance verification
Reviewer asked for a before-vs-after comparison
([comment](https://github.com/infiniflow/ragflow/pull/13941#issuecomment-4393667231)).
I built a self-contained microbenchmark that reproduces the exact
failure mode this PR targets: an async handler that performs blocking
DB/Redis-style calls (50 ms each, 3 per request, 30 concurrent requests)
is run twice — once with the pre-PR pattern (sync call directly inside
the async handler) and once with the post-PR pattern (`await
thread_pool_exec(...)`). The benchmark imports nothing from RAGFlow
except `thread_pool_exec` itself, so it is hermetic and reproducible
(`THREAD_POOL_MAX_WORKERS=128`, Python 3.13.12).
**Throughput — wall-clock for 30 concurrent requests (lower is better)**
| flavour | wall(s) | p50(s) | p95(s) | max(s) |
|---|---:|---:|---:|---:|
| before | 4.986 | 0.158 | 0.207 | 0.269 |
| after | 0.248 | 0.181 | 0.230 | 0.231 |
The pre-PR handler serializes the entire load on the event-loop thread,
so 30 × 3 × 50 ms ≈ 4.5 s shows up as the wall time. The post-PR handler
parallelizes the blocking work across the thread pool and finishes the
same load in 248 ms — a **~20× speedup** on this workload.
**Event-loop responsiveness — latency of an unrelated probe coroutine
while the 30 slow requests are running (lower is better)**
| flavour | samples | probe p50 (ms) | probe p95 (ms) | probe max (ms) |
|---|---:|---:|---:|---:|
| before | 1 | 5442.26 | 5442.26 | 5442.26 |
| after | 28 | 0.88 | 11.53 | 98.02 |
This is the metric that maps directly to "the API still answers other
requests while one is busy". A 5 ms-interval probe was scheduled while
the 30 slow handlers ran. With the pre-PR code the event loop was frozen
for the entire duration of the blocking work, so only one probe sample
was ever picked up and it waited **5,442 ms**. After the PR, 28 probe
samples landed with **p50 0.88 ms / p95 11.53 ms**, meaning unrelated
requests are no longer starved by the slow ones. That is the regression
mode behind the cascading 502/504s reported in #13825.
<details>
<summary>Raw benchmark output</summary>
```
config: 30 concurrent requests, 3 blocking calls of 50ms each per request, THREAD_POOL_MAX_WORKERS=128
=== Throughput (lower wall is better) ===
flavour wall(s) p50(s) p95(s) max(s)
before 4.986 0.158 0.207 0.269
after 0.248 0.181 0.230 0.231
=== Event-loop responsiveness (lower probe latency is better) ===
flavour samples probe p50(ms) probe p95(ms) probe max(ms)
before 1 5442.26 5442.26 5442.26
after 28 0.88 11.53 98.02
```
</details>
The benchmark script is included as a comment on the PR for
reproducibility.
### Type of change
- [x] Bug Fix (non-breaking change which fixes an issue)
- [x] Performance Improvement
Closes [#13825](https://github.com/infiniflow/ragflow/issues/13825)
---------
Co-authored-by: tmimmanuel <tmimmanuel@users.noreply.github.com>
Co-authored-by: Kevin Hu <kevinhu.sh@gmail.com>
2026-05-10 21:08:55 -10:00
|
|
|
cvs, dsl = await thread_pool_exec(UserCanvasService.get_agent_dsl_with_release, agent_id, release_mode=release_mode == "true", tenant_id=tenant_id)
|
2026-03-05 17:26:39 +08:00
|
|
|
|
2026-03-13 16:31:17 +08:00
|
|
|
session_id = get_uuid()
|
|
|
|
|
canvas = Canvas(dsl, tenant_id, agent_id, canvas_id=cvs.id, custom_header=custom_header)
|
2025-08-01 21:49:39 +08:00
|
|
|
canvas.reset()
|
2026-03-17 18:51:26 +08:00
|
|
|
# Get the version title based on release_mode
|
fix: offload blocking DB/Redis calls to thread pool for high-concurrency support (#13825) (#13941)
### What problem does this PR solve?
Addresses event-loop blocking under high concurrency reported in #13825.
When multiple requests hit the API simultaneously, synchronous DB/Redis
calls block the async event loop, preventing Quart from handling other
requests and causing cascading 502/504 timeouts.
This PR wraps all remaining blocking DB/Redis calls in `canvas_app.py`,
`chat_api.py`, `session.py`, and `canvas_service.py` with `await
thread_pool_exec()`
- Offload all synchronous `Service.*`, `REDIS_CONN.*`, and
`APIToken.query` calls to the thread pool
- Convert sync endpoint handlers (`list_chats`, `get_chat`, `templates`,
`sessions`, etc.) to `async def`
- Convert sync helper functions (`_ensure_owned_chat`,
`_validate_llm_id`, `_validate_dataset_ids`, etc.) to async - no
duplicate sync/async pairs
- Wrap `CanvasReplicaService` Redis IO calls (`bootstrap`,
`replace_for_set`, `commit_after_run`)
- Use `asyncio.gather()` for concurrent file uploads and chat response
building
**Note:** This fixes the code-level event-loop blocking, which is a
prerequisite for handling concurrent requests. For the full "30
concurrent requests without 502/504" goal described in the issue, users
should also tune deployment config:
- `WS=4` or higher (HTTP worker processes, default 1)
- `MAX_CONCURRENT_CHATS=50` (default 10)
- `SANDBOX_EXECUTOR_MANAGER_POOL_SIZE` for workflow-heavy workloads
### Performance verification
Reviewer asked for a before-vs-after comparison
([comment](https://github.com/infiniflow/ragflow/pull/13941#issuecomment-4393667231)).
I built a self-contained microbenchmark that reproduces the exact
failure mode this PR targets: an async handler that performs blocking
DB/Redis-style calls (50 ms each, 3 per request, 30 concurrent requests)
is run twice — once with the pre-PR pattern (sync call directly inside
the async handler) and once with the post-PR pattern (`await
thread_pool_exec(...)`). The benchmark imports nothing from RAGFlow
except `thread_pool_exec` itself, so it is hermetic and reproducible
(`THREAD_POOL_MAX_WORKERS=128`, Python 3.13.12).
**Throughput — wall-clock for 30 concurrent requests (lower is better)**
| flavour | wall(s) | p50(s) | p95(s) | max(s) |
|---|---:|---:|---:|---:|
| before | 4.986 | 0.158 | 0.207 | 0.269 |
| after | 0.248 | 0.181 | 0.230 | 0.231 |
The pre-PR handler serializes the entire load on the event-loop thread,
so 30 × 3 × 50 ms ≈ 4.5 s shows up as the wall time. The post-PR handler
parallelizes the blocking work across the thread pool and finishes the
same load in 248 ms — a **~20× speedup** on this workload.
**Event-loop responsiveness — latency of an unrelated probe coroutine
while the 30 slow requests are running (lower is better)**
| flavour | samples | probe p50 (ms) | probe p95 (ms) | probe max (ms) |
|---|---:|---:|---:|---:|
| before | 1 | 5442.26 | 5442.26 | 5442.26 |
| after | 28 | 0.88 | 11.53 | 98.02 |
This is the metric that maps directly to "the API still answers other
requests while one is busy". A 5 ms-interval probe was scheduled while
the 30 slow handlers ran. With the pre-PR code the event loop was frozen
for the entire duration of the blocking work, so only one probe sample
was ever picked up and it waited **5,442 ms**. After the PR, 28 probe
samples landed with **p50 0.88 ms / p95 11.53 ms**, meaning unrelated
requests are no longer starved by the slow ones. That is the regression
mode behind the cascading 502/504s reported in #13825.
<details>
<summary>Raw benchmark output</summary>
```
config: 30 concurrent requests, 3 blocking calls of 50ms each per request, THREAD_POOL_MAX_WORKERS=128
=== Throughput (lower wall is better) ===
flavour wall(s) p50(s) p95(s) max(s)
before 4.986 0.158 0.207 0.269
after 0.248 0.181 0.230 0.231
=== Event-loop responsiveness (lower probe latency is better) ===
flavour samples probe p50(ms) probe p95(ms) probe max(ms)
before 1 5442.26 5442.26 5442.26
after 28 0.88 11.53 98.02
```
</details>
The benchmark script is included as a comment on the PR for
reproducibility.
### Type of change
- [x] Bug Fix (non-breaking change which fixes an issue)
- [x] Performance Improvement
Closes [#13825](https://github.com/infiniflow/ragflow/issues/13825)
---------
Co-authored-by: tmimmanuel <tmimmanuel@users.noreply.github.com>
Co-authored-by: Kevin Hu <kevinhu.sh@gmail.com>
2026-05-10 21:08:55 -10:00
|
|
|
version_title = await thread_pool_exec(UserCanvasVersionService.get_latest_version_title, cvs.id, release_mode=release_mode == "true")
|
2026-03-17 18:51:26 +08:00
|
|
|
conv = {"id": session_id, "dialog_id": cvs.id, "user_id": user_id, "message": [], "source": "agent", "dsl": dsl, "reference": [], "version_title": version_title}
|
fix: offload blocking DB/Redis calls to thread pool for high-concurrency support (#13825) (#13941)
### What problem does this PR solve?
Addresses event-loop blocking under high concurrency reported in #13825.
When multiple requests hit the API simultaneously, synchronous DB/Redis
calls block the async event loop, preventing Quart from handling other
requests and causing cascading 502/504 timeouts.
This PR wraps all remaining blocking DB/Redis calls in `canvas_app.py`,
`chat_api.py`, `session.py`, and `canvas_service.py` with `await
thread_pool_exec()`
- Offload all synchronous `Service.*`, `REDIS_CONN.*`, and
`APIToken.query` calls to the thread pool
- Convert sync endpoint handlers (`list_chats`, `get_chat`, `templates`,
`sessions`, etc.) to `async def`
- Convert sync helper functions (`_ensure_owned_chat`,
`_validate_llm_id`, `_validate_dataset_ids`, etc.) to async - no
duplicate sync/async pairs
- Wrap `CanvasReplicaService` Redis IO calls (`bootstrap`,
`replace_for_set`, `commit_after_run`)
- Use `asyncio.gather()` for concurrent file uploads and chat response
building
**Note:** This fixes the code-level event-loop blocking, which is a
prerequisite for handling concurrent requests. For the full "30
concurrent requests without 502/504" goal described in the issue, users
should also tune deployment config:
- `WS=4` or higher (HTTP worker processes, default 1)
- `MAX_CONCURRENT_CHATS=50` (default 10)
- `SANDBOX_EXECUTOR_MANAGER_POOL_SIZE` for workflow-heavy workloads
### Performance verification
Reviewer asked for a before-vs-after comparison
([comment](https://github.com/infiniflow/ragflow/pull/13941#issuecomment-4393667231)).
I built a self-contained microbenchmark that reproduces the exact
failure mode this PR targets: an async handler that performs blocking
DB/Redis-style calls (50 ms each, 3 per request, 30 concurrent requests)
is run twice — once with the pre-PR pattern (sync call directly inside
the async handler) and once with the post-PR pattern (`await
thread_pool_exec(...)`). The benchmark imports nothing from RAGFlow
except `thread_pool_exec` itself, so it is hermetic and reproducible
(`THREAD_POOL_MAX_WORKERS=128`, Python 3.13.12).
**Throughput — wall-clock for 30 concurrent requests (lower is better)**
| flavour | wall(s) | p50(s) | p95(s) | max(s) |
|---|---:|---:|---:|---:|
| before | 4.986 | 0.158 | 0.207 | 0.269 |
| after | 0.248 | 0.181 | 0.230 | 0.231 |
The pre-PR handler serializes the entire load on the event-loop thread,
so 30 × 3 × 50 ms ≈ 4.5 s shows up as the wall time. The post-PR handler
parallelizes the blocking work across the thread pool and finishes the
same load in 248 ms — a **~20× speedup** on this workload.
**Event-loop responsiveness — latency of an unrelated probe coroutine
while the 30 slow requests are running (lower is better)**
| flavour | samples | probe p50 (ms) | probe p95 (ms) | probe max (ms) |
|---|---:|---:|---:|---:|
| before | 1 | 5442.26 | 5442.26 | 5442.26 |
| after | 28 | 0.88 | 11.53 | 98.02 |
This is the metric that maps directly to "the API still answers other
requests while one is busy". A 5 ms-interval probe was scheduled while
the 30 slow handlers ran. With the pre-PR code the event loop was frozen
for the entire duration of the blocking work, so only one probe sample
was ever picked up and it waited **5,442 ms**. After the PR, 28 probe
samples landed with **p50 0.88 ms / p95 11.53 ms**, meaning unrelated
requests are no longer starved by the slow ones. That is the regression
mode behind the cascading 502/504s reported in #13825.
<details>
<summary>Raw benchmark output</summary>
```
config: 30 concurrent requests, 3 blocking calls of 50ms each per request, THREAD_POOL_MAX_WORKERS=128
=== Throughput (lower wall is better) ===
flavour wall(s) p50(s) p95(s) max(s)
before 4.986 0.158 0.207 0.269
after 0.248 0.181 0.230 0.231
=== Event-loop responsiveness (lower probe latency is better) ===
flavour samples probe p50(ms) probe p95(ms) probe max(ms)
before 1 5442.26 5442.26 5442.26
after 28 0.88 11.53 98.02
```
</details>
The benchmark script is included as a comment on the PR for
reproducibility.
### Type of change
- [x] Bug Fix (non-breaking change which fixes an issue)
- [x] Performance Improvement
Closes [#13825](https://github.com/infiniflow/ragflow/issues/13825)
---------
Co-authored-by: tmimmanuel <tmimmanuel@users.noreply.github.com>
Co-authored-by: Kevin Hu <kevinhu.sh@gmail.com>
2026-05-10 21:08:55 -10:00
|
|
|
await thread_pool_exec(API4ConversationService.save, **conv)
|
2025-03-12 16:01:44 +07:00
|
|
|
conv = API4Conversation(**conv)
|
2024-12-09 12:38:04 +08:00
|
|
|
|
2025-07-30 19:41:09 +08:00
|
|
|
message_id = str(uuid4())
|
|
|
|
|
conv.message.append({
|
|
|
|
|
"role": "user",
|
|
|
|
|
"content": query,
|
2026-02-09 19:52:52 +08:00
|
|
|
"id": message_id,
|
|
|
|
|
"files": files
|
2025-07-30 19:41:09 +08:00
|
|
|
})
|
|
|
|
|
txt = ""
|
2026-05-22 02:15:49 -05:00
|
|
|
run_kwargs = {
|
|
|
|
|
"query": query,
|
|
|
|
|
"files": files,
|
|
|
|
|
"user_id": user_id,
|
|
|
|
|
"inputs": inputs,
|
|
|
|
|
}
|
|
|
|
|
if chat_template_kwargs is not None:
|
|
|
|
|
run_kwargs["chat_template_kwargs"] = chat_template_kwargs
|
|
|
|
|
|
|
|
|
|
async for ans in canvas.run(**run_kwargs):
|
2025-08-27 17:16:55 +08:00
|
|
|
ans["session_id"] = session_id
|
|
|
|
|
if ans["event"] == "message":
|
|
|
|
|
txt += ans["data"]["content"]
|
2025-11-20 10:11:28 +08:00
|
|
|
if ans["data"].get("start_to_think", False):
|
|
|
|
|
txt += "<think>"
|
|
|
|
|
elif ans["data"].get("end_to_think", False):
|
|
|
|
|
txt += "</think>"
|
2025-08-27 17:16:55 +08:00
|
|
|
yield "data:" + json.dumps(ans, ensure_ascii=False) + "\n\n"
|
2025-06-04 14:39:04 +08:00
|
|
|
|
2025-07-30 19:41:09 +08:00
|
|
|
conv.message.append({"role": "assistant", "content": txt, "created_at": time.time(), "id": message_id})
|
2025-08-27 17:16:55 +08:00
|
|
|
conv.reference = canvas.get_reference()
|
2025-07-30 19:41:09 +08:00
|
|
|
conv.errors = canvas.error
|
2025-08-08 17:05:55 +08:00
|
|
|
conv.dsl = str(canvas)
|
2025-08-05 09:49:47 +08:00
|
|
|
conv = conv.to_dict()
|
fix: offload blocking DB/Redis calls to thread pool for high-concurrency support (#13825) (#13941)
### What problem does this PR solve?
Addresses event-loop blocking under high concurrency reported in #13825.
When multiple requests hit the API simultaneously, synchronous DB/Redis
calls block the async event loop, preventing Quart from handling other
requests and causing cascading 502/504 timeouts.
This PR wraps all remaining blocking DB/Redis calls in `canvas_app.py`,
`chat_api.py`, `session.py`, and `canvas_service.py` with `await
thread_pool_exec()`
- Offload all synchronous `Service.*`, `REDIS_CONN.*`, and
`APIToken.query` calls to the thread pool
- Convert sync endpoint handlers (`list_chats`, `get_chat`, `templates`,
`sessions`, etc.) to `async def`
- Convert sync helper functions (`_ensure_owned_chat`,
`_validate_llm_id`, `_validate_dataset_ids`, etc.) to async - no
duplicate sync/async pairs
- Wrap `CanvasReplicaService` Redis IO calls (`bootstrap`,
`replace_for_set`, `commit_after_run`)
- Use `asyncio.gather()` for concurrent file uploads and chat response
building
**Note:** This fixes the code-level event-loop blocking, which is a
prerequisite for handling concurrent requests. For the full "30
concurrent requests without 502/504" goal described in the issue, users
should also tune deployment config:
- `WS=4` or higher (HTTP worker processes, default 1)
- `MAX_CONCURRENT_CHATS=50` (default 10)
- `SANDBOX_EXECUTOR_MANAGER_POOL_SIZE` for workflow-heavy workloads
### Performance verification
Reviewer asked for a before-vs-after comparison
([comment](https://github.com/infiniflow/ragflow/pull/13941#issuecomment-4393667231)).
I built a self-contained microbenchmark that reproduces the exact
failure mode this PR targets: an async handler that performs blocking
DB/Redis-style calls (50 ms each, 3 per request, 30 concurrent requests)
is run twice — once with the pre-PR pattern (sync call directly inside
the async handler) and once with the post-PR pattern (`await
thread_pool_exec(...)`). The benchmark imports nothing from RAGFlow
except `thread_pool_exec` itself, so it is hermetic and reproducible
(`THREAD_POOL_MAX_WORKERS=128`, Python 3.13.12).
**Throughput — wall-clock for 30 concurrent requests (lower is better)**
| flavour | wall(s) | p50(s) | p95(s) | max(s) |
|---|---:|---:|---:|---:|
| before | 4.986 | 0.158 | 0.207 | 0.269 |
| after | 0.248 | 0.181 | 0.230 | 0.231 |
The pre-PR handler serializes the entire load on the event-loop thread,
so 30 × 3 × 50 ms ≈ 4.5 s shows up as the wall time. The post-PR handler
parallelizes the blocking work across the thread pool and finishes the
same load in 248 ms — a **~20× speedup** on this workload.
**Event-loop responsiveness — latency of an unrelated probe coroutine
while the 30 slow requests are running (lower is better)**
| flavour | samples | probe p50 (ms) | probe p95 (ms) | probe max (ms) |
|---|---:|---:|---:|---:|
| before | 1 | 5442.26 | 5442.26 | 5442.26 |
| after | 28 | 0.88 | 11.53 | 98.02 |
This is the metric that maps directly to "the API still answers other
requests while one is busy". A 5 ms-interval probe was scheduled while
the 30 slow handlers ran. With the pre-PR code the event loop was frozen
for the entire duration of the blocking work, so only one probe sample
was ever picked up and it waited **5,442 ms**. After the PR, 28 probe
samples landed with **p50 0.88 ms / p95 11.53 ms**, meaning unrelated
requests are no longer starved by the slow ones. That is the regression
mode behind the cascading 502/504s reported in #13825.
<details>
<summary>Raw benchmark output</summary>
```
config: 30 concurrent requests, 3 blocking calls of 50ms each per request, THREAD_POOL_MAX_WORKERS=128
=== Throughput (lower wall is better) ===
flavour wall(s) p50(s) p95(s) max(s)
before 4.986 0.158 0.207 0.269
after 0.248 0.181 0.230 0.231
=== Event-loop responsiveness (lower probe latency is better) ===
flavour samples probe p50(ms) probe p95(ms) probe max(ms)
before 1 5442.26 5442.26 5442.26
after 28 0.88 11.53 98.02
```
</details>
The benchmark script is included as a comment on the PR for
reproducibility.
### Type of change
- [x] Bug Fix (non-breaking change which fixes an issue)
- [x] Performance Improvement
Closes [#13825](https://github.com/infiniflow/ragflow/issues/13825)
---------
Co-authored-by: tmimmanuel <tmimmanuel@users.noreply.github.com>
Co-authored-by: Kevin Hu <kevinhu.sh@gmail.com>
2026-05-10 21:08:55 -10:00
|
|
|
await thread_pool_exec(API4ConversationService.append_message, conv["id"], conv)
|
2024-12-09 12:38:04 +08:00
|
|
|
|
|
|
|
|
|
2025-11-20 14:31:12 +08:00
|
|
|
async def completion_openai(tenant_id, agent_id, question, session_id=None, stream=True, **kwargs):
|
2025-11-04 14:15:31 +08:00
|
|
|
tiktoken_encoder = tiktoken.get_encoding("cl100k_base")
|
|
|
|
|
prompt_tokens = len(tiktoken_encoder.encode(str(question)))
|
2025-08-05 17:47:25 +08:00
|
|
|
user_id = kwargs.get("user_id", "")
|
|
|
|
|
|
2025-04-03 15:51:37 +07:00
|
|
|
if stream:
|
2025-08-05 17:47:25 +08:00
|
|
|
completion_tokens = 0
|
2025-04-03 15:51:37 +07:00
|
|
|
try:
|
2025-11-20 14:31:12 +08:00
|
|
|
async for ans in completion(
|
2025-08-05 17:47:25 +08:00
|
|
|
tenant_id=tenant_id,
|
|
|
|
|
agent_id=agent_id,
|
|
|
|
|
session_id=session_id,
|
|
|
|
|
query=question,
|
|
|
|
|
user_id=user_id,
|
|
|
|
|
**kwargs
|
|
|
|
|
):
|
|
|
|
|
if isinstance(ans, str):
|
|
|
|
|
try:
|
|
|
|
|
ans = json.loads(ans[5:]) # remove "data:"
|
|
|
|
|
except Exception as e:
|
2025-11-04 14:15:31 +08:00
|
|
|
logging.exception(f"Agent OpenAI-Compatible completion_openai parse answer failed: {e}")
|
2025-08-05 17:47:25 +08:00
|
|
|
continue
|
2025-08-28 16:55:28 +08:00
|
|
|
if ans.get("event") not in ["message", "message_end"]:
|
2025-04-03 15:51:37 +07:00
|
|
|
continue
|
2025-08-28 16:55:28 +08:00
|
|
|
|
|
|
|
|
content_piece = ""
|
|
|
|
|
if ans["event"] == "message":
|
|
|
|
|
content_piece = ans["data"]["content"]
|
|
|
|
|
|
2025-11-04 14:15:31 +08:00
|
|
|
completion_tokens += len(tiktoken_encoder.encode(content_piece))
|
2025-08-05 17:47:25 +08:00
|
|
|
|
2025-08-28 16:55:28 +08:00
|
|
|
openai_data = get_data_openai(
|
2025-08-05 17:47:25 +08:00
|
|
|
id=session_id or str(uuid4()),
|
2025-04-03 15:51:37 +07:00
|
|
|
model=agent_id,
|
2025-08-05 17:47:25 +08:00
|
|
|
content=content_piece,
|
|
|
|
|
prompt_tokens=prompt_tokens,
|
2025-04-03 15:51:37 +07:00
|
|
|
completion_tokens=completion_tokens,
|
2025-08-05 17:47:25 +08:00
|
|
|
stream=True
|
2025-08-28 16:55:28 +08:00
|
|
|
)
|
|
|
|
|
|
|
|
|
|
if ans.get("data", {}).get("reference", None):
|
|
|
|
|
openai_data["choices"][0]["delta"]["reference"] = ans["data"]["reference"]
|
|
|
|
|
|
|
|
|
|
yield "data: " + json.dumps(openai_data, ensure_ascii=False) + "\n\n"
|
2025-08-05 17:47:25 +08:00
|
|
|
|
2025-04-03 15:51:37 +07:00
|
|
|
yield "data: [DONE]\n\n"
|
2025-08-05 17:47:25 +08:00
|
|
|
|
2025-04-03 15:51:37 +07:00
|
|
|
except Exception as e:
|
2025-08-28 16:55:28 +08:00
|
|
|
logging.exception(e)
|
2025-04-03 15:51:37 +07:00
|
|
|
yield "data: " + json.dumps(
|
|
|
|
|
get_data_openai(
|
2025-08-05 17:47:25 +08:00
|
|
|
id=session_id or str(uuid4()),
|
2025-04-03 15:51:37 +07:00
|
|
|
model=agent_id,
|
2025-08-05 17:47:25 +08:00
|
|
|
content=f"**ERROR**: {str(e)}",
|
2025-04-03 15:51:37 +07:00
|
|
|
finish_reason="stop",
|
2025-08-05 17:47:25 +08:00
|
|
|
prompt_tokens=prompt_tokens,
|
2025-11-04 14:15:31 +08:00
|
|
|
completion_tokens=len(tiktoken_encoder.encode(f"**ERROR**: {str(e)}")),
|
2025-08-05 17:47:25 +08:00
|
|
|
stream=True
|
2025-04-03 15:51:37 +07:00
|
|
|
),
|
|
|
|
|
ensure_ascii=False
|
|
|
|
|
) + "\n\n"
|
|
|
|
|
yield "data: [DONE]\n\n"
|
2025-08-05 17:47:25 +08:00
|
|
|
|
|
|
|
|
else:
|
2025-04-03 15:51:37 +07:00
|
|
|
try:
|
2025-08-05 17:47:25 +08:00
|
|
|
all_content = ""
|
2025-08-28 16:55:28 +08:00
|
|
|
reference = {}
|
2025-11-20 14:31:12 +08:00
|
|
|
async for ans in completion(
|
2025-08-05 17:47:25 +08:00
|
|
|
tenant_id=tenant_id,
|
|
|
|
|
agent_id=agent_id,
|
|
|
|
|
session_id=session_id,
|
|
|
|
|
query=question,
|
|
|
|
|
user_id=user_id,
|
|
|
|
|
**kwargs
|
|
|
|
|
):
|
|
|
|
|
if isinstance(ans, str):
|
|
|
|
|
ans = json.loads(ans[5:])
|
2025-08-28 16:55:28 +08:00
|
|
|
if ans.get("event") not in ["message", "message_end"]:
|
2025-04-03 15:51:37 +07:00
|
|
|
continue
|
2025-08-28 16:55:28 +08:00
|
|
|
|
|
|
|
|
if ans["event"] == "message":
|
|
|
|
|
all_content += ans["data"]["content"]
|
|
|
|
|
|
|
|
|
|
if ans.get("data", {}).get("reference", None):
|
|
|
|
|
reference.update(ans["data"]["reference"])
|
2025-08-05 17:47:25 +08:00
|
|
|
|
2025-11-04 14:15:31 +08:00
|
|
|
completion_tokens = len(tiktoken_encoder.encode(all_content))
|
2025-08-05 17:47:25 +08:00
|
|
|
|
2025-08-28 16:55:28 +08:00
|
|
|
openai_data = get_data_openai(
|
2025-08-05 17:47:25 +08:00
|
|
|
id=session_id or str(uuid4()),
|
2025-04-03 15:51:37 +07:00
|
|
|
model=agent_id,
|
|
|
|
|
prompt_tokens=prompt_tokens,
|
2025-08-05 17:47:25 +08:00
|
|
|
completion_tokens=completion_tokens,
|
|
|
|
|
content=all_content,
|
|
|
|
|
finish_reason="stop",
|
|
|
|
|
param=None
|
2025-04-03 15:51:37 +07:00
|
|
|
)
|
2025-08-05 17:47:25 +08:00
|
|
|
|
2025-08-28 16:55:28 +08:00
|
|
|
if reference:
|
|
|
|
|
openai_data["choices"][0]["message"]["reference"] = reference
|
|
|
|
|
|
|
|
|
|
yield openai_data
|
2025-04-03 15:51:37 +07:00
|
|
|
except Exception as e:
|
2025-08-28 16:55:28 +08:00
|
|
|
logging.exception(e)
|
2025-04-03 15:51:37 +07:00
|
|
|
yield get_data_openai(
|
2025-08-05 17:47:25 +08:00
|
|
|
id=session_id or str(uuid4()),
|
2025-04-03 15:51:37 +07:00
|
|
|
model=agent_id,
|
2025-08-05 17:47:25 +08:00
|
|
|
prompt_tokens=prompt_tokens,
|
2025-11-04 14:15:31 +08:00
|
|
|
completion_tokens=len(tiktoken_encoder.encode(f"**ERROR**: {str(e)}")),
|
2025-08-05 17:47:25 +08:00
|
|
|
content=f"**ERROR**: {str(e)}",
|
2025-04-03 15:51:37 +07:00
|
|
|
finish_reason="stop",
|
2025-08-05 17:47:25 +08:00
|
|
|
param=None
|
2025-04-03 15:51:37 +07:00
|
|
|
)
|