Skip to content

Feat: add modality_kwd to chunks and audio timestamp segmentation (#1… - #15766

Closed
enjoyandlove wants to merge 189 commits into
infiniflow:mainfrom
enjoyandlove:feat/unified-multimodal-chunk-pipeline
Closed

enjoyandlove wants to merge 189 commits into
infiniflow:mainfrom
enjoyandlove:feat/unified-multimodal-chunk-pipeline

Conversation

@enjoyandlove

Copy link
Copy Markdown
Contributor

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_kwd to "image" / "video", but the audio parser set
nothing. Additionally, no chunk in the system carried a unified modality_kwd
field, 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:

  • Stamping doc_type_kwd = "audio" on every audio chunk.
  • Preserving per-segment timestamps (audio_start_flt / audio_end_flt) when
    a Whisper-compatible model returns structured [{start, end, text}] output.
  • Inferring and writing modality_kwd (text / image / video / audio / table)
    onto every chunk at embedding time via EmbeddingUtils.attach_vectors, using
    doc_type_kwd set 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

  • Bug Fix (non-breaking change which fixes an issue)
  • New Feature (non-breaking change which adds functionality)
  • Documentation Update
  • Refactoring
  • Performance Improvement
  • Other (please describe):

Haruko386 and others added 30 commits May 21, 2026 18:28
### 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
### 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)
### 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]>
wangq8 and others added 13 commits June 2, 2026 17:28
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
…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)
@dosubot dosubot Bot added size:M This PR changes 30-99 lines, ignoring generated files. 💞 feature Feature request, pull request that fullfill a new feature. labels Jun 8, 2026
@coderabbitai

coderabbitai Bot commented Jun 8, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: b6c491c4-48ad-4af6-98d0-95277377eaf5

📥 Commits

Reviewing files that changed from the base of the PR and between 2f1e430 and 9edaf62.

📒 Files selected for processing (1)
  • test/unit_test/rag/svr/task_executor_refactor/test_embedding_utils.py

📝 Walkthrough

Walkthrough

Audio parsing tags documents with doc_type_kwd="audio" and converts Whisper-style timed segments into per-segment tokenized chunks with preserved start/end timestamps. EmbeddingUtils gains modality inference from doc_type_kwd or HTML table markers and stamps modality_kwd on chunks during vector attachment; tests verify inference and stamping.

Changes

Multimodal Chunk Pipeline: Audio Tagging and Modality Inference

Layer / File(s) Summary
Audio doc type tagging and Whisper segment-aware transcription
rag/app/audio.py
chunk sets doc_type_kwd="audio". If transcription returns a list of timed segments, the code creates per-segment tokenized chunks with audio_start_flt/audio_end_flt; otherwise it tokenizes the main doc using a stringified transcript fallback.
Modality inference and chunk stamping
rag/svr/task_executor_refactor/embedding_utils.py, test/unit_test/rag/svr/task_executor_refactor/test_embedding_utils.py
Adds EmbeddingUtils._DOC_TYPE_TO_MODALITY and _infer_modality to map doc_type_kwd to modalities, detect HTML table markup as "table", or default to "text". attach_vectors now sets chunk["modality_kwd"] when missing. Unit tests cover inference and stamping preservation.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Poem

🐰 I hopped through chunks both loud and small,
I tagged each tune and kept its call,
Segments stitched with timestamps bright,
Modality stamped just right,
A rabbit cheer — the pipeline sings! 🎶

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 55.56% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the primary changes: adding modality_kwd and audio timestamp segmentation, which align with the main objectives of the changeset.
Description check ✅ Passed The description follows the template structure with 'What problem does this PR solve?' and 'Type of change' sections, explaining the modality marker and timestamp preservation objectives clearly.
Linked Issues check ✅ Passed The PR addresses core backend objectives of #15761: stamping doc_type_kwd on audio, preserving audio timestamps, and inferring/writing modality_kwd on chunks via EmbeddingUtils, enabling downstream modality filtering.
Out of Scope Changes check ✅ Passed All changes are scoped to the stated objectives: audio.py adds doc_type_kwd and segment timestamps, embedding_utils.py adds modality inference, and tests validate the new functionality without introducing unrelated modifications.

✏️ 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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (2)
rag/svr/task_executor_refactor/embedding_utils.py (1)

153-156: ⚡ Quick win

Check knowledge_graph_kwd before inferring "table" from HTML.

