Files
ragflow/web/src/utils/llm-util.ts

180 lines
5.7 KiB
TypeScript
Raw Normal View History

import { getCachedLlmList } from './llm-cache';
// The names of the large models returned by the interface are similar to "deepseek-r1___OpenAI-API"
export function getRealModelName(llmName: string) {
return llmName.split('__').at(0) ?? '';
}
// Get tenant model ID from LLM list by model name and factory ID
export function getTenantModelId(
llmList: Record<string, any>,
modelName: string,
factoryId: string,
): string {
// Iterate through all providers in the LLM list
for (const [provider, data] of Object.entries(llmList)) {
if (data.llm && Array.isArray(data.llm)) {
// Handle /v1/llm/my_llms format
const model = data.llm.find(
(m: any) => m.name === modelName && provider === factoryId,
);
if (model && model.id) {
return model.id;
}
} else if (Array.isArray(data)) {
// Handle /v1/llm/list format
const model = data.find(
(m: any) => m.llm_name === modelName && m.fid === factoryId,
);
if (model && model.id) {
return model.id;
}
}
}
return '';
}
/** Build "modelName@instanceName@providerName" */
export function buildModelValue(model: {
model_name: string;
model_instance: string;
model_provider: string;
}) {
return `${model.model_name}@${model.model_instance}@${model.model_provider}`;
}
Fix: right-anchored split in web parseModelValue / parseModelUuid (#16737) Follow-up to #16468. PR #16468 fixed the Python (`api/db/joint_services/tenant_model_service.py split_model_name`) and Go (`internal/service/model_service.go parseModelName`) parsers to right-anchor the '@'-split on the composite "model_name@instance@provider" key, but the matching helper in the front-end (`web/src/utils/llm-util.ts parseModelValue`) was missed. parseModelValue used `split('@')` (anchored on the first '@'), which silently mangles composite keys whose model_name itself contains '@' (e.g. LM Studio embedding IDs like `text-embedding-nomic-embed-text-v1.5@q8_0`): text-embedding-nomic-embed-text-v1.5@q8_0@lmstudio@LM-Studio became model_name: text-embedding-nomic-embed-text-v1.5 model_instance: q8_0@lmstudio model_provider: LM-Studio `PATCH /api/v1/models/default` then sent those to the server, which returned HTTP 200 with body `{"code": 102, "message": "Instance 'q8_0@lmstudio' not found for provider 'LM-Studio'"}`. The UI swallowed the body-level error code, so the failure was silent: no toast, the Embedding field stayed empty. This change makes parseModelValue do a right-anchored split that mirrors the Python `split_model_name` `rsplit('@', 2)` exactly: - 3-part form: model_name@instance@provider -> same three fields. - 2-part form: model_name@provider -> model_instance defaults to "default" (matching Python). - 4+-part form (embedded '@' in model name): last two fields are anchored as instance and provider, everything to the left is the bare model name. `parseModelUuid` is updated to the same right-anchored split so the factoryId portion of `model_name@factory_id[#instance]` keeps the last '@' as the separator even when the model name itself contains '@'. Adds jest cases under `web/src/utils/tests/llm-util.test.ts` (12 total) covering the plain 3-part, 2-part, 4-part, multi-'@' name, buildModelValue round-trip and parseModelUuid variants. Note for reviewers: the front-end is bundled into the published docker image, so a release containing this fix will need `docker compose build --no-cache ragflow-cpu` (or equivalent) for it to be visible to end users. Refs #16468, #16467
2026-07-20 07:01:02 +05:30
/**
* Parse "modelName@instanceName@providerName" (or the 2-part
* "modelName@providerName" form where the instance defaults to "default").
*
* The composite key is right-anchored: the *last* '@'-separated field is the
* provider, the second-to-last is the instance, and everything to the left of
* the second-to-last '@' is the bare model name. Some model names legitimately
* contain '@' themselves (e.g. LM Studio embedding IDs such as
* `text-embedding-nomic-embed-text-v1.5@q8_0`), producing four-`@` composite
* keys like `text-embedding-nomic-embed-text-v1.5@q8_0@lmstudio@LM-Studio`.
*
* A naive `split("@")` (or anchoring on the first '@') mis-parses these keys
* PATCH /api/v1/models/default then sends `model_name="…v1.5"` and
* `model_instance="q8_0@lmstudio"`, and the server replies
* `Instance 'q8_0@lmstudio' not found for provider 'LM-Studio'`.
*
* Right-anchored split mirrors `api/db/joint_services/tenant_model_service.py`
* `split_model_name` and the Go `parseModelName` (PR #16468 family).
*/
export function parseModelValue(val: string) {
if (!val) return null;
const lastAt = val.lastIndexOf('@');
Fix: right-anchored split in web parseModelValue / parseModelUuid (#16737) Follow-up to #16468. PR #16468 fixed the Python (`api/db/joint_services/tenant_model_service.py split_model_name`) and Go (`internal/service/model_service.go parseModelName`) parsers to right-anchor the '@'-split on the composite "model_name@instance@provider" key, but the matching helper in the front-end (`web/src/utils/llm-util.ts parseModelValue`) was missed. parseModelValue used `split('@')` (anchored on the first '@'), which silently mangles composite keys whose model_name itself contains '@' (e.g. LM Studio embedding IDs like `text-embedding-nomic-embed-text-v1.5@q8_0`): text-embedding-nomic-embed-text-v1.5@q8_0@lmstudio@LM-Studio became model_name: text-embedding-nomic-embed-text-v1.5 model_instance: q8_0@lmstudio model_provider: LM-Studio `PATCH /api/v1/models/default` then sent those to the server, which returned HTTP 200 with body `{"code": 102, "message": "Instance 'q8_0@lmstudio' not found for provider 'LM-Studio'"}`. The UI swallowed the body-level error code, so the failure was silent: no toast, the Embedding field stayed empty. This change makes parseModelValue do a right-anchored split that mirrors the Python `split_model_name` `rsplit('@', 2)` exactly: - 3-part form: model_name@instance@provider -> same three fields. - 2-part form: model_name@provider -> model_instance defaults to "default" (matching Python). - 4+-part form (embedded '@' in model name): last two fields are anchored as instance and provider, everything to the left is the bare model name. `parseModelUuid` is updated to the same right-anchored split so the factoryId portion of `model_name@factory_id[#instance]` keeps the last '@' as the separator even when the model name itself contains '@'. Adds jest cases under `web/src/utils/tests/llm-util.test.ts` (12 total) covering the plain 3-part, 2-part, 4-part, multi-'@' name, buildModelValue round-trip and parseModelUuid variants. Note for reviewers: the front-end is bundled into the published docker image, so a release containing this fix will need `docker compose build --no-cache ragflow-cpu` (or equivalent) for it to be visible to end users. Refs #16468, #16467
2026-07-20 07:01:02 +05:30
if (lastAt === -1) return null;
const secondLastAt = val.lastIndexOf('@', lastAt - 1);
if (secondLastAt === -1) {
// 2-part form: "modelName@providerName" — instance defaults to "default".
return {
model_name: val.substring(0, lastAt),
model_instance: 'default',
model_provider: val.substring(lastAt + 1),
};
}
return {
Fix: right-anchored split in web parseModelValue / parseModelUuid (#16737) Follow-up to #16468. PR #16468 fixed the Python (`api/db/joint_services/tenant_model_service.py split_model_name`) and Go (`internal/service/model_service.go parseModelName`) parsers to right-anchor the '@'-split on the composite "model_name@instance@provider" key, but the matching helper in the front-end (`web/src/utils/llm-util.ts parseModelValue`) was missed. parseModelValue used `split('@')` (anchored on the first '@'), which silently mangles composite keys whose model_name itself contains '@' (e.g. LM Studio embedding IDs like `text-embedding-nomic-embed-text-v1.5@q8_0`): text-embedding-nomic-embed-text-v1.5@q8_0@lmstudio@LM-Studio became model_name: text-embedding-nomic-embed-text-v1.5 model_instance: q8_0@lmstudio model_provider: LM-Studio `PATCH /api/v1/models/default` then sent those to the server, which returned HTTP 200 with body `{"code": 102, "message": "Instance 'q8_0@lmstudio' not found for provider 'LM-Studio'"}`. The UI swallowed the body-level error code, so the failure was silent: no toast, the Embedding field stayed empty. This change makes parseModelValue do a right-anchored split that mirrors the Python `split_model_name` `rsplit('@', 2)` exactly: - 3-part form: model_name@instance@provider -> same three fields. - 2-part form: model_name@provider -> model_instance defaults to "default" (matching Python). - 4+-part form (embedded '@' in model name): last two fields are anchored as instance and provider, everything to the left is the bare model name. `parseModelUuid` is updated to the same right-anchored split so the factoryId portion of `model_name@factory_id[#instance]` keeps the last '@' as the separator even when the model name itself contains '@'. Adds jest cases under `web/src/utils/tests/llm-util.test.ts` (12 total) covering the plain 3-part, 2-part, 4-part, multi-'@' name, buildModelValue round-trip and parseModelUuid variants. Note for reviewers: the front-end is bundled into the published docker image, so a release containing this fix will need `docker compose build --no-cache ragflow-cpu` (or equivalent) for it to be visible to end users. Refs #16468, #16467
2026-07-20 07:01:02 +05:30
model_name: val.substring(0, secondLastAt),
model_instance: val.substring(secondLastAt + 1, lastAt),
model_provider: val.substring(lastAt + 1),
};
}
// Extract model name and factory ID from a model UUID
Fix: right-anchored split in web parseModelValue / parseModelUuid (#16737) Follow-up to #16468. PR #16468 fixed the Python (`api/db/joint_services/tenant_model_service.py split_model_name`) and Go (`internal/service/model_service.go parseModelName`) parsers to right-anchor the '@'-split on the composite "model_name@instance@provider" key, but the matching helper in the front-end (`web/src/utils/llm-util.ts parseModelValue`) was missed. parseModelValue used `split('@')` (anchored on the first '@'), which silently mangles composite keys whose model_name itself contains '@' (e.g. LM Studio embedding IDs like `text-embedding-nomic-embed-text-v1.5@q8_0`): text-embedding-nomic-embed-text-v1.5@q8_0@lmstudio@LM-Studio became model_name: text-embedding-nomic-embed-text-v1.5 model_instance: q8_0@lmstudio model_provider: LM-Studio `PATCH /api/v1/models/default` then sent those to the server, which returned HTTP 200 with body `{"code": 102, "message": "Instance 'q8_0@lmstudio' not found for provider 'LM-Studio'"}`. The UI swallowed the body-level error code, so the failure was silent: no toast, the Embedding field stayed empty. This change makes parseModelValue do a right-anchored split that mirrors the Python `split_model_name` `rsplit('@', 2)` exactly: - 3-part form: model_name@instance@provider -> same three fields. - 2-part form: model_name@provider -> model_instance defaults to "default" (matching Python). - 4+-part form (embedded '@' in model name): last two fields are anchored as instance and provider, everything to the left is the bare model name. `parseModelUuid` is updated to the same right-anchored split so the factoryId portion of `model_name@factory_id[#instance]` keeps the last '@' as the separator even when the model name itself contains '@'. Adds jest cases under `web/src/utils/tests/llm-util.test.ts` (12 total) covering the plain 3-part, 2-part, 4-part, multi-'@' name, buildModelValue round-trip and parseModelUuid variants. Note for reviewers: the front-end is bundled into the published docker image, so a release containing this fix will need `docker compose build --no-cache ragflow-cpu` (or equivalent) for it to be visible to end users. Refs #16468, #16467
2026-07-20 07:01:02 +05:30
// Supports both "model_name@factory_id" and "model_name@factory_id#instance_name".
// Uses right-anchored split for the same reason as parseModelValue:
// model names may contain '@' themselves, so a naive split('@') drops the
// last portion of the model name into factoryId.
export function parseModelUuid(uuid: string): {
modelName: string;
factoryId: string;
} {
const hashIndex = uuid.indexOf('#');
const core = hashIndex === -1 ? uuid : uuid.slice(0, hashIndex);
Fix: right-anchored split in web parseModelValue / parseModelUuid (#16737) Follow-up to #16468. PR #16468 fixed the Python (`api/db/joint_services/tenant_model_service.py split_model_name`) and Go (`internal/service/model_service.go parseModelName`) parsers to right-anchor the '@'-split on the composite "model_name@instance@provider" key, but the matching helper in the front-end (`web/src/utils/llm-util.ts parseModelValue`) was missed. parseModelValue used `split('@')` (anchored on the first '@'), which silently mangles composite keys whose model_name itself contains '@' (e.g. LM Studio embedding IDs like `text-embedding-nomic-embed-text-v1.5@q8_0`): text-embedding-nomic-embed-text-v1.5@q8_0@lmstudio@LM-Studio became model_name: text-embedding-nomic-embed-text-v1.5 model_instance: q8_0@lmstudio model_provider: LM-Studio `PATCH /api/v1/models/default` then sent those to the server, which returned HTTP 200 with body `{"code": 102, "message": "Instance 'q8_0@lmstudio' not found for provider 'LM-Studio'"}`. The UI swallowed the body-level error code, so the failure was silent: no toast, the Embedding field stayed empty. This change makes parseModelValue do a right-anchored split that mirrors the Python `split_model_name` `rsplit('@', 2)` exactly: - 3-part form: model_name@instance@provider -> same three fields. - 2-part form: model_name@provider -> model_instance defaults to "default" (matching Python). - 4+-part form (embedded '@' in model name): last two fields are anchored as instance and provider, everything to the left is the bare model name. `parseModelUuid` is updated to the same right-anchored split so the factoryId portion of `model_name@factory_id[#instance]` keeps the last '@' as the separator even when the model name itself contains '@'. Adds jest cases under `web/src/utils/tests/llm-util.test.ts` (12 total) covering the plain 3-part, 2-part, 4-part, multi-'@' name, buildModelValue round-trip and parseModelUuid variants. Note for reviewers: the front-end is bundled into the published docker image, so a release containing this fix will need `docker compose build --no-cache ragflow-cpu` (or equivalent) for it to be visible to end users. Refs #16468, #16467
2026-07-20 07:01:02 +05:30
const lastAt = core.lastIndexOf('@');
if (lastAt === -1) {
return { modelName: core, factoryId: '' };
}
return {
modelName: core.substring(0, lastAt),
factoryId: core.substring(lastAt + 1),
};
}
// Model parameter to tenant parameter mapping
type ModelParamMap = {
[key: string]: string;
};
const modelParamMap: ModelParamMap = {
llm_id: 'tenant_llm_id',
embd_id: 'tenant_embd_id',
asr_id: 'tenant_asr_id',
tts_id: 'tenant_tts_id',
img2txt_id: 'tenant_img2txt_id',
rerank_id: 'tenant_rerank_id',
};
// API endpoint whitelist - only these endpoints will have tenant parameters added
const API_WHITELIST = [
'/api/v1/users/me/models',
'/api/v1/chats',
'/v1/canvas/set',
'/v1/canvas/setting',
'/api/v1/searches/',
'/api/v1/memories',
feat(api): add unified index API and dataset management endpoints (#14222) ### What problem does this PR solve? ## Summary Refactor the dataset API layer into a clean service/REST separation pattern, add a unified `/index` API for graph/raptor/mindmap operations, and introduce several new dataset management endpoints with full test coverage. ## Changes ### Service Layer (`dataset_api_service.py`) - Added `trace_index(dataset_id, tenant_id, index_type)` — unified trace function for all index types - Added `run_index`, `delete_index` service functions - Added `get_dataset`, `get_ingestion_summary`, `list_ingestion_logs`, `get_ingestion_log` - Added `run_embedding`, `list_tags`, `aggregate_tags`, `delete_tags`, `rename_tag` - Added `get_flattened_metadata`, `get_auto_metadata`, `update_auto_metadata` ### REST API Layer (`dataset_api.py`) **New unified routes:** | Method | Route | Description | |--------|-------|-------------| | POST | `/datasets/<id>/index?type=graph\|raptor\|mindmap` | Run index task | | GET | `/datasets/<id>/index?type=graph\|raptor\|mindmap` | Trace index task | | DELETE | `/datasets/<id>/<index_type>` | Delete index | | GET | `/datasets/<id>` | Get dataset details | | GET | `/datasets/<id>/ingestions/summary` | Ingestion summary | | GET | `/datasets/<id>/ingestions` | List ingestion logs | | GET | `/datasets/<id>/ingestions/<log_id>` | Get single ingestion log | | POST | `/datasets/<id>/embedding` | Run embedding | | GET | `/datasets/<id>/tags` | List tags | | GET | `/datasets/tags/aggregation` | Aggregate tags across datasets | | DELETE | `/datasets/<id>/tags` | Delete tags | | PUT | `/datasets/<id>/tags` | Rename tag | | GET | `/datasets/metadata/flattened` | Get flattened metadata | | GET/PUT | `/datasets/<id>/metadata/config` | New metadata config path | **Removed routes (replaced by unified `/index`):** - `POST /datasets/<id>/mindmap` - `GET /datasets/<id>/mindmap` **Preserved legacy routes (backward compatibility):** - `/run_graphrag`, `/trace_graphrag`, `/run_raptor`, `/trace_raptor` - `/auto_metadata` GET/PUT ### Test Suite - Updated `common.py` helpers: added `trace_index`, removed `run_mindmap`/`trace_mindmap` - Added 7 new test files with 39 test cases total: | Test File | Cases | |-----------|-------| | `test_get_dataset.py` | 4 | | `test_ingestion_summary.py` | 2 | | `test_ingestion_logs.py` | 5 | | `test_index_api.py` | 14 | | `test_embedding.py` | 2 | | `test_tags.py` | 8 | | `test_flattened_metadata.py` | 4 | - Deleted `test_mindmap_tasks.py` (covered by unified index tests) ## Design Decisions 1. **Unified `/index?type=...`** — single endpoint replaces 3 separate route pairs for graph/raptor/mindmap 2. **Backward compatibility** — old routes (`/run_graphrag`, `/run_raptor`, `/auto_metadata`) preserved alongside new paths 3. **`_VALID_INDEX_TYPES = {"graph", "raptor", "mindmap"}`** — input validation via constant set 4. **`_INDEX_TYPE_TO_TASK_ID_FIELD`** — maps index type to KB model task ID field for clean dispatch ## Files Changed - `api/apps/restful_apis/dataset_api.py` - `api/apps/services/dataset_api_service.py` - `sdk/python/ragflow_sdk/modules/dataset.py` - `test/testcases/test_http_api/common.py` - `test/testcases/test_http_api/test_dataset_management/` (7 new files) ### Type of change - [x] New Feature (non-breaking change which adds functionality) - [x] Refactoring --------- Signed-off-by: noob <yixiao121314@outlook.com>
2026-04-27 01:38:01 +00:00
'/api/v1/datasets',
'/v1/dataflow/set',
];
// Check if the URL is in the whitelist
export function isUrlInWhitelist(url: string): boolean {
return API_WHITELIST.some((endpoint) => url.includes(endpoint));
}
// Add tenant model ID parameters to request data
export function addTenantParams(data: any, url?: string): any {
if (!data || typeof data !== 'object') return data;
// If URL is provided and not in whitelist, return original data
if (url && !isUrlInWhitelist(url)) {
return data;
}
const llmList = getCachedLlmList();
if (!llmList) return data;
// Handle arrays
if (Array.isArray(data)) {
return data.map((item) => addTenantParams(item, url));
}
const newData = { ...data };
// Iterate through model parameters and add corresponding tenant parameters
for (const [paramName, tenantParamName] of Object.entries(modelParamMap)) {
if (newData[paramName]) {
try {
const { modelName, factoryId } = parseModelUuid(newData[paramName]);
const tenantModelId = getTenantModelId(llmList, modelName, factoryId);
if (tenantModelId) {
newData[tenantParamName] = tenantModelId;
}
} catch (error) {
console.error(`Error processing ${paramName}:`, error);
}
}
}
// Recursively process nested objects
for (const [key, value] of Object.entries(newData)) {
if (value && typeof value === 'object' && !modelParamMap[key]) {
newData[key] = addTenantParams(value, url);
}
}
return newData;
}