Repository navigation
feat(embedding): profile + prefix support for multilingual retrieval (v4.8.0 Fase 1) - #148
Conversation
Introduces the v4.8.0 Fase 1 opt-in schema for embedding presets on top of the existing models.embedding block: - New Config fields: embedding_profile (default 'custom'), query_prefix, passage_prefix. - New _EMBEDDING_PROFILES dict with 'compact' (bge-small-en, 384D), 'quality' (bge-large-en, 1024D), 'multilingual' (intfloat/e5-large, 1024D with 'query: '/'passage: ' prefixes), and 'custom' (sentinel — no override). - Profile resolver in __post_init__ runs BEFORE the embedding_dim validator, so a valid profile can promote dim to 1024 without triggering the fallback. - User overrides win: models.embedding.model + profile != custom emits a '[WARN] profile takes precedence' log and profile wins; explicit query_prefix/passage_prefix in YAML overrides the profile default (empty string "" IS treated as an explicit override). - Invalid profile names fall back to 'custom' with a WARN log. - Backwards compat: with no 'profile' key in YAML, everything resolves to the prior bge-small-en-v1.5 / 384D / empty prefix behaviour.
Extracts the load + embed + validate loop into _embed so the query and passage paths can prepend distinct prefixes without going through each other: - _apply_prefix(texts, prefix) returns the input list unchanged when prefix is empty, so the default 'compact' profile never allocates a new list on the hot path. - __call__ (ChromaDB embedding_function contract) applies config.passage_prefix. In this codebase queries reach the embed layer via embed_query — not __call__ — so treating __call__ as the passage scope is correct; docstring documents the invariant. - embed_documents stays a pure alias for __call__; passage prefix is applied exactly once at __call__ (never in the alias). - embed_query calls _embed directly with config.query_prefix, bypassing __call__ so query and passage prefixes never collide. Backwards compat: with empty prefixes (default profile) the pipeline is byte-identical to the pre-refactor behaviour — same load path, same LOUD error semantics from v3.8.1, same dim/count sanity checks.
…l-e5-large
New opt-in preset for corpora that mix languages beyond English (PT-BR,
Spanish, French, German, Cyrillic, Arabic, CJK, 100+ others).
- models.embedding.profile: "multilingual" — pulls model, dimensions,
query_prefix ("query: ") and passage_prefix ("passage: ") from
_EMBEDDING_PROFILES automatically. The e5 family was trained with these
scoped prefixes and degrades without them.
- Neutral shell around the profile: general-purpose chunking (1000/200),
neutral supported_formats, empty category_mappings / keyword_routes /
query_expansions. Multilingual routing needs per-language stopword
awareness that is deferred to caller configuration.
- Reranker stays on (Xenova/ms-marco-MiniLM-L-6-v2). It was trained on
English MS-MARCO but still helps RRF ordering on non-English corpora;
file comment flags the trade-off and points at enabled: false for
operators who want to skip it.
- File header warns that switching profile REQUIRES
reindex_documents(force=True) — existing chunks were embedded with
the previous model+prefix combo and vectors are not comparable.
…ingual
Two contract updates in the preset validation suite:
- test_preset_embedding_section_intact now accepts BOTH shapes:
* legacy (model + dimensions explicit, no profile key or
profile: 'custom') — dim must be a positive int, defaults to 384.
* profile-driven (profile: '<known>') — model and dimensions
may be omitted because the Config resolver fills them from
_EMBEDDING_PROFILES at load time. If dimensions IS declared
alongside a non-custom profile it must agree with the profile's
canonical dim (384 for compact, 1024 for quality/multilingual).
Unknown profile names are a hard assertion failure.
- test_at_least_four_presets_shipped renamed to
test_at_least_five_presets_shipped and expanded to require the new
multilingual preset alongside the pre-existing four.
Prior 4 presets (cybersecurity, developer, research, general) all still
declare model + dimensions explicitly so they take the legacy
branch and remain byte-compatible with the old assertions.
Eight AAA tests across two suites:
TestProfileResolution (5)
- profile='custom' preserves explicit model/dim/prefix from YAML.
- profile='multilingual' populates the e5 model, 1024D, and
'query: '/'passage: ' prefixes with no other YAML input.
- profile + explicit models.embedding.model emits '[WARN] profile takes
precedence' and profile wins on both model and dim.
- Unknown profile name falls back to 'custom' with a WARN log and any
explicit model is honored (custom is the pass-through sentinel).
- Explicit query_prefix / passage_prefix in YAML override the profile
default even under a non-custom profile.
TestPrefixApplication (3)
- __call__ (ChromaDB embedding_function contract) prepends
passage_prefix before the strings reach model.embed().
- embed_query prepends query_prefix; passage prefix never leaks into
the query path.
- Empty prefix is an identity pass-through (called_texts is raw) so
the default 'compact' profile allocates zero new strings on the hot
ingest path.
Tests rebuild the Config dataclass under a monkey-patched _yaml dict
instead of mutating the process-global config instance, keeping the
suite isolation-clean.
….yaml Expands the models.embedding comment block to cover the v4.8.0 Fase 1 opt-in schema: - Option A (named profile) documents the four presets — compact (default), quality, multilingual, custom — with model/dim/prefix callouts and the ~2x / ~4-5x runtime cost hints. - Option B (custom profile) keeps the legacy shape story and calls out the community-model catalogue previously listed at the top of the block. - Explicit conflict rule: profile != 'custom' + declared models.embedding.model triggers a '[WARN] profile takes precedence' and the profile wins. (The wording in the internal spec suggested the opposite; docs follow the resolver's actual behaviour.) - New query_prefix / passage_prefix fields introduced with the invariant that an empty string is a legitimate explicit override (matches the resolver logic in Config.__post_init__). - Warning that changing profile / model / dim / prefix REQUIRES a full reindex — existing chunks were embedded with the prior configuration. - profile: 'multilingual' shown commented-out so users see the smallest possible switch to adopt the new preset. Zero runtime impact — this is comment/example-only content.
Inserts the Fase 1 changelog line at the top of the Unreleased section: opt-in profile shorthand + query/passage prefix wiring + shipped multilingual preset backed by intfloat/multilingual-e5-large. Flags the mandatory reindex when switching profile or prefix. PR number placeholder (#XXX) will be substituted in the next commit after 'gh pr create' returns the assigned number.
📝 WalkthroughWalkthroughThe change adds named embedding profiles, configurable query and passage prefixes, prefix-aware embedding execution, and a multilingual preset. Configuration and preset tests validate profile resolution, dimensions, prefix routing, and shipped preset coverage. ChangesEmbedding profiles and prefix-aware embeddings
Estimated code review effort: 3 (Moderate) | ~25 minutes Sequence Diagram(s)sequenceDiagram
participant ChromaDB
participant FastEmbedEmbeddings
participant Config
participant EmbeddingModel
ChromaDB->>FastEmbedEmbeddings: request document or query embeddings
FastEmbedEmbeddings->>Config: read passage or query prefix
FastEmbedEmbeddings->>EmbeddingModel: generate prefixed embeddings
EmbeddingModel-->>FastEmbedEmbeddings: return embedding results
FastEmbedEmbeddings-->>ChromaDB: return validated vectors
Suggested reviewers: 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
🧪 Generate unit tests (beta)
Comment |
Replaces the placeholder (#XXX) with the assigned PR number.
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 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 `@config.example.yaml`:
- Around line 152-166: Comment out or remove the default query_prefix and
passage_prefix entries in the profile example so selecting profile:
"multilingual" preserves that profile’s required prefixes; keep explicit
empty-string overrides documented separately if needed.
In `@tests/test_presets.py`:
- Around line 73-77: Strengthen the custom-profile validation in the preset
test: require embedding.model to be a non-empty value rather than only checking
key presence, and require embedding.dimensions to be explicitly present instead
of defaulting to 384. Continue validating that dimensions is a positive integer.
🪄 Autofix
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: defaults
Review profile: CHILL
Plan: Pro Plus
Run ID: 16e5b31b-9bc7-458b-979f-855561aa7869
📒 Files selected for processing (7)
README.mdconfig.example.yamlmcp_server/config.pymcp_server/server.pypresets/multilingual.yamltests/test_embedding_profile.pytests/test_presets.py
| # Uncomment to switch to a named profile (see Option A above). | ||
| # profile: "multilingual" | ||
|
|
||
| # Explicit model / dimensions — respected only when profile is | ||
| # "custom" (default). Ignored with a WARN under any other profile. | ||
| model: "BAAI/bge-small-en-v1.5" | ||
| dimensions: 384 | ||
|
|
||
| # Query / passage prefixes — prepended to text BEFORE embedding. | ||
| # Required by some model families (intfloat/e5, thenlper/gte, ...); | ||
| # leave empty for bge / mxbai. When a profile ships prefixes, this | ||
| # override wins ONLY if the key is present here (empty string "" IS | ||
| # an explicit override). | ||
| query_prefix: "" | ||
| passage_prefix: "" |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Do not declare empty prefix overrides in the profile example.
If a user only uncomments profile: "multilingual", lines 165-166 explicitly override the profile prefixes with empty strings. The resolver then embeds E5 queries and passages without the required query: and passage: prefixes.
Comment out these keys by default, or place them in a separate explicit-override example.
Proposed fix
- query_prefix: ""
- passage_prefix: ""
+ # Uncomment to override the selected profile prefixes.
+ # query_prefix: ""
+ # passage_prefix: ""📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| # Uncomment to switch to a named profile (see Option A above). | |
| # profile: "multilingual" | |
| # Explicit model / dimensions — respected only when profile is | |
| # "custom" (default). Ignored with a WARN under any other profile. | |
| model: "BAAI/bge-small-en-v1.5" | |
| dimensions: 384 | |
| # Query / passage prefixes — prepended to text BEFORE embedding. | |
| # Required by some model families (intfloat/e5, thenlper/gte, ...); | |
| # leave empty for bge / mxbai. When a profile ships prefixes, this | |
| # override wins ONLY if the key is present here (empty string "" IS | |
| # an explicit override). | |
| query_prefix: "" | |
| passage_prefix: "" | |
| # Uncomment to switch to a named profile (see Option A above). | |
| # profile: "multilingual" | |
| # Explicit model / dimensions — respected only when profile is | |
| # "custom" (default). Ignored with a WARN under any other profile. | |
| model: "BAAI/bge-small-en-v1.5" | |
| dimensions: 384 | |
| # Query / passage prefixes — prepended to text BEFORE embedding. | |
| # Required by some model families (intfloat/e5, thenlper/gte, ...); | |
| # leave empty for bge / mxbai. When a profile ships prefixes, this | |
| # override wins ONLY if the key is present here (empty string "" IS | |
| # an explicit override). | |
| # Uncomment to override the selected profile prefixes. | |
| # query_prefix: "" | |
| # passage_prefix: "" |
🤖 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 `@config.example.yaml` around lines 152 - 166, Comment out or remove the
default query_prefix and passage_prefix entries in the profile example so
selecting profile: "multilingual" preserves that profile’s required prefixes;
keep explicit empty-string overrides documented separately if needed.
| if profile == "custom": | ||
| # Legacy shape — model + dim required | ||
| assert has_model, f"{preset_yaml.name}: models.embedding.model is required for custom profile" | ||
| dim = embedding.get("dimensions", 384) | ||
| assert isinstance(dim, int) and dim > 0, f"{preset_yaml.name}: dimensions must be a positive int, got {dim!r}" |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Validate required custom embedding values.
Line 76 accepts a missing dimensions key by defaulting it to 384. Line 75 also accepts model: null or an empty model string. This lets malformed custom presets pass despite the stated requirement for a model and positive dimension.
Proposed fix
if profile == "custom":
- # Legacy shape — model + dim required
- assert has_model, f"{preset_yaml.name}: models.embedding.model is required for custom profile"
- dim = embedding.get("dimensions", 384)
+ # Legacy shape — model + dim required
+ assert isinstance(embedding.get("model"), str) and embedding["model"].strip(), (
+ f"{preset_yaml.name}: models.embedding.model must be a non-empty string for custom profile"
+ )
+ assert has_dim, f"{preset_yaml.name}: models.embedding.dimensions is required for custom profile"
+ dim = embedding["dimensions"]
assert isinstance(dim, int) and dim > 0, f"{preset_yaml.name}: dimensions must be a positive int, got {dim!r}"🤖 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 `@tests/test_presets.py` around lines 73 - 77, Strengthen the custom-profile
validation in the preset test: require embedding.model to be a non-empty value
rather than only checking key presence, and require embedding.dimensions to be
explicitly present instead of defaulting to 384. Continue validating that
dimensions is a positive integer.
Summary
Fase 1 do roadmap v4.8.0 — fundação de qualidade de retrieval.
Adiciona suporte a embedding profiles nomeados (`compact` / `quality` / `multilingual` / `custom`) e prefix opt-in por escopo (query vs passage), pré-requisito pra usar modelos e5 family que exigem `"query: "` / `"passage: "`. O preset `multilingual` ativa `intfloat/multilingual-e5-large` (1024D, 100+ idiomas) sem custo de reindex pra quem fica no default `compact`.
Closes N/A (roadmap task, no issue).
Type of change
What changed
Why
Retrieval multilingual hoje degrada silenciosamente porque bge-small-en foi treinado só em inglês. Adicionar profile nomeado sem quebrar quem tá no default resolve dois problemas: (1) usuários que precisam PT-BR / Cyrillic / CJK trocam `profile: "multilingual"` sem editar 4 campos manualmente e sem esquecer os prefixes obrigatórios do e5; (2) roadmap futuro (Fase 2 GPU, Fase 6 dual-collection swap) tem uma superfície de configuração estável pra evoluir.
Alternativas descartadas: manter modelo hardcoded (fere universality do repo — ver PR #147 discussion); exigir usuário declarar tudo manualmente (usabilidade ruim + risco de esquecer prefix); auto-detectar idioma do corpus (custo runtime alto + falha silenciosa em corpora mixed).
7 Pillars Quality Gate
1. Security
2. Stability
3. Memory leak
4. Versatility
5. Scalability
Performance impact (touched `server.py`):
```
metric before after delta
search p95 unchanged unchanged ~0% (one extra function call, early-return on empty prefix)
index docs/sec unchanged unchanged ~0% (same as above)
RSS @ 1k docs unchanged unchanged ~0% (no new state)
```
Números empíricos não medidos localmente — perf-gate do CI valida contra baseline v4.7.1.
6. Versioning
7. Quality
Migration / Breaking changes
N/A — 100% backwards compatible.
Adopting the multilingual profile (opt-in migration for users who need it):
```yaml
models:
embedding:
profile: "multilingual"
```
Test plan
Documentation
Reviewer checklist
By submitting this PR I confirm I read CONTRIBUTING.md and agree to the Code of Conduct.
Summary by CodeRabbit
Greptile Summary
The PR adds named embedding profiles and query/passage prefix configuration for multilingual retrieval.
Confidence Score: 4/5
The PR does not yet appear safe to merge because multilingual semantic queries can still be embedded with passage semantics.
_do_semanticcontinues to submitquery_textsthrough the Chroma collection while the registered embedding-function entrypoint appliespassage_prefix; the newembed_querymethod is only exercised directly and is not wired into that retrieval path.Files Needing Attention: mcp_server/server.py, tests/test_embedding_profile.py
Important Files Changed
Sequence Diagram
sequenceDiagram participant Search as Semantic search participant Chroma as Chroma collection participant Embed as FastEmbedEmbeddings Search->>Chroma: "query(query_texts=[text])" Chroma->>Embed: embedding function invocation Embed->>Embed: apply configured prefix and embed Chroma-->>Search: nearest document vectorsReviews (2): Last reviewed commit: "ci: re-trigger workflows (F1 initial pus..." | Re-trigger Greptile