Repository navigation
Feat: add modality_kwd to chunks and audio timestamp segmentation (#1… - #15766
enjoyandlove wants to merge 189 commits into
Conversation
### What problem does this PR solve? implement ASR and TTS for Xinference ### Type of change - [x] New Feature (non-breaking change which adds functionality) - [x] Refactoring
### What problem does this PR solve? 1. update python version to 3.13 2. upgrade ormsgpack to 1.6.0 ### Type of change - [x] Refactoring --------- Signed-off-by: Jin Hai <[email protected]>
…a different event loop (infiniflow#15100) Fix: <asyncio.locks.Semaphore object at 0xabcd [locked]> is bound to a different event loop
### 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]>
Feature: Add MiniMax M3
add the newanthropic and voyage models. Strip opus 4.7 and 4.8 of certain usnspported keys Co-authored-by: Idriss Sbaaoui <[email protected]>
### What problem does this PR solve? Fix: - Handle siliconflow and siliconflow_intl api_key ### Type of change - [x] Bug Fix (non-breaking change which fixes an issue)
…iflow#15475) ### What problem does this PR solve? **Verified from PostMan** GET http://127.0.0.1:9384/api/v1/providers/gitee/connection ```json body: { "api_key": "XXXXXXXXXXXXXXXXXXXXXXXXXXXX", "region": "default" } resp: { "code": 0, "message": "success" } ``` GET http://127.0.0.1:9384/api/v1/providers/gitee/connection ```json body: { "api_key": "XXXXXXXXXXXXXXXXXXXXXXXXXXXX", "region": "deprecated" } resp: { "code": 0, "message": "success" } ``` GET http://127.0.0.1:9384/api/v1/providers/gitee/connection ```json body: { "api_key": "XXXXXXXXXXXXXXXXXXXXXXXXXXXX", "region": "china" } resp: { "code": 0, "message": "success" } ``` GET http://127.0.0.1:9384/api/v1/providers/lmstudio/connection ```json body: { "api_key": "", "region": "test" } resp: { "code": 0, "message": "success" } ``` ### Type of change - [x] New Feature (non-breaking change which adds functionality)
…ow#15512) ### What problem does this PR solve? As title, all test are passed ### Type of change - [x] New Feature (non-breaking change which adds functionality)
## Summary - add CLI command `CHECK PROVIDER 'provider_name' REGION 'region_name' KEY 'api_key';` - route the command through CLI parser and command dispatcher - call `GET /api/v1/providers/:provider_name/connection` with `region` and `api_key` ## Testing - `go test ./internal/cli/...` - manually verified CLI command parsing and request flow
Fix: model provider orders
…hunks (infiniflow#15488) ## Problem When uploading `.md` files with `parser=naive` and `delimiter="\n"`, markdown headers (e.g., `## Quick Travel`) become separate chunks with very short content (16-18 characters). This causes retrieval issues: when the header is matched, the corresponding body text is not included in the chunk. ## Related Issues Closes infiniflow#15487 ## Checklist - [x] Code changes are minimal and focused - [x] Unit tests added (12/12 passed) - [x] No breaking changes
…w#15366) Fixes [infiniflow#15365](infiniflow#15365) — `get_document_image()` and document preview call `make_response(None)` when storage returns no bytes, causing HTTP 500.
### What problem does this PR solve? Closes infiniflow#15388. Chat completion routes did not reliably honor per-request generation settings: - `/api/v1/chat/completions` copied generation settings with a truthiness check, so valid zero values such as `temperature: 0`, `top_p: 0`, `frequency_penalty: 0`, `presence_penalty: 0`, and `max_tokens: 0` were dropped. - `/api/v1/openai/{chat_id}/chat/completions` did not forward standard generation settings into the request-specific dialog LLM settings before calling `async_chat`. This PR preserves explicitly supplied generation parameters, including zero values, and merges request-level overrides into existing dialog settings where appropriate. The supported generation parameter keys and merge behavior live in a shared REST API helper to keep both completion routes aligned. Validation: - `git diff --check` - `python3 -m py_compile api/apps/restful_apis/_generation_params.py api/apps/restful_apis/chat_api.py api/apps/restful_apis/openai_api.py test/testcases/test_http_api/test_session_management/test_session_sdk_routes_unit.py` - `uv run ruff check api/apps/restful_apis/_generation_params.py api/apps/restful_apis/chat_api.py api/apps/restful_apis/openai_api.py test/testcases/test_http_api/test_session_management/test_session_sdk_routes_unit.py` - `ZHIPU_AI_API_KEY=dummy uv run pytest test/testcases/test_http_api/test_session_management/test_session_sdk_routes_unit.py -q -k generation_params` ### Type of change - [x] Bug Fix (non-breaking change which fixes an issue)
### What problem does this PR solve? refine mysql migration version workflow ### Type of change - [x] Refactoring
…issue (infiniflow#15520) ### What problem does this PR solve? Fix: Model provider add verify and fixed form in modal not resetting issue ### Type of change - [x] Bug Fix (non-breaking change which fixes an issue)
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (1)
📝 WalkthroughWalkthroughAudio parsing tags documents with ChangesMultimodal Chunk Pipeline: Audio Tagging and Modality Inference
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 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 |
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (2)
rag/svr/task_executor_refactor/embedding_utils.py (1)
153-156: ⚡ Quick winCheck
knowledge_graph_kwdbefore inferring"table"from HTML.Right now any chunk whose
content_with_weightcontains table markup is retyped as"table", even inrag/**where graph-based entities/relations/reports are supposed to stay distinguishable viaknowledge_graph_kwd. That heuristic can blur graph chunks into the table modality just because of their rendering.As per coding guidelines, "Use knowledge_graph_kwd to differentiate graph-based chunks (entities/relations/reports) from regular text chunks".
🤖 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/svr/task_executor_refactor/embedding_utils.py` around lines 153 - 156, The current heuristic unconditionally returns "table" whenever content_with_weight contains table HTML; change it to first check for the presence of knowledge_graph_kwd (or the graph-specific marker) and, if that marker is present, preserve/return the graph modality (e.g., "text" or the existing graph type) instead of "table". Locate the block that does re.search(r"</?(?:table|tr|td|th)\b", content) in embedding_utils and add a guard that inspects knowledge_graph_kwd (or the chunk's graph flag) so table-detection only overrides modality when the chunk is not graph-based.Source: Coding guidelines
rag/app/audio.py (1)
55-66: ⚡ Quick winAdd a log for the segment-aware transcription branch.
This is a new ingestion flow with an early return, but it never records whether segment mode was used or how many timestamped chunks were emitted. That will make audio parsing regressions much harder to trace in production.
As per coding guidelines, "Add logging for new flows".
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@rag/app/audio.py` around lines 55 - 66, The segment-aware transcription branch (the isinstance(ans, list) ... early-return block) lacks logging; update it to emit a structured log when that branch is taken indicating segment mode is active and how many timestamped chunks were produced (use the same logger used elsewhere in rag/app/audio.py), e.g., log before returning with the count of chunks and any identifying context (e.g., doc or audio id). Ensure the log call is placed after chunks is populated and before the return so callers can trace that tokenize was run for each seg and seg_doc was created.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 `@rag/app/audio.py`:
- Around line 58-68: The guard misses the case where ans is an empty list
(silence), causing str(ans) -> "[]" to be tokenized; update the logic handling
ans in the function that processes transcription results so that when ans is a
list and empty you treat it as no-transcript (e.g., return an empty chunks list
or skip tokenization) rather than falling through to the string fallback.
Specifically, in the block around the variables ans, chunks, seg, seg_doc and
the calls to tokenize(), add an explicit branch for "if isinstance(ans, list)
and not ans" that returns [] (or otherwise avoids tokenizing "[]") before the
existing list-vs-string handling.
In `@rag/svr/task_executor_refactor/embedding_utils.py`:
- Around line 133-155: The _infer_modality logic currently prefers parser
metadata but _DOC_TYPE_TO_MODALITY lacks a mapping for parser-stamped tables, so
doc_type_kwd="table" falls through to the regex and can be mis-classified;
update the _DOC_TYPE_TO_MODALITY dict to include "table":"table" (so
_infer_modality will return the parser-provided modality immediately) and keep
the existing HTML-table regex as the secondary heuristic in the _infer_modality
method.
---
Nitpick comments:
In `@rag/app/audio.py`:
- Around line 55-66: The segment-aware transcription branch (the isinstance(ans,
list) ... early-return block) lacks logging; update it to emit a structured log
when that branch is taken indicating segment mode is active and how many
timestamped chunks were produced (use the same logger used elsewhere in
rag/app/audio.py), e.g., log before returning with the count of chunks and any
identifying context (e.g., doc or audio id). Ensure the log call is placed after
chunks is populated and before the return so callers can trace that tokenize was
run for each seg and seg_doc was created.
In `@rag/svr/task_executor_refactor/embedding_utils.py`:
- Around line 153-156: The current heuristic unconditionally returns "table"
whenever content_with_weight contains table HTML; change it to first check for
the presence of knowledge_graph_kwd (or the graph-specific marker) and, if that
marker is present, preserve/return the graph modality (e.g., "text" or the
existing graph type) instead of "table". Locate the block that does
re.search(r"</?(?:table|tr|td|th)\b", content) in embedding_utils and add a
guard that inspects knowledge_graph_kwd (or the chunk's graph flag) so
table-detection only overrides modality when the chunk is not graph-based.
🪄 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: c5bdb13d-e094-4f3c-9644-5f1d6b239e4e
📒 Files selected for processing (2)
rag/app/audio.pyrag/svr/task_executor_refactor/embedding_utils.py
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (3)
test/unit_test/rag/svr/task_executor_refactor/test_embedding_utils.py (3)
279-298: ⚡ Quick winConsider adding integration test for modality stamping in attach_vectors.
The
attach_vectorsmethod stampsmodality_kwdonto chunks when the field is absent by calling_infer_modality, which is a key integration point between modality inference and the embedding pipeline. The existingTestEmbeddingUtilsAttachVectorsclass (lines 188-222) doesn't verify this modality stamping behavior. Consider adding a test case there to ensureattach_vectorscorrectly populatesmodality_kwdbased ondoc_type_kwd.🧪 Suggested integration test
Add to the existing
TestEmbeddingUtilsAttachVectorsclass:def test_attach_vectors_stamps_modality_kwd(self): """Test that attach_vectors stamps modality_kwd when absent.""" docs = [ {"id": 1, "doc_type_kwd": "audio", "content_with_weight": "transcript"}, {"id": 2, "content_with_weight": "plain text"}, {"id": 3, "modality_kwd": "image", "content_with_weight": "existing"}, ] vectors = np.array([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]]) EmbeddingUtils.attach_vectors(docs, vectors) assert docs[0]["modality_kwd"] == "audio" assert docs[1]["modality_kwd"] == "text" assert docs[2]["modality_kwd"] == "image" # Should preserve existing🤖 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/svr/task_executor_refactor/test_embedding_utils.py` around lines 279 - 298, Add an integration test inside the TestEmbeddingUtilsAttachVectors test class that verifies EmbeddingUtils.attach_vectors stamps modality_kwd when the field is missing by calling _infer_modality: create docs with (1) a doc having doc_type_kwd "audio" and no modality_kwd, (2) a doc with only content_with_weight expecting default "text", and (3) a doc already containing modality_kwd "image"; call EmbeddingUtils.attach_vectors(docs, vectors) with a matching numpy vectors array and assert that docs[0]["modality_kwd"] == "audio", docs[1]["modality_kwd"] == "text", and docs[2]["modality_kwd"] remains "image".
279-298: ⚡ Quick winExtend test coverage to include image and video modalities.
The
_DOC_TYPE_TO_MODALITYmapping includes"image","video","audio", and"table", but the current tests only verify"audio"and"table". Consider adding tests for"image"and"video"to ensure complete coverage of the mapping.🧪 Suggested additional test cases
def test_infer_modality_from_doc_type_image(self): """Image chunks stamped by picture parser retain image modality.""" doc = {"doc_type_kwd": "image", "content_with_weight": "image description"} assert EmbeddingUtils._infer_modality(doc) == "image" def test_infer_modality_from_doc_type_video(self): """Video chunks stamped by picture parser retain video modality.""" doc = {"doc_type_kwd": "video", "content_with_weight": "video description"} assert EmbeddingUtils._infer_modality(doc) == "video"🤖 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/svr/task_executor_refactor/test_embedding_utils.py` around lines 279 - 298, Add two unit tests to cover the remaining modalities by asserting EmbeddingUtils._infer_modality returns "image" and "video" when doc["doc_type_kwd"] is "image" and "video" respectively; create tests named like test_infer_modality_from_doc_type_image and test_infer_modality_from_doc_type_video, each passing a doc dict with "doc_type_kwd" set to the modality and a simple "content_with_weight" value, and assert the returned modality equals the expected string.
287-289: 💤 Low valueAdd descriptive docstrings to remaining test methods for consistency.
The test at lines 282-285 includes a detailed docstring explaining the test scenario, but tests at lines 287-289 and 291-297 have minimal or no docstrings. For consistency and maintainability, consider adding descriptive docstrings to all test methods.
📝 Suggested docstrings
def test_infer_modality_from_doc_type_audio(self): + """Audio chunks stamped by audio parser retain audio modality.""" doc = {"doc_type_kwd": "audio", "content_with_weight": "transcript"} assert EmbeddingUtils._infer_modality(doc) == "audio" def test_infer_modality_from_html_table_markup(self): + """Chunks with HTML table markup are inferred as table modality.""" doc = {"content_with_weight": "<table><tr><td>Cell</td></tr></table>"} assert EmbeddingUtils._infer_modality(doc) == "table" def test_infer_modality_defaults_to_text(self): + """Chunks without modality signals default to text modality.""" doc = {"content_with_weight": "plain text"} assert EmbeddingUtils._infer_modality(doc) == "text"🤖 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/svr/task_executor_refactor/test_embedding_utils.py` around lines 287 - 289, Add a concise descriptive docstring to the test method test_infer_modality_from_doc_type_audio (and the nearby test_infer_modality_from_* tests) that explains the scenario being tested and the expected outcome — e.g., "Verify that _infer_modality returns 'audio' when doc_type_kwd is 'audio' and content_with_weight contains a transcript." Locate these tests by their function names (test_infer_modality_from_doc_type_audio and the other test_infer_modality_from_* helpers) and insert one-line or short multi-line docstrings above each test to match the detailed style used elsewhere in the file.
🤖 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 `@test/unit_test/rag/svr/task_executor_refactor/test_embedding_utils.py`:
- Around line 279-298: The tests in class TestEmbeddingUtilsInferModality
(test_infer_modality_from_doc_type_table,
test_infer_modality_from_doc_type_audio,
test_infer_modality_from_html_table_markup,
test_infer_modality_defaults_to_text) need pytest priority markers; add an
import for pytest if missing and annotate each test (or the whole
TestEmbeddingUtilsInferModality class) with the appropriate priority marker
(e.g., `@pytest.mark.p1` since these cover a critical path used by attach_vectors)
so the test runner picks up their priority.
---
Nitpick comments:
In `@test/unit_test/rag/svr/task_executor_refactor/test_embedding_utils.py`:
- Around line 279-298: Add an integration test inside the
TestEmbeddingUtilsAttachVectors test class that verifies
EmbeddingUtils.attach_vectors stamps modality_kwd when the field is missing by
calling _infer_modality: create docs with (1) a doc having doc_type_kwd "audio"
and no modality_kwd, (2) a doc with only content_with_weight expecting default
"text", and (3) a doc already containing modality_kwd "image"; call
EmbeddingUtils.attach_vectors(docs, vectors) with a matching numpy vectors array
and assert that docs[0]["modality_kwd"] == "audio", docs[1]["modality_kwd"] ==
"text", and docs[2]["modality_kwd"] remains "image".
- Around line 279-298: Add two unit tests to cover the remaining modalities by
asserting EmbeddingUtils._infer_modality returns "image" and "video" when
doc["doc_type_kwd"] is "image" and "video" respectively; create tests named like
test_infer_modality_from_doc_type_image and
test_infer_modality_from_doc_type_video, each passing a doc dict with
"doc_type_kwd" set to the modality and a simple "content_with_weight" value, and
assert the returned modality equals the expected string.
- Around line 287-289: Add a concise descriptive docstring to the test method
test_infer_modality_from_doc_type_audio (and the nearby
test_infer_modality_from_* tests) that explains the scenario being tested and
the expected outcome — e.g., "Verify that _infer_modality returns 'audio' when
doc_type_kwd is 'audio' and content_with_weight contains a transcript." Locate
these tests by their function names (test_infer_modality_from_doc_type_audio and
the other test_infer_modality_from_* helpers) and insert one-line or short
multi-line docstrings above each test to match the detailed style used elsewhere
in the file.
🪄 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: 7144c955-d0df-4fc4-aacf-0af5cff32034
📒 Files selected for processing (3)
rag/app/audio.pyrag/svr/task_executor_refactor/embedding_utils.pytest/unit_test/rag/svr/task_executor_refactor/test_embedding_utils.py
🚧 Files skipped from review as they are similar to previous changes (2)
- rag/app/audio.py
- rag/svr/task_executor_refactor/embedding_utils.py
|
Hi,@yingfeng! |
Review findingsThanks for the PR. The core logic is sound and the production path is correctly wired ( 1. Blocker for Infinity-backed deployments — new fields missing from the index schema
Must-fix before merge: add to "modality_kwd": {"type": "varchar", "default": ""},
"audio_start_flt": {"type": "float", "default": 0.0},
"audio_end_flt": {"type": "float", "default": 0.0}(Optionally also declare 2. Improvement — no test coverage for the audio segmentation change 3. Nit — HTML table heuristic can misclassify plain text Also note for the description: existing already-indexed chunks won't carry |
|
pls fix conflict |
|
@enjoyandlove Please re-open this PR and rebase to latest main (for golang) or 0.27.x (for python) if you still working on this PR. Close it for now. |
What problem does this PR solve?
Closes #15761
RAGFlow's audio parser produced chunks with no modality marker, making audio
indistinguishable from plain text in the document store. The picture parser
already set
doc_type_kwdto"image"/"video", but the audio parser setnothing. Additionally, no chunk in the system carried a unified
modality_kwdfield, so downstream retrieval and filtering had no reliable way to identify
content type (text, image, table, audio, video).
This PR lays the core backend foundation for issue #15761 by:
doc_type_kwd = "audio"on every audio chunk.audio_start_flt/audio_end_flt) whena Whisper-compatible model returns structured
[{start, end, text}]output.modality_kwd(text / image / video / audio / table)onto every chunk at embedding time via
EmbeddingUtils.attach_vectors, usingdoc_type_kwdset by parsers and HTML table markup detection as signals.Existing text-only knowledge bases are unaffected — the modality field is
additive and defaults to
"text".Type of change