Repository navigation
Conversation
### What problem does this PR solve? implement rerank, asr, tts for TogetherAI ### Type of change - [x] New Feature (non-breaking change which adds functionality)
### What problem does this PR solve? Updated v0.25.5 release notes. ### Type of change - [x] Documentation Update
### What problem does this PR solve? Fixed a docusaurus deployment issue. ### Type of change - [x] Documentation Update
…lename when ext is omitted (infiniflow#15052)" (infiniflow#15138) Reverts infiniflow#15053
### What problem does this PR solve? guard missing task language ### Type of change - [x] Bug Fix (non-breaking change which fixes an issue)
### What problem does this PR solve? Closes infiniflow#15089. Adds PPIO support to the Go model-provider layer so PPIO instances can be routed through the Go API server with the same OpenAI-compatible chat, streaming, model listing, and connection-check flow used by other SaaS providers. ### Type of change - [x] New Feature (non-breaking change which adds functionality) ## Summary - Added a PPIO Go model driver. - Added the PPIO provider catalog and default OpenAI-compatible API URL. - Registered PPIO in the model factory. - Added focused provider and provider-manager tests. ## What changed - Implemented chat completions, SSE streaming, ListModels, and CheckConnection for PPIO. - Covered request shape, stream termination, reasoning fallback, model listing, custom base URLs, safe transport setup, unsupported methods, and provider config loading. - Kept the provider catalog aligned with the existing RAGFlow PPIO factory model set. - Cleaned up pre-existing Go model package validation blockers so the scoped provider tests can run normally with vet enabled. ## Why The existing Python/provider catalog path includes PPIO, but the Go model-provider layer did not have a PPIO driver, so the Go API server could not instantiate or use PPIO as requested in infiniflow#15089.
### What problem does this PR solve? This PR implements ASR and TTS support for the ZhipuAI Go driver. The ZhipuAI model config already advertises `glm-asr-2512` as an ASR model, but the Go driver returned `zhipu, no such method` from `TranscribeAudio`. This adds the documented audio transcription endpoint suffix and sends multipart transcription requests with `model`, `stream=false`, and `file` fields. Per maintainer review, this also adds the ZhipuAI TTS endpoint suffix and implements `AudioSpeech` / `AudioSpeechWithSender` for `glm-tts`. Closes infiniflow#15133 ### Type of change - [x] Bug Fix (non-breaking change which fixes an issue) - [x] New Feature (non-breaking change which adds functionality)
…low#14868) ### What problem does this PR solve? Closes infiniflow#14865 `download_img` in `common/misc_utils.py` is used for OAuth avatar URLs. The previous implementation called `async_request` from `common.http_client`, which followed redirects without re-validating each hop and did not apply the same SSRF protections as this path needs. That made it possible to reach non-public or disallowed targets (for example via redirects or unsafe URLs) when fetching avatars. This change replaces that flow with an explicit, bounded fetch: each URL (including every redirect target) is checked with `common.ssrf_guard.assert_url_is_safe`, DNS is pinned with `pin_dns_global`, `httpx` streams the body with `follow_redirects=False` and a manual redirect loop (capped by `RAGFLOW_OAUTH_AVATAR_MAX_REDIRECTS`), and total response size is capped (`RAGFLOW_OAUTH_AVATAR_MAX_BYTES`). Timeouts, proxy, and user agent align with `HTTP_CLIENT_*` env vars without importing `http_client`, so lightweight tests stay simple. Unit tests cover empty/None URLs, loopback, cloud metadata-style addresses, and disallowed schemes so SSRF regressions are caught early. ### Type of change - [x] Bug Fix (non-breaking change which fixes an issue) --------- Co-authored-by: Kevin Hu <[email protected]>
… and retrieval (infiniflow#4310) (infiniflow#14208) Closes infiniflow#4310 ### What problem does this PR solve? Issue infiniflow#4310 requests practical examples for the RAGFlow SDK and HTTP API to help developers get started faster. The existing `example/sdk/` folder only contains `dataset_example.py`. This PR fills the remaining gaps by adding examples for three key API areas not yet covered in `main` or by other open PRs (infiniflow#13904, infiniflow#13284): - **Chunk management** — add, list, update, delete, and retrieve chunks within a dataset - **Chat assistant** — create a chat assistant, open a session, send messages (streaming and non-streaming), and clean up - **Retrieval** — perform semantic retrieval across one or multiple datasets ### Type of change - [x] Documentation Update - [x] New Feature (non-breaking change which adds functionality)
### What problem does this PR solve? 1. Enhance retry and timeout, and adjust the default timeout 2. NER: spacy do not batch chunks 3. extract _has_cancel_and_exit 4. enhance log messages ### Type of change - [x] New Feature (non-breaking change which adds functionality) - [x] Refactoring
### What problem does this PR solve? Refactor: enahnce CI ### Type of change - [x] Refactoring
…iniflow#14792) Closes infiniflow#14789 ### What problem does this PR solve? User API endpoints (`login`, `user_profile`, `user_add`, `forget_reset_password`) were returning full user objects via `to_json()` / `to_dict()`, which included sensitive fields like `password` and `access_token` in the response body. This leaks credentials to the client. This PR adds a `to_safe_dict()` method on the `User` model that strips sensitive fields (`password`, `access_token`) and replaces all affected call sites to use it. ### Type of change - [x] Bug Fix (non-breaking change which fixes an issue)
…flow#14542) ### What problem does this PR solve? The agent API currently does not pass chat_template_kwargs to the underlying LLM call path, so clients cannot control template-level model behavior (such as thinking-mode toggles) when invoking /agents/chat/completion. This PR adds passthrough support for chat_template_kwargs across agent execution flows (session and non-session, streaming and non-streaming) by propagating it through canvas runtime state and into LLM invocation kwargs. This addresses the feature gap raised in [Issue infiniflow#14182](infiniflow#14182). Closes infiniflow#14182 ### Type of change - [x] New Feature (non-breaking change which adds functionality)
### What problem does this PR solve? Fixes infiniflow#15066 OpenRouter now exposes an official speech-to-text endpoint at `POST /api/v1/audio/transcriptions`, but the Go model driver still returned `openrouter, no such method` from `TranscribeAudio`. This left OpenRouter ASR models unavailable through the Go API server even though the provider already has OpenRouter audio support for TTS. Related provider-tracking context: infiniflow#14736 ### Type of change - [x] New Feature (non-breaking change which adds functionality) Co-authored-by: Jin Hai <[email protected]>
…#13487) ## Summary Implements the TODO in `evaluation_service.py`: **Track token usage** in evaluation results. ## Changes - **Import** `num_tokens_from_string` from `common.token_utils` - **Prompt tokens**: Use the full prompt returned by `async_chat` when available (includes system prompt + knowledge base + query), otherwise fall back to the question token count - **Completion tokens**: Count tokens in the generated answer - **Storage**: Store `token_usage` as `{prompt_tokens, completion_tokens, total_tokens}` in each `EvaluationResult` instead of `None` ## Why The evaluation pipeline previously saved `token_usage: None` for every result. This change allows downstream consumers (e.g. evaluation dashboards, cost tracking) to see approximate token usage per test case using the same tokenizer (tiktoken cl100k_base) used elsewhere in RAGFlow. ## Testing - No new tests added; existing evaluation flow unchanged - Token counting uses existing `num_tokens_from_string` utility --------- Co-authored-by: kiannidev <[email protected]>
## Summary - Adds a `TokenPony` Go driver so the new API server can route TokenPony chat instances, matching the existing Python `TokenPonyChat` (`rag/llm/chat_model.py:1210`). Follows the same SaaS-driver shape used for Astraflow, Avian, Novita, TogetherAI, Replicate, DeepInfra, Upstage, and LongCat. Closes infiniflow#15086 --------- Co-authored-by: Jin Hai <[email protected]>
### What problem does this PR solve? move agent attachment download api to the correct route and update frontend callers ### Type of change - [x] Bug Fix (non-breaking change which fixes an issue) ### Notes - Move the attachment download endpoint from document routes to agent routes. - Update frontend download callers to use the agent attachment endpoint. - Reuse the shared file response header helper instead of duplicating it in `agent_api.py`.
### What problem does this PR solve? Add model_type into llm_setting ### Type of change - [x] Bug Fix (non-breaking change which fixes an issue)
### What problem does this PR solve? Closes infiniflow#15088. Adds Groq support to the Go model-provider layer so Groq instances can be routed through the Go API server with the same OpenAI-compatible chat, streaming, model listing, and connection-check flow used by other SaaS providers. ### Type of change - [x] New Feature (non-breaking change which adds functionality) ## Summary - Added a Groq Go model driver. - Added the Groq provider catalog and default OpenAI-compatible API URL. - Registered Groq in the model factory. - Added focused provider tests. ## What changed - Implemented chat completions, SSE streaming, ListModels, and CheckConnection for Groq. - Covered request shape, stream termination, reasoning fallback, model listing, custom base URLs, safe transport setup, and unsupported methods. - Kept the provider catalog scoped to current Groq chat-capable model IDs. - Cleaned up pre-existing Go model package validation blockers so the package can be tested normally with vet enabled. ## Why The existing Python/provider catalog path includes Groq, but the Go model-provider layer did not have a Groq driver, so the Go API server could not instantiate or use Groq as requested in infiniflow#15088. ## Notes The model package now validates without disabling vet. --------- Co-authored-by: Jin Hai <[email protected]>
### What problem does this PR solve? Fix search vector_similarity_weight ### Type of change - [x] Bug Fix (non-breaking change which fixes an issue)
Refactor: Move API files
### What problem does this PR solve? How to ingest messages from your Discord server. ### Type of change - [x] Documentation Update
### What problem does this PR solve?
implement embed, rerank, tts for AstraFlow
**Verify from CLI**
```
# Astraflow
RAGFlow(user)> tts with 'IndexTeam/IndexTTS-2@test3@astraflow' text 'hello? show yourself' play format 'wav' param '{"voice": "jack_cheng"}'
SUCCESS
RAGFlow(user)> rerank query 'what is rag' document 'rag is retrieval augment generation' 'rag need llm' 'famous rag project includes ragflow' with 'bge-reranker-v2-m3@test3@astraflow' top 3;
+-------+---------------------+
| index | relevance_score |
+-------+---------------------+
| 0 | 0.9837390184402466 |
| 2 | 0.06322699040174484 |
| 1 | 0.04663187265396118 |
+-------+---------------------+
RAGFlow(user)> embed text 'walkerwhat' 'jumperwho' with 'text-embedding-3-large@test3@astraflow' dimension 16
+-----------+-------+
| dimension | index |
+-----------+-------+
| 3072 | 0 |
| 3072 | 1 |
+-----------+-------+
# Xinference
```
### Type of change
- [x] New Feature (non-breaking change which adds functionality)
- [x] Refactoring
### What problem does this PR solve?
Go: implement reasoning_chat, TTS, ASR for Groq
**Verify from CLI**
```
RAGFlow(user)> think chat with 'qwen/qwen3-32b@test@groq' message 'who r u'
Thinking: Okay, the user asked, who r u. I need to determine what the user is asking. They may be asking about my identity. I should introduce my name and basic functions. The user might want to know what I can do, so I should list some common use cases, such as answering questions, creating writing, coding, and expressing opinions. The user may be curious about how they can interact with me, so they can be advised to ask any questions or provide instructions. Keep your answers conversational, avoid overly technical terms, keep answers concise, and encourage further interaction. Check if there's any ambiguity in the answer and make sure it's accurate and meets the user's needs. Also consider if there are other aspects the user may be interested in, such as my training data or performance. But since the question is basic, I'll focus on the essentials first and invite the user to ask more. In summary, respond to the user's questions by introducing yourself, your functions, and encouraging further interaction.
Answer: Hello! I'm Qwen. I am a large-scale language model developed by Tongyi Lab, designed to assist you in various ways, such as answering questions, creating text, logical reasoning, programming, and more. I aim to provide clear, accurate, and helpful information and support. How can I assist you today? Feel free to ask any questions or give me tasks! 😊
Time: 2.199908
RAGFlow(user)> stream think chat with 'openai/gpt-oss-20b@test@groq' message 'who r u'
Thinking: to respond politely.
Answer: ’m ChatGPT—an AI language model created by OpenAI. I’m here to answer questions, offer explanations, and help with a wide range of topics. How can I assist you today?
RAGFlow(user)> tts with 'canopylabs/orpheus-arabic-saudi@test@groq' text 'hello? show yourself' play format 'wav' param '{"voice": "fahad"}'
SUCCESS
RAGFlow(user)> asr with 'whisper-large-v3-turbo@test@groq' audio './internal/test.wav' param '{"language": "en"}'
+----------------------------------------------------------------------------------------------------------------------+
| text |
+----------------------------------------------------------------------------------------------------------------------+
| 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)
…niflow#15155) ### What problem does this PR solve? Fix: /openai/<chat_id>/chat/completions not aware of session_id ### Type of change - [x] Bug Fix (non-breaking change which fixes an issue)
### What problem does this PR solve? Closes infiniflow#15102. OpenAI's Go provider config advertises `whisper-1` as ASR and `tts-1` as TTS, but the Go driver returned `openai, no such method` for both audio paths and did not define `url_suffix.asr` / `url_suffix.tts`. This PR: - adds OpenAI audio URL suffixes for `audio/transcriptions` and `audio/speech` - implements non-streaming `TranscribeAudio` using multipart form uploads - implements non-streaming `AudioSpeech` using the OpenAI speech JSON request shape - keeps streaming TTS explicitly unsupported instead of sending binary audio through the text SSE sender - adds focused tests for config coverage, ASR/TTS request shape, required TTS voice validation, and unsupported streaming TTS ### Type of change - [x] Bug Fix (non-breaking change which fixes an issue) --------- Co-authored-by: Jin Hai <[email protected]>
…iniflow#15192) ## Summary - Brings the French locale (`web/src/locales/fr.ts`) to full parity with the English reference - Adds ~1400 missing translation keys across **all sections**: `common`, `chat`, `header`, `login`, `admin`, `setting`, `flow`, `knowledgeDetails`, `knowledgeConfiguration`, `memory`, `skills`, `skillSearch`, `chunk`, `mcp`, `fileManager`, `search`, `dataflowParser`, `datasetOverview`, `deleteModal`, `empty`, `explore`, `memories`, `pagination`, `language`, `knowledgeList` - All strings containing French apostrophes use double-quote delimiters (prevents JS syntax errors) ## Test plan - [ ] `npx esbuild src/locales/fr.ts --bundle=false` — no errors - [ ] `npx eslint src/locales/fr.ts` — no errors - [ ] Switch UI language to French and verify key sections render correctly (chat, knowledge base, admin panel, agent flow) 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Sonnet 4.6 <[email protected]>
### What problem does this PR solve? Fix /chat/completions not aware of conversation_id ### Type of change - [x] Bug Fix (non-breaking change which fixes an issue)
## Summary - Adds a `Hunyuan` Go driver so the new API server can route Tencent Hunyuan chat instances (registered in `conf/llm_factories.json:3830` as `Tencent Hunyuan`). Follows the same SaaS-driver shape used for Astraflow, Avian, Novita, TogetherAI, Replicate, DeepInfra, Upstage, and LongCat. Closes infiniflow#15087 --------- Co-authored-by: Jin Hai <[email protected]>
### What problem does this PR solve? Go: implement provider: PaddleOCR_Local **Verified from CLI** ``` RAGFlow(user)> ocr with 'PaddleOCR-VL@test@paddleocr_local' file './internal/test1.jpg' +----------------------+ | text | +----------------------+ | ## Parallel to these | +----------------------+ ``` ### Type of change - [X] Bug Fix (non-breaking change which fixes an issue) - [X] New Feature (non-breaking change which adds functionality) - [X] Refactoring
…ry_rewrite, community) (infiniflow#15690) ## Summary `KGSearchRetrieval` composes entity search, type search, relation search, N-hop analysis, score fusion, LLM-based query\_rewrite, and community reports into a single synthetic chunk for KG-enhanced retrieval. ### Components | Component | Source | Status | |-----------|--------|--------| | Entity/relation/community search | Direct `DocEngine.Search` calls | ✅ | | N-hop analysis + score fusion | `common.AnalyzeNHopPaths` / `DoubleHitBoost` / `FuseRelationScores` | ✅ infiniflow#15666 | | Query rewrite prompt + parser | `common.BuildQueryRewritePrompt` / `ParseQueryRewriteResponse` | ✅ infiniflow#15669 | | Token budget | `common.BuildKGContent` + `NumTokensFromString` | ✅ infiniflow#15666 | | LLM query rewrite integration | `queryRewrite` function with fallback | ✅ | ### Testing 11 tests (pure function + mock engine): ``` === RUN TestKgEntityFromChunk_Basic --- PASS === RUN TestKgEntityFromChunk_ScoreFallback --- PASS === RUN TestKgEntityFromChunk_MissingFields --- PASS === RUN TestKgRelationFromChunk_Basic --- PASS === RUN TestKgRelationFromChunk_MissingFrom --- PASS === RUN TestSearchKGTypeSamples_Success --- PASS === RUN TestSearchKGTypeSamples_Empty --- PASS === RUN TestKGSearchRetrieval_Basic --- PASS === RUN TestKGSearchRetrieval_NoEntities --- PASS === RUN TestQueryRewrite_Fallback --- PASS === RUN TestQueryRewrite_EmptyQuestion --- PASS ``` --------- Co-authored-by: Claude Opus 4.8 <[email protected]>
…ically pop up (infiniflow#15685) ### What problem does this PR solve? Fix: When adding a chat in the main interface, a warning will automatically pop up (even if embedding and LLM model have already been configured). ### Type of change - [x] Bug Fix (non-breaking change which fixes an issue)
…imension (infiniflow#15631) ## Summary This PR improves the Go CLI in two areas: 1. It adds batch model management support, allowing multiple models to be added or removed in a single command. 2. It makes the `dimension` argument optional for the `embed text` command. These changes keep the existing single-model and explicit-dimension behaviors compatible while making the CLI more convenient for common workflows. ## What Changed ### 1. Batch model add/remove support The CLI now supports operating on multiple model names provided in a single quoted string. Supported commands include: ``` add model 'x1 x2 x3' to provider 'vllm' instance 'test' with tokens 1024 chat think vision, token 2048 chat, token 1024 think vision; drop model 'x1 x2 x3' from 'vllm' 'test'; remove model 'x1 x2 x3' from 'vllm' 'test'; ``` For add model, each config segment after with is matched to the corresponding model name by position. Example mapping: - x1 -> tokens 1024, chat + vision, thinking=true - x2 -> tokens 2048, chat - x3 -> tokens 1024, vision, thinking=true The existing single-model syntax remains supported. ### 2. Optional embedding dimension Previously, the Go CLI required dimension to be explicitly provided for embed text. Before: embed text 'what is rag' 'who are you' with 'model@test@provider' dimension 8192; Now both forms are supported: embed text 'what is rag' 'who are you' with 'model@test@provider' dimension 8192; embed text 'what is rag' 'who are you' with 'model@test@provider'; When omitted, the CLI leaves dimension unset and relies on provider/backend behavior. ## Tests Added parser tests covering: - Multiple models with multiple config segments - Model type deduplication - Model/config count mismatch - Drop/remove multiple models - Optional embedding dimension parsing
## Summary Dify-compatible retrieval API for external knowledge base integration. ## Changes - **New handler**: DifyRetrievalHandler with POST/GET /api/v1/dify/retrieval - **Health check**: GET /api/v1/dify/retrieval/health - **Full pipeline**: KB validation -> permission check -> embedding -> metadata filter -> chunk retrieval -> child chunk aggregation -> optional KG search -> response assembly - **12 tests** covering all paths (success, errors, metadata filter, KG mode) - **Testability**: Handler dependencies defined as interfaces (KBServiceIface, ModelServiceIface, etc.) ## Files | File | Type | |------|------| | internal/handler/dify_retrieval_handler.go | New — handler + interfaces | | internal/handler/dify_retrieval_handler_test.go | New — 12 tests | | internal/router/router.go | Modified — route registration | | cmd/server_main.go | Modified — handler wiring | | internal/service/kg/pipeline.go | Modified — SetChatModel/SetEmbModel | | internal/service/kg/retrieval.go | New — helper functions | | internal/service/kg/scoring.go | Moved from service package | | internal/service/kg/search.go | New — KG search functions | | internal/service/kg/types.go | New — type definitions | --------- Co-authored-by: Claude Opus 4.8 <[email protected]>
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughAdds end-to-end persistent chunk-level metadata: API accepts/returns ChangesChunk Metadata Support End-to-End
Sequence Diagram (high-level flow): sequenceDiagram
participant Client
participant ChunkAPI
participant InfinityConnection
participant Elasticsearch
participant SDK
Client->>ChunkAPI: add_chunk / update_chunk / list_chunks (with chunk_metadata)
ChunkAPI->>InfinityConnection: persist/read chunk_metadata_kwd
InfinityConnection->>Elasticsearch: index/store chunk_metadata_kwd
Elasticsearch-->>InfinityConnection: return stored/search hits (chunk_metadata_kwd)
InfinityConnection-->>ChunkAPI: raw chunk with chunk_metadata_kwd
ChunkAPI->>ChunkAPI: _deserialize_chunk_metadata -> chunk_metadata
ChunkAPI-->>Client: response includes chunk_metadata
ChunkAPI-->>SDK: SDK reads chunk with chunk_metadata
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Suggested labels
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (1 warning, 1 inconclusive)
✅ Passed checks (3 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
6380ef5 to
1b9ada6
Compare
There was a problem hiding this comment.
Actionable comments posted: 5
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
agent/sandbox/providers/self_managed.py (1)
50-67:⚠️ Potential issue | 🟡 Minor | ⚡ Quick winDocstring default value is outdated.
Line 59 documents
pool_size: Container pool size for info (default: 10)but the actual default is now 3.📝 Proposed fix
- endpoint: HTTP endpoint (default: "http://sandbox-executor-manager:9385") - timeout: Request timeout in seconds (default: 30) - max_retries: Maximum retry attempts (default: 3) - - pool_size: Container pool size for info (default: 10) + - executor_manager_pool_size: Container pool size (default: 3)🤖 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 `@agent/sandbox/providers/self_managed.py` around lines 50 - 67, The docstring for initialize incorrectly states the default pool_size is 10; update the docstring so the "pool_size: Container pool size for info (default: 10)" line reflects the actual default of 3 (or mention the config key "executor_manager_pool_size" fallback). Modify the initialize method's docstring to show the default as 3 and/or note that the value comes from executor_manager_pool_size (falling back to pool_size) so maintainers can find the correct config keys; refer to the initialize function and the self.pool_size assignment.agent/sandbox/providers/local.py (1)
256-266:⚠️ Potential issue | 🟡 Minor | ⚡ Quick winOutdated error messages reference removed environment variables.
The error messages in
_validate_limits()still reference environment variable names (e.g.,SANDBOX_LOCAL_TIMEOUT) even though the provider no longer reads from environment variables. These should reference the config field names instead.📝 Proposed fix to update error messages
def _validate_limits(self) -> None: if self.timeout <= 0: - raise SandboxProviderConfigError("SANDBOX_LOCAL_TIMEOUT must be greater than 0.") + raise SandboxProviderConfigError("timeout must be greater than 0.") if self.max_memory_mb <= 0: - raise SandboxProviderConfigError("SANDBOX_LOCAL_MAX_MEMORY_MB must be greater than 0.") + raise SandboxProviderConfigError("max_memory_mb must be greater than 0.") if self.max_output_bytes <= 0: - raise SandboxProviderConfigError("SANDBOX_LOCAL_MAX_OUTPUT_BYTES must be greater than 0.") + raise SandboxProviderConfigError("max_output_bytes must be greater than 0.") if self.max_artifacts < 0: - raise SandboxProviderConfigError("SANDBOX_LOCAL_MAX_ARTIFACTS must be greater than or equal to 0.") + raise SandboxProviderConfigError("max_artifacts must be greater than or equal to 0.") if self.max_artifact_bytes <= 0: - raise SandboxProviderConfigError("SANDBOX_LOCAL_MAX_ARTIFACT_BYTES must be greater than 0.") + raise SandboxProviderConfigError("max_artifact_bytes must be greater than 0.")🤖 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 `@agent/sandbox/providers/local.py` around lines 256 - 266, The error messages in _validate_limits() still reference removed environment variables; update each SandboxProviderConfigError message in the _validate_limits method to mention the provider config fields instead of env var names—e.g., change "SANDBOX_LOCAL_TIMEOUT must be greater than 0." to "timeout must be greater than 0.", "SANDBOX_LOCAL_MAX_MEMORY_MB must be greater than 0." to "max_memory_mb must be greater than 0.", "SANDBOX_LOCAL_MAX_OUTPUT_BYTES must be greater than 0." to "max_output_bytes must be greater than 0.", "SANDBOX_LOCAL_MAX_ARTIFACTS must be greater than or equal to 0." to "max_artifacts must be greater than or equal to 0.", and "SANDBOX_LOCAL_MAX_ARTIFACT_BYTES must be greater than 0." to "max_artifact_bytes must be greater than 0." while keeping the same validation logic in _validate_limits.
🧹 Nitpick comments (7)
agent/sandbox/providers/ssh.py (1)
158-165: 💤 Low valueType hint says
intbut code handlesNone.The
timeoutparameter is typed asintwith default10, but line 186 checksif timeout is None. IfNoneis a valid input, update the type hint toOptional[int].def execute_code( self, instance_id: str, code: str, language: str, - timeout: int = 10, + timeout: Optional[int] = 10, arguments: Optional[Dict[str, Any]] = None, ) -> ExecutionResult:🤖 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 `@agent/sandbox/providers/ssh.py` around lines 158 - 165, The execute_code signature declares timeout: int but the implementation checks for timeout is None, so change the type hint to Optional[int] to reflect that None is valid; update the function signature for execute_code (and any related overloads or stubs) to use Optional[int], and run a quick search for callers of execute_code to ensure any places passing None are valid or adjust callers accordingly.docs/guides/agent/agent_quickstarts/sandbox_quickstart.md (1)
107-109: ⚡ Quick winClarify the guidance for modifying deployment defaults.
The phrase "Keep the self-managed deployment defaults in
.envif you need to change..." is ambiguous. It's unclear whether "keep" means "retain as-is" or "include these variables."Since these variables are commented out by default in
.env, users who need to customize them should uncomment and modify. Consider rewording for clarity.📝 Suggested rewording
-- Keep the self-managed deployment defaults in `.env` if you need to change the - sandbox-executor-manager image, pool size, base images, seccomp, memory, or - timeout. +- To customize the self-managed deployment defaults (executor-manager image, + pool size, base images, seccomp, memory, or timeout), uncomment and modify + the corresponding variables in `.env`.🤖 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 `@docs/guides/agent/agent_quickstarts/sandbox_quickstart.md` around lines 107 - 109, The sentence "Keep the self-managed deployment defaults in `.env` if you need to change the sandbox-executor-manager image, pool size, base images, seccomp, memory, or timeout." is ambiguous; update that line in sandbox_quickstart.md to clearly instruct users to uncomment and modify the commented variables in `.env` when they need to customize the sandbox-executor-manager image, pool size, base images, seccomp, memory, or timeout (e.g., replace the word "Keep" with explicit guidance like "Uncomment and set" or "Uncomment and modify" so it's clear those defaults are provided as commented variables to be changed).api/apps/restful_apis/chunk_api.py (2)
100-112: ⚡ Quick winAdd logging on the new chunk-metadata parse/write branches.
These new branches currently coerce malformed values to
{}or empty-string paths without telemetry, which will make storage/parse regressions hard to diagnose in production.As per coding guidelines,
**/*.py: "Add logging for new flows".Also applies to: 186-195, 295-299, 335-341, 451-455
🤖 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 100 - 112, The _deserialize_chunk_metadata function silently coerces malformed or unexpected chunk["chunk_metadata_kwd"] values to {} and drops the raw key; update the function to emit structured warning logs whenever (a) json.loads fails (include the exception and the raw string), (b) a non-dict non-string value is encountered, and (c) an empty string is treated as missing — include identifying fields from the chunk (e.g. chunk.get("id") or chunk.get("chunk_id")) in the log so operators can trace the offending record; apply the same logging additions to the other similar branches referenced (around the other ranges) so all parse/write fallback paths record telemetry.Source: Coding guidelines
295-299: 🏗️ Heavy liftMove new
chunk_metadatarequest validation into a Pydantic request model/service boundary.The new field is validated inline in route handlers. In this RESTful API module, this should follow the existing Pydantic request-validation + service-layer pattern to keep validation centralized and reusable.
As per coding guidelines,
api/apps/restful_apis/**/*.py: "Use Pydantic request validation with service layer pattern in newer RESTful APIs under api/apps/restful_apis/".Also applies to: 451-455
🤖 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 295 - 299, The inline validation for "chunk_metadata" in the route handler should be moved into the Pydantic request model and the service boundary: add an optional chunk_metadata: Dict[str, Any] field (with a validator that ensures it's a dict) to the endpoint's Pydantic request model, remove the inline isinstance check and get_error_data_result call from the handler, and have the handler pass the validated chunk_metadata to the service; perform the json.dumps(serialization) of chunk_metadata in the service layer (setting d["chunk_metadata_kwd"]) so the route stays thin. Apply the same refactor for the other occurrence referenced (lines 451-455).Source: Coding guidelines
agent/sandbox/client.py (1)
181-188: 💤 Low valueSimplify redundant fallback expression
The
getattr(provider, "__class__", type(provider))is unnecessary—every Python object has__class__, so the fallback never triggers. Usingtype(provider).__name__directly is clearer.♻️ Suggested simplification
- provider_name = provider_manager.get_provider_name() or getattr(provider, "__class__", type(provider)).__name__ + provider_name = provider_manager.get_provider_name() or type(provider).__name__🤖 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 `@agent/sandbox/client.py` around lines 181 - 188, The fallback using getattr(provider, "__class__", type(provider)) is redundant because every object has __class__; replace that expression with type(provider).__name__ for clarity: compute provider_name = provider_manager.get_provider_name() or type(provider).__name__ and keep the existing logger.info call that references provider_name, language, and timeout so behavior is unchanged (references: provider_manager.get_provider_name, provider, provider_name, logger.info).agent/tools/code_exec.py (1)
371-377: ⚖️ Poor tradeoffConsider caching provider instead of reloading on every execution.
Calling
reload_provider()on every_execute_codeinvocation ensures configuration changes take effect immediately but resets and re-initializes the provider manager each time. For high-throughput scenarios, this could introduce latency.Consider checking if configuration has changed before reloading, or documenting this as intentional behavior for immediate config propagation.
🤖 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 `@agent/tools/code_exec.py` around lines 371 - 377, The current _execute_code flow always calls reload_provider() before getting provider_info which reinitializes the provider every run; change this to cache the provider manager and only call reload_provider() when configuration has changed (e.g., track a config_version or checksum and compare before reloading) or make the reload behavior explicit in docs. Modify the logic around reload_provider(), get_provider_info(), and provider_type resolution so you first check a cached provider instance and a cached config fingerprint, call reload_provider() only on mismatch, and otherwise use the cached provider_info to avoid repeated re-initialization and reduce latency.web/src/pages/admin/sandbox-settings.tsx (1)
587-880: 💤 Low valueHardcoded English strings should use i18n.
Several user-facing strings are not internationalized:
- "Runtime Settings" (line 591)
- "Authentication" (line 655)
- "Choose one authentication method..." (line 658-659)
- "Password" / "Private Key" (lines 675, 678)
- "Execution" (line 779)
- "Deployment Defaults" (line 874)
These should use the
t()function with translation keys liket('admin.sandboxSettingsPage.runtimeSettings').🤖 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 `@web/src/pages/admin/sandbox-settings.tsx` around lines 587 - 880, Replace the hardcoded English UI strings in the sandbox settings Collapsible blocks with i18n t() calls: update the "Runtime Settings" heading in the CollapsibleTrigger, the "Authentication" h4 and its helper paragraph, the TabsTrigger labels "Password" and "Private Key", the "Execution" h4, and the "Deployment Defaults" heading to use t(...) keys (e.g., t('admin.sandboxSettingsPage.runtimeSettings'), t('admin.sandboxSettingsPage.authentication'), t('admin.sandboxSettingsPage.authenticationHelp'), t('admin.sandboxSettingsPage.password'), t('admin.sandboxSettingsPage.privateKey'), t('admin.sandboxSettingsPage.execution'), t('admin.sandboxSettingsPage.deploymentDefaults')). Locate these strings around the CollapsibleTrigger, CollapsibleContent, TabsList/TabsTrigger and the relevant h4/p elements and replace the literal text with the t(...) calls so all user-facing strings are internationalized.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 `@agent/sandbox/providers/ssh.py`:
- Around line 79-117: Add structured logging to the SSH provider initialize
flow: at the start of initialize(...) log an INFO message that initialization is
beginning with non-sensitive config summary (include host, port, username,
python_bin, node_bin, work_dir, timeout, max_output_bytes, max_artifacts,
max_artifact_bytes) while redacting password/private_key/passphrase; when
validate_config returns is_valid == False log an ERROR with the validation error
and then raise SandboxProviderConfigError(error_message); wrap the call to
_assert_connectivity() to catch exceptions and log an ERROR with the exception
details (stack/exception string) and re-raise; and finally log an INFO on
successful initialization (after setting _initialized=True) indicating
connectivity and readiness. Use the class logger (self.logger) if available,
falling back to the module logger, and ensure all logs include identifying
context (class name / method initialize).
- Around line 435-456: The SSH client currently uses paramiko.AutoAddPolicy()
which blindly trusts host keys; update _create_ssh_client to accept a
configurable host_key_policy option (e.g., values "reject", "auto_add",
"warning") on the provider class, call client.load_system_host_keys() and/or
client.load_host_keys(...) when policy is "reject" or to prefer known_hosts
verification, and only set AutoAddPolicy when the policy is explicitly
"auto_add" while emitting a clear warning log when AutoAddPolicy is used; ensure
existing behavior for key/password loading via _load_private_key remains
unchanged and that the logic references self.host_key_policy and
paramiko.AutoAddPolicy/RejectPolicy appropriately.
In `@conf/mapping.json`:
- Around line 23-25: The mapping for the field chunk_metadata_kwd is currently
typed as "keyword" and will attempt to index arbitrarily large JSON strings;
update the mapping for chunk_metadata_kwd to make it retrieval-only by setting
"index": false while keeping "store": true, or if you must index short values
add an "ignore_above" threshold (e.g. 32766) to the keyword definition to
prevent indexing oversized terms; locate the chunk_metadata_kwd entry in the
mapping.json and replace or augment its properties accordingly.
In `@rag/llm/chat_model.py`:
- Around line 1506-1510: The Base._verbose_tool_use method wasn't updated to
handle Exception objects during JSON serialization like
LiteLLMBase._verbose_tool_use; update Base._verbose_tool_use to convert
Exception results to strings before json.dumps (e.g., use the same pattern: use
str(res) if isinstance(res, Exception) else res) so when callers pass err (the
Exception) via the tool call site (the code using "err if err else result") the
JSON encoding won't fail; ensure the log format and ensure_ascii/indent behavior
mirrors LiteLLMBase._verbose_tool_use.
In `@rag/utils/infinity_conn.py`:
- Around line 451-456: The branch that serializes chunk_metadata_kwd to JSON
never runs because self.field_keyword(k) matches first; update the logic so
chunk_metadata_kwd is handled explicitly before keyword matching (or alter the
field_keyword handling to skip/avoid matching "chunk_metadata_kwd"), ensuring
that in the function where d, k, v are processed the chunk_metadata_kwd branch
runs and dict values are json.dumps(..., ensure_ascii=False) while
empty/non-dict values become ""; keep the rest of keyword handling unchanged.
---
Outside diff comments:
In `@agent/sandbox/providers/local.py`:
- Around line 256-266: The error messages in _validate_limits() still reference
removed environment variables; update each SandboxProviderConfigError message in
the _validate_limits method to mention the provider config fields instead of env
var names—e.g., change "SANDBOX_LOCAL_TIMEOUT must be greater than 0." to
"timeout must be greater than 0.", "SANDBOX_LOCAL_MAX_MEMORY_MB must be greater
than 0." to "max_memory_mb must be greater than 0.",
"SANDBOX_LOCAL_MAX_OUTPUT_BYTES must be greater than 0." to "max_output_bytes
must be greater than 0.", "SANDBOX_LOCAL_MAX_ARTIFACTS must be greater than or
equal to 0." to "max_artifacts must be greater than or equal to 0.", and
"SANDBOX_LOCAL_MAX_ARTIFACT_BYTES must be greater than 0." to
"max_artifact_bytes must be greater than 0." while keeping the same validation
logic in _validate_limits.
In `@agent/sandbox/providers/self_managed.py`:
- Around line 50-67: The docstring for initialize incorrectly states the default
pool_size is 10; update the docstring so the "pool_size: Container pool size for
info (default: 10)" line reflects the actual default of 3 (or mention the config
key "executor_manager_pool_size" fallback). Modify the initialize method's
docstring to show the default as 3 and/or note that the value comes from
executor_manager_pool_size (falling back to pool_size) so maintainers can find
the correct config keys; refer to the initialize function and the self.pool_size
assignment.
---
Nitpick comments:
In `@agent/sandbox/client.py`:
- Around line 181-188: The fallback using getattr(provider, "__class__",
type(provider)) is redundant because every object has __class__; replace that
expression with type(provider).__name__ for clarity: compute provider_name =
provider_manager.get_provider_name() or type(provider).__name__ and keep the
existing logger.info call that references provider_name, language, and timeout
so behavior is unchanged (references: provider_manager.get_provider_name,
provider, provider_name, logger.info).
In `@agent/sandbox/providers/ssh.py`:
- Around line 158-165: The execute_code signature declares timeout: int but the
implementation checks for timeout is None, so change the type hint to
Optional[int] to reflect that None is valid; update the function signature for
execute_code (and any related overloads or stubs) to use Optional[int], and run
a quick search for callers of execute_code to ensure any places passing None are
valid or adjust callers accordingly.
In `@agent/tools/code_exec.py`:
- Around line 371-377: The current _execute_code flow always calls
reload_provider() before getting provider_info which reinitializes the provider
every run; change this to cache the provider manager and only call
reload_provider() when configuration has changed (e.g., track a config_version
or checksum and compare before reloading) or make the reload behavior explicit
in docs. Modify the logic around reload_provider(), get_provider_info(), and
provider_type resolution so you first check a cached provider instance and a
cached config fingerprint, call reload_provider() only on mismatch, and
otherwise use the cached provider_info to avoid repeated re-initialization and
reduce latency.
In `@api/apps/restful_apis/chunk_api.py`:
- Around line 100-112: The _deserialize_chunk_metadata function silently coerces
malformed or unexpected chunk["chunk_metadata_kwd"] values to {} and drops the
raw key; update the function to emit structured warning logs whenever (a)
json.loads fails (include the exception and the raw string), (b) a non-dict
non-string value is encountered, and (c) an empty string is treated as missing —
include identifying fields from the chunk (e.g. chunk.get("id") or
chunk.get("chunk_id")) in the log so operators can trace the offending record;
apply the same logging additions to the other similar branches referenced
(around the other ranges) so all parse/write fallback paths record telemetry.
- Around line 295-299: The inline validation for "chunk_metadata" in the route
handler should be moved into the Pydantic request model and the service
boundary: add an optional chunk_metadata: Dict[str, Any] field (with a validator
that ensures it's a dict) to the endpoint's Pydantic request model, remove the
inline isinstance check and get_error_data_result call from the handler, and
have the handler pass the validated chunk_metadata to the service; perform the
json.dumps(serialization) of chunk_metadata in the service layer (setting
d["chunk_metadata_kwd"]) so the route stays thin. Apply the same refactor for
the other occurrence referenced (lines 451-455).
In `@docs/guides/agent/agent_quickstarts/sandbox_quickstart.md`:
- Around line 107-109: The sentence "Keep the self-managed deployment defaults
in `.env` if you need to change the sandbox-executor-manager image, pool size,
base images, seccomp, memory, or timeout." is ambiguous; update that line in
sandbox_quickstart.md to clearly instruct users to uncomment and modify the
commented variables in `.env` when they need to customize the
sandbox-executor-manager image, pool size, base images, seccomp, memory, or
timeout (e.g., replace the word "Keep" with explicit guidance like "Uncomment
and set" or "Uncomment and modify" so it's clear those defaults are provided as
commented variables to be changed).
In `@web/src/pages/admin/sandbox-settings.tsx`:
- Around line 587-880: Replace the hardcoded English UI strings in the sandbox
settings Collapsible blocks with i18n t() calls: update the "Runtime Settings"
heading in the CollapsibleTrigger, the "Authentication" h4 and its helper
paragraph, the TabsTrigger labels "Password" and "Private Key", the "Execution"
h4, and the "Deployment Defaults" heading to use t(...) keys (e.g.,
t('admin.sandboxSettingsPage.runtimeSettings'),
t('admin.sandboxSettingsPage.authentication'),
t('admin.sandboxSettingsPage.authenticationHelp'),
t('admin.sandboxSettingsPage.password'),
t('admin.sandboxSettingsPage.privateKey'),
t('admin.sandboxSettingsPage.execution'),
t('admin.sandboxSettingsPage.deploymentDefaults')). Locate these strings around
the CollapsibleTrigger, CollapsibleContent, TabsList/TabsTrigger and the
relevant h4/p elements and replace the literal text with the t(...) calls so all
user-facing strings are internationalized.
🪄 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: f08a1c3f-f982-4905-aecf-8e8981d8f0ef
⛔ Files ignored due to path filters (2)
uv.lockis excluded by!**/*.lockweb/src/assets/admin-sandbox-settings.pngis excluded by!**/*.png
📒 Files selected for processing (24)
admin/server/services.pyagent/sandbox/client.pyagent/sandbox/providers/__init__.pyagent/sandbox/providers/local.pyagent/sandbox/providers/self_managed.pyagent/sandbox/providers/ssh.pyagent/tools/base.pyagent/tools/code_exec.pyapi/apps/restful_apis/chunk_api.pyconf/infinity_mapping.jsonconf/llm_factories.jsonconf/mapping.jsondocker/.envdocs/guides/agent/agent_quickstarts/sandbox_quickstart.mdpyproject.tomlrag/llm/chat_model.pyrag/utils/infinity_conn.pysdk/python/ragflow_sdk/modules/chunk.pytest/unit_test/agent/sandbox/test_local_provider.pytest/unit_test/agent/sandbox/test_sandbox_client.pytest/unit_test/agent/sandbox/test_ssh_provider.pyweb/src/interfaces/database/dataset.tsweb/src/pages/admin/sandbox-settings.tsxweb/src/services/admin.service.d.ts
💤 Files with no reviewable changes (1)
- conf/llm_factories.json
There was a problem hiding this comment.
Caution
Inline review comments failed to post. This is likely due to GitHub's internal server error or limits when posting large numbers of comments. If you are seeing this consistently it is likely a permissions issue. Please check "Moderation" -> "Code review limits" under your organization settings.
Actionable comments posted: 5
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
agent/sandbox/providers/self_managed.py (1)
50-67:⚠️ Potential issue | 🟡 Minor | ⚡ Quick winDocstring default value is outdated.
Line 59 documents
pool_size: Container pool size for info (default: 10)but the actual default is now 3.📝 Proposed fix
- endpoint: HTTP endpoint (default: "http://sandbox-executor-manager:9385") - timeout: Request timeout in seconds (default: 30) - max_retries: Maximum retry attempts (default: 3) - - pool_size: Container pool size for info (default: 10) + - executor_manager_pool_size: Container pool size (default: 3)🤖 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 `@agent/sandbox/providers/self_managed.py` around lines 50 - 67, The docstring for initialize incorrectly states the default pool_size is 10; update the docstring so the "pool_size: Container pool size for info (default: 10)" line reflects the actual default of 3 (or mention the config key "executor_manager_pool_size" fallback). Modify the initialize method's docstring to show the default as 3 and/or note that the value comes from executor_manager_pool_size (falling back to pool_size) so maintainers can find the correct config keys; refer to the initialize function and the self.pool_size assignment.agent/sandbox/providers/local.py (1)
256-266:⚠️ Potential issue | 🟡 Minor | ⚡ Quick winOutdated error messages reference removed environment variables.
The error messages in
_validate_limits()still reference environment variable names (e.g.,SANDBOX_LOCAL_TIMEOUT) even though the provider no longer reads from environment variables. These should reference the config field names instead.📝 Proposed fix to update error messages
def _validate_limits(self) -> None: if self.timeout <= 0: - raise SandboxProviderConfigError("SANDBOX_LOCAL_TIMEOUT must be greater than 0.") + raise SandboxProviderConfigError("timeout must be greater than 0.") if self.max_memory_mb <= 0: - raise SandboxProviderConfigError("SANDBOX_LOCAL_MAX_MEMORY_MB must be greater than 0.") + raise SandboxProviderConfigError("max_memory_mb must be greater than 0.") if self.max_output_bytes <= 0: - raise SandboxProviderConfigError("SANDBOX_LOCAL_MAX_OUTPUT_BYTES must be greater than 0.") + raise SandboxProviderConfigError("max_output_bytes must be greater than 0.") if self.max_artifacts < 0: - raise SandboxProviderConfigError("SANDBOX_LOCAL_MAX_ARTIFACTS must be greater than or equal to 0.") + raise SandboxProviderConfigError("max_artifacts must be greater than or equal to 0.") if self.max_artifact_bytes <= 0: - raise SandboxProviderConfigError("SANDBOX_LOCAL_MAX_ARTIFACT_BYTES must be greater than 0.") + raise SandboxProviderConfigError("max_artifact_bytes must be greater than 0.")🤖 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 `@agent/sandbox/providers/local.py` around lines 256 - 266, The error messages in _validate_limits() still reference removed environment variables; update each SandboxProviderConfigError message in the _validate_limits method to mention the provider config fields instead of env var names—e.g., change "SANDBOX_LOCAL_TIMEOUT must be greater than 0." to "timeout must be greater than 0.", "SANDBOX_LOCAL_MAX_MEMORY_MB must be greater than 0." to "max_memory_mb must be greater than 0.", "SANDBOX_LOCAL_MAX_OUTPUT_BYTES must be greater than 0." to "max_output_bytes must be greater than 0.", "SANDBOX_LOCAL_MAX_ARTIFACTS must be greater than or equal to 0." to "max_artifacts must be greater than or equal to 0.", and "SANDBOX_LOCAL_MAX_ARTIFACT_BYTES must be greater than 0." to "max_artifact_bytes must be greater than 0." while keeping the same validation logic in _validate_limits.
🧹 Nitpick comments (7)
agent/sandbox/providers/ssh.py (1)
158-165: 💤 Low valueType hint says
intbut code handlesNone.The
timeoutparameter is typed asintwith default10, but line 186 checksif timeout is None. IfNoneis a valid input, update the type hint toOptional[int].def execute_code( self, instance_id: str, code: str, language: str, - timeout: int = 10, + timeout: Optional[int] = 10, arguments: Optional[Dict[str, Any]] = None, ) -> ExecutionResult:🤖 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 `@agent/sandbox/providers/ssh.py` around lines 158 - 165, The execute_code signature declares timeout: int but the implementation checks for timeout is None, so change the type hint to Optional[int] to reflect that None is valid; update the function signature for execute_code (and any related overloads or stubs) to use Optional[int], and run a quick search for callers of execute_code to ensure any places passing None are valid or adjust callers accordingly.docs/guides/agent/agent_quickstarts/sandbox_quickstart.md (1)
107-109: ⚡ Quick winClarify the guidance for modifying deployment defaults.
The phrase "Keep the self-managed deployment defaults in
.envif you need to change..." is ambiguous. It's unclear whether "keep" means "retain as-is" or "include these variables."Since these variables are commented out by default in
.env, users who need to customize them should uncomment and modify. Consider rewording for clarity.📝 Suggested rewording
-- Keep the self-managed deployment defaults in `.env` if you need to change the - sandbox-executor-manager image, pool size, base images, seccomp, memory, or - timeout. +- To customize the self-managed deployment defaults (executor-manager image, + pool size, base images, seccomp, memory, or timeout), uncomment and modify + the corresponding variables in `.env`.🤖 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 `@docs/guides/agent/agent_quickstarts/sandbox_quickstart.md` around lines 107 - 109, The sentence "Keep the self-managed deployment defaults in `.env` if you need to change the sandbox-executor-manager image, pool size, base images, seccomp, memory, or timeout." is ambiguous; update that line in sandbox_quickstart.md to clearly instruct users to uncomment and modify the commented variables in `.env` when they need to customize the sandbox-executor-manager image, pool size, base images, seccomp, memory, or timeout (e.g., replace the word "Keep" with explicit guidance like "Uncomment and set" or "Uncomment and modify" so it's clear those defaults are provided as commented variables to be changed).api/apps/restful_apis/chunk_api.py (2)
100-112: ⚡ Quick winAdd logging on the new chunk-metadata parse/write branches.
These new branches currently coerce malformed values to
{}or empty-string paths without telemetry, which will make storage/parse regressions hard to diagnose in production.As per coding guidelines,
**/*.py: "Add logging for new flows".Also applies to: 186-195, 295-299, 335-341, 451-455
🤖 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 100 - 112, The _deserialize_chunk_metadata function silently coerces malformed or unexpected chunk["chunk_metadata_kwd"] values to {} and drops the raw key; update the function to emit structured warning logs whenever (a) json.loads fails (include the exception and the raw string), (b) a non-dict non-string value is encountered, and (c) an empty string is treated as missing — include identifying fields from the chunk (e.g. chunk.get("id") or chunk.get("chunk_id")) in the log so operators can trace the offending record; apply the same logging additions to the other similar branches referenced (around the other ranges) so all parse/write fallback paths record telemetry.Source: Coding guidelines
295-299: 🏗️ Heavy liftMove new
chunk_metadatarequest validation into a Pydantic request model/service boundary.The new field is validated inline in route handlers. In this RESTful API module, this should follow the existing Pydantic request-validation + service-layer pattern to keep validation centralized and reusable.
As per coding guidelines,
api/apps/restful_apis/**/*.py: "Use Pydantic request validation with service layer pattern in newer RESTful APIs under api/apps/restful_apis/".Also applies to: 451-455
🤖 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 295 - 299, The inline validation for "chunk_metadata" in the route handler should be moved into the Pydantic request model and the service boundary: add an optional chunk_metadata: Dict[str, Any] field (with a validator that ensures it's a dict) to the endpoint's Pydantic request model, remove the inline isinstance check and get_error_data_result call from the handler, and have the handler pass the validated chunk_metadata to the service; perform the json.dumps(serialization) of chunk_metadata in the service layer (setting d["chunk_metadata_kwd"]) so the route stays thin. Apply the same refactor for the other occurrence referenced (lines 451-455).Source: Coding guidelines
agent/sandbox/client.py (1)
181-188: 💤 Low valueSimplify redundant fallback expression
The
getattr(provider, "__class__", type(provider))is unnecessary—every Python object has__class__, so the fallback never triggers. Usingtype(provider).__name__directly is clearer.♻️ Suggested simplification
- provider_name = provider_manager.get_provider_name() or getattr(provider, "__class__", type(provider)).__name__ + provider_name = provider_manager.get_provider_name() or type(provider).__name__🤖 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 `@agent/sandbox/client.py` around lines 181 - 188, The fallback using getattr(provider, "__class__", type(provider)) is redundant because every object has __class__; replace that expression with type(provider).__name__ for clarity: compute provider_name = provider_manager.get_provider_name() or type(provider).__name__ and keep the existing logger.info call that references provider_name, language, and timeout so behavior is unchanged (references: provider_manager.get_provider_name, provider, provider_name, logger.info).agent/tools/code_exec.py (1)
371-377: ⚖️ Poor tradeoffConsider caching provider instead of reloading on every execution.
Calling
reload_provider()on every_execute_codeinvocation ensures configuration changes take effect immediately but resets and re-initializes the provider manager each time. For high-throughput scenarios, this could introduce latency.Consider checking if configuration has changed before reloading, or documenting this as intentional behavior for immediate config propagation.
🤖 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 `@agent/tools/code_exec.py` around lines 371 - 377, The current _execute_code flow always calls reload_provider() before getting provider_info which reinitializes the provider every run; change this to cache the provider manager and only call reload_provider() when configuration has changed (e.g., track a config_version or checksum and compare before reloading) or make the reload behavior explicit in docs. Modify the logic around reload_provider(), get_provider_info(), and provider_type resolution so you first check a cached provider instance and a cached config fingerprint, call reload_provider() only on mismatch, and otherwise use the cached provider_info to avoid repeated re-initialization and reduce latency.web/src/pages/admin/sandbox-settings.tsx (1)
587-880: 💤 Low valueHardcoded English strings should use i18n.
Several user-facing strings are not internationalized:
- "Runtime Settings" (line 591)
- "Authentication" (line 655)
- "Choose one authentication method..." (line 658-659)
- "Password" / "Private Key" (lines 675, 678)
- "Execution" (line 779)
- "Deployment Defaults" (line 874)
These should use the
t()function with translation keys liket('admin.sandboxSettingsPage.runtimeSettings').🤖 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 `@web/src/pages/admin/sandbox-settings.tsx` around lines 587 - 880, Replace the hardcoded English UI strings in the sandbox settings Collapsible blocks with i18n t() calls: update the "Runtime Settings" heading in the CollapsibleTrigger, the "Authentication" h4 and its helper paragraph, the TabsTrigger labels "Password" and "Private Key", the "Execution" h4, and the "Deployment Defaults" heading to use t(...) keys (e.g., t('admin.sandboxSettingsPage.runtimeSettings'), t('admin.sandboxSettingsPage.authentication'), t('admin.sandboxSettingsPage.authenticationHelp'), t('admin.sandboxSettingsPage.password'), t('admin.sandboxSettingsPage.privateKey'), t('admin.sandboxSettingsPage.execution'), t('admin.sandboxSettingsPage.deploymentDefaults')). Locate these strings around the CollapsibleTrigger, CollapsibleContent, TabsList/TabsTrigger and the relevant h4/p elements and replace the literal text with the t(...) calls so all user-facing strings are internationalized.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 `@agent/sandbox/providers/ssh.py`:
- Around line 79-117: Add structured logging to the SSH provider initialize
flow: at the start of initialize(...) log an INFO message that initialization is
beginning with non-sensitive config summary (include host, port, username,
python_bin, node_bin, work_dir, timeout, max_output_bytes, max_artifacts,
max_artifact_bytes) while redacting password/private_key/passphrase; when
validate_config returns is_valid == False log an ERROR with the validation error
and then raise SandboxProviderConfigError(error_message); wrap the call to
_assert_connectivity() to catch exceptions and log an ERROR with the exception
details (stack/exception string) and re-raise; and finally log an INFO on
successful initialization (after setting _initialized=True) indicating
connectivity and readiness. Use the class logger (self.logger) if available,
falling back to the module logger, and ensure all logs include identifying
context (class name / method initialize).
- Around line 435-456: The SSH client currently uses paramiko.AutoAddPolicy()
which blindly trusts host keys; update _create_ssh_client to accept a
configurable host_key_policy option (e.g., values "reject", "auto_add",
"warning") on the provider class, call client.load_system_host_keys() and/or
client.load_host_keys(...) when policy is "reject" or to prefer known_hosts
verification, and only set AutoAddPolicy when the policy is explicitly
"auto_add" while emitting a clear warning log when AutoAddPolicy is used; ensure
existing behavior for key/password loading via _load_private_key remains
unchanged and that the logic references self.host_key_policy and
paramiko.AutoAddPolicy/RejectPolicy appropriately.
In `@conf/mapping.json`:
- Around line 23-25: The mapping for the field chunk_metadata_kwd is currently
typed as "keyword" and will attempt to index arbitrarily large JSON strings;
update the mapping for chunk_metadata_kwd to make it retrieval-only by setting
"index": false while keeping "store": true, or if you must index short values
add an "ignore_above" threshold (e.g. 32766) to the keyword definition to
prevent indexing oversized terms; locate the chunk_metadata_kwd entry in the
mapping.json and replace or augment its properties accordingly.
In `@rag/llm/chat_model.py`:
- Around line 1506-1510: The Base._verbose_tool_use method wasn't updated to
handle Exception objects during JSON serialization like
LiteLLMBase._verbose_tool_use; update Base._verbose_tool_use to convert
Exception results to strings before json.dumps (e.g., use the same pattern: use
str(res) if isinstance(res, Exception) else res) so when callers pass err (the
Exception) via the tool call site (the code using "err if err else result") the
JSON encoding won't fail; ensure the log format and ensure_ascii/indent behavior
mirrors LiteLLMBase._verbose_tool_use.
In `@rag/utils/infinity_conn.py`:
- Around line 451-456: The branch that serializes chunk_metadata_kwd to JSON
never runs because self.field_keyword(k) matches first; update the logic so
chunk_metadata_kwd is handled explicitly before keyword matching (or alter the
field_keyword handling to skip/avoid matching "chunk_metadata_kwd"), ensuring
that in the function where d, k, v are processed the chunk_metadata_kwd branch
runs and dict values are json.dumps(..., ensure_ascii=False) while
empty/non-dict values become ""; keep the rest of keyword handling unchanged.
---
Outside diff comments:
In `@agent/sandbox/providers/local.py`:
- Around line 256-266: The error messages in _validate_limits() still reference
removed environment variables; update each SandboxProviderConfigError message in
the _validate_limits method to mention the provider config fields instead of env
var names—e.g., change "SANDBOX_LOCAL_TIMEOUT must be greater than 0." to
"timeout must be greater than 0.", "SANDBOX_LOCAL_MAX_MEMORY_MB must be greater
than 0." to "max_memory_mb must be greater than 0.",
"SANDBOX_LOCAL_MAX_OUTPUT_BYTES must be greater than 0." to "max_output_bytes
must be greater than 0.", "SANDBOX_LOCAL_MAX_ARTIFACTS must be greater than or
equal to 0." to "max_artifacts must be greater than or equal to 0.", and
"SANDBOX_LOCAL_MAX_ARTIFACT_BYTES must be greater than 0." to
"max_artifact_bytes must be greater than 0." while keeping the same validation
logic in _validate_limits.
In `@agent/sandbox/providers/self_managed.py`:
- Around line 50-67: The docstring for initialize incorrectly states the default
pool_size is 10; update the docstring so the "pool_size: Container pool size for
info (default: 10)" line reflects the actual default of 3 (or mention the config
key "executor_manager_pool_size" fallback). Modify the initialize method's
docstring to show the default as 3 and/or note that the value comes from
executor_manager_pool_size (falling back to pool_size) so maintainers can find
the correct config keys; refer to the initialize function and the self.pool_size
assignment.
---
Nitpick comments:
In `@agent/sandbox/client.py`:
- Around line 181-188: The fallback using getattr(provider, "__class__",
type(provider)) is redundant because every object has __class__; replace that
expression with type(provider).__name__ for clarity: compute provider_name =
provider_manager.get_provider_name() or type(provider).__name__ and keep the
existing logger.info call that references provider_name, language, and timeout
so behavior is unchanged (references: provider_manager.get_provider_name,
provider, provider_name, logger.info).
In `@agent/sandbox/providers/ssh.py`:
- Around line 158-165: The execute_code signature declares timeout: int but the
implementation checks for timeout is None, so change the type hint to
Optional[int] to reflect that None is valid; update the function signature for
execute_code (and any related overloads or stubs) to use Optional[int], and run
a quick search for callers of execute_code to ensure any places passing None are
valid or adjust callers accordingly.
In `@agent/tools/code_exec.py`:
- Around line 371-377: The current _execute_code flow always calls
reload_provider() before getting provider_info which reinitializes the provider
every run; change this to cache the provider manager and only call
reload_provider() when configuration has changed (e.g., track a config_version
or checksum and compare before reloading) or make the reload behavior explicit
in docs. Modify the logic around reload_provider(), get_provider_info(), and
provider_type resolution so you first check a cached provider instance and a
cached config fingerprint, call reload_provider() only on mismatch, and
otherwise use the cached provider_info to avoid repeated re-initialization and
reduce latency.
In `@api/apps/restful_apis/chunk_api.py`:
- Around line 100-112: The _deserialize_chunk_metadata function silently coerces
malformed or unexpected chunk["chunk_metadata_kwd"] values to {} and drops the
raw key; update the function to emit structured warning logs whenever (a)
json.loads fails (include the exception and the raw string), (b) a non-dict
non-string value is encountered, and (c) an empty string is treated as missing —
include identifying fields from the chunk (e.g. chunk.get("id") or
chunk.get("chunk_id")) in the log so operators can trace the offending record;
apply the same logging additions to the other similar branches referenced
(around the other ranges) so all parse/write fallback paths record telemetry.
- Around line 295-299: The inline validation for "chunk_metadata" in the route
handler should be moved into the Pydantic request model and the service
boundary: add an optional chunk_metadata: Dict[str, Any] field (with a validator
that ensures it's a dict) to the endpoint's Pydantic request model, remove the
inline isinstance check and get_error_data_result call from the handler, and
have the handler pass the validated chunk_metadata to the service; perform the
json.dumps(serialization) of chunk_metadata in the service layer (setting
d["chunk_metadata_kwd"]) so the route stays thin. Apply the same refactor for
the other occurrence referenced (lines 451-455).
In `@docs/guides/agent/agent_quickstarts/sandbox_quickstart.md`:
- Around line 107-109: The sentence "Keep the self-managed deployment defaults
in `.env` if you need to change the sandbox-executor-manager image, pool size,
base images, seccomp, memory, or timeout." is ambiguous; update that line in
sandbox_quickstart.md to clearly instruct users to uncomment and modify the
commented variables in `.env` when they need to customize the
sandbox-executor-manager image, pool size, base images, seccomp, memory, or
timeout (e.g., replace the word "Keep" with explicit guidance like "Uncomment
and set" or "Uncomment and modify" so it's clear those defaults are provided as
commented variables to be changed).
In `@web/src/pages/admin/sandbox-settings.tsx`:
- Around line 587-880: Replace the hardcoded English UI strings in the sandbox
settings Collapsible blocks with i18n t() calls: update the "Runtime Settings"
heading in the CollapsibleTrigger, the "Authentication" h4 and its helper
paragraph, the TabsTrigger labels "Password" and "Private Key", the "Execution"
h4, and the "Deployment Defaults" heading to use t(...) keys (e.g.,
t('admin.sandboxSettingsPage.runtimeSettings'),
t('admin.sandboxSettingsPage.authentication'),
t('admin.sandboxSettingsPage.authenticationHelp'),
t('admin.sandboxSettingsPage.password'),
t('admin.sandboxSettingsPage.privateKey'),
t('admin.sandboxSettingsPage.execution'),
t('admin.sandboxSettingsPage.deploymentDefaults')). Locate these strings around
the CollapsibleTrigger, CollapsibleContent, TabsList/TabsTrigger and the
relevant h4/p elements and replace the literal text with the t(...) calls so all
user-facing strings are internationalized.
🪄 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: f08a1c3f-f982-4905-aecf-8e8981d8f0ef
⛔ Files ignored due to path filters (2)
uv.lockis excluded by!**/*.lockweb/src/assets/admin-sandbox-settings.pngis excluded by!**/*.png
📒 Files selected for processing (24)
admin/server/services.pyagent/sandbox/client.pyagent/sandbox/providers/__init__.pyagent/sandbox/providers/local.pyagent/sandbox/providers/self_managed.pyagent/sandbox/providers/ssh.pyagent/tools/base.pyagent/tools/code_exec.pyapi/apps/restful_apis/chunk_api.pyconf/infinity_mapping.jsonconf/llm_factories.jsonconf/mapping.jsondocker/.envdocs/guides/agent/agent_quickstarts/sandbox_quickstart.mdpyproject.tomlrag/llm/chat_model.pyrag/utils/infinity_conn.pysdk/python/ragflow_sdk/modules/chunk.pytest/unit_test/agent/sandbox/test_local_provider.pytest/unit_test/agent/sandbox/test_sandbox_client.pytest/unit_test/agent/sandbox/test_ssh_provider.pyweb/src/interfaces/database/dataset.tsweb/src/pages/admin/sandbox-settings.tsxweb/src/services/admin.service.d.ts
💤 Files with no reviewable changes (1)
- conf/llm_factories.json
🛑 Comments failed to post (5)
agent/sandbox/providers/ssh.py (2)
79-117: 🛠️ Refactor suggestion | 🟠 Major | ⚡ Quick win
Add logging for SSH provider initialization and connectivity.
This new flow has no logging statements. Add appropriate logging for initialization success/failure and connectivity checks to aid debugging and operational monitoring.
Based on learnings: "Add logging for new flows" per coding guidelines.
Example logging additions
+import logging + +logger = logging.getLogger(__name__) + class SSHProvider(SandboxProvider): ... def initialize(self, config: Dict[str, Any]) -> bool: ... self._assert_connectivity() + logger.info("SSH provider initialized: %s@%s:%d", self.username, self.host, self.port) self._initialized = True return True🤖 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 `@agent/sandbox/providers/ssh.py` around lines 79 - 117, Add structured logging to the SSH provider initialize flow: at the start of initialize(...) log an INFO message that initialization is beginning with non-sensitive config summary (include host, port, username, python_bin, node_bin, work_dir, timeout, max_output_bytes, max_artifacts, max_artifact_bytes) while redacting password/private_key/passphrase; when validate_config returns is_valid == False log an ERROR with the validation error and then raise SandboxProviderConfigError(error_message); wrap the call to _assert_connectivity() to catch exceptions and log an ERROR with the exception details (stack/exception string) and re-raise; and finally log an INFO on successful initialization (after setting _initialized=True) indicating connectivity and readiness. Use the class logger (self.logger) if available, falling back to the module logger, and ensure all logs include identifying context (class name / method initialize).Source: Coding guidelines
435-456:
⚠️ Potential issue | 🟠 Major | 🏗️ Heavy lift
AutoAddPolicyaccepts unknown SSH host keys without verification.Using
AutoAddPolicyautomatically trusts any host key, making the connection vulnerable to man-in-the-middle attacks. For production use, consider:
- Adding a
host_key_policyconfig option (e.g.,reject,auto_add,warning)- Supporting known_hosts file verification via
load_system_host_keys()orload_host_keys()- At minimum, logging a warning when AutoAddPolicy is in effect
Suggested approach
def _create_ssh_client(self) -> paramiko.SSHClient: paramiko = _get_paramiko_module() client = paramiko.SSHClient() - client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + # TODO: Consider making host key policy configurable for production security + # Options: load_system_host_keys(), load_host_keys(path), or RejectPolicy() + client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + logger.warning( + "SSH connection to %s:%d uses AutoAddPolicy - host key verification disabled", + self.host, + self.port, + )🤖 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 `@agent/sandbox/providers/ssh.py` around lines 435 - 456, The SSH client currently uses paramiko.AutoAddPolicy() which blindly trusts host keys; update _create_ssh_client to accept a configurable host_key_policy option (e.g., values "reject", "auto_add", "warning") on the provider class, call client.load_system_host_keys() and/or client.load_host_keys(...) when policy is "reject" or to prefer known_hosts verification, and only set AutoAddPolicy when the policy is explicitly "auto_add" while emitting a clear warning log when AutoAddPolicy is used; ensure existing behavior for key/password loading via _load_private_key remains unchanged and that the logic references self.host_key_policy and paramiko.AutoAddPolicy/RejectPolicy appropriately.conf/mapping.json (1)
23-25:
⚠️ Potential issue | 🟠 Major🧩 Analysis chain
🌐 Web query:
For the Elasticsearch version used by this repository, what is the maximum indexed term length forkeywordfields, and what happens when akeywordvalue exceeds that limit? Also confirm best practice for storing large JSON blobs that are returned but not searched.💡 Result:
In Elasticsearch, the absolute technical limit for a term in a Lucene index is 32,766 UTF-8 encoded bytes [1][2]. If a value exceeds this limit, Elasticsearch will reject the document entirely [1][3]. For
keywordfields, theignore_abovemapping parameter is used to manage this limitation [2][4]. When akeywordvalue exceeds theignore_abovethreshold: * The field is not indexed, meaning it cannot be used for searches, aggregations, or sorting [2][4]. * The value remains available in the_sourcefield (assuming it is enabled) and can be retrieved, but the field itself acts as if it does not exist for indexing-dependent operations [2][4][5]. * Settingignore_aboveto 8,191 characters or less is considered a best practice to ensure you never hit the underlying 32,766-byte Lucene limit, as UTF-8 characters can consume up to 4 bytes each [2][3][4]. For storing large JSON blobs that are returned but not searched, the best practice is to keep them in the_sourcefield [6][7]. Since_sourceis stored by default and is not indexed, it does not contribute to the term-length limits or the mapping explosion risks associated with indexed fields [7]. To optimize storage, consider the following: * If disk space is a concern, do not disable_source(which would break reindexing and update capabilities), but rather useindex.mapping.source.mode: "synthetic"to reconstruct the source on the fly, or increase the index compression level [7]. * Avoid mapping these large blobs as specific types (liketextorkeyword) unless you explicitly need to search them [8]. If you only need to store them for retrieval, they can exist in the document without an explicit mapping, keeping the cluster state clean [8].Citations:
- 1: https://www.elastic.co/docs/reference/elasticsearch/mapping-reference/keyword
- 2: https://www.elastic.co/docs/reference/elasticsearch/mapping-reference/ignore-above
- 3: http://www.elasticsearch.com/docs/reference/elasticsearch/mapping-reference/keyword
- 4: https://www.elastic.co/guide/en/elasticsearch/reference/8.19/ignore-above.html
- 5: elastic/elasticsearch#57307
- 6: https://www.elastic.co/guide/en/elasticsearch/reference/8.19/mapping-store.html
- 7: https://www.elastic.co/guide/en/elasticsearch/reference/8.16/mapping-source-field.html
- 8: https://jsonic.io/guides/json-in-elasticsearch
Stop indexing
chunk_metadata_kwdas akeywordwhen it can contain arbitrary/large JSON strings.Elasticsearch/Lucene enforces an absolute 32,766 UTF-8 byte limit for indexed terms; without an
ignore_aboveguard (not present in the mapping shown), oversized values can cause the write to fail. If the field is retrieval-only, setindex: false(keepstore: true), or add anignore_abovethreshold to prevent indexing when the value is too large.⚙️ Suggested mapping adjustment
"chunk_metadata_kwd": { "type": "keyword", - "store": true + "store": true, + "index": false }📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements."chunk_metadata_kwd": { "type": "keyword", "store": true, "index": 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 `@conf/mapping.json` around lines 23 - 25, The mapping for the field chunk_metadata_kwd is currently typed as "keyword" and will attempt to index arbitrarily large JSON strings; update the mapping for chunk_metadata_kwd to make it retrieval-only by setting "index": false while keeping "store": true, or if you must index short values add an "ignore_above" threshold (e.g. 32766) to the keyword definition to prevent indexing oversized terms; locate the chunk_metadata_kwd entry in the mapping.json and replace or augment its properties accordingly.rag/llm/chat_model.py (1)
1506-1510:
⚠️ Potential issue | 🟠 Major | ⚡ Quick win
Base._verbose_tool_usenot updated for Exception handling.
LiteLLMBase._verbose_tool_usenow convertsExceptionresults to strings for JSON serialization, but the equivalent method inBase(line 296-297) was not updated. When a tool call fails, theerr(an Exception object) is passed to_verbose_tool_use(e.g., line 411:err if err else result), which will causejson.dumpsto fail in theBaseclass.Proposed fix for Base._verbose_tool_use
def _verbose_tool_use(self, name, args, res): - return "<tool_call>" + json.dumps({"name": name, "args": args, "result": res}, ensure_ascii=False, indent=2) + "</tool_call>" + return "<tool_call>" + json.dumps( + {"name": name, "args": args, "result": str(res) if isinstance(res, Exception) else res}, + ensure_ascii=False, + indent=2, + ) + "</tool_call>"📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.def _verbose_tool_use(self, name, args, res): return "<tool_call>" + json.dumps( {"name": name, "args": args, "result": str(res) if isinstance(res, Exception) else res}, ensure_ascii=False, indent=2, ) + "</tool_call>"🤖 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 `@rag/llm/chat_model.py` around lines 1506 - 1510, The Base._verbose_tool_use method wasn't updated to handle Exception objects during JSON serialization like LiteLLMBase._verbose_tool_use; update Base._verbose_tool_use to convert Exception results to strings before json.dumps (e.g., use the same pattern: use str(res) if isinstance(res, Exception) else res) so when callers pass err (the Exception) via the tool call site (the code using "err if err else result") the JSON encoding won't fail; ensure the log format and ensure_ascii/indent behavior mirrors LiteLLMBase._verbose_tool_use.rag/utils/infinity_conn.py (1)
451-456:
⚠️ Potential issue | 🟠 Major | ⚡ Quick win
chunk_metadata_kwdserialization branch is dead code due earlierfield_keyword()match.This block never runs because
chunk_metadata_kwdis already handled byelif self.field_keyword(k)above. That prevents the intended dict→JSON serialization here and also keepschunk_metadata_kwdin keyword-list semantics, which can break round-trip metadata shape.🛠️ Targeted fix direction
def field_keyword(field_name: str): - if field_name == "source_id" or ( + if field_name == "source_id" or ( field_name.endswith("_kwd") and field_name not in ["knowledge_graph_kwd", "docnm_kwd", "important_kwd", - "question_kwd"]): + "question_kwd", "chunk_metadata_kwd"]): return True- elif self.field_keyword(k): + elif k == "chunk_metadata_kwd": + if isinstance(v, dict): + d[k] = json.dumps(v, ensure_ascii=False) + else: + d[k] = v if v else "" + elif self.field_keyword(k): if isinstance(v, list): d[k] = "###".join(v) else: d[k] = v🤖 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 `@rag/utils/infinity_conn.py` around lines 451 - 456, The branch that serializes chunk_metadata_kwd to JSON never runs because self.field_keyword(k) matches first; update the logic so chunk_metadata_kwd is handled explicitly before keyword matching (or alter the field_keyword handling to skip/avoid matching "chunk_metadata_kwd"), ensuring that in the function where d, k, v are processed the chunk_metadata_kwd branch runs and dict values are json.dumps(..., ensure_ascii=False) while empty/non-dict values become ""; keep the rest of keyword handling unchanged.
There was a problem hiding this comment.
🧹 Nitpick comments (2)
api/apps/restful_apis/chunk_api.py (2)
457-466: 💤 Low valueDRY: Inline deserialization duplicates
_deserialize_chunk_metadatalogic.This block replicates the same parsing logic from lines 146-158. Consider extracting a pure helper function that both paths can share:
♻️ Suggested refactor
Extract a pure parsing function:
def _parse_chunk_metadata(raw) -> dict: """Parse chunk_metadata_kwd value into a dict, returning {} on failure.""" if isinstance(raw, str) and raw: try: return json.loads(raw) except (json.JSONDecodeError, ValueError): return {} elif isinstance(raw, dict): return raw return {}Then use it in both places:
_deserialize_chunk_metadata:chunk["chunk_metadata"] = _parse_chunk_metadata(raw)- Search results loop:
chunk_metadata = _parse_chunk_metadata(raw_meta)🤖 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 457 - 466, The parsing logic for chunk metadata is duplicated; extract a pure helper (e.g., _parse_chunk_metadata(raw) -> dict) that implements the JSON-or-dict-with-fallback behavior and return {} on error, then replace the duplicated code in _deserialize_chunk_metadata and the search results loop (where raw_meta is read and assigned to chunk_metadata) to call this helper instead.
146-158: ⚡ Quick winConsider logging a warning when deserialization fails.
When
json.loads()fails (line 151-152), the code silently falls back to an empty dict. This defensive behavior is good, but silent failures can mask data corruption issues in production.🔧 Suggested fix
def _deserialize_chunk_metadata(chunk): raw = chunk.get("chunk_metadata_kwd") if isinstance(raw, str) and raw: try: chunk["chunk_metadata"] = json.loads(raw) except (json.JSONDecodeError, ValueError): + logging.warning("Failed to deserialize chunk_metadata_kwd: %r", raw[:200] if len(raw) > 200 else raw) chunk["chunk_metadata"] = {} elif isinstance(raw, dict): chunk["chunk_metadata"] = raw else: chunk["chunk_metadata"] = {} chunk.pop("chunk_metadata_kwd", None)As per coding guidelines: "Add logging for new flows" applies to
**/*.pyfiles.🤖 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 146 - 158, The _deserialize_chunk_metadata function currently swallows JSON decode errors and silently sets chunk["chunk_metadata"] = {}, so update it to log a warning when json.loads(raw) fails: inside the except block for json.JSONDecodeError/ValueError, call the module logger (e.g., logger.warning(...)) and include identifying context such as the chunk (or chunk.get("id")/chunk key), the raw value (or a truncated snippet) and the caught exception message, then continue to set chunk["chunk_metadata"] = {} and pop "chunk_metadata_kwd" as before; ensure a module-level logger is used or created if absent.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.
Nitpick comments:
In `@api/apps/restful_apis/chunk_api.py`:
- Around line 457-466: The parsing logic for chunk metadata is duplicated;
extract a pure helper (e.g., _parse_chunk_metadata(raw) -> dict) that implements
the JSON-or-dict-with-fallback behavior and return {} on error, then replace the
duplicated code in _deserialize_chunk_metadata and the search results loop
(where raw_meta is read and assigned to chunk_metadata) to call this helper
instead.
- Around line 146-158: The _deserialize_chunk_metadata function currently
swallows JSON decode errors and silently sets chunk["chunk_metadata"] = {}, so
update it to log a warning when json.loads(raw) fails: inside the except block
for json.JSONDecodeError/ValueError, call the module logger (e.g.,
logger.warning(...)) and include identifying context such as the chunk (or
chunk.get("id")/chunk key), the raw value (or a truncated snippet) and the
caught exception message, then continue to set chunk["chunk_metadata"] = {} and
pop "chunk_metadata_kwd" as before; ensure a module-level logger is used or
created if absent.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 0f711846-c924-4088-9da1-3ec7ea27ae03
📒 Files selected for processing (4)
api/apps/restful_apis/chunk_api.pyconf/infinity_mapping.jsonconf/mapping.jsondocs/guides/agent/agent_quickstarts/sandbox_quickstart.md
💤 Files with no reviewable changes (1)
- docs/guides/agent/agent_quickstarts/sandbox_quickstart.md
🚧 Files skipped from review as they are similar to previous changes (2)
- conf/mapping.json
- conf/infinity_mapping.json
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
rag/utils/infinity_conn.py (1)
454-459:⚠️ Potential issue | 🟡 Minor | ⚡ Quick winAdd logging for the new chunk_metadata_kwd serialization flow.
The coding guidelines require logging for new flows in
rag/**/*.py. This new serialization path forchunk_metadata_kwdlacks logging for cases where the value is unexpectedly not a dict or when serialization might fail. While the API layer validates inputs, this defensive branch may be reached by non-API callers (background jobs, migrations), and observability would help diagnose issues.As per coding guidelines, add logging for new flows.
📊 Suggested logging addition
elif k == "chunk_metadata_kwd": # chunk_metadata_kwd is a varchar column; serialize dicts to JSON. if isinstance(v, dict): + self.logger.debug(f"Serializing chunk_metadata_kwd as JSON for chunk {d.get('id', 'unknown')}") d[k] = json.dumps(v, ensure_ascii=False) else: + if v and not isinstance(v, str): + self.logger.warning(f"chunk_metadata_kwd has unexpected type {type(v).__name__} for chunk {d.get('id', 'unknown')}; using as-is") d[k] = v if v else ""🤖 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 `@rag/utils/infinity_conn.py` around lines 454 - 459, Add defensive logging around the new chunk_metadata_kwd serialization: in rag/utils/infinity_conn.py update the branch that handles "chunk_metadata_kwd" so that if v is not a dict you log a warning with the key name and the unexpected value, and when serializing (json.dumps) wrap it in try/except to catch and log exceptions (including the exception message and the offending value) before falling back to the existing d[k] = "" or d[k] = v behavior; use the module logger (e.g. logging.getLogger(__name__) or the existing logger variable) and include identifying context (key name "chunk_metadata_kwd" and the value) in the logs.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.
Outside diff comments:
In `@rag/utils/infinity_conn.py`:
- Around line 454-459: Add defensive logging around the new chunk_metadata_kwd
serialization: in rag/utils/infinity_conn.py update the branch that handles
"chunk_metadata_kwd" so that if v is not a dict you log a warning with the key
name and the unexpected value, and when serializing (json.dumps) wrap it in
try/except to catch and log exceptions (including the exception message and the
offending value) before falling back to the existing d[k] = "" or d[k] = v
behavior; use the module logger (e.g. logging.getLogger(__name__) or the
existing logger variable) and include identifying context (key name
"chunk_metadata_kwd" and the value) in the logs.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 3e3c9255-858c-4d52-8992-f1eda16afe4e
📒 Files selected for processing (3)
api/apps/restful_apis/chunk_api.pyconf/mapping.jsonrag/utils/infinity_conn.py
🚧 Files skipped from review as they are similar to previous changes (2)
- conf/mapping.json
- api/apps/restful_apis/chunk_api.py
…conn branch, set index:false on chunk_metadata_kwd (infiniflow#15725)
…onn (infiniflow#15725) Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
77d4a91 to
b782b37
Compare
|
Appreciations! |
|
Hi,@KevinHuSh. |
|
@dale053 would you please resolve the conflicts? |
What problem does this PR solve?
Closes #15725.
Currently, metadata in RAGFlow only exists at the document level. This forces developers who need structural or contextual information attached to individual chunks to resort to workarounds such as over-applying parent-child chunking strategies. There is no first-class way to store arbitrary key-value metadata alongside a specific chunk and have it persist through the storage and retrieval cycle.
This PR introduces a
chunk_metadatafield — a free-form JSON dictionary — that can be set per chunk at creation or update time, is stored in the document store (Elasticsearch / Infinity), and is returned in all chunk retrieval responses.Type of change
Changes
conf/mapping.jsonchunk_metadata_kwdas an explicitkeywordproperty in the Elasticsearch index schemaconf/infinity_mapping.jsonchunk_metadata_kwdas avarcharcolumn in the Infinity schemaapi/apps/restful_apis/chunk_api.pychunk_metadatato the Pydantic model; wired read/write/deserialize logic inadd_chunk,update_chunk,list_chunks, andget_chunkrag/utils/infinity_conn.pychunk_metadata_kwdon the Infinity write path (dict → JSON string), consistent with the existingextrafield patternsdk/python/ragflow_sdk/modules/chunk.pychunk_metadata = {}so the field survives the SDK key-filterweb/src/interfaces/database/dataset.tschunk_metadata?: Record<string, unknown>to theIChunkTypeScript interfaceAPI
Create a chunk with metadata
Update chunk metadata
Response — chunk with metadata
{ "id": "abc123", "content": "Alice founded the company in 2012.", "chunk_metadata": { "author": "Alice", "section": "introduction", "reviewed": true, "priority": 1 }, ... }Screen Shot