Right now any chunk whose content_with_weight contains table markup is retyped as "table", even in rag/** where graph-based entities/relations/reports are supposed to stay distinguishable via knowledge_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 win

Add 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

📥 Commits

Reviewing files that changed from the base of the PR and between e81bca7 and 63292ba.

📒 Files selected for processing (2)
  • rag/app/audio.py
  • rag/svr/task_executor_refactor/embedding_utils.py

Comment thread rag/app/audio.py Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (3)
test/unit_test/rag/svr/task_executor_refactor/test_embedding_utils.py (3)

279-298: ⚡ Quick win

Consider adding integration test for modality stamping in attach_vectors.

The attach_vectors method stamps modality_kwd onto chunks when the field is absent by calling _infer_modality, which is a key integration point between modality inference and the embedding pipeline. The existing TestEmbeddingUtilsAttachVectors class (lines 188-222) doesn't verify this modality stamping behavior. Consider adding a test case there to ensure attach_vectors correctly populates modality_kwd based on doc_type_kwd.

🧪 Suggested integration test

Add to the existing TestEmbeddingUtilsAttachVectors class:

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 win

Extend test coverage to include image and video modalities.

The _DOC_TYPE_TO_MODALITY mapping 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 value

Add 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

📥 Commits

Reviewing files that changed from the base of the PR and between 63292ba and 2f1e430.

📒 Files selected for processing (3)
  • rag/app/audio.py
  • rag/svr/task_executor_refactor/embedding_utils.py
  • test/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

@enjoyandlove

Copy link
Copy Markdown
Contributor Author

Hi,@yingfeng!
Could you please review this PR?

@xugangqiang

xugangqiang commented Sep 4, 2026 •

Copy link
Copy Markdown
Contributor

Review findings

Thanks for the PR. The core logic is sound and the production path is correctly wired (rag/app/audio.py → chunk_builder → attach_vectors stamps modality_kwd). The CodeRabbit items (empty-list "[]", missing table in _DOC_TYPE_TO_MODALITY, p1 markers) are already addressed in the latest commits. The following are the remaining problems I found:

1. Blocker for Infinity-backed deployments — new fields missing from the index schema
modality_kwd, audio_start_flt, and audio_end_flt are only ever written to chunk dicts and never declared in any index mapping.

  • ES/OS use "dynamic": "true" (conf/mapping.json:127, conf/os_mapping.json:128), so they get auto-indexed — fine.
  • conf/infinity_mapping.json is an explicit, fixed schema (doc_type_kwd is declared at line 39, but modality_kwd/audio_*_flt are absent). Infinity has no dynamic columns, so on Infinity these fields are silently dropped and the stated "downstream retrieval/filtering" benefit does not work at all.

Must-fix before merge: add to conf/infinity_mapping.json:

"modality_kwd":      {"type": "varchar", "default": ""},
"audio_start_flt":   {"type": "float",   "default": 0.0},
"audio_end_flt":     {"type": "float",   "default": 0.0}

(Optionally also declare modality_kwd as a keyword column in the ES mapping for stable term filtering.)

2. Improvement — no test coverage for the audio segmentation change
rag/app/audio.py now splits a Whisper-style [{start,end,text}] response into per-segment chunks with audio_start_flt/audio_end_flt, but there is no test exercising it (test/unit_test/rag/app/ has no audio test file). Please add a unit test covering: list-of-dicts → multiple segment docs; empty list; and non-dict list fallback.

3. Nit — HTML table heuristic can misclassify plain text
EmbeddingUtils._infer_modality (embedding_utils.py:155) falls back to re.search(r"</?(?:table|tr|td|th)\b", content) for any chunk whose doc_type_kwd is not in the map. A text chunk that happens to contain the literal <td>/<th> in its content_with_weight (with doc_type_kwd="text") would be stamped as "table". Low probability, but worth noting.

Also note for the description: existing already-indexed chunks won't carry modality_kwd until re-indexed (additive field).

@xugangqiang

Copy link
Copy Markdown
Contributor

pls fix conflict

@xugangqiang

Copy link
Copy Markdown
Contributor

@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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

💞 feature Feature request, pull request that fullfill a new feature. size:M This PR changes 30-99 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature Request]:Unified Multimodal Chunk Pipeline — Native Image, Table & Audio Embeddings With Cross-Modal Retrieval