Repository navigation
fix(llm): guard GoogleCV (Google Vertex vision) key against non-JSON / JSON non-object - #17464
Harsh23Kashyap wants to merge 1396 commits into
Conversation
…infiniflow#17081) ### Summary Fix: model provider save button label and light mode input background Co-authored-by: Wang Qi <[email protected]>
### Summary Move stats to a specific service from system --------- Signed-off-by: Jin Hai <[email protected]>
### Summary ``` RAGFlow(admin)> STATS USERS TOP 5 FROM '2026-01-01' TO '2026-02-01'; +-----------------------+----------------------------------------------+------------+---------------------+-----+ | command | error | from_date | to_date | top | +-----------------------+----------------------------------------------+------------+---------------------+-----+ | get_token_users_stats | 'Get API token users stats' is not supported | 2026-01-01 | 2026-02-01 23:59:59 | 5 | +-----------------------+----------------------------------------------+------------+---------------------+-----+ RAGFlow(admin)> STATS USER '[email protected]' FROM '2026-01-01' TO '2026-02-01' MONTH; +-----------------+----------------------------------------+------------+-------------+---------------------+-------------+ | command | error | from_date | granularity | to_date | user_name | +-----------------+----------------------------------------+------------+-------------+---------------------+-------------+ | get_token_stats | 'Get API token stats' is not supported | 2026-01-01 | month | 2026-02-01 23:59:59 | [email protected] | +-----------------+----------------------------------------+------------+-------------+---------------------+-------------+ RAGFlow(admin)> STATS SUMMARY FROM '2026-01-01' TO '2026-02-01' MONTH; +-----------+------------------------------------------------+ | field | value | +-----------+------------------------------------------------+ | to_date | 2026-02-01 23:59:59 | | command | get_token_stats_summary | | error | 'Get API token stats summary' is not supported | | from_date | 2026-01-01 | +-----------+------------------------------------------------+ ``` --------- Signed-off-by: Jin Hai <[email protected]>
### Summary Bump to infinity v0.7.2 Infinity image: infiniflow/infinity:v0.7.2-x64-v3
### Summary As title. Signed-off-by: Jin Hai <[email protected]>
As title. Signed-off-by: Jin Hai <[email protected]>
### Summary As title
## Summary - Enable synchronous and streaming tool calls for Aliyun models. - Preserve provider-specific chat endpoints and prevent repeated qwen-flash tool calls. - Restrict retrieval tool inputs to model-provided query parameters. ## Testing - `bash build.sh --test ./internal/entity/models ./internal/agent/component ./internal/agent/tool` - Manual frontend UI testing passed.
### Summary 1. fix the issue of ci failures under specific circumstances. 2. fix ci port allocated 3. modified unit_test file only run on python
### Summary 1. Fix docker/service_conf.yaml.template 2. Remove unused config --------- Signed-off-by: Jin Hai <[email protected]>
…7064) ### Summary `agent/tools/github.py` indexes `response["items"]` directly after `requests.get(...).json()`. the github search api returns `{"message": ...}` **without** an `items` key on realistic conditions — a rate limit (403/429; this tool sends no auth token, so the unauthenticated ~10 req/min search limit is easy to hit) or an invalid query (422). that raised `KeyError('items')`, which the tool's retry loop then surfaced to the model as the opaque `"GitHub error: 'items'"` instead of the real reason. this guards the missing key and raises the api's actual `message` (with a clear fallback) into the existing retry/`_ERROR` path, so the model sees e.g. `"GitHub error: API rate limit exceeded ..."`. valid responses are unchanged. adds `test/unit_test/agent/tools/test_github_unit.py` covering the rate-limit response (asserts the real message is surfaced, no `KeyError`) and the normal result path. Co-authored-by: Yaroslav98214 <[email protected]> Co-authored-by: Haruko386 <[email protected]>
### Summary Feat: Render the skills list using a tree view.
### Summary As title --------- Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
### Summary As title
…/1.8/2.6/2.7, Tokenizer 6x fixes) (infiniflow#17419) ## Summary Continuation of the Python→Go ingestion pipeline migration (File → Parser → Chunker → Extractor → Tokenizer). Fixes cover Parser, Chunker, and Tokenizer gaps identified. Fix page number (0-indexed and 1-index mixed before fix; use 1-indexed after fix) and chunk order issues. ### Parser - **Slides TCADP (1.7):** `pptx_tcadp.go` + TCADP branch in `pptx_parser.go`/`ppt_parser.go` — PowerPoint files now support `parse_method="tcadp"` via the TCADP cloud service, matching the spreadsheet-family TCADP pattern. PPT containers pass `"PPT"` as fileType (not hardcoded `"PPTX"`). - **Audio default output_format (2.11):** `defaultSetups()` audio default changed from `"text"` to `"json"`, aligning with Python `parser.py:232` and `AllowedOutputFormat["audio"]={"json"}`. - **PDF VLM enhancement (1.1):** `maybeDispatchPDFVisionEnhancement` in `pdf_vision_dispatch.go` enriches image/table items with IMAGE2TEXT model descriptions after PDF parsing, mirroring Python `enhance_media_sections_with_vision`. Semaphore fix: acquire before goroutine start to prevent unbounded goroutine creation. - **json family (2.3):** reclassified as Keep Go — `json_parser.go` is a functional enhancement, not a parity gap. - **page number:** changed from "mixed use of 1-indexed & 0-indexed" to "1-indexed" ### Chunker - **BULLET_PATTERN fallback (1.7):** 4th-level fallback in `resolveTitleLevels` (`title.go`) detects bullet/numbered-list patterns (Chinese legal, numbering, English) when outline + regex levels produce only bodyLevel. Guarded by `allBodyLevel` to never override existing structure. - **Tag/One chunker fields (1.8):** `tag.go` sets `TopInt` from source row index; `one.go` preserves `Positions`/`PDFPositions` from source items. TSV multi-line RowNum fix: tracks `contentStart` for correct row attribution. - **Overlapped_percent normalization (2.6):** `NormalizeOverlappedPercent` in `schema/chunker.go` mirrors Python `common/float_utils.py:50-58` — accepts `[0,1)` fraction or `[0,90]` percent, normalizes to canonical `[0,90]`. - **Paragraph splitting (2.7):** aligned to Python flow `naive_merge` — `CRLF` normalization, `splitKeepingDelimiter` preserves sentence delimiters, single-section merge with token-budget-governed chunking. - **chunk order:** sort by reading order ### Tokenizer - **Phantom chunk filtering (Omission 2):** `isPhantomChunk` + filter loop in `chunksFromTokenizerUpstream` skips zero-value ChunkDocs. - **Batch size env var (Omission 3):** `embeddingBatchSize()` reads `TOKENIZER_EMBEDDING_BATCH_SIZE`, defaults to 16. - **Summary empty check (Diff 5):** `TrimSpace(s) != ""` → `s != ""`, matching Python truthy check. - **chunk_order_int all paths (Diff 8):** set unconditionally before full_text/embedding branching. - **Timeout default (Diff 10):** `600s` → `60s`, matching Python `@timeout(60)`. - **Small maxTokens truncation (Diff 14):** `truncateForEmbedding` returns `""` when `maxTokens <= 10`, matching Python. ### Code review fixes - Semaphore acquire moved before goroutine in `pdf_vision_dispatch.go` (concurrency control) - Context propagation in `pptx_tcadp.go` (cancellation support) - Test resolver leak fix in `media_dispatch_test.go` (defer restore) - Migration history comments removed per AGENTS.md ## Test plan ``` bash build.sh --test ./internal/parser/parser/... ./internal/ingestion/component/... ``` ## Notes - Migration diff tracking: `docs/migration_python_go_diff.md` - Remaining gaps: Extractor component only (21 items)
…niflow#17463) The GoogleCV (Google Cloud Vertex vision) provider in rag/llm parses its API key as JSON to extract the service-account fields. The constructor had no try/except around the bare `json.loads(key)` call: # rag/llm/cv_model.py:1319 (GoogleCV.__init__) key = json.loads(key) access_token = json.loads(base64.b64decode(key.get("google_service_account_key", ""))) project_id = key.get("google_project_id", "") region = key.get("google_region", "") The Google Cloud Vertex provider REQUIRES a JSON object key (per the schema in api/apps/llm_app.py:291 and the test fixture in test/testcases/test_web_api/test_llm_app/test_llm_list_unit.py:635-640): { "google_project_id": "<project-id>", "google_region": "<region>", "google_service_account_key": "<base64-encoded-service-account-json>" } A user pasting a non-JSON string or a JSON non-object -- e.g. `"[1,2,3]"`, `"42"", `'"hello"'`, `"true"", `"null"` -- parses fine and then crashes on the `.get(...)` call with `AttributeError: 'list' object has no attribute 'get'` (or `'int'`, `'str'`, `'NoneType'`, `'bool'`) from inside rag/llm internals -- no indication of what the user did wrong. Fix: add `_resolve_google_service_account_key` to rag/llm/key_utils and wire `GoogleCV.__init__` through it. The helper: - Accepts a dict (returned verbatim) or a JSON-string-encoded dict (parsed and returned) with all three fields extracted (`google_project_id`, `google_region`, `google_service_account_key`). - On non-JSON input, on a JSON top-level type that is not a dict (list, string, number, bool, null), or on any other input type (None, int, list, ...), raises a clear `ModelException(retryable=False)` naming the required object shape and pointing at the schema in `api/apps/llm_app.py:291`. Unlike the Bedrock/BaiduYiyan/VolcEngine/OpenRouter helpers, the Google Vertex helper does NOT have a plain-string-key fallback -- the provider genuinely requires the full object. The pre-existing `access_token = json.loads(base64.b64decode(...))` line still crashes with JSONDecodeError if `google_service_account_key` is missing, matching the pre-fix behavior; that is a separate missing-field bug, intentionally left out of scope. The chat counterpart `GoogleChat` (rag/llm/chat_model.py:1284) has the same shape of bug but is owned by @glu000 (PR infiniflow#15994) actively working on that class. The chat-side fix is intentionally OUT OF SCOPE for this PR to avoid a conflicting change. After this PR, no remaining LLM-provider JSON-decode sites in rag/llm/ that we own crash with `AttributeError` on JSON non-object keys. The only remaining site is the chat-side GoogleChat (rag/llm/chat_model.py:1284), which is owned by @glu000 via infiniflow#15994. Fixes infiniflow#17463.
…w#17463) 19 p0 tests in test/unit_test/rag/llm/test_googlecv_json_key_fallback.py: - TestResolveGoogleServiceAccountKey (16 tests on the helper directly): Python dict passes through, JSON dict with all/missing/empty fields is tolerated, plain string raises ModelException (the provider requires a JSON object), empty string raises, malformed JSON raises, JSON top-level non-object types (array, string, number, float, null, bool) all raise a clear ModelException naming the type, non-string non-dict input raises. - TestGoogleCVCallSite (3 tests on the GoogleCV constructor): JSON array raises ModelException, JSON number raises ModelException, plain string raises ModelException. The Google SDK modules (google.oauth2.service_account, google.auth.transport.requests) are stubbed via sys.modules monkeypatch because GoogleCV.__init__ imports them lazily inside the function body. All 19 pass against the fix. The helper raises ModelException (retryable=False) on every non-JSON-object input with a message that names the required fields and points at the schema in api/apps/llm_app.py:291. Fixes infiniflow#17463.
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (2)
🚧 Files skipped from review as they are similar to previous changes (1)
📝 WalkthroughWalkthroughGoogle Vertex AI service-account keys now pass through a shared resolver. Invalid JSON, non-object JSON, and unsupported input types raise non-retryable ChangesGoogle service-account key validation
Estimated code review effort: 3 (Moderate) | ~20 minutes Possibly related issues
Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
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 |
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (2)
test/unit_test/rag/llm/test_googlecv_json_key_fallback.py (1)
242-333: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win
KEY_VALID_JSONis defined but unused.Neither
TestResolveGoogleServiceAccountKeynorTestGoogleCVCallSitereferencesKEY_VALID_JSON. Either use it in a happy-pathGoogleCVconstructor test (verifyingproject_id/region/access_tokenresolve correctly end-to-end — currently only failure paths are exercised through the constructor), or remove it.As per path instructions: "Remove dead tests, commented-out code, stale documentation, and 'move later' notes instead of preserving them."
🤖 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 `@test/unit_test/rag/llm/test_googlecv_json_key_fallback.py` around lines 242 - 333, Remove the unused KEY_VALID_JSON fixture from the test module, since neither TestResolveGoogleServiceAccountKey nor TestGoogleCVCallSite uses it and the current tests intentionally cover only failure paths.Source: Path instructions
rag/llm/key_utils.py (1)
65-94: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winConsider logging before raising in the new validation flow.
None of the three failure branches (malformed JSON, wrong input type, non-object JSON) emit a log line before raising
ModelException, making it harder to correlate provider misconfiguration with server logs.As per path instructions: "Add logging for new flows" (
**/*.py).🤖 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/key_utils.py` around lines 65 - 94, Update the validation branches in the key-parsing flow to log the provider misconfiguration immediately before raising ModelException: malformed JSON in the string parser, unsupported input types, and non-object JSON payloads. Use the module’s existing logging mechanism and include the relevant error context, while preserving the current exception messages and retryable=False behavior.Source: Path instructions
🤖 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 `@rag/llm/key_utils.py`:
- Around line 68-74: Update the JSON parsing exception handler around json.loads
in the key utility to bind the caught exception and raise ModelException with
explicit exception chaining using from exc. Preserve the existing error message
and retryable=False behavior.
In `@test/unit_test/rag/llm/test_googlecv_json_key_fallback.py`:
- Around line 116-122: The test_json_dict_missing_google_service_account_key
case currently duplicates the missing-region scenario. Update its input to
include google_project_id and google_region while omitting only
google_service_account_key, and assert that the resolver preserves those values
and returns an empty service-account key.
---
Nitpick comments:
In `@rag/llm/key_utils.py`:
- Around line 65-94: Update the validation branches in the key-parsing flow to
log the provider misconfiguration immediately before raising ModelException:
malformed JSON in the string parser, unsupported input types, and non-object
JSON payloads. Use the module’s existing logging mechanism and include the
relevant error context, while preserving the current exception messages and
retryable=False behavior.
In `@test/unit_test/rag/llm/test_googlecv_json_key_fallback.py`:
- Around line 242-333: Remove the unused KEY_VALID_JSON fixture from the test
module, since neither TestResolveGoogleServiceAccountKey nor
TestGoogleCVCallSite uses it and the current tests intentionally cover only
failure paths.
🪄 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 Plus
Run ID: 09f336b9-7840-4646-9e9c-44e1dcae4df0
📒 Files selected for processing (3)
rag/llm/cv_model.pyrag/llm/key_utils.pytest/unit_test/rag/llm/test_googlecv_json_key_fallback.py
Two follow-ups from the CodeRabbit review on the GoogleCV key
fallback PR:
1. rag/llm/key_utils.py: the `ModelException` raise inside the
`(json.JSONDecodeError, TypeError)` branch dropped the underlying
cause from the traceback. Added `from exc` to preserve the
chain. Static analysis correctly flags the missing chaining; pytest
-tb=long now shows both exception messages.
2. test/unit_test/rag/llm/test_googlecv_json_key_fallback.py: the
three "missing X" tests all shared the same body
(`{"google_project_id": "p"}` -> defaults for region and
service_account_key). The first two had the wrong name (one
claimed "missing project_id" but the input has project_id; the
other claimed "missing region" but the input has no region
either). Renamed all three to "with_only_X" and gave the third
test an input that actually has only google_service_account_key.
The set of three now covers the "each field can be set
independently, the other two default" contract end-to-end.
|
Opened #17464 for the same |
|
@tuankg1028 Would you please help review this PR? |
|
@Harsh23Kashyap would you please resolve the conflicts? |
Lynn-Inf
left a comment
There was a problem hiding this comment.
LGTM. Please also handle JSONDecodeError when decoding google_service_account_key.
Summary
Closes #17463. The
GoogleCV(Google Cloud Vertex vision) provider inrag/llm/parses its API key as JSON to extract the service-account fields. The constructor had no try/except around the barejson.loads(key)call:The Google Cloud Vertex provider REQUIRES a JSON object key (per the schema in
api/apps/llm_app.py:291and the test fixture intest/testcases/test_web_api/test_llm_app/test_llm_list_unit.py:635-640):{ "google_project_id": "<project-id>", "google_region": "<region>", "google_service_account_key": "<base64-encoded-service-account-json>" }A user pasting a non-JSON string or a JSON non-object — e.g.
"[1,2,3]","42",'"hi"',"true","null"— parses fine and then crashes on the subsequent.get(...)call withAttributeError: 'list' object has no attribute 'get'from insiderag/llminternals — no indication of what the user did wrong.This is the same class of bug PR #17215 fixed for Azure, PR #17377 fixed for Bedrock, PR #17390 fixed for BaiduYiyan, PR #17457 fixed for VolcEngine/Ark, and PR #17459 fixed for OpenRouter. After this PR, no remaining LLM-provider JSON-decode sites in
rag/llm/that we own crash withAttributeErroron JSON non-object keys.Changes
1 helper, 1 call site, 1 test file:
rag/llm/key_utils.py— add_resolve_google_service_account_key(key). Returns a dict{"google_project_id": str, "google_region": str, "google_service_account_key": str}.""if missing).ModelException(retryable=False)naming the required schema and pointing atapi/apps/llm_app.py:291. Unlike the Bedrock/BaiduYiyan/VolcEngine/OpenRouter helpers, this one does NOT have a plain-key fallback — the Google Vertex provider genuinely requires the full object.ModelException(retryable=False)naming the actual type and the required schema.ModelException.rag/llm/cv_model.py—GoogleCV.__init__calls the helper instead of the barejson.loads(key).get(...)calls.test/unit_test/rag/llm/test_googlecv_json_key_fallback.py— 19 p0 regression tests:GoogleCVconstructor (JSON array, JSON number, plain string). The Google SDK modules (google.oauth2.service_account,google.auth.transport.requests) are stubbed viasys.modulesmonkeypatch becauseGoogleCV.__init__imports them lazily inside the function body.Out of scope
GoogleChat(rag/llm/chat_model.py:1284-1289) has the same shape of bug, but PR fix(llm): implement async chat methods for GoogleChat (Vertex AI Gemini) #15994 is open by @glu000 actively working on that class. The chat-side JSON-decode fix is intentionally OUT OF SCOPE here to avoid a conflicting PR.rag/llm/embedding_model.py:1014) has the same shape — filed separately.access_token = json.loads(base64.b64decode(...))line still raisesJSONDecodeErrorifgoogle_service_account_keyis missing (matching the pre-fix behavior). That is a separate missing-field bug, intentionally out of scope.Behavior unchanged for the existing happy path
project_id,region, andaccess_tokenpopulate correctly (unchanged).""(unchanged from the pre-fixdict.get(k, "")calls).No public API change. No data-model change. No migration.
Testing
Cross-references
rag/llm/that we own crash withAttributeErroron JSON non-object keys. The only remaining site is the chat-sideGoogleChat(rag/llm/chat_model.py:1284), which is owned by @glu000 via fix(llm): implement async chat methods for GoogleChat (Vertex AI Gemini) #15994.