Repository navigation
Refa: unify REST API response envelope — replace get_json_result/get_… - #15796
enjoyandlove wants to merge 299 commits into
Conversation
…t. (infiniflow#15218) ### What problem does this PR solve? Fix: The prompt variable for the agent operator disappears after input. ### Type of change - [x] Bug Fix (non-breaking change which fixes an issue)
… loop nesting) (infiniflow#14761) ## Summary Fixes the confirmed asyncio anti-patterns from infiniflow#14755. Only the three verified bugs are addressed; patterns already correctly using `asyncio.new_event_loop()` in a fresh thread are left untouched. ### Changes **`api/apps/restful_apis/tenant_api.py` — fire-and-forget `send_invite_email`** `asyncio.create_task()` was called without storing the `Task` reference. CPython's GC can collect an unfinished task, silently cancelling it and swallowing exceptions. Fixed by storing the task in a module-level `_background_tasks: set[Task]` with a `done_callback` to discard it on completion — the standard Python idiom for safe background tasks. **`api/apps/restful_apis/agent_api.py` — fire-and-forget `background_run`** Same root cause in the webhook "Immediately" execution path. Same fix applied. **`rag/llm/chat_model.py` (`LocalLLM._stream_response`) — `asyncio.get_event_loop()` on running loop** `asyncio.get_event_loop()` returns Quart's running event loop when called from an async context. Calling `loop.run_until_complete()` on it raises `RuntimeError`. Replaced with `asyncio.new_event_loop()` so the generator uses a dedicated fresh loop, closed in a `finally` block. ## What was NOT changed - `llm_service._sync_from_async_stream` and `evaluation_service._sync_from_async_gen`: both already correctly use `asyncio.new_event_loop()` inside a fresh thread. - `llm_service._run_coroutine_sync`: only caller is `rag/app/resume.py` (sync context), so `thread.join()` is correct there. - `requests` in agent tools: sync methods dispatched through thread pools; httpx migration is a separate, larger refactor. ## Test plan - [ ] Invite a team member and confirm the email is sent with no task warnings in logs. - [ ] Trigger a webhook agent in "Immediately" mode; confirm canvas state is persisted after background run. - [ ] Verify `LocalLLM` (Jina backend) chat and streaming work end-to-end. Closes infiniflow#14755 --------- Co-authored-by: Zhichang Yu <[email protected]>
…orking infiniflow#15175 (infiniflow#15177) ### What problem does this PR solve? Fix [Bug]: Save parser configs in dataset configuration page is not working infiniflow#15175 ### Type of change - [x] Bug Fix (non-breaking change which fixes an issue)
### What problem does this PR solve? Closes infiniflow#15142. ZhipuAI lists `glm-ocr` as an OCR model, but the Go driver still returned `no such method` from `OCRFile`. This wires the advertised model to Z.AI's documented `layout_parsing` endpoint and returns the `md_results` Markdown output through the existing `OCRFileResponse.Text` field. This PR also adds focused tests for URL input, raw file-content base64 input, and validation errors. ### Type of change - [x] Bug Fix (non-breaking change which fixes an issue) - [ ] New Feature (non-breaking change which adds functionality) - [ ] Documentation Update - [ ] Refactoring - [ ] Performance Improvement - [ ] Other (please describe): ### Test - [x] `go test -vet=off ./internal/entity/models -run 'TestZhipuAIOCRFile'`
### What problem does this PR solve? Closes infiniflow#15167. The Baidu Go provider advertises OCR support through `paddleocr-vl-0.9b`, but `BaiduModel.OCRFile` dereferenced required inputs before validating them. Calling OCR with a missing API config, API key, or model name could panic instead of returning a normal error. This PR adds explicit input validation for those required values. ### Type of change - [x] Bug Fix (non-breaking change which fixes an issue) --------- Co-authored-by: Jin Hai <[email protected]>
### What problem does this PR solve? Add a Go driver for **FuturMix** (https://futurmix.ai/docs), one of the unchecked providers on the umbrella tracking issue infiniflow#14736. FuturMix is documented as an "OpenAI-compatible API" aggregator over Claude / GPT / Gemini / DeepSeek (~22 models per their `/models` page). Until this PR, a tenant who configured `futurmix` as a model provider in the Go layer fell through to the default branch of `internal/entity/models/factory.go` and got the dummy driver. --------- Co-authored-by: sxxtony <[email protected]> Co-authored-by: Jin Hai <[email protected]>
### What problem does this PR solve?
The Go DeepInfra driver returned a stub error for `Rerank()` even though
DeepInfra serves reranker models at `POST /v1/inference/{model}` with
`query`, `documents`, and a `scores[]` response.
### Type of change
- [x] New Feature (non-breaking change which adds functionality)
Co-authored-by: Cursor <[email protected]>
…ow#15201) ### What problem does this PR solve? Creating or updating an agent via `POST /api/v1/agents` and `PUT /api/v1/agents/{agent_id}` did not persist `canvas_type` because the handler `req` dict never assigned the field before `UserCanvasService.save` / `update_by_id`. ### Type of change - [x] Bug Fix (non-breaking change which fixes an issue) - [ ] New Feature (non-breaking change which adds functionality) - [ ] Documentation Update - [ ] Refactoring - [ ] Performance Improvement - [ ] Other (please describe): Co-authored-by: Cursor <[email protected]>
Fix: empty file with better message
### What problem does this PR solve? Fix: Fixed metadata issue - The dataset's built-in metadata is now active, but it appears to be disabled in the individual file configuration. ### Type of change - [x] Bug Fix (non-breaking change which fixes an issue)
## Summary Closes infiniflow#15165. Implements the AWS Bedrock model provider for the Go API server, tracked under infiniflow#14736. Adds Converse + Converse-Stream chat and foundation-model listing, with SigV4 signing over a hand-rolled `net/http` path that matches the established pattern in `internal/entity/models/` (no new direct `go.mod` deps). ## Linked tracker Tracked under infiniflow#14736 (Implement model providers of RAGFlow API server in Go). Closes infiniflow#15165.
## Summary - Wire the Go TokenHub provider through the model factory. - Harden TokenHub request handling for chat, streaming, embeddings, and model listing. - Add focused TokenHub unit coverage for factory wiring and provider behavior. ## Notes - Refs infiniflow#14736. - Follows up infiniflow#15159. Co-authored-by: Jin Hai <[email protected]>
### What problem does this PR solve? This PR adds HuaweiCloud provider integration in RAGFlow. Supported capabilities: - [x] Chat / Think Chat / Stream Chat / Stream Think Chat - [x] Embedding - [x] Rerank - [x] Model listing - [x] Provider connection checking Verified examples from the CLI: ``` check instance 'test' from 'HuaweiCloud'; chat with 'deepseek-v4-flash@test@HuaweiCloud' message 'hello'; think chat with 'deepseek-v4-flash@test@HuaweiCloud' message 'hello'; stream chat with 'deepseek-v4-flash@test@HuaweiCloud' message 'hello'; stream think chat with 'deepseek-v4-flash@test@HuaweiCloud' message 'hello'; embed text 'what is rag' 'who are you' with 'bge-m3@test@HuaweiCloud' dimension 1024; rerank query 'what is rag' document 'rag is retrieval augmented generation' 'rag need llm' 'famous rag project includes ragflow' with 'bge-reranker-v2-m3@test@HuaweiCloud' top 3; list supported models from 'HuaweiCloud' 'test'; LIST MODELS FROM 'HuaweiCloud' 'test'; ``` ### Type of change - [x] New Feature - [x] Provider integration
Closes infiniflow#15040. ModelScope was listed unchecked in the Go-rewrite tracker infiniflow#14736 and already had an llm_factories.json entry (tags: LLM) but no Go driver, so the new Go API server could not route ModelScope instances. The Python side has supported it through the OpenAI-compatible base at rag/llm/chat_model.py:618 (ModelScopeChat), which requires a user-supplied base URL and appends /v1. This adds: - internal/entity/models/modelscope.go: self-hosted OpenAI-compatible driver with chat (sync + SSE stream with idle-timeout cancellation), list_models, and check_connection. Auth header is optional, matching the xinference pattern, so deployments without auth and auth-enabled deployments both work. Base URL is normalized so users can configure either the root endpoint or the /v1 endpoint. - internal/entity/models/modelscope_test.go: 12 tests covering name, URL normalization, factory routing, chat happy path / auth header / reasoning_content extraction, stream happy path / stream=false rejection / idle cancellation, list_models + check_connection, missing-base-URL clear error, and the no-such-method sentinels. - conf/models/modelscope.json: shipped config (class: "local", url_suffix v1/chat/completions and v1/models). - internal/entity/models/factory.go: case "modelscope" → ModelScopeModel. - internal/service/llm.go: ModelScope added to the selfDeployed map alongside Ollama, Xinference, LocalAI, LM-Studio, GPUStack — the Python side requires user-supplied URL with no default, so the Go side classifies it the same way. Follow-on issues will add Embed and Rerank, in line with how Novita, NVIDIA, TogetherAI, and other providers landed method-by-method. --------- Co-authored-by: Jin Hai <[email protected]>
### What problem does this PR solve? implement provider `OrcaRouter` **The following functionalities are now supported:** **Cohere:** - [x] Chat / Think Chat / Stream Chat / Stream Think Chat - [x] Model listing - [x] TTS - [ ] Balance ### Type of change - [x] New Feature (non-breaking change which adds functionality) --------- Co-authored-by: Jin Hai <[email protected]>
…iflow#15248) ### What problem does this PR solve? - Update version tags in README files (including translations) from v0.25.5 to v0.25.6 - Modify Docker image references and documentation to reflect new version - Update version badges and image descriptions - Maintain consistency across all language variants of README files ### Type of change - [x] Documentation Update
### What problem does this PR solve? Initial draft: v0.25.6 release notes. ### Type of change - [x] Documentation Update
## Summary - add the xAI `models` URL suffix used by the existing Go `ListModels` implementation - return a clear error when the xAI models suffix is missing - add focused xAI model-listing and connection-check regression tests ## What changed - Added `url_suffix.models` to `conf/models/xai.json`. - Normalized the configured models suffix before building the request URL. - Covered config loading, successful model listing, upstream errors, API-key validation, missing suffix handling, and `CheckConnection` delegation. ## Why `XAIModel.ListModels` already builds requests from `URLSuffix.Models`, and `CheckConnection` delegates to that method. The bundled xAI config did not define that suffix, which left the model-listing path unable to call the provider `/models` endpoint from the existing provider config. ## Validation - `go test ./internal/entity/models -run TestXAI -count=1` - `go test ./internal/entity -count=1` - `git diff HEAD~1..HEAD --check` ## Notes - `go test ./internal/entity/models -count=1` currently fails in unchanged Astraflow coverage: `TestAstraflowEmbedReturnsNoSuchMethod` panics before reaching any xAI assertions. --------- Co-authored-by: Jin Hai <[email protected]>
## Summary - Add LongCat model-list support through the documented OpenAI-compatible models endpoint. ## What changed - Add the LongCat `models` URL suffix for `/openai/v1/models`. - Implement `ListModels` for the LongCat Go driver. - Delegate `CheckConnection` to the lightweight model-list request. - Add focused regression coverage for successful, malformed, oversized, and missing-key responses. ## Why LongCat documents a models endpoint under the OpenAI-compatible API surface, but the Go driver still returned `no such method` for model listing and connection checks. ## Validation - `go test ./internal/entity/models -run TestLongCat -count=1` - `go test -race ./internal/entity/models -run TestLongCat -count=1` - `go test ./internal/entity -count=1` - `git diff --check` ## Notes - Related to the broader Go model provider tracking in infiniflow#14736, but this PR only handles LongCat model listing. - `go test ./internal/entity/models -count=1` is currently blocked by an unrelated Astraflow test panic outside this LongCat change. --------- Co-authored-by: Jin Hai <[email protected]>
…w#15233) ## Summary - route hosted MinerU.Net and PaddleOCR.Net provider names to their existing Go drivers - add regression coverage for loading the hosted OCR provider configs through ProviderManager ## What changed - Added canonical provider-name aliases for the hosted OCR provider display names. - Covered both bundled configs with a focused provider-manager test. ## Why The hosted provider configs use display names with `.Net`, while model factory dispatch lowercases the provider name. Without aliases, those configs fall through to `DummyModel` instead of using the existing MinerU and PaddleOCR drivers. --------- Co-authored-by: Jin Hai <[email protected]>
### What problem does this PR solve? v0.25.6 release notes draft updated. ### Type of change - [x] Documentation Update
### What problem does this PR solve? Fix: The Creativity parameter of chat was not saved. ### Type of change - [x] Bug Fix (non-breaking change which fixes an issue)
## Summary - add the VolcEngine `models` URL suffix used by the existing Go `ListModels` implementation - return a clear error when the VolcEngine models suffix is missing - add focused VolcEngine model-listing regression tests ## What changed - Added `url_suffix.models` to `conf/models/volcengine.json`. - Normalized the configured models suffix before building the request URL. - Covered config loading, successful model listing, upstream errors, and missing suffix handling. ## Why `VolcEngine.ListModels` already builds requests from `URLSuffix.Models`, but the bundled VolcEngine config did not define that suffix. That left the model-listing path unable to call the documented `/models` endpoint from the existing provider config. Fixes infiniflow#14701 Co-authored-by: Jin Hai <[email protected]>
### What problem does this PR solve? This PR adds Qiniu provider integration for the Go model driver layer in RAGFlow. Supported capabilities: - [X] Chat - [X] Think Chat - [X] Stream Chat - [X] Stream Think Chat - [X] Model listing - [X] Provider configuration and factory registration Verified examples from the CLI: ``` login user '***' password '***'; ADD PROVIDER 'qiniu'; CREATE PROVIDER 'qiniu' INSTANCE 'test' KEY '***'; chat with 'deepseek/deepseek-v3.1-terminus-thinking@test@qiniu' message 'hello'; think chat with 'deepseek/deepseek-v3.1-terminus-thinking@test@qiniu' message 'hello'; stream chat with 'deepseek/deepseek-v3.1-terminus-thinking@test@qiniu' message 'hello, what are you'; stream think chat with 'deepseek/deepseek-v3.1-terminus-thinking@test@qiniu' message 'hello, what are you'; stream think chat with 'qwen3-max-2026-01-23@test@qiniu' message 'hello, what are you'; LIST MODELS FROM 'qiniu' 'test'; ``` ### Type of change - [X] New Feature - [X] Provider integration
### What problem does this PR solve? Closes infiniflow#15090. Adds GiteeAI support to the Go model-provider layer so GiteeAI chat models can be routed through the Go API server using the same OpenAI-compatible chat, streaming, model listing, and connection-check flow used by other SaaS providers. GiteeAI is implemented as a separate provider from the existing `gitee` provider. ### Type of change - [x] New Feature (non-breaking change which adds functionality) ## Summary - Added a GiteeAI Go model driver. - Added the GiteeAI provider catalog with default base URL `https://ai.gitee.com/v1`. - Registered `giteeai` in the model factory separately from `gitee`. - Added focused provider tests for sync chat, streaming chat, model listing, connection checks, base URL override, SSE parsing, `[DONE]` handling, and unsupported methods. ## What changed - Implemented `ChatWithMessages` for `POST /chat/completions`. - Implemented `ChatStreamlyWithSender` with SSE parsing, `delta` extraction, `finish_reason`, `[DONE]`, and `<think>` tag handling. - Implemented `ListModels` for `GET /models`. - Implemented `CheckConnection` by delegating to `ListModels`. - Returned standard `no such method` errors for unsupported embedding, rerank, image-to-text, ASR, and TTS paths. ## Tests ```bash go test -vet=off ./internal/entity/models -run 'TestGiteeAI' -count=1 go test -vet=off ./internal/entity -run 'Test.*Provider|Test.*Model' -count=1 ``` --------- Co-authored-by: Jin Hai <[email protected]>
### What problem does this PR solve? `ReplicateModel.Rerank` in `internal/entity/models/replicate.go` was a `"replicate, no such method"` stub. The chat path landed in infiniflow#14958 and the embed path in infiniflow#15073; rerank is the last major retrieval surface still missing on this provider. Until this PR, a tenant who selected a Replicate reranker model got the sentinel error on every rerank call. Co-authored-by: sxxtony <[email protected]> Co-authored-by: Jin Hai <[email protected]>
…ow#15773) ### What problem does this PR solve? Fix: Add a waiting status to the messages on the chat page. ### Type of change - [x] Bug Fix (non-breaking change which fixes an issue)
### What problem does this PR solve? Fix LM-Studio provider connection verification so embedding checks await the async wrapper correctly and log the full traceback on failures. ### Type of change - [x] Bug Fix (non-breaking change which fixes an issue)
Fix OpenRouter key JSONDecodeError
…5528) ## Summary - keep Moonshot chat calls in non-streaming mode and streaming calls in SSE mode - make Moonshot model listing and balance checks use bodyless GET requests - add focused Moonshot request/response regression tests
### What problem does this PR solve?
**Verified from CLI**
```
RAGFlow(user)> chat with 'mimo-v2.5@test@xiaomi' message 'who r u'
Answer: Hello! I'm MiMo-v2.5, a large language model developed by Xiaomi's LLM Core Team. You can think of me as a friendly AI assistant ready to help you answer questions, have conversations, or work on creative tasks. My context window can handle up to 1 million tokens, so we can dive into pretty long discussions or documents if you'd like. What can I help you with today?
Time: 3.831830
RAGFlow(user)> stream chat with 'mimo-v2.5@test@xiaomi' message 'who r u'
Answer: there! I'm MiMo-v2.5, an AI assistant created by the Xiaomi LLM Core Team. I'm here to chat, help out, answer questions, or just have a friendly conversation. Think of me as a helpful buddy with a pretty big memory (1 million tokens worth!). What can I do for you today?😊
Time: 2.421630
RAGFlow(user)> think chat with 'mimo-v2.5@test@xiaomi' message 'who r u'
Thinking: The user is asking a simple question about who I am. According to my system prompt, I should:
- Identify myself as **MiMo-v2.5**
- State that I was developed by the **Xiaomi LLM Core Team**
- Answer in first person and be warm and conversational
Answer: Hey there! 👋
I'm **MiMo**, an AI assistant created by the **Xiaomi LLM Core Team**. Think of me as a friendly chat buddy who's here to help you with all sorts of questions and tasks!
I love having conversations, answering questions, brainstorming ideas, and helping people figure things out. Whether you want to chat, need help with something specific, or just want to explore ideas together — I'm here for it! 😊
What can I help you with today?
Time: 6.651589
RAGFlow(user)> tts with 'mimo-v2.5-tts@test@xiaomi' text 'hello? show yourself' play format 'wav' param '{"voice": "Chloe"}'
SUCCESS
RAGFlow(user)> asr with 'mimo-v2.5-asr@test@xiaomi' audio './internal/test.wav' param '{"language": "zh"}'
+------------------------------------------------------------------------------------------------------------------------+
| text |
+------------------------------------------------------------------------------------------------------------------------+
| 1 The examination and testimony of the experts enabled the commission to conclude that five shots may have been fired. |
+------------------------------------------------------------------------------------------------------------------------+
```
### Type of change
- [x] New Feature (non-breaking change which adds functionality)
- [x] Refactoring
## Summary Fixes typoed model-provider URL suffix keys and adds strict nested decoding so future URL suffix config mistakes fail during provider loading instead of being silently ignored.
## Summary - keep MiniMax chat calls in non-streaming mode and streaming calls in SSE mode - make MiniMax model listing and connection checks use a bodyless GET /v1/models - add focused MiniMax request/response regression tests
## Summary Normalizes Qwen model-family names before reasoning extraction so provider-prefixed Qwen models use the existing `<think>...</think>` fallback.
Delete not supported model providers list
## What problem does this PR solve? Go test files are never compiled in CI — only production binaries via `go build`. This allowed a missing `"sort"` import in `metadata_filter_test.go` to be merged without detection. ## Type of change - [x] Bug Fix (non-breaking change which fixes an issue) - [x] New Feature (non-breaking change which adds functionality) ## Changes - Add `go test -count=1 ./internal/...` step after Go build in CI workflow - Fix missing `"sort"` import in `metadata_filter_test.go` (pre-existing compile error) 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 4.8 <[email protected]>
### What problem does this PR solve? Support model list for VolcEngine. ### Type of change - [x] New Feature (non-breaking change which adds functionality)
…e detection) (infiniflow#15489) ### What problem does this PR solve? `is_english()` in `rag/nlp/__init__.py` compiles a **single-character** regex class and `fullmatch`es it against each item: ```python pattern = re.compile(r"[`a-zA-Z0-9\s.,':;/\"?<>!\(\)\-]") # no quantifier ... eng = sum(1 for t in texts if pattern.fullmatch(t.strip())) ``` For a **string** argument the text is first split into single characters (`texts = list(texts)`), so each `fullmatch` sees one character and works. But for a **list** argument each item is a whole multi-character string, and `fullmatch` of a one-character pattern against a multi-character string always fails — so `is_english()` returns `False` for **any** list, regardless of content. ```python is_english("This is English") # True (ok) is_english(["The quick brown fox jumps.", "Hello world."]) # False (bug — should be True) is_english(["这是中文。"]) # False (right answer, wrong reason) ``` Many call sites pass lists and were therefore silently always-`False`, e.g.: - `rag/llm/chat_model.py:1088`, `rag/llm/cv_model.py:168,1155` — `is_english([ans])` when an answer is truncated at `max_tokens`, so an English reply gets the Chinese "······由于长度的原因,回答被截断了,要继续吗?" continuation suffix instead of the English one. - `rag/app/book.py` — `remove_contents_table(..., eng=is_english([...sections...]))`, so English books have their contents table stripped in Chinese mode. - `common/doc_store/es_conn_base.py:339`, `rag/utils/opensearch_conn.py:733` — `is_english(txt.split())` in highlight handling. - plus `rag/app/qa.py`, `rag/flow/parser/utils.py`, `common/doc_store/infinity_conn_base.py`. ### Fix Add a `+` quantifier so an all-English multi-character item matches: ```python pattern = re.compile(r"[`a-zA-Z0-9\s.,':;/\"?<>!\(\)\-]+") ``` The string path is unchanged (single characters still match) and non-English lists still return `False`. Adds `test/unit_test/rag/test_is_english.py`; the two list cases fail before this change and pass after. ### Type of change - [x] Bug Fix (non-breaking change which fixes an issue) Used the Claude CLI while working on this.
…infiniflow#15787) ## Problem `TestXiaomiNewModelWithCustomDefaultTransport` panics on Go 1.25: ``` panic: interface conversion: http.RoundTripper is models.roundTripperFunc, not *http.Transport ``` In Go 1.25, `http.DefaultTransport` is no longer `*http.Transport`, so the unchecked type assertion in `NewXiaomiModel` panics when the test replaces it with a `roundTripperFunc`. ## Fix Use a safe type assertion with fallback to a new `http.Transport`, matching the pattern already used in `modelscope.go`. ## Verification ```bash go test -run TestXiaomiNewModelWithCustomDefaultTransport ./internal/entity/models/... # PASS ``` Internal contributors only. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 4.8 <[email protected]>
### What problem does this PR solve? ``` RAGFlow(user)> list models; +---------------------------+------------+-------------+--------------------+---------------------------------------------+ | alias | max_tokens | model_types | name | thinking | +---------------------------+------------+-------------+--------------------+---------------------------------------------+ | | 1048576 | [chat] | deepseek-v4-flash | map[clear_thinking:true default_value:true] | | | 1048576 | [chat] | deepseek-v4-pro | map[clear_thinking:true default_value:true] | | | 1024000 | [chat] | minimax-m3 | map[clear_thinking:true default_value:true] | | | 64000 | [vision] | glm-4.5v | map[clear_thinking:true default_value:true] | | [baai/bge-m3] | 8192 | [embedding] | bge-m3 | | | [baai/bge-reranker-v2-m3] | 1024 | [rerank] | bge-reranker-v2-m3 | | | | | [tts] | step-audio-tts-3b | | | [qwen/qwen3-asr-1.7b] | | [asr] | qwen3-asr-1.7b | | | [paddleocr-vl-1.5] | | [ocr] | paddleocr-vl-0.9b | | +---------------------------+------------+-------------+--------------------+---------------------------------------------+ RAGFlow(user)> show model 'minimax-m3'; +--------------+---------------------------------------------+ | field | value | +--------------+---------------------------------------------+ | name | minimax-m3 | | max_tokens | 1024000 | | model_types | [chat] | | thinking | map[clear_thinking:true default_value:true] | | class | | | alias | | | ModelTypeMap | | +--------------+---------------------------------------------+ RAGFlow(user)> show model 'baai/bge-m3'; +--------------+---------------+ | field | value | +--------------+---------------+ | model_types | [embedding] | | thinking | | | class | | | alias | [baai/bge-m3] | | ModelTypeMap | | | name | bge-m3 | | max_tokens | 8192 | +--------------+---------------+ ``` --------- Signed-off-by: Jin Hai <[email protected]>
…data_error_result/build_error_result/construct_json_result with single get_result() across all restful_apis handlers
📝 WalkthroughWalkthroughThis PR systematically replaces fragmented REST API response helpers across 20+ handlers with a unified ChangesUnified REST API Response Envelope Refactor
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
Suggested reviewers
|
There was a problem hiding this comment.
Actionable comments posted: 9
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (11)
api/apps/restful_apis/chunk_api.py (1)
172-178:⚠️ Potential issue | 🟡 Minor | ⚡ Quick winUnreachable dead code: ownership check never executes.
Lines 174-176 check
if not doc, append tonot_found, andcontinueto the next iteration. The subsequent check at line 177if not doc:is unreachable and never executes. The error message "You don't own the document" suggests an intended ownership validation, but the logic is broken.While this is pre-existing code, the changed response helper on line 178 surfaces the issue. Consider removing the dead code or implementing the intended ownership check if needed.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@api/apps/restful_apis/chunk_api.py` around lines 172 - 178, The loop over doc_list contains a dead second `if not doc:` check after already continuing when doc is falsy; update the logic in the loop that uses DocumentService.query to either remove the unreachable second check or implement the intended ownership validation: after retrieving doc via DocumentService.query(id=id, kb_id=dataset_id) validate ownership (e.g., check doc.owner_id or a DocumentService.owns(doc, current_user) call) and call get_result(code=RetCode.DATA_ERROR, message=f"You don't own the document {id}.") when ownership fails, otherwise append missing ids to not_found and continue as appropriate; ensure you only have one branch handling a missing doc (append to not_found and continue) and a separate branch for an ownership failure that returns the DATA_ERROR.api/apps/restful_apis/agent_api.py (1)
612-624:⚠️ Potential issue | 🟠 Major | ⚡ Quick winExpose pagination via the envelope’s
totalfield.This returns
{"data": {"canvas": ..., "total": ...}, "total": null}, so clients migrated to the canonical{code, message, data, total}shape will miss pagination metadata on this endpoint. Passtotalas the fourth envelope field instead of burying it insidedata.Suggested fix
- return get_result(data={"canvas": canvas, "total": total}) + return get_result(data={"canvas": canvas}, total=total)🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@api/apps/restful_apis/agent_api.py` around lines 612 - 624, The endpoint currently embeds pagination metadata inside the data payload by returning get_result(data={"canvas": canvas, "total": total}); update the return to pass total as the envelope's fourth field instead (e.g., return get_result(data={"canvas": canvas}, total=total)) so that get_result produces the canonical {code, message, data, total} response; change the return site that calls get_result and leave UserCanvasService.get_by_tenant_ids unchanged.api/apps/restful_apis/bot_api.py (1)
275-283:⚠️ Potential issue | 🟠 Major | ⚡ Quick winDo not index into
get_result()here.
get_result()returns a response object, not a plain dict. On this exception path,error_result["code"]/error_result["message"]will raise and the stream will fail exactly when it is trying to report an error. Build a plain payload dict first, then serialize that into the SSE frame.Suggested fix
- error_result = get_result(code=RetCode.DATA_ERROR, message=str(e) or "Unknown error") + error_result = { + "code": RetCode.DATA_ERROR, + "message": str(e) or "Unknown error", + "data": None, + "total": None, + } yield "data:" + json.dumps( { "event": "message", "data": {"content": f"Error {error_result['code']}: {error_result['message']}\n\n"}, **error_result, },🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@api/apps/restful_apis/bot_api.py` around lines 275 - 283, The exception handling currently indexes into the object returned by get_result() (error_result["code"]/["message"]) which will raise because get_result() returns a response object; instead, call get_result(e.g., error_result = get_result(...)), build a plain dict payload by extracting the code and message from that response object (via its attributes or by converting it to a dict/new dict like {"code": resp.code, "message": resp.message, "data": ...}), then json.dumps that plain payload and yield the SSE frame; update the except block around get_result, error_result and the yield to use this plain payload rather than indexing the response object.api/apps/restful_apis/document_api.py (1)
1911-1911:⚠️ Potential issue | 🟠 Major | ⚡ Quick winMigrate remaining legacy helper to unified envelope.
Line 1911 still uses the deprecated
get_data_error_resulthelper, which is inconsistent with the PR objective to replace all legacy helpers withget_result. The rest of the function has been migrated (lines 1915, 1920), but this line was missed.🔧 Complete the migration
- return get_data_error_result(message="Document not found!") + return get_result(code=RetCode.DATA_ERROR, message="Document not found!")🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@api/apps/restful_apis/document_api.py` at line 1911, Replace the deprecated helper call get_data_error_result at the return on line 1911 with the unified envelope helper get_result, using the same failure semantics as the nearby migrated lines (pass success=False, an appropriate error message "Document not found!" and no data payload). Update the return to call get_result(...) so it matches the surrounding returned responses that were already migrated (see existing get_result usage on lines 1915 and 1920).api/apps/restful_apis/connector_api.py (2)
144-149:⚠️ Potential issue | 🟠 Major | ⚡ Quick winMove
totalout ofdatain the logs response.This branch still nests pagination metadata under
data["total"], which leaves the canonical envelope's top-leveltotalasnull. Clients migrated to the unified response contract will read the wrong field here.Suggested fix
- return get_result(data={"total": total, "logs": arr}) + return get_result(data={"logs": arr}, total=total)🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@api/apps/restful_apis/connector_api.py` around lines 144 - 149, The response currently nests pagination metadata by returning get_result(data={"total": total, "logs": arr}); change this to return the total as a top-level envelope field instead of inside data: after calling SyncLogsService.list_sync_tasks(connector_id, ... ) which yields arr and total, call get_result with data containing only {"logs": arr} and pass total as the separate/top-level parameter (i.e., use get_result(data={"logs": arr}, total=total) or equivalent) so that the canonical envelope's total is populated; update the usages of arr and total accordingly.
344-348:⚠️ Potential issue | 🟠 Major | ⚡ Quick winDon't print uploaded OAuth credentials.
credentialscan contain client secrets and refresh tokens. Printing it leaks sensitive material to stdout/log aggregation.Suggested fix
try: credentials = _load_credentials(raw_credentials) - print(credentials) except ValueError as exc: return get_result(code=RetCode.ARGUMENT_ERROR, message=str(exc))🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@api/apps/restful_apis/connector_api.py` around lines 344 - 348, The code prints sensitive OAuth data after calling _load_credentials; remove the print(credentials) to avoid leaking client secrets/refresh tokens and instead, if needed, log a non-sensitive confirmation (e.g., "credentials loaded" or user/credential ID) or validate silently; update the try/except around _load_credentials (and any callers of get_result/RetCode.ARGUMENT_ERROR) to ensure no sensitive fields are emitted to stdout or logs.api/apps/restful_apis/chat_api.py (2)
1077-1088:⚠️ Potential issue | 🟠 Major | ⚡ Quick winDelete the uploaded temp file on every failure path.
Line 1079 can return after
temp_audio_pathhas already been created and written, and the non-streaming branch only removes that file on success. A broken ASR configuration or transcription exception will leak each uploaded audio file to disk.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@api/apps/restful_apis/chat_api.py` around lines 1077 - 1088, The temp audio file (temp_audio_path) can be left on disk on error paths; ensure it is always deleted by moving file removal into a finally or guaranteed cleanup block around the ASR flow: after calling get_tenant_default_model_by_type and before any early return, wrap creation/use of LLMBundle and asr_mdl.transcription in a try/except/finally (or use try/finally) so that temp_audio_path is removed in the finally regardless of success or exceptions, and also delete the file before returning get_result in the outer exception handler; use LLMBundle, asr_mdl.transcription, stream_mode and temp_audio_path identifiers to locate where to add the cleanup and log failures to remove the file.
462-481:⚠️ Potential issue | 🟠 Major | ⚡ Quick winRecreate the authorized-owner set before this filter runs.
Line 464 subtracts
authorized_owner_ids, but this function never defines that set. Any/chats?owner_ids=...request now raisesNameErrorand returns 500 before the new authorization check can respond. The validated list should also drive the query, not the raw request values.Suggested fix
+ tenants = await thread_pool_exec(TenantService.get_joined_tenants_by_user_id, current_user.id) + authorized_owner_ids = {member["tenant_id"] for member in tenants} + authorized_owner_ids.add(current_user.id) + if owner_ids: requested_owner_ids = set(owner_ids) unauthorized_owner_ids = requested_owner_ids - authorized_owner_ids if unauthorized_owner_ids: logging.warning( @@ effective_owner_ids = list(requested_owner_ids) chats, total = await thread_pool_exec( DialogService.get_by_tenant_ids, - owner_ids, current_user.id, 0, 0, orderby, desc, keywords, **exact_filters, + effective_owner_ids, current_user.id, 0, 0, orderby, desc, keywords, **exact_filters, ) - chats = [chat for chat in chats if chat["tenant_id"] in owner_ids] + chats = [chat for chat in chats if chat["tenant_id"] in effective_owner_ids]🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@api/apps/restful_apis/chat_api.py` around lines 462 - 481, The code references authorized_owner_ids but never defines it, causing a NameError and using raw owner_ids in the DB query; fix by constructing the authorized_owner_ids set (e.g., from current_user's tenant/owner list or existing authorization helper) before the subtraction, compute effective_owner_ids = list(requested_owner_ids & authorized_owner_ids), and pass that effective_owner_ids into the DialogService.get_by_tenant_ids call via thread_pool_exec (and use it for the final filtering) instead of the original owner_ids; update variable names in the block around list_chats, unauthorized_owner_ids, effective_owner_ids, and the DialogService.get_by_tenant_ids invocation accordingly.api/apps/restful_apis/user_api.py (2)
634-638:⚠️ Potential issue | 🔴 Critical | ⚡ Quick winAuthorize
tenant_idbefore updating tenant model settings.
set_tenant_info()truststenant_idfrom the request and writes it straight through toTenantService.update_by_id(...). Any authenticated user can therefore submit another tenant’s ID and change that tenant’s model configuration.Suggested fix
async def set_tenant_info(): req = await get_request_json() try: tid = req.pop("tenant_id") + allowed_tenants = {tenant["id"] for tenant in TenantService.get_info_by(current_user.id)} + if tid not in allowed_tenants: + return get_result( + data=False, + code=RetCode.AUTHENTICATION_ERROR, + message="No authorization.", + ) TenantService.update_by_id(tid, req) return get_result(data=True) except Exception as e: return server_error_response(e)🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@api/apps/restful_apis/user_api.py` around lines 634 - 638, The handler currently trusts tenant_id from get_request_json and calls TenantService.update_by_id(tid, req) without checking permissions; update set_tenant_info to authorize the requested tid before updating by fetching the authenticated user/session (e.g., current_user or request context) and asserting they either belong to tid or have an admin/tenant-management permission, or call an existing auth helper (e.g., authorize_tenant_action or TenantPolicy.check_access) to validate access to TenantService.update_by_id; if authorization fails, return an appropriate error (403) and do not call TenantService.update_by_id.
104-108:⚠️ Potential issue | 🟠 Major | ⚡ Quick winStop leaking account existence across auth flows.
These branches still distinguish “email exists” from “credentials/OTP are wrong,” which makes
/auth/loginand the password-reset endpoints usable for account enumeration. Return the same generic failure for nonexistent and invalid-credential cases, and keep the detailed reason only in logs.Also applies to: 138-142, 656-657, 687-688, 758-759, 834-835
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@api/apps/restful_apis/user_api.py` around lines 104 - 108, The responses currently leak account existence by returning distinct messages like "Email: {email} is not registered!" (calls to get_result with RetCode.AUTHENTICATION_ERROR); change all branches (including the occurrences at the other ranges listed) to return a single generic failure message for both nonexistent and invalid-credential/OTP cases (e.g., "Invalid email or credentials") while moving the specific reason (e.g., "email not registered" or "invalid OTP") into a server-side log call; update each get_result invocation (and any matching error-return paths in the login/password-reset handlers) to use the generic message and add a logger.debug/logger.info entry with the detailed reason and email for auditing.api/apps/restful_apis/search_api.py (1)
109-122:⚠️ Potential issue | 🟠 Major | ⚡ Quick winFinish the
list_searches()migration.This block is still half on the old contract:
get_result()already has a top-leveltotal, so returningdata={"search_apps": ..., "total": total}produces an off-contract payload withdata.totalpopulated and envelopetotalleftnull. The dead fallback below is also unreachable and still referencesget_json_result, which will trip linting after the import cleanup.Suggested fix
search_apps, total = SearchService.get_by_tenant_ids( effective_owner_ids, current_user.id, page_number, items_per_page, orderby, desc, keywords ) - return get_result(data={"search_apps": search_apps, "total": total}) - if not owner_ids: - tenants = [] - search_apps, total = SearchService.get_by_tenant_ids(tenants, current_user.id, page_number, items_per_page, orderby, desc, keywords) - else: - search_apps, total = SearchService.get_by_tenant_ids(owner_ids, current_user.id, 0, 0, orderby, desc, keywords) - search_apps = [s for s in search_apps if s["tenant_id"] in owner_ids] - total = len(search_apps) - if page_number and items_per_page: - search_apps = search_apps[(page_number - 1) * items_per_page: page_number * items_per_page] - return get_json_result(data={"search_apps": search_apps, "total": total}) + return get_result(data={"search_apps": search_apps}, total=total)As per coding guidelines, Python changes should pass
ruff check, and this PR’s sharedget_result()contract definestotalas a top-level field.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@api/apps/restful_apis/search_api.py` around lines 109 - 122, The list_searches() endpoint currently returns get_result(data={"search_apps": ..., "total": total}) which violates the shared contract (total must be a top-level field) and contains unreachable legacy fallback that uses get_json_result; fix by returning get_result({"search_apps": search_apps}, total=total) (i.e. pass search_apps in data and total as the top-level total argument) and delete the dead fallback block that references get_json_result and owner_ids handling; ensure you locate the logic around SearchService.get_by_tenant_ids and remove any remaining get_json_result imports/usages to satisfy ruff.Source: Coding guidelines
🧹 Nitpick comments (5)
api/apps/restful_apis/dify_retrieval_api.py (1)
32-34: ⚡ Quick winClean up unused deprecated imports.
Line 34 imports
build_error_resultandget_json_result, which are deprecated helpers that are no longer used after this file's migration toget_result. Remove these unused imports for clarity.🧹 Cleanup diff
-from api.utils.api_utils import add_tenant_id_to_kwargs, build_error_result, get_request_json, get_json_result +from api.utils.api_utils import add_tenant_id_to_kwargs🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@api/apps/restful_apis/dify_retrieval_api.py` around lines 32 - 34, Remove the unused deprecated imports build_error_result and get_json_result from the import list in dify_retrieval_api.py; keep the currently used helpers (get_result, get_request_json, apikey_required, add_tenant_id_to_kwargs, login_required) and update the from-import to no longer reference build_error_result or get_json_result so there are no dead/deprecated symbols imported.api/apps/restful_apis/bot_api.py (1)
101-151: ⚡ Quick winAdd logs around this new SDK session-deletion flow.
This path deletes sessions, supports
delete_all, and returns partial-success/error aggregates, but it emits no request or outcome logs. That makes support and audit much harder once this token-based flow is live. As per coding guidelines,**/*.py: Add logging for new flows.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@api/apps/restful_apis/bot_api.py` around lines 101 - 151, Add structured logging to the delete_agent_session flow: log entry to delete_agent_session with tenant_id and agent_id and the incoming request payload (req); log whether delete_all was requested and the resolved ids/conv_list after check_duplicate_ids; log each session deletion attempt with session_id and outcome (success or specific error appended to errors), and increment success_count; finally log the aggregate outcome before each return (full success, partial success with errors/duplicate_messages, or full failure) including success_count and error lists. Use the same logger used elsewhere in this module and reference variables/function names delete_agent_session, req, ids, conv_list, unique_conv_ids, duplicate_messages, errors, success_count, and API4ConversationService calls so logs map clearly to code paths.Source: Coding guidelines
api/apps/restful_apis/document_api.py (2)
1207-1207: 💤 Low valueUse canonical parameter order for consistency.
The call
get_result(data=False, message=..., code=...)works but deviates from the canonical signatureget_result(code, message, data, total). For consistency across the codebase, placecodefirst, thenmessage, thendata.♻️ Suggested parameter order
- return get_result(data=False, message='Lack of "Document ID"', code=RetCode.ARGUMENT_ERROR) + return get_result(code=RetCode.ARGUMENT_ERROR, message='Lack of "Document ID"', data=False)🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@api/apps/restful_apis/document_api.py` at line 1207, Call get_result using the canonical parameter order (code, message, data, total) instead of positional mix; change the current call that uses get_result(data=False, message=..., code=RetCode.ARGUMENT_ERROR) to pass RetCode.ARGUMENT_ERROR first, the message second, and the data boolean third (e.g., get_result(RetCode.ARGUMENT_ERROR, 'Lack of "Document ID"', False)), leaving total omitted if not needed; update the call site of get_result in this block to follow that ordering.
1897-1897: 💤 Low valueUse canonical parameter order for consistency.
Similar to line 1207, this call uses
get_result(data=..., message=..., code=...)instead of the canonicalget_result(code, message, data, total). For consistency, placecodefirst.♻️ Suggested parameter order
- return get_result(data=result, message="Partial failure", code=RetCode.SERVER_ERROR) + return get_result(code=RetCode.SERVER_ERROR, message="Partial failure", data=result)🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@api/apps/restful_apis/document_api.py` at line 1897, The call to get_result currently uses keyword args (get_result(data=result, message="Partial failure", code=RetCode.SERVER_ERROR)); change it to the canonical positional order used elsewhere: call get_result(RetCode.SERVER_ERROR, "Partial failure", result, total) — or omit the total argument if none is available — so that parameters are (code, message, data, total) and match other uses of get_result.api/utils/api_utils.py (1)
253-272: ⚡ Quick winAdd sanitized logging to the new auth flows.
These decorators introduce several new reject/fallback branches, but none of them log which branch failed. That will make production auth failures harder to trace. Log the reason and branch, but never the token value. As per coding guidelines,
**/*.py: Add logging for new flows.Also applies to: 289-349
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@api/utils/api_utils.py` around lines 253 - 272, The apikey_required decorator lacks logging for its reject branches; add sanitized package-level logging calls (e.g., using the module logger) inside each failure branch in apikey_required (missing Authorization header, malformed Authorization parts, and APIToken.query miss) to record the failure reason/branch and requester context (e.g., remote IP or header presence) but never log the token value itself; update the branches around request.headers.get("Authorization"), parts length check, and the APIToken.query(token=token) check to call logger.warn/info with a concise message referencing the branch (e.g., "auth: missing header", "auth: malformed header", "auth: invalid api-key") and include non-sensitive identifiers like request.remote_addr or tenant_id when available, leaving the rest of the logic (inspect.iscoroutinefunction(func) and get_result(...)) unchanged.Source: Coding guidelines
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@api/apps/restful_apis/bot_api.py`:
- Around line 226-237: The route decorator is applied to a short precheck stub
(chatbots_inputs) leaving the real handler (another chatbots_inputs defined
below with `@login_required/`@add_tenant_id_to_kwargs) unregistered; fix by
removing the duplicate stub or by moving the
`@manager.route`("/chatbots/<dialog_id>/info", methods=["GET"]) decorator to the
actual business logic function (the one decorated with
`@login_required`(auth_types=AUTH_BETA) and `@add_tenant_id_to_kwargs`) and ensure
the function name is unique/unambiguous (or merge the precheck into that
handler) so the routed endpoint executes the real handler rather than falling
through.
- Around line 64-98: The create_agent_session function is not registered as a
Quart route; add the same route decorator pattern used by the companion delete
handler so Quart will dispatch requests to it (e.g. decorate
create_agent_session with the appropriate `@app.route` or blueprint.route
specifying the path and HTTP method used by the SDK, and keep the existing
`@token_required` above it), ensuring the route path includes tenant_id and
agent_id parameters to match the function signature.
- Around line 39-43: The module uses UserCanvasVersionService and APIToken but
never imports them, causing NameError on the new SDK/token branches; add
explicit imports for UserCanvasVersionService and APIToken from the SDK modules
that define them (place them alongside the existing imports at the top of
bot_api.py), and while editing tidy up duplicate imports (remove the duplicated
thread_pool_exec/get_result imports) so all referenced symbols are properly
imported and no duplicate lines remain.
In `@api/apps/restful_apis/connector_api.py`:
- Around line 578-580: Check Redis via
REDIS_CONN.get(_web_state_cache_key(flow_id, "box")) before calling json.loads
so you don't attempt to decode a missing/expired value; if the value is
missing/invalid return the OAuth popup flow using _render_web_oauth_popup(...)
(keeping the popup/postMessage flow) instead of returning get_result(...).
Update the code around cache_payload, _web_state_cache_key(flow_id, "box"), and
the error branch to validate the raw redis value, handle JSON decode errors
gracefully, and call _render_web_oauth_popup on failure.
In `@api/apps/restful_apis/langfuse_api.py`:
- Around line 75-76: The ApiError except block currently returns
get_result(message=...) which omits an error code and therefore defaults to
RetCode.SUCCESS; update the ApiError handler in langfuse_api.py (the except
langfuse.api.core.api_error.ApiError as api_err block) to pass
code=RetCode.DATA_ERROR alongside the message so the response correctly signals
failure (follow the pattern used elsewhere in the file where get_result(...) is
called with code=RetCode.DATA_ERROR).
In `@api/apps/restful_apis/memory_api.py`:
- Line 54: Several handlers in memory_api.py call get_result(..., message=True)
which passes a boolean instead of the expected string; locate all occurrences of
the get_result call that include message=True and replace the boolean with a
descriptive string (e.g., "success", "memory created", "memory updated", "memory
deleted") or remove the message argument to fall back to the default "success".
Update each call site referencing get_result so the message parameter is a
string (search for the literal message=True) and keep the rest of the return
unchanged to preserve payload structure.
In `@api/apps/restful_apis/openai_api.py`:
- Around line 254-259: The length check runs before normalizing so messages can
be None and cause a TypeError; call _normalize_openai_messages(messages) first,
check normalize_error and return get_result(code=RetCode.DATA_ERROR,
message=normalize_error) if present, then validate the normalized messages
(e.g., ensure it's a list and length >= 1) before using len(messages); reference
the variables/functions messages, _normalize_openai_messages, get_result and
RetCode.DATA_ERROR when making the change.
In `@api/utils/api_utils.py`:
- Around line 258-265: Multiple auth failure paths exist: apikey_required() uses
get_result(...RetCode.FORBIDDEN) while token_required() and
server_error_response() use different codes, causing inconsistent body codes and
HTTP 200 responses; unify them by routing all auth errors (missing Authorization
header, malformed header, invalid APIToken from APIToken.query, and exceptions
raised in token_required()) to the same unauthorized response helper (use the
server_error_response()/or a new unauthorized_response that emits
RetCode.UNAUTHORIZED and sets the proper HTTP status), update apikey_required(),
token_required(), and any direct get_result(...) calls in these branches to call
that unified helper instead of returning get_result(...) with FORBIDDEN so every
auth failure returns the same body code and HTTP status.
- Around line 253-266: The decorators apikey_required and token_required
reference missing names (APIToken, os, WerkzeugUnauthorized) causing NameError
at runtime; import the required dependencies at top of api/utils/api_utils.py
(e.g., import os, from werkzeug.exceptions import Unauthorized as
WerkzeugUnauthorized, and the APIToken model or its module) so APIToken, os, and
WerkzeugUnauthorized are defined before apikey_required and token_required are
used; ensure the imports are added alongside other auth-related imports and run
tests to confirm the unified auth error responses behave as intended.
---
Outside diff comments:
In `@api/apps/restful_apis/agent_api.py`:
- Around line 612-624: The endpoint currently embeds pagination metadata inside
the data payload by returning get_result(data={"canvas": canvas, "total":
total}); update the return to pass total as the envelope's fourth field instead
(e.g., return get_result(data={"canvas": canvas}, total=total)) so that
get_result produces the canonical {code, message, data, total} response; change
the return site that calls get_result and leave
UserCanvasService.get_by_tenant_ids unchanged.
In `@api/apps/restful_apis/bot_api.py`:
- Around line 275-283: The exception handling currently indexes into the object
returned by get_result() (error_result["code"]/["message"]) which will raise
because get_result() returns a response object; instead, call get_result(e.g.,
error_result = get_result(...)), build a plain dict payload by extracting the
code and message from that response object (via its attributes or by converting
it to a dict/new dict like {"code": resp.code, "message": resp.message, "data":
...}), then json.dumps that plain payload and yield the SSE frame; update the
except block around get_result, error_result and the yield to use this plain
payload rather than indexing the response object.
In `@api/apps/restful_apis/chat_api.py`:
- Around line 1077-1088: The temp audio file (temp_audio_path) can be left on
disk on error paths; ensure it is always deleted by moving file removal into a
finally or guaranteed cleanup block around the ASR flow: after calling
get_tenant_default_model_by_type and before any early return, wrap creation/use
of LLMBundle and asr_mdl.transcription in a try/except/finally (or use
try/finally) so that temp_audio_path is removed in the finally regardless of
success or exceptions, and also delete the file before returning get_result in
the outer exception handler; use LLMBundle, asr_mdl.transcription, stream_mode
and temp_audio_path identifiers to locate where to add the cleanup and log
failures to remove the file.
- Around line 462-481: The code references authorized_owner_ids but never
defines it, causing a NameError and using raw owner_ids in the DB query; fix by
constructing the authorized_owner_ids set (e.g., from current_user's
tenant/owner list or existing authorization helper) before the subtraction,
compute effective_owner_ids = list(requested_owner_ids & authorized_owner_ids),
and pass that effective_owner_ids into the DialogService.get_by_tenant_ids call
via thread_pool_exec (and use it for the final filtering) instead of the
original owner_ids; update variable names in the block around list_chats,
unauthorized_owner_ids, effective_owner_ids, and the
DialogService.get_by_tenant_ids invocation accordingly.
In `@api/apps/restful_apis/chunk_api.py`:
- Around line 172-178: The loop over doc_list contains a dead second `if not
doc:` check after already continuing when doc is falsy; update the logic in the
loop that uses DocumentService.query to either remove the unreachable second
check or implement the intended ownership validation: after retrieving doc via
DocumentService.query(id=id, kb_id=dataset_id) validate ownership (e.g., check
doc.owner_id or a DocumentService.owns(doc, current_user) call) and call
get_result(code=RetCode.DATA_ERROR, message=f"You don't own the document {id}.")
when ownership fails, otherwise append missing ids to not_found and continue as
appropriate; ensure you only have one branch handling a missing doc (append to
not_found and continue) and a separate branch for an ownership failure that
returns the DATA_ERROR.
In `@api/apps/restful_apis/connector_api.py`:
- Around line 144-149: The response currently nests pagination metadata by
returning get_result(data={"total": total, "logs": arr}); change this to return
the total as a top-level envelope field instead of inside data: after calling
SyncLogsService.list_sync_tasks(connector_id, ... ) which yields arr and total,
call get_result with data containing only {"logs": arr} and pass total as the
separate/top-level parameter (i.e., use get_result(data={"logs": arr},
total=total) or equivalent) so that the canonical envelope's total is populated;
update the usages of arr and total accordingly.
- Around line 344-348: The code prints sensitive OAuth data after calling
_load_credentials; remove the print(credentials) to avoid leaking client
secrets/refresh tokens and instead, if needed, log a non-sensitive confirmation
(e.g., "credentials loaded" or user/credential ID) or validate silently; update
the try/except around _load_credentials (and any callers of
get_result/RetCode.ARGUMENT_ERROR) to ensure no sensitive fields are emitted to
stdout or logs.
In `@api/apps/restful_apis/document_api.py`:
- Line 1911: Replace the deprecated helper call get_data_error_result at the
return on line 1911 with the unified envelope helper get_result, using the same
failure semantics as the nearby migrated lines (pass success=False, an
appropriate error message "Document not found!" and no data payload). Update the
return to call get_result(...) so it matches the surrounding returned responses
that were already migrated (see existing get_result usage on lines 1915 and
1920).
In `@api/apps/restful_apis/search_api.py`:
- Around line 109-122: The list_searches() endpoint currently returns
get_result(data={"search_apps": ..., "total": total}) which violates the shared
contract (total must be a top-level field) and contains unreachable legacy
fallback that uses get_json_result; fix by returning get_result({"search_apps":
search_apps}, total=total) (i.e. pass search_apps in data and total as the
top-level total argument) and delete the dead fallback block that references
get_json_result and owner_ids handling; ensure you locate the logic around
SearchService.get_by_tenant_ids and remove any remaining get_json_result
imports/usages to satisfy ruff.
In `@api/apps/restful_apis/user_api.py`:
- Around line 634-638: The handler currently trusts tenant_id from
get_request_json and calls TenantService.update_by_id(tid, req) without checking
permissions; update set_tenant_info to authorize the requested tid before
updating by fetching the authenticated user/session (e.g., current_user or
request context) and asserting they either belong to tid or have an
admin/tenant-management permission, or call an existing auth helper (e.g.,
authorize_tenant_action or TenantPolicy.check_access) to validate access to
TenantService.update_by_id; if authorization fails, return an appropriate error
(403) and do not call TenantService.update_by_id.
- Around line 104-108: The responses currently leak account existence by
returning distinct messages like "Email: {email} is not registered!" (calls to
get_result with RetCode.AUTHENTICATION_ERROR); change all branches (including
the occurrences at the other ranges listed) to return a single generic failure
message for both nonexistent and invalid-credential/OTP cases (e.g., "Invalid
email or credentials") while moving the specific reason (e.g., "email not
registered" or "invalid OTP") into a server-side log call; update each
get_result invocation (and any matching error-return paths in the
login/password-reset handlers) to use the generic message and add a
logger.debug/logger.info entry with the detailed reason and email for auditing.
---
Nitpick comments:
In `@api/apps/restful_apis/bot_api.py`:
- Around line 101-151: Add structured logging to the delete_agent_session flow:
log entry to delete_agent_session with tenant_id and agent_id and the incoming
request payload (req); log whether delete_all was requested and the resolved
ids/conv_list after check_duplicate_ids; log each session deletion attempt with
session_id and outcome (success or specific error appended to errors), and
increment success_count; finally log the aggregate outcome before each return
(full success, partial success with errors/duplicate_messages, or full failure)
including success_count and error lists. Use the same logger used elsewhere in
this module and reference variables/function names delete_agent_session, req,
ids, conv_list, unique_conv_ids, duplicate_messages, errors, success_count, and
API4ConversationService calls so logs map clearly to code paths.
In `@api/apps/restful_apis/dify_retrieval_api.py`:
- Around line 32-34: Remove the unused deprecated imports build_error_result and
get_json_result from the import list in dify_retrieval_api.py; keep the
currently used helpers (get_result, get_request_json, apikey_required,
add_tenant_id_to_kwargs, login_required) and update the from-import to no longer
reference build_error_result or get_json_result so there are no dead/deprecated
symbols imported.
In `@api/apps/restful_apis/document_api.py`:
- Line 1207: Call get_result using the canonical parameter order (code, message,
data, total) instead of positional mix; change the current call that uses
get_result(data=False, message=..., code=RetCode.ARGUMENT_ERROR) to pass
RetCode.ARGUMENT_ERROR first, the message second, and the data boolean third
(e.g., get_result(RetCode.ARGUMENT_ERROR, 'Lack of "Document ID"', False)),
leaving total omitted if not needed; update the call site of get_result in this
block to follow that ordering.
- Line 1897: The call to get_result currently uses keyword args
(get_result(data=result, message="Partial failure", code=RetCode.SERVER_ERROR));
change it to the canonical positional order used elsewhere: call
get_result(RetCode.SERVER_ERROR, "Partial failure", result, total) — or omit the
total argument if none is available — so that parameters are (code, message,
data, total) and match other uses of get_result.
In `@api/utils/api_utils.py`:
- Around line 253-272: The apikey_required decorator lacks logging for its
reject branches; add sanitized package-level logging calls (e.g., using the
module logger) inside each failure branch in apikey_required (missing
Authorization header, malformed Authorization parts, and APIToken.query miss) to
record the failure reason/branch and requester context (e.g., remote IP or
header presence) but never log the token value itself; update the branches
around request.headers.get("Authorization"), parts length check, and the
APIToken.query(token=token) check to call logger.warn/info with a concise
message referencing the branch (e.g., "auth: missing header", "auth: malformed
header", "auth: invalid api-key") and include non-sensitive identifiers like
request.remote_addr or tenant_id when available, leaving the rest of the logic
(inspect.iscoroutinefunction(func) and get_result(...)) unchanged.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 596c60c4-a532-4f39-8b94-d266005a57b0
📒 Files selected for processing (25)
api/apps/restful_apis/agent_api.pyapi/apps/restful_apis/bot_api.pyapi/apps/restful_apis/chat_api.pyapi/apps/restful_apis/chunk_api.pyapi/apps/restful_apis/connector_api.pyapi/apps/restful_apis/dataset_api.pyapi/apps/restful_apis/dify_retrieval_api.pyapi/apps/restful_apis/document_api.pyapi/apps/restful_apis/file2document_api.pyapi/apps/restful_apis/file_api.pyapi/apps/restful_apis/langfuse_api.pyapi/apps/restful_apis/mcp_api.pyapi/apps/restful_apis/memory_api.pyapi/apps/restful_apis/models_api.pyapi/apps/restful_apis/openai_api.pyapi/apps/restful_apis/plugin_api.pyapi/apps/restful_apis/provider_api.pyapi/apps/restful_apis/search_api.pyapi/apps/restful_apis/stats_api.pyapi/apps/restful_apis/system_api.pyapi/apps/restful_apis/task_api.pyapi/apps/restful_apis/tenant_api.pyapi/apps/restful_apis/user_api.pyapi/utils/api_utils.pytest/testcases/restful_api/test_datasets.py
|
Hi, @yingfeng |
|
@enjoyandlove would you please resolve the conflicts? |
Closes #15794
What problem does this PR solve?
api/apps/restful_apis/used five structurally incompatible response helpers (get_json_result,get_data_error_result,get_error_data_result,build_error_result,construct_json_result) producing different envelope shapes — some missingmessage, some missingdata, and pagination returned undertotal_datasetsin some routes. API clients, SDK consumers, and the Go mirror handlers could not rely on a stable response contract.This PR converges all 23 handler files onto a single canonical envelope emitted on every response:
{ "code": 0, "message": "success", "data": null, "total": null }Files changed:
api/utils/api_utils.py—get_result()rewritten as the sole builder;total_datasetskey renamed tototal; old helpers kept as thin deprecated shimsapi/apps/restful_apis/(23 files) — all call-sites migrated toget_result(); import lines cleanedtest/testcases/restful_api/test_datasets.py— two assertions updated fromtotal_datasets→totalType of change