From 94375575e6db674ebdbd22c423e6b3663c222c04 Mon Sep 17 00:00:00 2001 From: clh02467605 Date: Mon, 30 Nov 2026 15:21:27 +0800 Subject: [PATCH 1/3] feat: add embedding create and rerank commands --- README.md | 1 + README.zh.md | 1 + packages/cli/README.md | 1 + packages/cli/README.zh.md | 1 + packages/cli/src/commands.ts | 4 + .../commands/src/commands/embedding/create.ts | 407 +++++++++++ packages/commands/src/commands/rerank.ts | 636 ++++++++++++++++++ packages/commands/src/index.ts | 2 + .../tests/e2e/embedding-create.e2e.test.ts | 575 ++++++++++++++++ .../commands/tests/e2e/rerank.e2e.test.ts | 571 ++++++++++++++++ packages/commands/tests/e2e/topic-routes.ts | 8 + packages/core/src/client/embedding-routes.ts | 316 +++++++++ packages/core/src/client/endpoints.ts | 16 + packages/core/src/client/index.ts | 20 + packages/core/src/types/api.ts | 83 +++ packages/core/tests/embedding-routes.test.ts | 134 ++++ skills/bailian-cli/SKILL.md | 7 +- skills/bailian-cli/reference/embedding.md | 51 ++ skills/bailian-cli/reference/index.md | 4 + skills/bailian-cli/reference/rerank.md | 53 ++ 20 files changed, 2890 insertions(+), 1 deletion(-) create mode 100644 packages/commands/src/commands/embedding/create.ts create mode 100644 packages/commands/src/commands/rerank.ts create mode 100644 packages/commands/tests/e2e/embedding-create.e2e.test.ts create mode 100644 packages/commands/tests/e2e/rerank.e2e.test.ts create mode 100644 packages/core/src/client/embedding-routes.ts create mode 100644 packages/core/tests/embedding-routes.test.ts create mode 100644 skills/bailian-cli/reference/embedding.md create mode 100644 skills/bailian-cli/reference/rerank.md diff --git a/README.md b/README.md index e134db63a..279c5f16c 100644 --- a/README.md +++ b/README.md @@ -24,6 +24,7 @@ _Built for AI Agents. Every command works as a structured tool call._ ## Features - **Model generation** — Full-modality generation across text, image, video, and speech, with editing and reference-based generation +- **Embeddings & rerank** — Create text / multimodal vectors (`bl embedding create`) and score candidate documents (`bl rerank`) - **Asset understanding** — Parse and ask questions about images, documents, audio, and long videos - **App orchestration** — Call Managed Agents, agents, and workflows published on Aliyun Model Studio, wired to knowledge bases, memory, web search, and MCP tools; create, update, publish, copy, and delete agents/workflows, and edit workflow canvases from the CLI - **Workspace connectors** — Discover tools with `bl connector tools --query`, inspect a selected account's schema with `bl connector schema`, and execute a tool with `bl connector call`. diff --git a/README.zh.md b/README.zh.md index cb702d5e2..4b8dbf68a 100644 --- a/README.zh.md +++ b/README.zh.md @@ -23,6 +23,7 @@ _专为 AI Agent 打造,每个命令均可作为结构化工具调用。_ ## 功能特性 - **模型生成** — 文本、图像、视频、语音全模态生成,支持编辑与参考生成 +- **向量与重排序** — 创建文本/多模态向量(`bl embedding create`)与候选文档打分排序(`bl rerank`) - **素材理解** — 图像、文档、音频、长视频的解析与问答 - **应用编排** — 调用百炼已发布的 Managed Agent、智能体和工作流,接入知识库、记忆库、联网搜索与 MCP 工具;并可在命令行创建/更新/发布/复制/删除智能体与工作流、编辑工作流画布 - **工作空间连接器** — 用 `bl connector tools --query` 查找工具,用 `bl connector schema` 查看所选账号下的入参,再用 `bl connector call` 执行。 diff --git a/packages/cli/README.md b/packages/cli/README.md index e134db63a..279c5f16c 100644 --- a/packages/cli/README.md +++ b/packages/cli/README.md @@ -24,6 +24,7 @@ _Built for AI Agents. Every command works as a structured tool call._ ## Features - **Model generation** — Full-modality generation across text, image, video, and speech, with editing and reference-based generation +- **Embeddings & rerank** — Create text / multimodal vectors (`bl embedding create`) and score candidate documents (`bl rerank`) - **Asset understanding** — Parse and ask questions about images, documents, audio, and long videos - **App orchestration** — Call Managed Agents, agents, and workflows published on Aliyun Model Studio, wired to knowledge bases, memory, web search, and MCP tools; create, update, publish, copy, and delete agents/workflows, and edit workflow canvases from the CLI - **Workspace connectors** — Discover tools with `bl connector tools --query`, inspect a selected account's schema with `bl connector schema`, and execute a tool with `bl connector call`. diff --git a/packages/cli/README.zh.md b/packages/cli/README.zh.md index cb702d5e2..4b8dbf68a 100644 --- a/packages/cli/README.zh.md +++ b/packages/cli/README.zh.md @@ -23,6 +23,7 @@ _专为 AI Agent 打造,每个命令均可作为结构化工具调用。_ ## 功能特性 - **模型生成** — 文本、图像、视频、语音全模态生成,支持编辑与参考生成 +- **向量与重排序** — 创建文本/多模态向量(`bl embedding create`)与候选文档打分排序(`bl rerank`) - **素材理解** — 图像、文档、音频、长视频的解析与问答 - **应用编排** — 调用百炼已发布的 Managed Agent、智能体和工作流,接入知识库、记忆库、联网搜索与 MCP 工具;并可在命令行创建/更新/发布/复制/删除智能体与工作流、编辑工作流画布 - **工作空间连接器** — 用 `bl connector tools --query` 查找工具,用 `bl connector schema` 查看所选账号下的入参,再用 `bl connector call` 执行。 diff --git a/packages/cli/src/commands.ts b/packages/cli/src/commands.ts index e252584a3..6883a8320 100644 --- a/packages/cli/src/commands.ts +++ b/packages/cli/src/commands.ts @@ -7,6 +7,8 @@ import { authGenerateAccessToken, textChat, textTranslate, + embeddingCreate, + rerank, batchConvert, batchCreate, batchList, @@ -421,6 +423,8 @@ export const commands: Record = { "auth generate-access-token": authGenerateAccessToken, "text chat": textChat, "text translate": textTranslate, + "embedding create": embeddingCreate, + rerank, "batch convert": batchConvert, "batch create": batchCreate, "batch list": batchList, diff --git a/packages/commands/src/commands/embedding/create.ts b/packages/commands/src/commands/embedding/create.ts new file mode 100644 index 000000000..99af98443 --- /dev/null +++ b/packages/commands/src/commands/embedding/create.ts @@ -0,0 +1,407 @@ +import { dirname } from "node:path"; +import { existsSync, mkdirSync, statSync, writeFileSync } from "node:fs"; +import { + BailianError, + ExitCode, + assertEmbeddingDimensions, + assertEmbeddingFusion, + assertEmbeddingInputCounts, + defineCommand, + EmbeddingRouteError, + imageFileToDataUri, + LOCAL_IMAGE_PENDING_ENCODE, + redactDataUri, + resolveEmbeddingRoute, + stripUndefined, + type FlagsDef, + type LocalizedText, + type MultimodalEmbeddingContent, + type MultimodalEmbeddingRequest, + type MultimodalEmbeddingResponse, + type TextEmbeddingRequest, + type TextEmbeddingResponse, +} from "bailian-cli-core"; + +const CREATE_FLAGS = { + text: { + type: "array", + valueHint: "", + description: { + "en-US": "Text to embed (repeatable; order preserved among --text values)", + "zh-CN": "待向量化文本(可重复;同类 --text 之间保留顺序)", + }, + }, + image: { + type: "array", + valueHint: "", + description: { + "en-US": + "Image URL or local path (repeatable; public HTTP(S) URL or Data URI preferred for large files)", + "zh-CN": "图片 URL 或本地路径(可重复;大图优先公网 HTTP(S) URL 或 Data URI)", + }, + }, + video: { + type: "array", + valueHint: "", + description: { + "en-US": "Public HTTP(S) video URL only (repeatable; local video paths are not supported)", + "zh-CN": "仅支持公网 HTTP(S) 视频 URL(可重复;不支持本地视频路径)", + }, + }, + model: { + type: "string", + valueHint: "", + description: { + "en-US": + "Embedding model (default: text-embedding-v4 for text-only; qwen3-vl-embedding when media is present)", + "zh-CN": "向量模型(默认:纯文本为 text-embedding-v4;含图片/视频为 qwen3-vl-embedding)", + }, + }, + dimensions: { + type: "number", + valueHint: "", + description: { + "en-US": "Embedding dimensions (model-dependent)", + "zh-CN": "向量维度(取值由模型决定)", + }, + }, + fuse: { + type: "boolean", + valueHint: "", + description: { + "en-US": + "Enable fusion for qwen3-vl-embedding (maps to parameters.enable_fusion); other models reject this flag", + "zh-CN": "qwen3-vl-embedding 融合向量(映射为 parameters.enable_fusion);其他型号拒绝此参数", + }, + }, + out: { + type: "string", + valueHint: "", + description: { + "en-US": "Save the full server response JSON to a file", + "zh-CN": "将完整服务端响应 JSON 保存到文件", + }, + }, +} satisfies FlagsDef; + +function usageError(localize: (text: LocalizedText) => string, text: LocalizedText): never { + throw new BailianError(localize(text), ExitCode.USAGE); +} + +function routeError(localize: (text: LocalizedText) => string, error: EmbeddingRouteError): never { + throw new BailianError( + localize({ "en-US": error.message, "zh-CN": error.zhMessage }), + ExitCode.USAGE, + ); +} + +function nonEmptyStrings( + values: string[] | undefined, + flagName: string, + localize: (text: LocalizedText) => string, +): string[] { + if (!values?.length) return []; + return values.map((value, index) => { + const trimmed = value.trim(); + if (!trimmed) { + usageError(localize, { + "en-US": `${flagName}[${index}] must be a non-empty string.`, + "zh-CN": `${flagName}[${index}] 必须为非空字符串。`, + }); + } + return trimmed; + }); +} + +function isHttpUrl(value: string): boolean { + return /^https?:\/\//i.test(value); +} + +function isDataUri(value: string): boolean { + return /^data:/i.test(value); +} + +function isLocalPathCandidate(value: string): boolean { + if (isHttpUrl(value) || isDataUri(value)) return false; + if (value.startsWith("oss://")) return false; + return true; +} + +function redactImageForDryRun(image: string): string { + if (isDataUri(image)) return redactDataUri(image); + if (isLocalPathCandidate(image)) return LOCAL_IMAGE_PENDING_ENCODE; + return image; +} + +function resolveLocalImage( + image: string, + maxImageBytes: number, + localize: (text: LocalizedText) => string, +): string { + if (!existsSync(image)) { + usageError(localize, { + "en-US": `Image file not found: ${image}`, + "zh-CN": `找不到图片文件:${image}`, + }); + } + const stats = statSync(image); + if (!stats.isFile()) { + usageError(localize, { + "en-US": `Not a file: ${image}`, + "zh-CN": `不是文件:${image}`, + }); + } + if (maxImageBytes > 0 && stats.size > maxImageBytes) { + usageError(localize, { + "en-US": `Local image exceeds the ${Math.round(maxImageBytes / (1024 * 1024))} MB limit for this model (${image}). Prefer a public HTTP(S) URL for large images.`, + "zh-CN": `本地图片超过该模型 ${Math.round(maxImageBytes / (1024 * 1024))} MB 上限(${image})。大图请优先使用公网 HTTP(S) URL。`, + }); + } + return imageFileToDataUri(image); +} + +function resolveImageInput( + image: string, + maxImageBytes: number, + localize: (text: LocalizedText) => string, +): string { + if (isDataUri(image) || isHttpUrl(image)) return image; + if (image.startsWith("oss://")) { + usageError(localize, { + "en-US": + "oss:// image URLs are not supported for embedding. Use a public HTTP(S) URL, Data URI, or local image path.", + "zh-CN": + "embedding 不支持 oss:// 图片 URL。请使用公网 HTTP(S) URL、Data URI 或本地图片路径。", + }); + } + return resolveLocalImage(image, maxImageBytes, localize); +} + +function assertVideoUrl(video: string, localize: (text: LocalizedText) => string): string { + if (isHttpUrl(video)) return video; + usageError(localize, { + "en-US": `Video input must be a public HTTP(S) URL (got "${video}"). Local video paths are not supported in this command.`, + "zh-CN": `视频输入必须是公网 HTTP(S) URL(收到 "${video}")。本命令不支持本地视频路径。`, + }); +} + +function writeResponseFile( + outPath: string, + response: unknown, + localize: (text: LocalizedText) => string, +): string { + try { + mkdirSync(dirname(outPath), { recursive: true }); + writeFileSync(outPath, `${JSON.stringify(response, null, 2)}\n`); + return outPath; + } catch (error) { + const reason = error instanceof Error ? error.message : String(error); + throw new BailianError( + localize({ + "en-US": `Failed to write --out file "${outPath}": ${reason}`, + "zh-CN": `写入 --out 文件 "${outPath}" 失败:${reason}`, + }), + ExitCode.GENERAL, + ); + } +} + +function formatTextSummary(options: { + model: string; + count: number; + dimensions?: number; + fusion?: boolean; + saved?: string; +}): string { + const parts = [`model: ${options.model}`, `count: ${options.count}`]; + if (options.dimensions !== undefined) parts.push(`dimensions: ${options.dimensions}`); + if (options.fusion !== undefined) parts.push(`fusion: ${options.fusion}`); + if (options.saved) parts.push(`saved: ${options.saved}`); + return parts.join("\n"); +} + +function embeddingCount(response: TextEmbeddingResponse | MultimodalEmbeddingResponse): number { + if ("data" in response && Array.isArray(response.data)) return response.data.length; + if ("output" in response && Array.isArray(response.output?.embeddings)) { + return response.output.embeddings.length; + } + return 0; +} + +function embeddingDimensions( + response: TextEmbeddingResponse | MultimodalEmbeddingResponse, +): number | undefined { + if ("data" in response && response.data?.[0]?.embedding) { + return response.data[0].embedding.length; + } + if ("output" in response && response.output?.embeddings?.[0]?.embedding) { + return response.output.embeddings[0].embedding.length; + } + return undefined; +} + +export default defineCommand({ + description: { + "en-US": "Create text or multimodal embeddings", + "zh-CN": "创建文本或多模态向量", + }, + auth: "apiKey", + usageArgs: "(--text | --image | --video )... [flags]", + flags: CREATE_FLAGS, + exampleArgs: [ + { + "en-US": '--text "城市夜景" --text "繁忙街道" --dimensions 1024 --dry-run --output json', + "zh-CN": '--text "城市夜景" --text "繁忙街道" --dimensions 1024 --dry-run --output json', + }, + { + "en-US": + '--text "城市夜景" --image ./city.png --model qwen3-vl-embedding --fuse true --out vectors.json', + "zh-CN": + '--text "城市夜景" --image ./city.png --model qwen3-vl-embedding --fuse true --out vectors.json', + }, + ], + notes: [ + { + "en-US": + "Content order is fixed as text → image → video across flags (repeatable flags keep their own order). Multiple inputs do not imply fusion — use --fuse with qwen3-vl-embedding. Local video is unsupported; prefer public HTTP(S) URLs for large images. Billed per call; this command does not auto-batch. For knowledge-base indexing / retrieval use knowledge commands, not embedding create.", + "zh-CN": + "跨 flag 的内容顺序固定为 text → image → video(可重复 flag 保留各自顺序)。多输入不等于融合向量——qwen3-vl-embedding 请用 --fuse。不支持本地视频;大图优先公网 HTTP(S) URL。按调用计费,不会自动分批。建库 / 召回请用 knowledge 命令,不要用 embedding create。", + }, + ], + validate: (flags) => { + const texts = (flags.text as string[] | undefined)?.length ?? 0; + const images = (flags.image as string[] | undefined)?.length ?? 0; + const videos = (flags.video as string[] | undefined)?.length ?? 0; + if (texts + images + videos === 0) { + return { + "en-US": "Provide at least one of --text, --image, or --video.", + "zh-CN": "请至少提供 --text、--image 或 --video 之一。", + }; + } + return undefined; + }, + async run(ctx) { + const { settings, flags } = ctx; + const localize = ctx.localize; + const texts = nonEmptyStrings(flags.text as string[] | undefined, "--text", localize); + const images = nonEmptyStrings(flags.image as string[] | undefined, "--image", localize); + const videos = nonEmptyStrings(flags.video as string[] | undefined, "--video", localize); + const hasMedia = images.length > 0 || videos.length > 0; + + let route; + try { + route = resolveEmbeddingRoute({ + model: flags.model as string | undefined, + hasMedia, + }); + assertEmbeddingDimensions(route.spec, flags.dimensions as number | undefined); + assertEmbeddingFusion(route.spec, flags.fuse as boolean | undefined); + assertEmbeddingInputCounts(route.spec, { + texts: texts.length, + images: images.length, + videos: videos.length, + }); + } catch (error) { + if (error instanceof EmbeddingRouteError) routeError(localize, error); + throw error; + } + + for (const video of videos) assertVideoUrl(video, localize); + + const dimensions = flags.dimensions as number | undefined; + const fuse = flags.fuse as boolean | undefined; + const endpoint = ctx.client.url(route.path); + + if (route.spec.kind === "compatible-text") { + const request: TextEmbeddingRequest = { + model: route.model, + input: texts, + encoding_format: "float", + }; + if (dimensions !== undefined) request.dimensions = dimensions; + + if (settings.dryRun) { + ctx.output.result({ endpoint, request }); + return; + } + + const response = await ctx.client.requestJson({ + path: route.path, + method: "POST", + body: request, + }); + + let saved: string | undefined; + if (flags.out) { + saved = writeResponseFile(flags.out as string, response, localize); + } + + const result = saved ? { ...response, saved } : response; + const text = formatTextSummary({ + model: route.model, + count: embeddingCount(response), + dimensions: dimensions ?? embeddingDimensions(response), + saved, + }); + ctx.output.result(result, settings.output === "text" ? { text } : undefined); + return; + } + + const dryRunContents: MultimodalEmbeddingContent[] = [ + ...texts.map((text) => ({ text })), + ...images.map((image) => ({ image: redactImageForDryRun(image) })), + ...videos.map((video) => ({ video })), + ]; + + const parameters = stripUndefined({ + dimension: dimensions, + enable_fusion: fuse, + }); + + const dryRunRequest: MultimodalEmbeddingRequest = stripUndefined({ + model: route.model, + input: { contents: dryRunContents }, + parameters: Object.keys(parameters).length > 0 ? parameters : undefined, + }); + + if (settings.dryRun) { + ctx.output.result({ endpoint, request: dryRunRequest }); + return; + } + + const contents: MultimodalEmbeddingContent[] = [ + ...texts.map((text) => ({ text })), + ...images.map((image) => ({ + image: resolveImageInput(image, route.spec.maxImageBytes, localize), + })), + ...videos.map((video) => ({ video: assertVideoUrl(video, localize) })), + ]; + + const request: MultimodalEmbeddingRequest = stripUndefined({ + model: route.model, + input: { contents }, + parameters: Object.keys(parameters).length > 0 ? parameters : undefined, + }); + + const response = await ctx.client.requestJson({ + path: route.path, + method: "POST", + body: request, + }); + + let saved: string | undefined; + if (flags.out) { + saved = writeResponseFile(flags.out as string, response, localize); + } + + const result = saved ? { ...response, saved } : response; + const text = formatTextSummary({ + model: route.model, + count: embeddingCount(response), + dimensions: dimensions ?? embeddingDimensions(response), + fusion: fuse, + saved, + }); + ctx.output.result(result, settings.output === "text" ? { text } : undefined); + }, +}); diff --git a/packages/commands/src/commands/rerank.ts b/packages/commands/src/commands/rerank.ts new file mode 100644 index 000000000..131f9f4e2 --- /dev/null +++ b/packages/commands/src/commands/rerank.ts @@ -0,0 +1,636 @@ +import { dirname, isAbsolute, resolve as resolvePath } from "node:path"; +import { existsSync, readFileSync, statSync } from "node:fs"; +import { + BailianError, + ExitCode, + defineCommand, + imageFileToDataUri, + LOCAL_IMAGE_PENDING_ENCODE, + redactDataUri, + rerankPath, + stripUndefined, + type FlagsDef, + type LocalizedText, + type RerankDocumentInput, + type RerankQueryInput, + type RerankRequest, + type RerankResponse, + type RerankResultItem, +} from "bailian-cli-core"; + +const DEFAULT_MODEL = "qwen3-rerank"; + +type RerankModelKind = "text" | "vl"; + +interface RerankModelSpec { + model: string; + kind: RerankModelKind; + maxDocuments: number; + maxTextDocuments?: number; + maxImageDocuments?: number; + maxVideoDocuments?: number; + supportsInstruct: boolean; + /** Local image byte limit for Data URI encoding. */ + maxImageBytes: number; +} + +const RERANK_MODELS: readonly RerankModelSpec[] = [ + { + model: "qwen3-rerank", + kind: "text", + maxDocuments: 500, + supportsInstruct: true, + maxImageBytes: 0, + }, + { + model: "gte-rerank-v2", + kind: "text", + maxDocuments: 500, + supportsInstruct: false, + maxImageBytes: 0, + }, + { + model: "qwen3.7-text-rerank", + kind: "text", + maxDocuments: 500, + supportsInstruct: true, + maxImageBytes: 0, + }, + { + model: "qwen3-vl-rerank", + kind: "vl", + maxDocuments: Number.POSITIVE_INFINITY, + maxTextDocuments: 100, + maxImageDocuments: 40, + maxVideoDocuments: 4, + supportsInstruct: true, + maxImageBytes: 10 * 1024 * 1024, + }, +]; + +const RERANK_MODEL_BY_ID = new Map(RERANK_MODELS.map((spec) => [spec.model, spec])); + +const RERANK_FLAGS = { + query: { + type: "string", + valueHint: "", + description: { + "en-US": "Query text (mutually exclusive with --query-image)", + "zh-CN": "查询文本(与 --query-image 二选一)", + }, + }, + queryImage: { + type: "string", + valueHint: "", + description: { + "en-US": + "Query image URL or local path (qwen3-vl-rerank only; mutually exclusive with --query)", + "zh-CN": "查询图片 URL 或本地路径(仅 qwen3-vl-rerank;与 --query 二选一)", + }, + }, + document: { + type: "array", + valueHint: "", + description: { + "en-US": "Candidate document text (repeatable; mutually exclusive with --documents-file)", + "zh-CN": "候选文档文本(可重复;与 --documents-file 二选一)", + }, + }, + documentsFile: { + type: "string", + valueHint: "", + description: { + "en-US": "JSON file containing candidate documents", + "zh-CN": "候选文档 JSON 文件", + }, + }, + model: { + type: "string", + valueHint: "", + description: { + "en-US": + "Rerank model (default: qwen3-rerank; also gte-rerank-v2, qwen3.7-text-rerank, qwen3-vl-rerank)", + "zh-CN": + "重排序模型(默认:qwen3-rerank;另支持 gte-rerank-v2、qwen3.7-text-rerank、qwen3-vl-rerank)", + }, + }, + topN: { + type: "number", + valueHint: "", + description: { + "en-US": + "Return top N results (positive integer; values larger than the candidate count are allowed)", + "zh-CN": "返回前 N 条结果(正整数;大于候选数时由服务端返回全部)", + }, + }, + instruct: { + type: "string", + valueHint: "", + description: { + "en-US": "Rerank instruction (qwen3 / qwen3.7 / qwen3-vl; rejected by gte-rerank-v2)", + "zh-CN": "重排序指令(qwen3 / qwen3.7 / qwen3-vl;gte-rerank-v2 拒绝)", + }, + }, + returnDocuments: { + type: "boolean", + valueHint: "", + description: { + "en-US": + "Ask the server to return document payloads (false is preserved; qwen3.7 support follows the server)", + "zh-CN": "请求服务端返回文档内容(false 会保留;qwen3.7 是否支持以服务端为准)", + }, + }, + fps: { + type: "number", + valueHint: "", + description: { + "en-US": "Video frame sampling rate for qwen3-vl-rerank only, in (0, 5] frames per second", + "zh-CN": "仅 qwen3-vl-rerank 视频抽帧率,取值 (0, 5] 帧/秒", + }, + }, +} satisfies FlagsDef; + +function usageError(localize: (text: LocalizedText) => string, text: LocalizedText): never { + throw new BailianError(localize(text), ExitCode.USAGE); +} + +function isHttpUrl(value: string): boolean { + return /^https?:\/\//i.test(value); +} + +function isDataUri(value: string): boolean { + return /^data:/i.test(value); +} + +function isLocalPathCandidate(value: string): boolean { + if (isHttpUrl(value) || isDataUri(value) || value.startsWith("oss://")) return false; + return true; +} + +function lookupModel(model: string, localize: (text: LocalizedText) => string): RerankModelSpec { + const spec = RERANK_MODEL_BY_ID.get(model); + if (!spec) { + usageError(localize, { + "en-US": `Unknown rerank model "${model}". Supported: ${RERANK_MODELS.map((item) => item.model).join(", ")}.`, + "zh-CN": `未知重排序模型 "${model}"。支持:${RERANK_MODELS.map((item) => item.model).join(", ")}。`, + }); + } + return spec; +} + +function resolveImageRelativeTo(image: string, baseDir: string | undefined): string { + if (!isLocalPathCandidate(image)) return image; + if (isAbsolute(image) || baseDir === undefined) return image; + return resolvePath(baseDir, image); +} + +function resolveImageValue( + image: string, + options: { + baseDir?: string; + maxImageBytes: number; + dryRun: boolean; + localize: (text: LocalizedText) => string; + }, +): string { + const resolved = resolveImageRelativeTo(image, options.baseDir); + if (isDataUri(resolved)) { + return options.dryRun ? redactDataUri(resolved) : resolved; + } + if (isHttpUrl(resolved)) return resolved; + if (resolved.startsWith("oss://")) { + usageError(options.localize, { + "en-US": + "oss:// media URLs are not supported for rerank. Use a public HTTP(S) URL, Data URI, or local image path.", + "zh-CN": "rerank 不支持 oss:// 媒体 URL。请使用公网 HTTP(S) URL、Data URI 或本地图片路径。", + }); + } + if (options.dryRun) return LOCAL_IMAGE_PENDING_ENCODE; + if (!existsSync(resolved)) { + usageError(options.localize, { + "en-US": `Image file not found: ${resolved}`, + "zh-CN": `找不到图片文件:${resolved}`, + }); + } + const stats = statSync(resolved); + if (!stats.isFile()) { + usageError(options.localize, { + "en-US": `Not a file: ${resolved}`, + "zh-CN": `不是文件:${resolved}`, + }); + } + if (options.maxImageBytes > 0 && stats.size > options.maxImageBytes) { + usageError(options.localize, { + "en-US": `Local image exceeds the ${Math.round(options.maxImageBytes / (1024 * 1024))} MB limit (${resolved}). Prefer a public HTTP(S) URL.`, + "zh-CN": `本地图片超过 ${Math.round(options.maxImageBytes / (1024 * 1024))} MB 上限(${resolved})。请优先使用公网 HTTP(S) URL。`, + }); + } + return imageFileToDataUri(resolved); +} + +function assertVideoUrl(video: string, localize: (text: LocalizedText) => string): string { + if (isHttpUrl(video)) return video; + usageError(localize, { + "en-US": `Video document must be a public HTTP(S) URL (got "${video}"). Local video paths are not supported.`, + "zh-CN": `视频文档必须是公网 HTTP(S) URL(收到 "${video}")。不支持本地视频路径。`, + }); +} + +function parseDocumentsFile(filePath: string, localize: (text: LocalizedText) => string): unknown { + if (!existsSync(filePath)) { + usageError(localize, { + "en-US": `Documents file not found: ${filePath}`, + "zh-CN": `找不到候选文档文件:${filePath}`, + }); + } + let raw: string; + try { + raw = readFileSync(filePath, "utf8"); + } catch (error) { + const reason = error instanceof Error ? error.message : String(error); + usageError(localize, { + "en-US": `Failed to read documents file "${filePath}": ${reason}`, + "zh-CN": `读取候选文档文件 "${filePath}" 失败:${reason}`, + }); + } + try { + return JSON.parse(raw); + } catch (error) { + const reason = error instanceof Error ? error.message : String(error); + usageError(localize, { + "en-US": `Documents file is not valid JSON: ${reason}`, + "zh-CN": `候选文档文件不是合法 JSON:${reason}`, + }); + } +} + +function normalizeDocumentEntry( + entry: unknown, + index: number, + localize: (text: LocalizedText) => string, +): RerankDocumentInput { + if (typeof entry === "string") { + if (!entry.trim()) { + usageError(localize, { + "en-US": `Document[${index}] must be a non-empty string.`, + "zh-CN": `Document[${index}] 必须为非空字符串。`, + }); + } + return entry; + } + if (!entry || typeof entry !== "object" || Array.isArray(entry)) { + usageError(localize, { + "en-US": `Document[${index}] must be a string or an object with exactly one of text/image/video.`, + "zh-CN": `Document[${index}] 必须是字符串,或仅含 text/image/video 之一的对象。`, + }); + } + const record = entry as Record; + const keys = ["text", "image", "video"].filter((key) => record[key] !== undefined); + if (keys.length !== 1) { + usageError(localize, { + "en-US": `Document[${index}] must contain exactly one of text/image/video.`, + "zh-CN": `Document[${index}] 必须且只能包含 text/image/video 之一。`, + }); + } + const key = keys[0]!; + const value = record[key]; + if (typeof value !== "string" || !value.trim()) { + usageError(localize, { + "en-US": `Document[${index}].${key} must be a non-empty string.`, + "zh-CN": `Document[${index}].${key} 必须为非空字符串。`, + }); + } + if (key === "text") return { text: value }; + if (key === "image") return { image: value }; + return { video: value }; +} + +function countModalities(documents: RerankDocumentInput[]): { + text: number; + image: number; + video: number; +} { + let text = 0; + let image = 0; + let video = 0; + for (const document of documents) { + if (typeof document === "string" || "text" in document) text += 1; + else if ("image" in document) image += 1; + else if ("video" in document) video += 1; + } + return { text, image, video }; +} + +function assertDocumentLimits( + spec: RerankModelSpec, + documents: RerankDocumentInput[], + localize: (text: LocalizedText) => string, +): void { + if (documents.length === 0) { + usageError(localize, { + "en-US": "Provide at least one candidate document.", + "zh-CN": "请至少提供一条候选文档。", + }); + } + if (documents.length > spec.maxDocuments) { + usageError(localize, { + "en-US": `Model "${spec.model}" accepts at most ${spec.maxDocuments} documents; got ${documents.length}.`, + "zh-CN": `模型 "${spec.model}" 最多接受 ${spec.maxDocuments} 条候选;当前为 ${documents.length}。`, + }); + } + const counts = countModalities(documents); + if (spec.kind === "text" && (counts.image > 0 || counts.video > 0)) { + usageError(localize, { + "en-US": `Model "${spec.model}" only accepts text documents. Use qwen3-vl-rerank for image/video candidates.`, + "zh-CN": `模型 "${spec.model}" 仅接受文本文档。图/视频候选请使用 qwen3-vl-rerank。`, + }); + } + if (spec.maxTextDocuments !== undefined && counts.text > spec.maxTextDocuments) { + usageError(localize, { + "en-US": `Model "${spec.model}" accepts at most ${spec.maxTextDocuments} text documents; got ${counts.text}.`, + "zh-CN": `模型 "${spec.model}" 最多接受 ${spec.maxTextDocuments} 条文本文档;当前为 ${counts.text}。`, + }); + } + if (spec.maxImageDocuments !== undefined && counts.image > spec.maxImageDocuments) { + usageError(localize, { + "en-US": `Model "${spec.model}" accepts at most ${spec.maxImageDocuments} image documents; got ${counts.image}.`, + "zh-CN": `模型 "${spec.model}" 最多接受 ${spec.maxImageDocuments} 张图片文档;当前为 ${counts.image}。`, + }); + } + if (spec.maxVideoDocuments !== undefined && counts.video > spec.maxVideoDocuments) { + usageError(localize, { + "en-US": `Model "${spec.model}" accepts at most ${spec.maxVideoDocuments} video documents; got ${counts.video}.`, + "zh-CN": `模型 "${spec.model}" 最多接受 ${spec.maxVideoDocuments} 个视频文档;当前为 ${counts.video}。`, + }); + } +} + +function encodeDocuments( + documents: RerankDocumentInput[], + options: { + baseDir?: string; + maxImageBytes: number; + dryRun: boolean; + localize: (text: LocalizedText) => string; + }, +): RerankDocumentInput[] { + return documents.map((document) => { + if (typeof document === "string") return document; + if ("text" in document) return document; + if ("image" in document) { + return { + image: resolveImageValue(document.image, options), + }; + } + return { video: assertVideoUrl(document.video, options.localize) }; + }); +} + +function summarizeDocument(document: unknown): string { + if (document === undefined || document === null) return ""; + if (typeof document === "string") { + return document.length > 80 ? `${document.slice(0, 77)}...` : document; + } + if (typeof document === "object") { + const record = document as Record; + if (typeof record.text === "string") { + return record.text.length > 80 ? `${record.text.slice(0, 77)}...` : record.text; + } + if (typeof record.image === "string") { + const image = isDataUri(record.image) ? redactDataUri(record.image) : record.image; + return `image:${image.length > 60 ? `${image.slice(0, 57)}...` : image}`; + } + if (typeof record.video === "string") return `video:${record.video}`; + return JSON.stringify(document); + } + if ( + typeof document === "number" || + typeof document === "boolean" || + typeof document === "bigint" + ) { + return String(document); + } + return JSON.stringify(document); +} + +function formatTextResults(results: RerankResultItem[]): string { + if (results.length === 0) return "No results."; + return results + .map((item) => { + const documentSummary = summarizeDocument(item.document); + const suffix = documentSummary ? ` ${documentSummary}` : ""; + return `#${item.index} score=${item.relevance_score}${suffix}`; + }) + .join("\n"); +} + +export default defineCommand({ + description: { + "en-US": "Rerank candidate documents for a query", + "zh-CN": "对查询与候选文档进行重排序", + }, + auth: "apiKey", + usageArgs: + "(--query | --query-image ) (--document ... | --documents-file ) [flags]", + flags: RERANK_FLAGS, + exampleArgs: [ + { + "en-US": + '--query "城市夜景" --document "白天的田野" --document "霓虹街道与夜空" --top-n 1 --return-documents true --dry-run --output json', + "zh-CN": + '--query "城市夜景" --document "白天的田野" --document "霓虹街道与夜空" --top-n 1 --return-documents true --dry-run --output json', + }, + { + "en-US": + '--model qwen3-vl-rerank --query "城市夜景" --documents-file candidates.json --output json', + "zh-CN": + '--model qwen3-vl-rerank --query "城市夜景" --documents-file candidates.json --output json', + }, + ], + notes: [ + { + "en-US": + "relevance_score is comparable only within one request; this CLI never re-sorts or merges scores across batches. Paths in --documents-file are resolved relative to that file's directory; --query-image uses the process cwd. Local video is unsupported. Billed per call (up to 500 candidates). For knowledge-base retrieval / server-side hybrid ranking use knowledge commands, not rerank.", + "zh-CN": + "relevance_score 仅可在单次请求内比较;CLI 不会二次排序或跨批合并分数。--documents-file 内相对路径相对该文件目录解析;--query-image 相对进程 cwd。不支持本地视频。按调用计费(最多 500 候选)。建库 / 召回 / 服务侧混排请用 knowledge 命令,不要用 rerank。", + }, + ], + validate: (flags) => { + const queryCount = + (flags.query !== undefined ? 1 : 0) + (flags.queryImage !== undefined ? 1 : 0); + if (queryCount !== 1) { + return { + "en-US": + queryCount === 0 + ? "Provide --query or --query-image." + : "Use only one of --query or --query-image.", + "zh-CN": + queryCount === 0 + ? "请提供 --query 或 --query-image。" + : "--query 与 --query-image 只能选择一个。", + }; + } + const documentCount = + ((flags.document as string[] | undefined)?.length ? 1 : 0) + + (flags.documentsFile !== undefined ? 1 : 0); + if (documentCount !== 1) { + return { + "en-US": + documentCount === 0 + ? "Provide --document or --documents-file." + : "Use only one of --document or --documents-file.", + "zh-CN": + documentCount === 0 + ? "请提供 --document 或 --documents-file。" + : "--document 与 --documents-file 只能选择一个。", + }; + } + return undefined; + }, + async run(ctx) { + const { settings, flags } = ctx; + const localize = ctx.localize; + const model = ((flags.model as string | undefined) || DEFAULT_MODEL).trim(); + const spec = lookupModel(model, localize); + + const queryText = flags.query as string | undefined; + const queryImage = flags.queryImage as string | undefined; + if (queryText !== undefined && !queryText.trim()) { + usageError(localize, { + "en-US": "--query must be a non-empty string.", + "zh-CN": "--query 必须为非空字符串。", + }); + } + if (queryImage !== undefined && spec.kind !== "vl") { + usageError(localize, { + "en-US": `--query-image is only supported by qwen3-vl-rerank (got "${model}").`, + "zh-CN": `--query-image 仅 qwen3-vl-rerank 支持(当前为 "${model}")。`, + }); + } + + const topN = flags.topN as number | undefined; + if (topN !== undefined) { + if (!Number.isInteger(topN) || topN <= 0 || !Number.isFinite(topN)) { + usageError(localize, { + "en-US": "--top-n must be a positive integer.", + "zh-CN": "--top-n 必须为正整数。", + }); + } + } + + const instruct = flags.instruct as string | undefined; + if (instruct !== undefined) { + if (!instruct.trim()) { + usageError(localize, { + "en-US": "--instruct must be a non-empty string.", + "zh-CN": "--instruct 必须为非空字符串。", + }); + } + if (!spec.supportsInstruct) { + usageError(localize, { + "en-US": `Model "${model}" does not support --instruct.`, + "zh-CN": `模型 "${model}" 不支持 --instruct。`, + }); + } + } + + const fps = flags.fps as number | undefined; + if (fps !== undefined) { + if (spec.kind !== "vl") { + usageError(localize, { + "en-US": `--fps is only supported by qwen3-vl-rerank (got "${model}").`, + "zh-CN": `--fps 仅 qwen3-vl-rerank 支持(当前为 "${model}")。`, + }); + } + if (!(fps > 0 && fps <= 5) || !Number.isFinite(fps)) { + usageError(localize, { + "en-US": "--fps must be in (0, 5].", + "zh-CN": "--fps 必须在 (0, 5] 范围内。", + }); + } + } + + let documents: RerankDocumentInput[] = []; + let documentsBaseDir: string | undefined; + if (flags.documentsFile !== undefined) { + const filePath = flags.documentsFile as string; + const parsed = parseDocumentsFile(filePath, localize); + if (!Array.isArray(parsed) || parsed.length === 0) { + usageError(localize, { + "en-US": "Documents file must be a non-empty JSON array.", + "zh-CN": "候选文档文件必须是非空 JSON 数组。", + }); + } + documents = parsed.map((entry, index) => normalizeDocumentEntry(entry, index, localize)); + documentsBaseDir = dirname(resolvePath(filePath)); + } else { + const documentFlags = flags.document as string[] | undefined; + documents = (documentFlags ?? []).map((value, index) => { + if (!value.trim()) { + usageError(localize, { + "en-US": `--document[${index}] must be a non-empty string.`, + "zh-CN": `--document[${index}] 必须为非空字符串。`, + }); + } + return value; + }); + } + + assertDocumentLimits(spec, documents, localize); + + const dryRun = settings.dryRun; + const encodedDocuments = encodeDocuments(documents, { + baseDir: documentsBaseDir, + maxImageBytes: spec.maxImageBytes, + dryRun, + localize, + }); + + let query: RerankQueryInput; + if (queryImage !== undefined) { + query = { + image: resolveImageValue(queryImage, { + maxImageBytes: spec.maxImageBytes, + dryRun, + localize, + }), + }; + } else { + query = queryText!.trim(); + } + + const parameters = stripUndefined({ + top_n: topN, + return_documents: flags.returnDocuments as boolean | undefined, + instruct: instruct?.trim(), + fps, + }); + + const request: RerankRequest = stripUndefined({ + model, + input: { + query, + documents: encodedDocuments, + }, + parameters: Object.keys(parameters).length > 0 ? parameters : undefined, + }); + + const endpoint = ctx.client.url(rerankPath()); + if (dryRun) { + ctx.output.result({ endpoint, request }); + return; + } + + const response = await ctx.client.requestJson({ + path: rerankPath(), + method: "POST", + body: request, + }); + + const results = response.output?.results ?? []; + ctx.output.result( + response, + settings.output === "text" ? { text: formatTextResults(results) } : undefined, + ); + }, +}); diff --git a/packages/commands/src/index.ts b/packages/commands/src/index.ts index 4968da6f4..52aec2a86 100644 --- a/packages/commands/src/index.ts +++ b/packages/commands/src/index.ts @@ -9,6 +9,8 @@ export { default as authLogout } from "./commands/auth/logout.ts"; export { default as authGenerateAccessToken } from "./commands/auth/generate-access-token.ts"; export { default as textChat } from "./commands/text/chat.ts"; export { default as textTranslate } from "./commands/text/translate.ts"; +export { default as embeddingCreate } from "./commands/embedding/create.ts"; +export { default as rerank } from "./commands/rerank.ts"; export { default as batchConvert } from "./commands/batch/convert.ts"; export { default as batchCreate } from "./commands/batch/create.ts"; export { default as batchList } from "./commands/batch/list.ts"; diff --git a/packages/commands/tests/e2e/embedding-create.e2e.test.ts b/packages/commands/tests/e2e/embedding-create.e2e.test.ts new file mode 100644 index 000000000..5033c5205 --- /dev/null +++ b/packages/commands/tests/e2e/embedding-create.e2e.test.ts @@ -0,0 +1,575 @@ +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { createServer, type IncomingMessage, type Server, type ServerResponse } from "node:http"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterEach, beforeEach, describe, expect, test } from "vite-plus/test"; +import { + isBailianE2EMediaEnabled, + isDashScopeE2EReady, + makeE2eOutputDir, + parseStdoutJson, + runCommandE2e, + runCommandHelp, + runCommandInProcess, +} from "./helpers.ts"; +import { EMBEDDING_ROUTES } from "./topic-routes.ts"; + +let isolatedDirectory: string; +const servers: Server[] = []; + +beforeEach(() => { + isolatedDirectory = mkdtempSync(join(tmpdir(), "bl-embedding-e2e-")); + writeFileSync(join(isolatedDirectory, "config.json"), "{}"); +}); + +afterEach(async () => { + await Promise.all( + servers.splice(0).map( + (server) => + new Promise((resolve, reject) => { + server.close((error) => (error ? reject(error) : resolve())); + }), + ), + ); + rmSync(isolatedDirectory, { recursive: true, force: true }); +}); + +async function startServer( + handler: (request: IncomingMessage, response: ServerResponse, body: string) => void, +): Promise<{ + origin: string; + requests: Array<{ method?: string; path: string; auth?: string; body: unknown }>; +}> { + const requests: Array<{ method?: string; path: string; auth?: string; body: unknown }> = []; + const server = createServer((request, response) => { + const chunks: Buffer[] = []; + request.on("data", (chunk: Buffer) => chunks.push(chunk)); + request.on("end", () => { + const raw = Buffer.concat(chunks).toString("utf8"); + let body: unknown = raw; + try { + body = raw ? JSON.parse(raw) : undefined; + } catch { + body = raw; + } + requests.push({ + method: request.method, + path: request.url ?? "", + auth: request.headers.authorization, + body, + }); + handler(request, response, raw); + }); + }); + await new Promise((resolve, reject) => { + server.once("error", reject); + server.listen(0, "127.0.0.1", resolve); + }); + servers.push(server); + const address = server.address(); + if (!address || typeof address === "string") throw new Error("Expected TCP address"); + return { origin: `http://127.0.0.1:${address.port}`, requests }; +} + +const TINY_PNG = Buffer.from( + "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==", + "base64", +); + +function isolatedEnv(extra: NodeJS.ProcessEnv = {}) { + return { + BAILIAN_CONFIG_DIR: isolatedDirectory, + HOME: isolatedDirectory, + USERPROFILE: isolatedDirectory, + DASHSCOPE_API_KEY: "", + DASHSCOPE_BASE_URL: "", + ...extra, + }; +} + +describe("e2e: embedding create", () => { + test("help lists flags bilingually", async () => { + const { stderr, exitCode } = await runCommandHelp(EMBEDDING_ROUTES, [ + "embedding", + "create", + "--help", + ]); + expect(exitCode, stderr).toBe(0); + expect(stderr).toMatch(/--text/); + expect(stderr).toMatch(/--image/); + expect(stderr).toMatch(/--video/); + expect(stderr).toMatch(/--dimensions/); + expect(stderr).toMatch(/Embedding dimensions|向量维度/); + expect(stderr).toMatch(/text-embedding-v4/); + expect(stderr).toMatch(/qwen3-vl-embedding/); + }); + + test("missing inputs → 2", async () => { + const { stderr, exitCode } = await runCommandInProcess( + EMBEDDING_ROUTES, + ["embedding", "create", "--dry-run", "--quiet"], + isolatedEnv(), + ); + expect(exitCode).toBe(2); + expect(stderr).toMatch(/--text|--image|--video/); + }); + + test("blank --text → 2", async () => { + const { stderr, exitCode } = await runCommandInProcess( + EMBEDDING_ROUTES, + ["embedding", "create", "--text", " ", "--dry-run", "--quiet"], + isolatedEnv(), + ); + expect(exitCode).toBe(2); + expect(stderr).toMatch(/non-empty|非空/); + }); + + test("text model + media → 2", async () => { + const { stderr, exitCode } = await runCommandInProcess( + EMBEDDING_ROUTES, + [ + "embedding", + "create", + "--model", + "text-embedding-v4", + "--text", + "a", + "--image", + "https://example.com/a.png", + "--dry-run", + "--quiet", + ], + isolatedEnv(), + ); + expect(exitCode).toBe(2); + expect(stderr).toMatch(/does not accept|--image/); + }); + + test("unknown model → 2", async () => { + const { stderr, exitCode } = await runCommandInProcess( + EMBEDDING_ROUTES, + ["embedding", "create", "--model", "no-such-embed", "--text", "a", "--dry-run", "--quiet"], + isolatedEnv(), + ); + expect(exitCode).toBe(2); + expect(stderr).toMatch(/Unknown embedding model|未知向量模型/); + }); + + test("fuse on text model → 2; fuse=false preserved for qwen3", async () => { + const rejected = await runCommandInProcess( + EMBEDDING_ROUTES, + ["embedding", "create", "--text", "a", "--fuse", "true", "--dry-run", "--quiet"], + isolatedEnv(), + ); + expect(rejected.exitCode).toBe(2); + expect(rejected.stderr).toMatch(/does not support --fuse|不支持 --fuse/); + + const ok = await runCommandInProcess( + EMBEDDING_ROUTES, + [ + "embedding", + "create", + "--model", + "qwen3-vl-embedding", + "--text", + "a", + "--fuse", + "false", + "--dry-run", + "--output", + "json", + ], + isolatedEnv({ DASHSCOPE_API_KEY: "sk-e2e-placeholder" }), + ); + expect(ok.exitCode, ok.stderr).toBe(0); + const data = parseStdoutJson<{ + request?: { parameters?: { enable_fusion?: boolean } }; + }>(ok.stdout); + expect(data.request?.parameters?.enable_fusion).toBe(false); + }); + + test("dry-run text uses dimensions; multimodal uses dimension", async () => { + const text = await runCommandInProcess( + EMBEDDING_ROUTES, + [ + "embedding", + "create", + "--text", + "城市夜景", + "--text", + "繁忙街道", + "--dimensions", + "1024", + "--dry-run", + "--output", + "json", + ], + isolatedEnv({ DASHSCOPE_API_KEY: "sk-e2e-placeholder" }), + ); + expect(text.exitCode, text.stderr).toBe(0); + const textData = parseStdoutJson<{ + endpoint?: string; + request?: Record; + }>(text.stdout); + expect(textData.endpoint).toMatch(/\/compatible-mode\/v1\/embeddings$/); + expect(textData.request).toMatchObject({ + model: "text-embedding-v4", + input: ["城市夜景", "繁忙街道"], + dimensions: 1024, + encoding_format: "float", + }); + expect(textData.request).not.toHaveProperty("parameters"); + + const imagePath = join(isolatedDirectory, "city.png"); + writeFileSync(imagePath, TINY_PNG); + const multimodal = await runCommandInProcess( + EMBEDDING_ROUTES, + [ + "embedding", + "create", + "--text", + "城市夜景", + "--image", + imagePath, + "--image", + "data:image/png;base64,QUJDRA==", + "--video", + "https://example.com/clip.mp4", + "--model", + "qwen3-vl-embedding", + "--dimensions", + "1024", + "--fuse", + "true", + "--dry-run", + "--output", + "json", + ], + isolatedEnv({ DASHSCOPE_API_KEY: "sk-e2e-placeholder" }), + ); + expect(multimodal.exitCode, multimodal.stderr).toBe(0); + const multiData = parseStdoutJson<{ + endpoint?: string; + request?: { + model?: string; + input?: { contents?: Array> }; + parameters?: { dimension?: number; enable_fusion?: boolean; dimensions?: number }; + }; + }>(multimodal.stdout); + expect(multiData.endpoint).toMatch(/multimodal-embedding\/multimodal-embedding$/); + expect(multiData.request?.model).toBe("qwen3-vl-embedding"); + expect(multiData.request?.parameters?.dimension).toBe(1024); + expect(multiData.request?.parameters?.enable_fusion).toBe(true); + expect(multiData.request?.parameters).not.toHaveProperty("dimensions"); + expect(multiData.request?.input?.contents).toEqual([ + { text: "城市夜景" }, + { image: "" }, + { image: "data:image/png;base64," }, + { video: "https://example.com/clip.mp4" }, + ]); + expect(JSON.stringify(multiData)).not.toMatch(/QUJDRA/); + }); + + test("local video path rejected", async () => { + const { stderr, exitCode } = await runCommandInProcess( + EMBEDDING_ROUTES, + [ + "embedding", + "create", + "--model", + "qwen3-vl-embedding", + "--video", + "./local.mp4", + "--dry-run", + "--quiet", + ], + isolatedEnv(), + ); + expect(exitCode).toBe(2); + expect(stderr).toMatch(/HTTP\(S\)|本地视频/); + }); + + test("loopback HTTP text + multimodal contracts", async () => { + const { origin, requests } = await startServer((_request, response) => { + response.writeHead(200, { "Content-Type": "application/json" }); + if ((_request.url ?? "").includes("compatible-mode")) { + response.end( + JSON.stringify({ + data: [ + { embedding: [0.1, 0.2, 0.3], index: 0 }, + { embedding: [0.4, 0.5, 0.6], index: 1 }, + ], + usage: { prompt_tokens: 4, total_tokens: 4 }, + request_id: "emb-text", + }), + ); + return; + } + response.end( + JSON.stringify({ + output: { + embeddings: [ + { embedding: [1, 2], index: 0, type: "text" }, + { embedding: [3, 4], index: 1, type: "image" }, + ], + }, + usage: { image_tokens: 1 }, + request_id: "emb-mm", + }), + ); + }); + + const text = await runCommandInProcess( + EMBEDDING_ROUTES, + [ + "embedding", + "create", + "--text", + "a", + "--text", + "b", + "--dimensions", + "1024", + "--api-key", + "sk-e2e", + "--base-url", + origin, + "--output", + "json", + ], + isolatedEnv(), + ); + expect(text.exitCode, text.stderr).toBe(0); + const textBody = parseStdoutJson<{ + data?: unknown[]; + usage?: unknown; + request_id?: string; + }>(text.stdout); + expect(textBody.data).toHaveLength(2); + expect(textBody.request_id).toBe("emb-text"); + expect(requests[0]).toMatchObject({ + method: "POST", + path: "/compatible-mode/v1/embeddings", + auth: "Bearer sk-e2e", + body: { + model: "text-embedding-v4", + input: ["a", "b"], + dimensions: 1024, + encoding_format: "float", + }, + }); + + const imagePath = join(isolatedDirectory, "dot.png"); + writeFileSync(imagePath, TINY_PNG); + const multimodal = await runCommandInProcess( + EMBEDDING_ROUTES, + [ + "embedding", + "create", + "--text", + "city", + "--image", + imagePath, + "--model", + "qwen3-vl-embedding", + "--api-key", + "sk-e2e", + "--base-url", + origin, + "--output", + "json", + "--quiet", + ], + isolatedEnv(), + ); + expect(multimodal.exitCode, multimodal.stderr).toBe(0); + const mmBody = parseStdoutJson<{ + output?: { embeddings?: unknown[] }; + usage?: unknown; + request_id?: string; + }>(multimodal.stdout); + expect(mmBody.output?.embeddings).toHaveLength(2); + expect(mmBody.request_id).toBe("emb-mm"); + expect(JSON.stringify(mmBody)).not.toMatch(/0\.1,0\.2,0\.3/); + const mmRequest = requests[1]; + expect(mmRequest.path).toBe( + "/api/v1/services/embeddings/multimodal-embedding/multimodal-embedding", + ); + expect(mmRequest.auth).toBe("Bearer sk-e2e"); + const mmPayload = mmRequest.body as { + input?: { contents?: Array<{ text?: string; image?: string }> }; + }; + expect(mmPayload.input?.contents?.[0]).toEqual({ text: "city" }); + expect(mmPayload.input?.contents?.[1]?.image?.startsWith("data:image/png;base64,")).toBe(true); + }); + + test("server business error is passed through", async () => { + const { origin } = await startServer((_request, response) => { + response.writeHead(400, { "Content-Type": "application/json" }); + response.end(JSON.stringify({ code: "InvalidParameter", message: "boom-embedding" })); + }); + const { stderr, exitCode } = await runCommandInProcess( + EMBEDDING_ROUTES, + [ + "embedding", + "create", + "--text", + "a", + "--api-key", + "sk-e2e", + "--base-url", + origin, + "--quiet", + ], + isolatedEnv(), + ); + expect(exitCode).not.toBe(0); + expect(stderr).toMatch(/boom-embedding/); + }); + + test("--out writes full response without saved; text summarizes", async () => { + const { origin } = await startServer((_request, response) => { + response.writeHead(200, { "Content-Type": "application/json" }); + response.end( + JSON.stringify({ + data: [{ embedding: Array.from({ length: 8 }, (_, index) => index), index: 0 }], + usage: { total_tokens: 1 }, + request_id: "save-1", + }), + ); + }); + const outDir = makeE2eOutputDir("embedding-create-out"); + const outPath = join(outDir, "vectors.json"); + const { stdout, stderr, exitCode } = await runCommandE2e( + EMBEDDING_ROUTES, + [ + "embedding", + "create", + "--text", + "hello", + "--api-key", + "sk-e2e", + "--base-url", + origin, + "--out", + outPath, + "--output", + "text", + ], + isolatedEnv(), + ); + expect(exitCode, stderr).toBe(0); + expect(stdout).toMatch(/model: text-embedding-v4/); + expect(stdout).toMatch(/count: 1/); + expect(stdout).toMatch(/dimensions: 8/); + expect(stdout).toMatch(/saved:/); + expect(stdout).not.toMatch(/0,1,2,3,4,5,6,7/); + const saved = JSON.parse(readFileSync(outPath, "utf8")) as Record; + expect(saved).not.toHaveProperty("saved"); + expect(saved.request_id).toBe("save-1"); + }); + + test("missing image file → 2 via subprocess", async () => { + const missing = join(isolatedDirectory, "nope.png"); + const { stderr, exitCode } = await runCommandE2e( + EMBEDDING_ROUTES, + [ + "embedding", + "create", + "--model", + "qwen3-vl-embedding", + "--image", + missing, + "--api-key", + "sk-e2e", + "--quiet", + ], + isolatedEnv(), + ); + expect(exitCode).toBe(2); + expect(stderr).toMatch(/not found|找不到/); + }); + + test("live text + multimodal when gated", async () => { + if (!isDashScopeE2EReady()) return; + const text = await runCommandE2e( + EMBEDDING_ROUTES, + [ + "embedding", + "create", + "--text", + "城市夜景", + "--text", + "繁忙街道", + "--dimensions", + "1024", + "--output", + "json", + "--quiet", + ], + isolatedEnv({ + DASHSCOPE_API_KEY: process.env.DASHSCOPE_API_KEY, + }), + ); + expect(text.exitCode, text.stderr).toBe(0); + const textData = parseStdoutJson<{ data?: Array<{ embedding?: number[] }> }>(text.stdout); + expect(textData.data).toHaveLength(2); + expect(textData.data?.[0]?.embedding).toHaveLength(1024); + expect(textData.data?.[0]?.embedding?.every((value) => Number.isFinite(value))).toBe(true); + + if (!isBailianE2EMediaEnabled()) return; + const imagePath = join(isolatedDirectory, "live.png"); + writeFileSync(imagePath, TINY_PNG); + const independent = await runCommandE2e( + EMBEDDING_ROUTES, + [ + "embedding", + "create", + "--model", + "qwen3-vl-embedding", + "--text", + "城市夜景", + "--image", + imagePath, + "--output", + "json", + "--quiet", + ], + isolatedEnv({ + DASHSCOPE_API_KEY: process.env.DASHSCOPE_API_KEY, + }), + ); + expect(independent.exitCode, independent.stderr).toBe(0); + const independentData = parseStdoutJson<{ + output?: { embeddings?: unknown[] }; + }>(independent.stdout); + expect((independentData.output?.embeddings ?? []).length).toBeGreaterThanOrEqual(2); + + const fused = await runCommandE2e( + EMBEDDING_ROUTES, + [ + "embedding", + "create", + "--model", + "qwen3-vl-embedding", + "--text", + "城市夜景", + "--image", + imagePath, + "--fuse", + "true", + "--output", + "json", + "--quiet", + ], + isolatedEnv({ + DASHSCOPE_API_KEY: process.env.DASHSCOPE_API_KEY, + }), + ); + expect(fused.exitCode, fused.stderr).toBe(0); + const fusedData = parseStdoutJson<{ + output?: { embeddings?: unknown[] }; + }>(fused.stdout); + expect(fusedData.output?.embeddings).toHaveLength(1); + }); +}); diff --git a/packages/commands/tests/e2e/rerank.e2e.test.ts b/packages/commands/tests/e2e/rerank.e2e.test.ts new file mode 100644 index 000000000..8bcfca539 --- /dev/null +++ b/packages/commands/tests/e2e/rerank.e2e.test.ts @@ -0,0 +1,571 @@ +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { createServer, type IncomingMessage, type Server, type ServerResponse } from "node:http"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterEach, beforeEach, describe, expect, test } from "vite-plus/test"; +import { + isBailianE2EMediaEnabled, + isDashScopeE2EReady, + parseStdoutJson, + runCommandE2e, + runCommandHelp, + runCommandInProcess, +} from "./helpers.ts"; +import { RERANK_ROUTES } from "./topic-routes.ts"; + +let isolatedDirectory: string; +const servers: Server[] = []; + +beforeEach(() => { + isolatedDirectory = mkdtempSync(join(tmpdir(), "bl-rerank-e2e-")); + writeFileSync(join(isolatedDirectory, "config.json"), "{}"); +}); + +afterEach(async () => { + await Promise.all( + servers.splice(0).map( + (server) => + new Promise((resolve, reject) => { + server.close((error) => (error ? reject(error) : resolve())); + }), + ), + ); + rmSync(isolatedDirectory, { recursive: true, force: true }); +}); + +async function startServer( + handler: (request: IncomingMessage, response: ServerResponse) => void, +): Promise<{ + origin: string; + requests: Array<{ method?: string; path: string; auth?: string; body: unknown }>; +}> { + const requests: Array<{ method?: string; path: string; auth?: string; body: unknown }> = []; + const server = createServer((request, response) => { + const chunks: Buffer[] = []; + request.on("data", (chunk: Buffer) => chunks.push(chunk)); + request.on("end", () => { + const raw = Buffer.concat(chunks).toString("utf8"); + let body: unknown = raw; + try { + body = raw ? JSON.parse(raw) : undefined; + } catch { + body = raw; + } + requests.push({ + method: request.method, + path: request.url ?? "", + auth: request.headers.authorization, + body, + }); + handler(request, response); + }); + }); + await new Promise((resolve, reject) => { + server.once("error", reject); + server.listen(0, "127.0.0.1", resolve); + }); + servers.push(server); + const address = server.address(); + if (!address || typeof address === "string") throw new Error("Expected TCP address"); + return { origin: `http://127.0.0.1:${address.port}`, requests }; +} + +const TINY_PNG = Buffer.from( + "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==", + "base64", +); + +function isolatedEnv(extra: NodeJS.ProcessEnv = {}) { + return { + BAILIAN_CONFIG_DIR: isolatedDirectory, + HOME: isolatedDirectory, + USERPROFILE: isolatedDirectory, + DASHSCOPE_API_KEY: "", + DASHSCOPE_BASE_URL: "", + ...extra, + }; +} + +describe("e2e: rerank", () => { + test("help lists flags and default model bilingually", async () => { + const { stderr, exitCode } = await runCommandHelp(RERANK_ROUTES, ["rerank", "--help"]); + expect(exitCode, stderr).toBe(0); + expect(stderr).toMatch(/--query/); + expect(stderr).toMatch(/--documents-file/); + expect(stderr).toMatch(/JSON file containing candidate documents|候选文档 JSON 文件/); + expect(stderr).toMatch(/qwen3-rerank/); + expect(stderr).toMatch(/--top-n/); + expect(stderr).toMatch(/--return-documents/); + }); + + test("missing query / documents / conflicts → 2", async () => { + const noQuery = await runCommandInProcess( + RERANK_ROUTES, + ["rerank", "--document", "a", "--dry-run", "--quiet"], + isolatedEnv(), + ); + expect(noQuery.exitCode).toBe(2); + expect(noQuery.stderr).toMatch(/--query|--query-image/); + + const noDocs = await runCommandInProcess( + RERANK_ROUTES, + ["rerank", "--query", "q", "--dry-run", "--quiet"], + isolatedEnv(), + ); + expect(noDocs.exitCode).toBe(2); + expect(noDocs.stderr).toMatch(/--document|--documents-file/); + + const conflict = await runCommandInProcess( + RERANK_ROUTES, + [ + "rerank", + "--query", + "q", + "--query-image", + "https://example.com/a.png", + "--document", + "a", + "--dry-run", + "--quiet", + ], + isolatedEnv(), + ); + expect(conflict.exitCode).toBe(2); + expect(conflict.stderr).toMatch(/--query|--query-image/); + }); + + test("blank query / empty array / illegal JSON → 2", async () => { + const blank = await runCommandInProcess( + RERANK_ROUTES, + ["rerank", "--query", " ", "--document", "a", "--dry-run", "--quiet"], + isolatedEnv(), + ); + expect(blank.exitCode).toBe(2); + expect(blank.stderr).toMatch(/non-empty|非空/); + + const emptyFile = join(isolatedDirectory, "empty.json"); + writeFileSync(emptyFile, "[]"); + const empty = await runCommandInProcess( + RERANK_ROUTES, + ["rerank", "--query", "q", "--documents-file", emptyFile, "--dry-run", "--quiet"], + isolatedEnv(), + ); + expect(empty.exitCode).toBe(2); + expect(empty.stderr).toMatch(/non-empty JSON array|非空 JSON 数组/); + + const badFile = join(isolatedDirectory, "bad.json"); + writeFileSync(badFile, "{"); + const bad = await runCommandInProcess( + RERANK_ROUTES, + ["rerank", "--query", "q", "--documents-file", badFile, "--dry-run", "--quiet"], + isolatedEnv(), + ); + expect(bad.exitCode).toBe(2); + expect(bad.stderr).toMatch(/valid JSON|合法 JSON/); + }); + + test("top-n 0/fraction rejected; larger than candidates allowed", async () => { + for (const value of ["0", "1.5"]) { + const result = await runCommandInProcess( + RERANK_ROUTES, + ["rerank", "--query", "q", "--document", "a", "--top-n", value, "--dry-run", "--quiet"], + isolatedEnv(), + ); + expect(result.exitCode, value).toBe(2); + expect(result.stderr).toMatch(/positive integer|正整数/); + } + + const ok = await runCommandInProcess( + RERANK_ROUTES, + [ + "rerank", + "--query", + "q", + "--document", + "a", + "--top-n", + "9", + "--dry-run", + "--output", + "json", + ], + isolatedEnv({ DASHSCOPE_API_KEY: "sk-e2e" }), + ); + expect(ok.exitCode, ok.stderr).toBe(0); + expect( + parseStdoutJson<{ request?: { parameters?: { top_n?: number } } }>(ok.stdout).request + ?.parameters?.top_n, + ).toBe(9); + }); + + test("return-documents=false preserved; instruct rejected on gte", async () => { + const keepFalse = await runCommandInProcess( + RERANK_ROUTES, + [ + "rerank", + "--query", + "q", + "--document", + "a", + "--return-documents", + "false", + "--dry-run", + "--output", + "json", + ], + isolatedEnv({ DASHSCOPE_API_KEY: "sk-e2e" }), + ); + expect(keepFalse.exitCode, keepFalse.stderr).toBe(0); + expect( + parseStdoutJson<{ request?: { parameters?: { return_documents?: boolean } } }>( + keepFalse.stdout, + ).request?.parameters?.return_documents, + ).toBe(false); + + const gte = await runCommandInProcess( + RERANK_ROUTES, + [ + "rerank", + "--model", + "gte-rerank-v2", + "--query", + "q", + "--document", + "a", + "--instruct", + "prefer night scenes", + "--dry-run", + "--quiet", + ], + isolatedEnv(), + ); + expect(gte.exitCode).toBe(2); + expect(gte.stderr).toMatch(/does not support --instruct|不支持 --instruct/); + }); + + test("media body + relative path from documents-file directory", async () => { + const mediaDir = join(isolatedDirectory, "media"); + mkdirSync(mediaDir); + const imagePath = join(mediaDir, "city.png"); + writeFileSync(imagePath, TINY_PNG); + const docsFile = join(mediaDir, "candidates.json"); + writeFileSync( + docsFile, + JSON.stringify([ + { text: "夜景描述" }, + { image: "./city.png" }, + { video: "https://example.com/clip.mp4" }, + { image: "data:image/png;base64,QUJDRA==" }, + ]), + ); + + const dryRun = await runCommandInProcess( + RERANK_ROUTES, + [ + "rerank", + "--model", + "qwen3-vl-rerank", + "--query", + "城市夜景", + "--documents-file", + docsFile, + "--fps", + "2", + "--dry-run", + "--output", + "json", + ], + isolatedEnv({ DASHSCOPE_API_KEY: "sk-e2e" }), + ); + expect(dryRun.exitCode, dryRun.stderr).toBe(0); + const data = parseStdoutJson<{ + request?: { + input?: { documents?: unknown[] }; + parameters?: { fps?: number }; + }; + }>(dryRun.stdout); + expect(data.request?.parameters?.fps).toBe(2); + expect(data.request?.input?.documents).toEqual([ + { text: "夜景描述" }, + { image: "" }, + { video: "https://example.com/clip.mp4" }, + { image: "data:image/png;base64," }, + ]); + expect(JSON.stringify(data)).not.toMatch(/QUJDRA/); + + writeFileSync( + join(isolatedDirectory, "bad-video.json"), + JSON.stringify([{ video: "./local.mp4" }]), + ); + const localVideo = await runCommandInProcess( + RERANK_ROUTES, + [ + "rerank", + "--model", + "qwen3-vl-rerank", + "--query", + "q", + "--documents-file", + join(isolatedDirectory, "bad-video.json"), + "--dry-run", + "--quiet", + ], + isolatedEnv(), + ); + expect(localVideo.exitCode).toBe(2); + expect(localVideo.stderr).toMatch(/HTTP\(S\)|本地视频/); + }); + + test("fps bounds and text-model media rejection", async () => { + const fpsBad = await runCommandInProcess( + RERANK_ROUTES, + [ + "rerank", + "--model", + "qwen3-vl-rerank", + "--query", + "q", + "--document", + "a", + "--fps", + "0", + "--dry-run", + "--quiet", + ], + isolatedEnv(), + ); + expect(fpsBad.exitCode).toBe(2); + expect(fpsBad.stderr).toMatch(/\(0, 5\]/); + + const fpsOnText = await runCommandInProcess( + RERANK_ROUTES, + ["rerank", "--query", "q", "--document", "a", "--fps", "1", "--dry-run", "--quiet"], + isolatedEnv(), + ); + expect(fpsOnText.exitCode).toBe(2); + expect(fpsOnText.stderr).toMatch(/only supported by qwen3-vl-rerank|仅 qwen3-vl-rerank/); + + writeFileSync( + join(isolatedDirectory, "mm.json"), + JSON.stringify([{ image: "https://x/a.png" }]), + ); + const mediaOnText = await runCommandInProcess( + RERANK_ROUTES, + [ + "rerank", + "--query", + "q", + "--documents-file", + join(isolatedDirectory, "mm.json"), + "--dry-run", + "--quiet", + ], + isolatedEnv(), + ); + expect(mediaOnText.exitCode).toBe(2); + expect(mediaOnText.stderr).toMatch(/only accepts text|仅接受文本/); + }); + + test("loopback keeps server order/index and full response", async () => { + const { origin, requests } = await startServer((_request, response) => { + response.writeHead(200, { "Content-Type": "application/json" }); + response.end( + JSON.stringify({ + output: { + results: [ + { index: 1, relevance_score: 0.9, document: { text: "霓虹街道与夜空" } }, + { index: 0, relevance_score: 0.9, document: { weird: true, image: "x" } }, + ], + }, + usage: { total_tokens: 12 }, + request_id: "rerank-1", + }), + ); + }); + + const result = await runCommandInProcess( + RERANK_ROUTES, + [ + "rerank", + "--query", + "城市夜景", + "--document", + "白天的田野", + "--document", + "霓虹街道与夜空", + "--top-n", + "2", + "--return-documents", + "true", + "--api-key", + "sk-e2e", + "--base-url", + origin, + "--output", + "json", + ], + isolatedEnv(), + ); + expect(result.exitCode, result.stderr).toBe(0); + const data = parseStdoutJson<{ + output?: { results?: Array<{ index: number; relevance_score: number; document?: unknown }> }; + usage?: unknown; + request_id?: string; + }>(result.stdout); + expect(data.request_id).toBe("rerank-1"); + expect(data.usage).toEqual({ total_tokens: 12 }); + expect(data.output?.results?.map((item) => item.index)).toEqual([1, 0]); + expect(data.output?.results?.[1]?.document).toEqual({ weird: true, image: "x" }); + expect(requests[0]).toMatchObject({ + method: "POST", + path: "/api/v1/services/rerank/text-rerank/text-rerank", + auth: "Bearer sk-e2e", + body: { + model: "qwen3-rerank", + input: { + query: "城市夜景", + documents: ["白天的田野", "霓虹街道与夜空"], + }, + parameters: { + top_n: 2, + return_documents: true, + }, + }, + }); + + const textMode = await runCommandInProcess( + RERANK_ROUTES, + [ + "rerank", + "--query", + "城市夜景", + "--document", + "白天的田野", + "--document", + "霓虹街道与夜空", + "--return-documents", + "true", + "--api-key", + "sk-e2e", + "--base-url", + origin, + "--output", + "text", + ], + isolatedEnv(), + ); + expect(textMode.exitCode, textMode.stderr).toBe(0); + expect(textMode.stdout).toMatch(/#1/); + expect(textMode.stdout).toMatch(/#0/); + }); + + test("server error passed through; missing file subprocess", async () => { + const { origin } = await startServer((_request, response) => { + response.writeHead(400, { "Content-Type": "application/json" }); + response.end(JSON.stringify({ code: "InvalidParameter", message: "boom-rerank" })); + }); + const err = await runCommandInProcess( + RERANK_ROUTES, + [ + "rerank", + "--query", + "q", + "--document", + "a", + "--api-key", + "sk-e2e", + "--base-url", + origin, + "--quiet", + ], + isolatedEnv(), + ); + expect(err.exitCode).not.toBe(0); + expect(err.stderr).toMatch(/boom-rerank/); + + const missing = await runCommandE2e( + RERANK_ROUTES, + [ + "rerank", + "--query", + "q", + "--documents-file", + join(isolatedDirectory, "missing.json"), + "--api-key", + "sk-e2e", + "--quiet", + ], + isolatedEnv(), + ); + expect(missing.exitCode).toBe(2); + expect(missing.stderr).toMatch(/not found|找不到/); + }); + + test("live text and multimodal when gated", async () => { + if (!isDashScopeE2EReady()) return; + const text = await runCommandE2e( + RERANK_ROUTES, + [ + "rerank", + "--query", + "城市夜景", + "--document", + "白天的田野", + "--document", + "霓虹街道与夜空", + "--document", + "江边灯火", + "--top-n", + "2", + "--return-documents", + "true", + "--output", + "json", + "--quiet", + ], + isolatedEnv({ + DASHSCOPE_API_KEY: process.env.DASHSCOPE_API_KEY, + }), + ); + expect(text.exitCode, text.stderr).toBe(0); + const textData = parseStdoutJson<{ + output?: { results?: Array<{ index: number; relevance_score: number }> }; + }>(text.stdout); + expect((textData.output?.results ?? []).length).toBeGreaterThan(0); + for (const item of textData.output?.results ?? []) { + expect(Number.isInteger(item.index)).toBe(true); + expect(item.index).toBeGreaterThanOrEqual(0); + expect(item.index).toBeLessThan(3); + expect(Number.isFinite(item.relevance_score)).toBe(true); + } + + if (!isBailianE2EMediaEnabled()) return; + const imagePath = join(isolatedDirectory, "live.png"); + writeFileSync(imagePath, TINY_PNG); + const docsFile = join(isolatedDirectory, "live-docs.json"); + writeFileSync(docsFile, JSON.stringify([{ text: "夜景描述" }, { image: imagePath }])); + const multimodal = await runCommandE2e( + RERANK_ROUTES, + [ + "rerank", + "--model", + "qwen3-vl-rerank", + "--query", + "城市夜景", + "--documents-file", + docsFile, + "--output", + "json", + "--quiet", + ], + isolatedEnv({ + DASHSCOPE_API_KEY: process.env.DASHSCOPE_API_KEY, + }), + ); + expect(multimodal.exitCode, multimodal.stderr).toBe(0); + const mmData = parseStdoutJson<{ + output?: { results?: Array<{ index: number }> }; + }>(multimodal.stdout); + expect((mmData.output?.results ?? []).length).toBeGreaterThan(0); + }); +}); diff --git a/packages/commands/tests/e2e/topic-routes.ts b/packages/commands/tests/e2e/topic-routes.ts index 451a4f7a0..a779b5d8d 100644 --- a/packages/commands/tests/e2e/topic-routes.ts +++ b/packages/commands/tests/e2e/topic-routes.ts @@ -26,6 +26,14 @@ export const TEXT_TRANSLATE_ROUTES: E2eRouteExports = { "text chat": "textChat", }; +export const EMBEDDING_ROUTES: E2eRouteExports = { + "embedding create": "embeddingCreate", +}; + +export const RERANK_ROUTES: E2eRouteExports = { + rerank: "rerank", +}; + export const BATCH_ROUTES: E2eRouteExports = { "batch convert": "batchConvert", "batch create": "batchCreate", diff --git a/packages/core/src/client/embedding-routes.ts b/packages/core/src/client/embedding-routes.ts new file mode 100644 index 000000000..74ba2177a --- /dev/null +++ b/packages/core/src/client/embedding-routes.ts @@ -0,0 +1,316 @@ +import { embeddingPath, multimodalEmbeddingPath } from "./endpoints.ts"; + +/** Compatible text vs native multimodal embedding protocols. */ +export type EmbeddingApiKind = "compatible-text" | "native-multimodal"; + +/** + * How `--fuse` maps onto a model family. + * - `optional`: qwen3-vl `parameters.enable_fusion` + * - `always`: always fused; `--fuse false` is rejected + * - `none`: independent only; `--fuse` is rejected + */ +export type EmbeddingFusionMode = "optional" | "always" | "none"; + +export interface EmbeddingModelSpec { + model: string; + kind: EmbeddingApiKind; + /** Allowed dimensions; `null` means fixed / not adjustable. */ + dimensions: readonly number[] | null; + /** Fixed output dimension when `dimensions` is null. */ + fixedDimension?: number; + maxTexts: number; + maxImages: number; + maxVideos: number; + /** Total contents cap when the docs state one; omit when none is documented. */ + maxTotal?: number; + /** Local image byte limit before Data URI encoding. */ + maxImageBytes: number; + fusion: EmbeddingFusionMode; +} + +const MB = 1024 * 1024; + +const EMBEDDING_MODELS: readonly EmbeddingModelSpec[] = [ + { + model: "text-embedding-v4", + kind: "compatible-text", + dimensions: [2048, 1536, 1024, 768, 512, 256, 128, 64], + maxTexts: 10, + maxImages: 0, + maxVideos: 0, + maxImageBytes: 0, + fusion: "none", + }, + { + // Beijing lists 1024…64 (no 2048/1536); Singapore lists 1024/768/512. + // Accept the broader Beijing set so Singapore-only dims are not rejected locally. + model: "text-embedding-v3", + kind: "compatible-text", + dimensions: [1024, 768, 512, 256, 128, 64], + maxTexts: 10, + maxImages: 0, + maxVideos: 0, + maxImageBytes: 0, + fusion: "none", + }, + { + model: "text-embedding-v2", + kind: "compatible-text", + dimensions: null, + fixedDimension: 1536, + maxTexts: 25, + maxImages: 0, + maxVideos: 0, + maxImageBytes: 0, + fusion: "none", + }, + { + model: "text-embedding-v1", + kind: "compatible-text", + dimensions: null, + fixedDimension: 1536, + maxTexts: 25, + maxImages: 0, + maxVideos: 0, + maxImageBytes: 0, + fusion: "none", + }, + { + model: "qwen3.7-text-embedding", + kind: "compatible-text", + dimensions: [2560, 2048, 1536, 1024, 768, 512, 256], + maxTexts: 20, + maxImages: 0, + maxVideos: 0, + maxImageBytes: 0, + fusion: "none", + }, + { + model: "qwen3.7-text-embedding-flash", + kind: "compatible-text", + dimensions: [1024, 768, 512, 256], + maxTexts: 20, + maxImages: 0, + maxVideos: 0, + maxImageBytes: 0, + fusion: "none", + }, + { + model: "qwen3-vl-embedding", + kind: "native-multimodal", + dimensions: [2560, 2048, 1536, 1024, 768, 512, 256], + maxTexts: 20, + maxImages: 10, + maxVideos: 1, + maxTotal: 20, + maxImageBytes: 10 * MB, + fusion: "optional", + }, + { + model: "qwen2.5-vl-embedding", + kind: "native-multimodal", + dimensions: [2048, 1024, 768, 512], + maxTexts: 1, + maxImages: 1, + maxVideos: 1, + maxTotal: 3, + maxImageBytes: 5 * MB, + fusion: "always", + }, + { + model: "tongyi-embedding-vision-plus", + kind: "native-multimodal", + dimensions: [1152, 1024, 512, 256, 128, 64], + maxTexts: Number.POSITIVE_INFINITY, + maxImages: Number.POSITIVE_INFINITY, + maxVideos: Number.POSITIVE_INFINITY, + maxImageBytes: 3 * MB, + fusion: "none", + }, + { + model: "tongyi-embedding-vision-plus-2026-03-06", + kind: "native-multimodal", + dimensions: [1152, 1024, 512, 256, 128, 64], + maxTexts: Number.POSITIVE_INFINITY, + maxImages: Number.POSITIVE_INFINITY, + maxVideos: Number.POSITIVE_INFINITY, + maxImageBytes: 3 * MB, + fusion: "none", + }, + { + model: "tongyi-embedding-vision-flash", + kind: "native-multimodal", + dimensions: [768, 512, 256, 128, 64], + maxTexts: Number.POSITIVE_INFINITY, + maxImages: Number.POSITIVE_INFINITY, + maxVideos: Number.POSITIVE_INFINITY, + maxImageBytes: 3 * MB, + fusion: "none", + }, + { + model: "tongyi-embedding-vision-flash-2026-03-06", + kind: "native-multimodal", + dimensions: [768, 512, 256, 128, 64], + maxTexts: Number.POSITIVE_INFINITY, + maxImages: Number.POSITIVE_INFINITY, + maxVideos: Number.POSITIVE_INFINITY, + maxImageBytes: 3 * MB, + fusion: "none", + }, + { + model: "multimodal-embedding-v1", + kind: "native-multimodal", + dimensions: null, + fixedDimension: 1024, + maxTexts: 20, + maxImages: 1, + maxVideos: 1, + maxTotal: 20, + maxImageBytes: 3 * MB, + fusion: "none", + }, +]; + +const MODEL_BY_ID = new Map(EMBEDDING_MODELS.map((spec) => [spec.model, spec])); + +export const DEFAULT_TEXT_EMBEDDING_MODEL = "text-embedding-v4"; +export const DEFAULT_MULTIMODAL_EMBEDDING_MODEL = "qwen3-vl-embedding"; + +/** Dry-run placeholder for a local image that has not been encoded yet. */ +export const LOCAL_IMAGE_PENDING_ENCODE = ""; + +/** Look up a known embedding model; unknown IDs return undefined (no prefix guessing). */ +export function lookupEmbeddingModel(model: string): EmbeddingModelSpec | undefined { + return MODEL_BY_ID.get(model); +} + +export function listEmbeddingModels(): readonly EmbeddingModelSpec[] { + return EMBEDDING_MODELS; +} + +export interface ResolveEmbeddingRouteInput { + model?: string; + hasMedia: boolean; +} + +export interface EmbeddingRoute { + model: string; + spec: EmbeddingModelSpec; + path: string; +} + +/** + * Resolve model + endpoint. Defaults by media presence; an explicit multimodal + * model with text-only input still uses the multimodal endpoint. + */ +export function resolveEmbeddingRoute(input: ResolveEmbeddingRouteInput): EmbeddingRoute { + const model = + input.model?.trim() || + (input.hasMedia ? DEFAULT_MULTIMODAL_EMBEDDING_MODEL : DEFAULT_TEXT_EMBEDDING_MODEL); + const spec = lookupEmbeddingModel(model); + if (!spec) { + throw new EmbeddingRouteError( + `Unknown embedding model "${model}". Add it to the local embedding route table or use a known model ID.`, + `未知向量模型 "${model}"。请使用已知模型 ID,或将其补充到本地路由表。`, + ); + } + if (spec.kind === "compatible-text" && input.hasMedia) { + throw new EmbeddingRouteError( + `Model "${model}" is a text embedding model and does not accept --image/--video.`, + `模型 "${model}" 为文本向量模型,不接受 --image/--video。`, + ); + } + return { + model, + spec, + path: spec.kind === "compatible-text" ? embeddingPath() : multimodalEmbeddingPath(), + }; +} + +export class EmbeddingRouteError extends Error { + readonly zhMessage: string; + constructor(enMessage: string, zhMessage: string) { + super(enMessage); + this.name = "EmbeddingRouteError"; + this.zhMessage = zhMessage; + } +} + +/** Validate --dimensions against the model table. */ +export function assertEmbeddingDimensions( + spec: EmbeddingModelSpec, + dimensions: number | undefined, +): void { + if (dimensions === undefined) return; + if (!Number.isInteger(dimensions) || dimensions <= 0 || !Number.isFinite(dimensions)) { + throw new EmbeddingRouteError( + "--dimensions must be a positive integer.", + "--dimensions 必须为正整数。", + ); + } + if (spec.dimensions === null) { + throw new EmbeddingRouteError( + `Model "${spec.model}" uses a fixed dimension` + + (spec.fixedDimension !== undefined ? ` (${spec.fixedDimension})` : "") + + " and does not accept --dimensions.", + `模型 "${spec.model}" 维度固定` + + (spec.fixedDimension !== undefined ? `(${spec.fixedDimension})` : "") + + ",不接受 --dimensions。", + ); + } + if (!spec.dimensions.includes(dimensions)) { + throw new EmbeddingRouteError( + `Model "${spec.model}" does not support dimensions=${dimensions}. Allowed: ${spec.dimensions.join(", ")}.`, + `模型 "${spec.model}" 不支持 dimensions=${dimensions}。可选:${spec.dimensions.join(", ")}。`, + ); + } +} + +/** Validate input counts against the model table. */ +export function assertEmbeddingInputCounts( + spec: EmbeddingModelSpec, + counts: { texts: number; images: number; videos: number }, +): void { + const total = counts.texts + counts.images + counts.videos; + if (counts.texts > spec.maxTexts) { + throw new EmbeddingRouteError( + `Model "${spec.model}" accepts at most ${spec.maxTexts} text input(s); got ${counts.texts}.`, + `模型 "${spec.model}" 最多接受 ${spec.maxTexts} 条文本;当前为 ${counts.texts}。`, + ); + } + if (counts.images > spec.maxImages) { + throw new EmbeddingRouteError( + `Model "${spec.model}" accepts at most ${spec.maxImages} image input(s); got ${counts.images}.`, + `模型 "${spec.model}" 最多接受 ${spec.maxImages} 张图片;当前为 ${counts.images}。`, + ); + } + if (counts.videos > spec.maxVideos) { + throw new EmbeddingRouteError( + `Model "${spec.model}" accepts at most ${spec.maxVideos} video input(s); got ${counts.videos}.`, + `模型 "${spec.model}" 最多接受 ${spec.maxVideos} 个视频;当前为 ${counts.videos}。`, + ); + } + if (spec.maxTotal !== undefined && total > spec.maxTotal) { + throw new EmbeddingRouteError( + `Model "${spec.model}" accepts at most ${spec.maxTotal} content item(s); got ${total}.`, + `模型 "${spec.model}" 最多接受 ${spec.maxTotal} 个内容项;当前为 ${total}。`, + ); + } +} + +/** Validate --fuse against the model fusion mode. */ +export function assertEmbeddingFusion(spec: EmbeddingModelSpec, fuse: boolean | undefined): void { + if (fuse === undefined) return; + if (spec.fusion === "none") { + throw new EmbeddingRouteError( + `Model "${spec.model}" does not support --fuse (independent embeddings only).`, + `模型 "${spec.model}" 不支持 --fuse(仅独立向量模式)。`, + ); + } + if (spec.fusion === "always" && fuse === false) { + throw new EmbeddingRouteError( + `Model "${spec.model}" always returns a fused embedding; --fuse false is not supported.`, + `模型 "${spec.model}" 始终返回融合向量,不支持 --fuse false。`, + ); + } +} diff --git a/packages/core/src/client/endpoints.ts b/packages/core/src/client/endpoints.ts index cc81f8297..43bfc8931 100644 --- a/packages/core/src/client/endpoints.ts +++ b/packages/core/src/client/endpoints.ts @@ -90,6 +90,22 @@ export function decisionPath(): string { return "/compatible-mode/v1/systemone"; } +// ---- Embeddings ---- +/** OpenAI-compatible text embeddings. */ +export function embeddingPath(): string { + return "/compatible-mode/v1/embeddings"; +} + +/** Native multimodal embeddings. */ +export function multimodalEmbeddingPath(): string { + return "/api/v1/services/embeddings/multimodal-embedding/multimodal-embedding"; +} + +// ---- Rerank (DashScope native) ---- +export function rerankPath(): string { + return "/api/v1/services/rerank/text-rerank/text-rerank"; +} + // ---- Image Generation (DashScope) ---- /** Async image API used by wan2.6-t2i / wan2.6-image (T2I) and similar message-format models. */ export function imagePath(): string { diff --git a/packages/core/src/client/index.ts b/packages/core/src/client/index.ts index 4b0776e0b..22d34c100 100644 --- a/packages/core/src/client/index.ts +++ b/packages/core/src/client/index.ts @@ -3,6 +3,9 @@ export { parsexEndpoint, appCompletionPath, chatPath, + embeddingPath, + multimodalEmbeddingPath, + rerankPath, imagePath, imageSyncPath, multimodalGenerationPath, @@ -67,6 +70,23 @@ export { type ImageInputStyle, type ImageSizeProfile, } from "./image-routes.ts"; +export { + assertEmbeddingDimensions, + assertEmbeddingFusion, + assertEmbeddingInputCounts, + DEFAULT_MULTIMODAL_EMBEDDING_MODEL, + DEFAULT_TEXT_EMBEDDING_MODEL, + EmbeddingRouteError, + listEmbeddingModels, + LOCAL_IMAGE_PENDING_ENCODE, + lookupEmbeddingModel, + resolveEmbeddingRoute, + type EmbeddingApiKind, + type EmbeddingFusionMode, + type EmbeddingModelSpec, + type EmbeddingRoute, + type ResolveEmbeddingRouteInput, +} from "./embedding-routes.ts"; export { buildAsrContextMessages, buildAsrFlashRequest, diff --git a/packages/core/src/types/api.ts b/packages/core/src/types/api.ts index 8edbd7bf5..71aa40772 100644 --- a/packages/core/src/types/api.ts +++ b/packages/core/src/types/api.ts @@ -156,6 +156,89 @@ export interface ResponsesStreamEvent { [key: string]: unknown; } +// ---- Text embeddings (OpenAI Compatible) ---- + +export interface TextEmbeddingRequest { + model: string; + input: string[]; + dimensions?: number; + encoding_format?: "float" | "base64"; +} + +export interface TextEmbeddingResponse { + object?: string; + data: Array<{ + object?: string; + embedding: number[]; + index: number; + }>; + model?: string; + usage?: Record; + request_id?: string; +} + +// ---- Multimodal embeddings (DashScope native) ---- + +export type MultimodalEmbeddingContent = { text: string } | { image: string } | { video: string }; + +export interface MultimodalEmbeddingRequest { + model: string; + input: { + contents: MultimodalEmbeddingContent[]; + }; + parameters?: { + dimension?: number; + enable_fusion?: boolean; + }; +} + +export interface MultimodalEmbeddingResponse { + output: { + embeddings: Array<{ + embedding: number[]; + index?: number; + type?: string; + }>; + }; + usage?: Record; + request_id?: string; +} + +// ---- Rerank (DashScope native) ---- + +export type RerankDocumentInput = string | { text: string } | { image: string } | { video: string }; + +export type RerankQueryInput = string | { image: string }; + +export interface RerankRequest { + model: string; + input: { + query: RerankQueryInput; + documents: RerankDocumentInput[]; + }; + parameters?: { + top_n?: number; + return_documents?: boolean; + instruct?: string; + /** qwen3-vl video frame sampling rate in (0, 5]. */ + fps?: number; + }; +} + +export interface RerankResultItem { + index: number; + relevance_score: number; + document?: unknown; +} + +export interface RerankResponse { + output: { + results: RerankResultItem[]; + }; + usage?: Record; + request_id?: string; +} + // ---- Image (DashScope) ---- export interface DashScopeImageRequest { diff --git a/packages/core/tests/embedding-routes.test.ts b/packages/core/tests/embedding-routes.test.ts new file mode 100644 index 000000000..f3d0a7e7a --- /dev/null +++ b/packages/core/tests/embedding-routes.test.ts @@ -0,0 +1,134 @@ +import { expect, test } from "vite-plus/test"; +import { + assertEmbeddingDimensions, + assertEmbeddingFusion, + assertEmbeddingInputCounts, + DEFAULT_MULTIMODAL_EMBEDDING_MODEL, + DEFAULT_TEXT_EMBEDDING_MODEL, + EmbeddingRouteError, + lookupEmbeddingModel, + resolveEmbeddingRoute, +} from "../src/client/embedding-routes.ts"; + +test("defaults: text-only uses text-embedding-v4; media uses qwen3-vl-embedding", () => { + const textRoute = resolveEmbeddingRoute({ hasMedia: false }); + expect(textRoute.model).toBe(DEFAULT_TEXT_EMBEDDING_MODEL); + expect(textRoute.path).toBe("/compatible-mode/v1/embeddings"); + + const mediaRoute = resolveEmbeddingRoute({ hasMedia: true }); + expect(mediaRoute.model).toBe(DEFAULT_MULTIMODAL_EMBEDDING_MODEL); + expect(mediaRoute.path).toBe( + "/api/v1/services/embeddings/multimodal-embedding/multimodal-embedding", + ); +}); + +test("explicit multimodal model with text-only still uses multimodal endpoint", () => { + const route = resolveEmbeddingRoute({ + model: "qwen3-vl-embedding", + hasMedia: false, + }); + expect(route.spec.kind).toBe("native-multimodal"); + expect(route.path).toContain("multimodal-embedding"); +}); + +test("text model with media is rejected", () => { + expect(() => resolveEmbeddingRoute({ model: "text-embedding-v4", hasMedia: true })).toThrow( + EmbeddingRouteError, + ); +}); + +test("unknown model is rejected without prefix guessing", () => { + expect(() => resolveEmbeddingRoute({ model: "text-embedding-v9", hasMedia: false })).toThrow( + /Unknown embedding model/, + ); + expect(lookupEmbeddingModel("text-embedding")).toBeUndefined(); +}); + +test("dimension boundaries per model", () => { + const cases = [ + { model: "text-embedding-v4", ok: 2048, bad: 4096 }, + { model: "text-embedding-v4", ok: 64, bad: 32 }, + { model: "text-embedding-v3", ok: 1024, bad: 2048 }, + { model: "qwen3.7-text-embedding", ok: 2560, bad: 128 }, + { model: "qwen3.7-text-embedding-flash", ok: 256, bad: 2048 }, + { model: "tongyi-embedding-vision-flash", ok: 768, bad: 1024 }, + { model: "tongyi-embedding-vision-flash-2026-03-06", ok: 768, bad: 1024 }, + { model: "tongyi-embedding-vision-plus", ok: 1024, bad: 768 }, + { model: "tongyi-embedding-vision-plus-2026-03-06", ok: 1024, bad: 768 }, + { model: "qwen3-vl-embedding", ok: 2560, bad: 1152 }, + { model: "qwen2.5-vl-embedding", ok: 2048, bad: 2560 }, + ] as const; + + for (const item of cases) { + const spec = lookupEmbeddingModel(item.model)!; + expect(() => assertEmbeddingDimensions(spec, item.ok)).not.toThrow(); + expect(() => assertEmbeddingDimensions(spec, item.bad)).toThrow(EmbeddingRouteError); + } +}); + +test("fixed-dimension models reject --dimensions", () => { + for (const model of ["text-embedding-v1", "text-embedding-v2", "multimodal-embedding-v1"]) { + const spec = lookupEmbeddingModel(model)!; + expect(() => assertEmbeddingDimensions(spec, 1536)).toThrow(/fixed dimension|维度固定/); + expect(() => assertEmbeddingDimensions(spec, undefined)).not.toThrow(); + } +}); + +test("invalid dimension values are rejected", () => { + const spec = lookupEmbeddingModel("text-embedding-v4")!; + for (const value of [0, -1, 1.5, Number.NaN, Number.POSITIVE_INFINITY]) { + expect(() => assertEmbeddingDimensions(spec, value)).toThrow(/positive integer|正整数/); + } +}); + +test("fusion rules differ by family and are not mixed across dated snapshots", () => { + const qwen3 = lookupEmbeddingModel("qwen3-vl-embedding")!; + expect(() => assertEmbeddingFusion(qwen3, true)).not.toThrow(); + expect(() => assertEmbeddingFusion(qwen3, false)).not.toThrow(); + + const qwen25 = lookupEmbeddingModel("qwen2.5-vl-embedding")!; + expect(() => assertEmbeddingFusion(qwen25, true)).not.toThrow(); + expect(() => assertEmbeddingFusion(qwen25, false)).toThrow(/always|始终/); + + for (const model of [ + "tongyi-embedding-vision-plus", + "tongyi-embedding-vision-plus-2026-03-06", + "tongyi-embedding-vision-flash", + "tongyi-embedding-vision-flash-2026-03-06", + "text-embedding-v4", + "multimodal-embedding-v1", + ]) { + const spec = lookupEmbeddingModel(model)!; + expect(spec.fusion).toBe("none"); + expect(() => assertEmbeddingFusion(spec, true)).toThrow( + /does not support --fuse|不支持 --fuse/, + ); + } +}); + +test("input count limits", () => { + const v4 = lookupEmbeddingModel("text-embedding-v4")!; + expect(() => assertEmbeddingInputCounts(v4, { texts: 10, images: 0, videos: 0 })).not.toThrow(); + expect(() => assertEmbeddingInputCounts(v4, { texts: 11, images: 0, videos: 0 })).toThrow( + /at most 10/, + ); + + const qwen3 = lookupEmbeddingModel("qwen3-vl-embedding")!; + expect(() => + assertEmbeddingInputCounts(qwen3, { texts: 9, images: 10, videos: 1 }), + ).not.toThrow(); + expect(() => assertEmbeddingInputCounts(qwen3, { texts: 10, images: 10, videos: 1 })).toThrow( + /at most 20 content/, + ); + expect(() => assertEmbeddingInputCounts(qwen3, { texts: 0, images: 11, videos: 0 })).toThrow( + /at most 10 image/, + ); + + const qwen25 = lookupEmbeddingModel("qwen2.5-vl-embedding")!; + expect(() => + assertEmbeddingInputCounts(qwen25, { texts: 1, images: 1, videos: 1 }), + ).not.toThrow(); + expect(() => assertEmbeddingInputCounts(qwen25, { texts: 2, images: 0, videos: 0 })).toThrow( + /at most 1 text/, + ); +}); diff --git a/skills/bailian-cli/SKILL.md b/skills/bailian-cli/SKILL.md index 42b5d127b..94a42daf8 100644 --- a/skills/bailian-cli/SKILL.md +++ b/skills/bailian-cli/SKILL.md @@ -6,7 +6,8 @@ metadata: bins: ["bl"] description: >- 阿里云百炼 / Aliyun Bailian / DashScope 资源管理与 `bl` CLI hub: - 应用调用与管理(bl flow-agent:调用/创建/更新/发布/删除/复制/版本、工作流画布;旧 bl app call/list 已废弃)、决策模型推理(bl decision)、模型目录/模型列表、用量/额度/配额、免费额度、 + 应用调用与管理(bl flow-agent:调用/创建/更新/发布/删除/复制/版本、工作流画布;旧 bl app call/list 已废弃)、决策模型推理(bl decision)、 + 文本/多模态向量(bl embedding create)、候选文档重排序(bl rerank)、模型目录/模型列表、用量/额度/配额、免费额度、 工作空间、MCP 市场、pipeline、文件上传、ParseX 文档/音视频解析与字段抽取、Batch 批量推理与 CSV 转换、同步 Batch Chat、console API、登录鉴权与配置、 云端 Skill 检索与详情(bl skill search|get),Agent Skill 安装/列表/更新/卸载(bl skill add|list|update|remove,百炼 skill registry)。 用户点名百炼 / DashScope / `bl`,或继续既有 `bl` 工作流时直接使用。 @@ -73,6 +74,8 @@ Use this table only after the decision table in [`bailian-protocol`](../bailian- | ----------------------------------------------------- | -------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | Explicit Bailian model chat / text execution | `bl text chat` | Default `qwen3.8-max` | | Dedicated text translation (Qwen-MT) | `bl text translate --target-lang ` | Default `qwen-mt-flash`; language names are English full names (`Chinese`/`English`), not `zh`/`en`; only user messages; see `reference/text.md` | +| Create text / multimodal embeddings directly | `bl embedding create` | Default `text-embedding-v4` (text) / `qwen3-vl-embedding` (media); full vectors in JSON/`--out`. For knowledge-base indexing / retrieval → `bailian-knowledge`, not this command. See `reference/embedding.md`. | +| Rerank candidate documents for a query | `bl rerank` | Default `qwen3-rerank`; scores comparable only within one request. For knowledge-base retrieval / server-side hybrid ranking → `bailian-knowledge`, not this command. See `reference/rerank.md`. | | 百炼异步文件批量推理 / CSV 转换 | `bl batch convert` / `create` / `list` / `get` / `cancel` / `download` | CSV → JSONL → 异步任务 → 原始结果,可额外导出 CSV;格式样例见 `reference/batch.md` | | 百炼单次同步 Batch Chat | `bl text chat --batch` | 等待单次响应,不创建任务 ID;messages-file 是同一请求的对话上下文,边界见 `reference/text.md` | | Typed decision model inference | `bl decision` | Workspace endpoint; returns `choice` / `noul` / `score` values and probabilities, not generated text | @@ -127,6 +130,8 @@ Flags, usage, and examples: see hub [`reference/`](reference/index.md) or `bl --state "Is this requesting a refund?" --questions '{"refund":{"type":"noul"}}' bl flow-agent list --output json bl flow-agent call --app-id --prompt "Hello" diff --git a/skills/bailian-cli/reference/embedding.md b/skills/bailian-cli/reference/embedding.md new file mode 100644 index 000000000..ce2c005dd --- /dev/null +++ b/skills/bailian-cli/reference/embedding.md @@ -0,0 +1,51 @@ +# `bl embedding` commands + +> Auto-generated from `packages/cli/src/commands.ts`. Do not edit by hand. +> Regenerate: `pnpm --filter bailian-cli run generate:reference`. + +Index: [index.md](index.md) + +## Commands in this group + +| Command | Authentication | Description | +| --------------------- | -------------- | ------------------------------------ | +| `bl embedding create` | API Key | Create text or multimodal embeddings | + +## Command details + +### `bl embedding create` + +| Field | Value | +| ------------------ | ------------------------------------------------------------------------------------------ | +| **Name** | `embedding create` | +| **Description** | Create text or multimodal embeddings | +| **Authentication** | API Key | +| **Usage** | `bl embedding create (--text \| --image \| --video )... [flags]` | + +#### Flags + +| Flag | Type | Required | Description | +| ----------------------- | ------- | -------- | ------------------------------------------------------------------------------------------------------ | +| `--text ` | array | no | Text to embed (repeatable; order preserved among --text values) | +| `--image ` | array | no | Image URL or local path (repeatable; public HTTP(S) URL or Data URI preferred for large files) | +| `--video ` | array | no | Public HTTP(S) video URL only (repeatable; local video paths are not supported) | +| `--model ` | string | no | Embedding model (default: text-embedding-v4 for text-only; qwen3-vl-embedding when media is present) | +| `--dimensions ` | number | no | Embedding dimensions (model-dependent) | +| `--fuse ` | boolean | no | Enable fusion for qwen3-vl-embedding (maps to parameters.enable_fusion); other models reject this flag | +| `--out ` | string | no | Save the full server response JSON to a file | +| `--api-key ` | string | no | API key | +| `--base-url ` | string | no | API base URL | + +#### Notes + +- Content order is fixed as text → image → video across flags (repeatable flags keep their own order). Multiple inputs do not imply fusion — use --fuse with qwen3-vl-embedding. Local video is unsupported; prefer public HTTP(S) URLs for large images. Billed per call; this command does not auto-batch. For knowledge-base indexing / retrieval use knowledge commands, not embedding create. + +#### Examples + +```bash +bl embedding create --text "城市夜景" --text "繁忙街道" --dimensions 1024 --dry-run --output json +``` + +```bash +bl embedding create --text "城市夜景" --image ./city.png --model qwen3-vl-embedding --fuse true --out vectors.json +``` diff --git a/skills/bailian-cli/reference/index.md b/skills/bailian-cli/reference/index.md index bfe6bcd59..dc128a811 100644 --- a/skills/bailian-cli/reference/index.md +++ b/skills/bailian-cli/reference/index.md @@ -55,6 +55,7 @@ Use this index for the skill-scoped quick index and global flags. | `bl connector tools` | API Key | Discover connector tools and authorized accounts by intent | [connector.md](connector.md) | | `bl console call` | Console | Call a Bailian console API via the CLI gateway | [console.md](console.md) | | `bl decision` | API Key | Run the decision model: typed choice / noul / score answers with probabilities | [decision.md](decision.md) | +| `bl embedding create` | API Key | Create text or multimodal embeddings | [embedding.md](embedding.md) | | `bl file upload` | API Key | Upload a local file to DashScope temporary storage (48h) | [file.md](file.md) | | `bl file url` | Console | Resolve a Console business file key to a file URL | [file.md](file.md) | | `bl flow-agent call` | API Key | Call a Bailian application (agent or workflow) | [flow-agent.md](flow-agent.md) | @@ -126,6 +127,7 @@ Use this index for the skill-scoped quick index and global flags. | `bl quota history` | Console | View quota change history | [quota.md](quota.md) | | `bl quota list` | API Key | View model rate limits (QPM/TPM, account and workspace level) | [quota.md](quota.md) | | `bl quota update` | API Key | Update model rate limits (QPM/TPM) | [quota.md](quota.md) | +| `bl rerank` | API Key | Rerank candidate documents for a query | [rerank.md](rerank.md) | | `bl search web` | API Key | Search the web via a chat model with built-in web search (default) or the DashScope MCP WebSearch service | [search.md](search.md) | | `bl skill add` | API Key when required by source | Install skills from the Bailian skill registry into local agents | [skill.md](skill.md) | | `bl skill get` | API Key when required by source | Get skill details, installed versions and paths from the public registry or OpenAPI | [skill.md](skill.md) | @@ -166,6 +168,7 @@ Use this index for the skill-scoped quick index and global flags. | `connector` | `call`, `schema`, `tools` | [connector.md](connector.md) | | `console` | `call` | [console.md](console.md) | | `decision` | `(root)` | [decision.md](decision.md) | +| `embedding` | `create` | [embedding.md](embedding.md) | | `file` | `upload`, `url` | [file.md](file.md) | | `flow-agent` | `call`, `copy`, `create`, `delete`, `get`, `list`, `publish`, `update`, `versions`, `workflow export`, `workflow get`, `workflow publish`, `workflow save` | [flow-agent.md](flow-agent.md) | | `log` | `audit count`, `audit disable`, `audit enable`, `audit get`, `audit list`, `inference count`, `inference disable`, `inference enable`, `inference get`, `inference list`, `status`, `trace get`, `trace list`, `trace stats` | [log.md](log.md) | @@ -177,6 +180,7 @@ Use this index for the skill-scoped quick index and global flags. | `pipeline` | `run`, `validate` | [pipeline.md](pipeline.md) | | `plugin` | `install`, `link`, `list`, `remove` | [plugin.md](plugin.md) | | `quota` | `check`, `delete`, `history`, `list`, `update` | [quota.md](quota.md) | +| `rerank` | `(root)` | [rerank.md](rerank.md) | | `search` | `web` | [search.md](search.md) | | `skill` | `add`, `get`, `init`, `list`, `remove`, `search`, `update` | [skill.md](skill.md) | | `text` | `chat`, `translate` | [text.md](text.md) | diff --git a/skills/bailian-cli/reference/rerank.md b/skills/bailian-cli/reference/rerank.md new file mode 100644 index 000000000..8e39cf197 --- /dev/null +++ b/skills/bailian-cli/reference/rerank.md @@ -0,0 +1,53 @@ +# `bl rerank` commands + +> Auto-generated from `packages/cli/src/commands.ts`. Do not edit by hand. +> Regenerate: `pnpm --filter bailian-cli run generate:reference`. + +Index: [index.md](index.md) + +## Commands in this group + +| Command | Authentication | Description | +| ----------- | -------------- | -------------------------------------- | +| `bl rerank` | API Key | Rerank candidate documents for a query | + +## Command details + +### `bl rerank` + +| Field | Value | +| ------------------ | --------------------------------------------------------------------------------------------------------------------- | +| **Name** | `rerank` | +| **Description** | Rerank candidate documents for a query | +| **Authentication** | API Key | +| **Usage** | `bl rerank (--query \| --query-image ) (--document ... \| --documents-file ) [flags]` | + +#### Flags + +| Flag | Type | Required | Description | +| ----------------------------- | ------- | -------- | --------------------------------------------------------------------------------------------------- | +| `--query ` | string | no | Query text (mutually exclusive with --query-image) | +| `--query-image ` | string | no | Query image URL or local path (qwen3-vl-rerank only; mutually exclusive with --query) | +| `--document ` | array | no | Candidate document text (repeatable; mutually exclusive with --documents-file) | +| `--documents-file ` | string | no | JSON file containing candidate documents | +| `--model ` | string | no | Rerank model (default: qwen3-rerank; also gte-rerank-v2, qwen3.7-text-rerank, qwen3-vl-rerank) | +| `--top-n ` | number | no | Return top N results (positive integer; values larger than the candidate count are allowed) | +| `--instruct ` | string | no | Rerank instruction (qwen3 / qwen3.7 / qwen3-vl; rejected by gte-rerank-v2) | +| `--return-documents ` | boolean | no | Ask the server to return document payloads (false is preserved; qwen3.7 support follows the server) | +| `--fps ` | number | no | Video frame sampling rate for qwen3-vl-rerank only, in (0, 5] frames per second | +| `--api-key ` | string | no | API key | +| `--base-url ` | string | no | API base URL | + +#### Notes + +- relevance_score is comparable only within one request; this CLI never re-sorts or merges scores across batches. Paths in --documents-file are resolved relative to that file's directory; --query-image uses the process cwd. Local video is unsupported. Billed per call (up to 500 candidates). For knowledge-base retrieval / server-side hybrid ranking use knowledge commands, not rerank. + +#### Examples + +```bash +bl rerank --query "城市夜景" --document "白天的田野" --document "霓虹街道与夜空" --top-n 1 --return-documents true --dry-run --output json +``` + +```bash +bl rerank --model qwen3-vl-rerank --query "城市夜景" --documents-file candidates.json --output json +``` From f22d638918eeaee0bc8ec2ed9607ef2b4c3c2c29 Mon Sep 17 00:00:00 2001 From: clh02467605 Date: Tue, 1 Dec 2026 15:32:33 +0800 Subject: [PATCH 2/3] refactor: streamline rerank and embedding commands - Removed unused functions and constants from rerank and embedding command files. - Simplified error handling by replacing custom usageError function with throwUsage. - Updated embedding model specifications to enforce input limits for new models. - Enhanced error messages to include supported model IDs for better user guidance. - Improved documentation for embedding and rerank commands to clarify usage and limitations. --- .../commands/src/commands/embedding/create.ts | 316 ++++++++++-------- packages/commands/src/commands/rerank.ts | 260 ++++++-------- .../tests/e2e/embedding-create.e2e.test.ts | 205 +++++++++++- .../commands/tests/e2e/rerank.e2e.test.ts | 161 +++++++++ .../core/src/client/embedding-region-hint.ts | 55 +++ packages/core/src/client/embedding-routes.ts | 36 +- packages/core/src/client/index.ts | 24 ++ packages/core/src/client/model-unavailable.ts | 13 + .../core/src/client/rerank-region-hint.ts | 49 +++ packages/core/src/client/rerank-routes.ts | 88 +++++ packages/core/src/config/index.ts | 1 + packages/core/src/config/model-endpoints.ts | 5 + packages/core/src/files/index.ts | 11 + packages/core/src/files/media-input.ts | 88 +++++ packages/core/src/types/api.ts | 2 + .../core/tests/embedding-region-hint.test.ts | 98 ++++++ packages/core/tests/embedding-routes.test.ts | 35 +- packages/core/tests/media-input.test.ts | 71 ++++ .../core/tests/rerank-region-hint.test.ts | 58 ++++ packages/core/tests/rerank-routes.test.ts | 30 ++ skills/bailian-cli/reference/embedding.md | 24 +- skills/bailian-cli/reference/rerank.md | 2 +- 22 files changed, 1302 insertions(+), 330 deletions(-) create mode 100644 packages/core/src/client/embedding-region-hint.ts create mode 100644 packages/core/src/client/model-unavailable.ts create mode 100644 packages/core/src/client/rerank-region-hint.ts create mode 100644 packages/core/src/client/rerank-routes.ts create mode 100644 packages/core/src/files/media-input.ts create mode 100644 packages/core/tests/embedding-region-hint.test.ts create mode 100644 packages/core/tests/media-input.test.ts create mode 100644 packages/core/tests/rerank-region-hint.test.ts create mode 100644 packages/core/tests/rerank-routes.test.ts diff --git a/packages/commands/src/commands/embedding/create.ts b/packages/commands/src/commands/embedding/create.ts index 99af98443..46ed2d67f 100644 --- a/packages/commands/src/commands/embedding/create.ts +++ b/packages/commands/src/commands/embedding/create.ts @@ -1,18 +1,20 @@ import { dirname } from "node:path"; -import { existsSync, mkdirSync, statSync, writeFileSync } from "node:fs"; +import { accessSync, constants, existsSync, mkdirSync, statSync, writeFileSync } from "node:fs"; import { BailianError, ExitCode, assertEmbeddingDimensions, assertEmbeddingFusion, assertEmbeddingInputCounts, + assertPublicHttpUrl, defineCommand, EmbeddingRouteError, - imageFileToDataUri, - LOCAL_IMAGE_PENDING_ENCODE, - redactDataUri, resolveEmbeddingRoute, + resolveImageMediaInput, + rethrowWithQwen3VlRegionHint, stripUndefined, + throwUsage, + type CommandContext, type FlagsDef, type LocalizedText, type MultimodalEmbeddingContent, @@ -70,24 +72,22 @@ const CREATE_FLAGS = { valueHint: "", description: { "en-US": - "Enable fusion for qwen3-vl-embedding (maps to parameters.enable_fusion); other models reject this flag", - "zh-CN": "qwen3-vl-embedding 融合向量(映射为 parameters.enable_fusion);其他型号拒绝此参数", + "Enable fusion for qwen3-vl-embedding (maps to parameters.enable_fusion); ignored on always-fusion models; rejected elsewhere", + "zh-CN": + "qwen3-vl-embedding 融合向量(映射为 parameters.enable_fusion);始终融合型号会忽略;其余型号拒绝", }, }, out: { type: "string", valueHint: "", description: { - "en-US": "Save the full server response JSON to a file", - "zh-CN": "将完整服务端响应 JSON 保存到文件", + "en-US": + "Save the full server response JSON to a file; JSON stdout then prints a summary only", + "zh-CN": "将完整服务端响应 JSON 保存到文件;此时 JSON stdout 仅输出摘要", }, }, } satisfies FlagsDef; -function usageError(localize: (text: LocalizedText) => string, text: LocalizedText): never { - throw new BailianError(localize(text), ExitCode.USAGE); -} - function routeError(localize: (text: LocalizedText) => string, error: EmbeddingRouteError): never { throw new BailianError( localize({ "en-US": error.message, "zh-CN": error.zhMessage }), @@ -95,114 +95,108 @@ function routeError(localize: (text: LocalizedText) => string, error: EmbeddingR ); } +/** Keep original text values; trim only for emptiness checks. Paths/URLs are trimmed. */ function nonEmptyStrings( values: string[] | undefined, flagName: string, localize: (text: LocalizedText) => string, + options?: { preserveWhitespace?: boolean }, ): string[] { if (!values?.length) return []; return values.map((value, index) => { - const trimmed = value.trim(); - if (!trimmed) { - usageError(localize, { + if (!value.trim()) { + throwUsage(localize, { "en-US": `${flagName}[${index}] must be a non-empty string.`, "zh-CN": `${flagName}[${index}] 必须为非空字符串。`, }); } - return trimmed; + return options?.preserveWhitespace ? value : value.trim(); }); } -function isHttpUrl(value: string): boolean { - return /^https?:\/\//i.test(value); -} - -function isDataUri(value: string): boolean { - return /^data:/i.test(value); -} - -function isLocalPathCandidate(value: string): boolean { - if (isHttpUrl(value) || isDataUri(value)) return false; - if (value.startsWith("oss://")) return false; - return true; -} - -function redactImageForDryRun(image: string): string { - if (isDataUri(image)) return redactDataUri(image); - if (isLocalPathCandidate(image)) return LOCAL_IMAGE_PENDING_ENCODE; - return image; -} - -function resolveLocalImage( - image: string, - maxImageBytes: number, - localize: (text: LocalizedText) => string, -): string { - if (!existsSync(image)) { - usageError(localize, { - "en-US": `Image file not found: ${image}`, - "zh-CN": `找不到图片文件:${image}`, - }); - } - const stats = statSync(image); - if (!stats.isFile()) { - usageError(localize, { - "en-US": `Not a file: ${image}`, - "zh-CN": `不是文件:${image}`, - }); - } - if (maxImageBytes > 0 && stats.size > maxImageBytes) { - usageError(localize, { - "en-US": `Local image exceeds the ${Math.round(maxImageBytes / (1024 * 1024))} MB limit for this model (${image}). Prefer a public HTTP(S) URL for large images.`, - "zh-CN": `本地图片超过该模型 ${Math.round(maxImageBytes / (1024 * 1024))} MB 上限(${image})。大图请优先使用公网 HTTP(S) URL。`, - }); - } - return imageFileToDataUri(image); -} - -function resolveImageInput( +function resolveEmbeddingImage( image: string, maxImageBytes: number, + dryRun: boolean, localize: (text: LocalizedText) => string, ): string { - if (isDataUri(image) || isHttpUrl(image)) return image; - if (image.startsWith("oss://")) { - usageError(localize, { + return resolveImageMediaInput(image, { + maxImageBytes, + dryRun, + localize, + ossUnsupported: { "en-US": "oss:// image URLs are not supported for embedding. Use a public HTTP(S) URL, Data URI, or local image path.", "zh-CN": "embedding 不支持 oss:// 图片 URL。请使用公网 HTTP(S) URL、Data URI 或本地图片路径。", - }); - } - return resolveLocalImage(image, maxImageBytes, localize); + }, + }); } function assertVideoUrl(video: string, localize: (text: LocalizedText) => string): string { - if (isHttpUrl(video)) return video; - usageError(localize, { + return assertPublicHttpUrl(video, localize, { "en-US": `Video input must be a public HTTP(S) URL (got "${video}"). Local video paths are not supported in this command.`, "zh-CN": `视频输入必须是公网 HTTP(S) URL(收到 "${video}")。本命令不支持本地视频路径。`, }); } -function writeResponseFile( +/** Fail early before a billed request when --out cannot be written. */ +function assertWritableOutPath(outPath: string, localize: (text: LocalizedText) => string): void { + if (!outPath.trim()) { + throwUsage(localize, { + "en-US": "--out must be a non-empty path.", + "zh-CN": "--out 必须为非空路径。", + }); + } + if (existsSync(outPath)) { + const stats = statSync(outPath); + if (stats.isDirectory()) { + throwUsage(localize, { + "en-US": `--out path is a directory: ${outPath}`, + "zh-CN": `--out 路径是目录:${outPath}`, + }); + } + } + const parentDir = dirname(outPath); + if (existsSync(parentDir)) { + const parentStats = statSync(parentDir); + if (!parentStats.isDirectory()) { + throwUsage(localize, { + "en-US": `--out parent path is not a directory: ${parentDir}`, + "zh-CN": `--out 父路径不是目录:${parentDir}`, + }); + } + try { + accessSync(parentDir, constants.W_OK); + } catch { + throwUsage(localize, { + "en-US": `--out parent directory is not writable: ${parentDir}`, + "zh-CN": `--out 父目录不可写:${parentDir}`, + }); + } + return; + } + try { + mkdirSync(parentDir, { recursive: true }); + } catch (error) { + const reason = error instanceof Error ? error.message : String(error); + throwUsage(localize, { + "en-US": `Cannot create --out parent directory "${parentDir}": ${reason}`, + "zh-CN": `无法创建 --out 父目录 "${parentDir}":${reason}`, + }); + } +} + +function tryWriteResponseFile( outPath: string, response: unknown, - localize: (text: LocalizedText) => string, -): string { +): { saved?: string; error?: string } { try { mkdirSync(dirname(outPath), { recursive: true }); writeFileSync(outPath, `${JSON.stringify(response, null, 2)}\n`); - return outPath; + return { saved: outPath }; } catch (error) { - const reason = error instanceof Error ? error.message : String(error); - throw new BailianError( - localize({ - "en-US": `Failed to write --out file "${outPath}": ${reason}`, - "zh-CN": `写入 --out 文件 "${outPath}" 失败:${reason}`, - }), - ExitCode.GENERAL, - ); + return { error: error instanceof Error ? error.message : String(error) }; } } @@ -240,6 +234,67 @@ function embeddingDimensions( return undefined; } +/** Compatible text responses often expose `id`; native multimodal uses `request_id`. */ +function embeddingRequestId( + response: TextEmbeddingResponse | MultimodalEmbeddingResponse, +): string | undefined { + if ("data" in response) return response.request_id ?? response.id; + return response.request_id; +} + +function emitEmbeddingResult( + ctx: CommandContext, + options: { + response: TextEmbeddingResponse | MultimodalEmbeddingResponse; + model: string; + dimensions?: number; + fusion?: boolean; + outPath?: string; + }, +): void { + const count = embeddingCount(options.response); + const dimensions = options.dimensions ?? embeddingDimensions(options.response); + let saved: string | undefined; + let useSummary = false; + + if (options.outPath) { + const writeResult = tryWriteResponseFile(options.outPath, options.response); + if (writeResult.saved) { + saved = writeResult.saved; + useSummary = true; + } else { + ctx.output.warning({ + code: "EMBEDDING_OUT_WRITE_FAILED", + message: { + "en-US": `Failed to write --out (${writeResult.error}); printing the response to stdout instead.`, + "zh-CN": `写入 --out 失败(${writeResult.error});改为将响应输出到 stdout。`, + }, + }); + } + } + + const result = useSummary + ? stripUndefined({ + model: options.model, + count, + dimensions, + usage: options.response.usage, + request_id: embeddingRequestId(options.response), + fusion: options.fusion, + saved, + }) + : options.response; + + const text = formatTextSummary({ + model: options.model, + count, + dimensions, + fusion: options.fusion, + saved, + }); + ctx.output.result(result, ctx.settings.output === "text" ? { text } : undefined); +} + export default defineCommand({ description: { "en-US": "Create text or multimodal embeddings", @@ -263,9 +318,9 @@ export default defineCommand({ notes: [ { "en-US": - "Content order is fixed as text → image → video across flags (repeatable flags keep their own order). Multiple inputs do not imply fusion — use --fuse with qwen3-vl-embedding. Local video is unsupported; prefer public HTTP(S) URLs for large images. Billed per call; this command does not auto-batch. For knowledge-base indexing / retrieval use knowledge commands, not embedding create.", + "Content order is fixed as text → image → video across flags (repeatable flags keep their own order). Multiple inputs do not imply fusion — use --fuse with qwen3-vl-embedding. Text embeddings use the OpenAI-compatible API in this release (no text_type / instruct / sparse). Dated tongyi-*-2026-03-06 snapshots stay independent-only here. Default multimodal model qwen3-vl-embedding is Beijing-only; on international endpoints use --model tongyi-embedding-vision-plus. With --out, JSON stdout prints a summary only; --dry-run never writes --out. Local video is unsupported; prefer public HTTP(S) URLs for large images. Billed per call; this command does not auto-batch. For knowledge-base indexing / retrieval use knowledge commands, not embedding create.", "zh-CN": - "跨 flag 的内容顺序固定为 text → image → video(可重复 flag 保留各自顺序)。多输入不等于融合向量——qwen3-vl-embedding 请用 --fuse。不支持本地视频;大图优先公网 HTTP(S) URL。按调用计费,不会自动分批。建库 / 召回请用 knowledge 命令,不要用 embedding create。", + "跨 flag 的内容顺序固定为 text → image → video(可重复 flag 保留各自顺序)。多输入不等于融合向量——qwen3-vl-embedding 请用 --fuse。本版文本向量走 OpenAI 兼容接口(不支持 text_type / instruct / 稀疏向量)。tongyi-*-2026-03-06 快照版在此仅支持独立模式。默认多模态模型 qwen3-vl-embedding 仅北京可用;国际站请用 --model tongyi-embedding-vision-plus。传 --out 时 JSON stdout 只输出摘要;--dry-run 不会写入 --out。不支持本地视频;大图优先公网 HTTP(S) URL。按调用计费,不会自动分批。建库 / 召回请用 knowledge 命令,不要用 embedding create。", }, ], validate: (flags) => { @@ -283,10 +338,13 @@ export default defineCommand({ async run(ctx) { const { settings, flags } = ctx; const localize = ctx.localize; - const texts = nonEmptyStrings(flags.text as string[] | undefined, "--text", localize); + const texts = nonEmptyStrings(flags.text as string[] | undefined, "--text", localize, { + preserveWhitespace: true, + }); const images = nonEmptyStrings(flags.image as string[] | undefined, "--image", localize); const videos = nonEmptyStrings(flags.video as string[] | undefined, "--video", localize); const hasMedia = images.length > 0 || videos.length > 0; + const outPath = flags.out as string | undefined; let route; try { @@ -311,6 +369,7 @@ export default defineCommand({ const dimensions = flags.dimensions as number | undefined; const fuse = flags.fuse as boolean | undefined; const endpoint = ctx.client.url(route.path); + const dryRun = settings.dryRun; if (route.spec.kind === "compatible-text") { const request: TextEmbeddingRequest = { @@ -320,88 +379,75 @@ export default defineCommand({ }; if (dimensions !== undefined) request.dimensions = dimensions; - if (settings.dryRun) { + if (dryRun) { ctx.output.result({ endpoint, request }); return; } + if (outPath) assertWritableOutPath(outPath, localize); + const response = await ctx.client.requestJson({ path: route.path, method: "POST", body: request, }); - let saved: string | undefined; - if (flags.out) { - saved = writeResponseFile(flags.out as string, response, localize); - } - - const result = saved ? { ...response, saved } : response; - const text = formatTextSummary({ + emitEmbeddingResult(ctx, { + response, model: route.model, - count: embeddingCount(response), - dimensions: dimensions ?? embeddingDimensions(response), - saved, + dimensions, + outPath, }); - ctx.output.result(result, settings.output === "text" ? { text } : undefined); return; } - const dryRunContents: MultimodalEmbeddingContent[] = [ + const contents: MultimodalEmbeddingContent[] = [ ...texts.map((text) => ({ text })), - ...images.map((image) => ({ image: redactImageForDryRun(image) })), - ...videos.map((video) => ({ video })), + ...images.map((image) => ({ + image: resolveEmbeddingImage(image, route.spec.maxImageBytes, dryRun, localize), + })), + ...videos.map((video) => ({ video: assertVideoUrl(video, localize) })), ]; const parameters = stripUndefined({ dimension: dimensions, - enable_fusion: fuse, + enable_fusion: route.spec.fusion === "optional" ? fuse : undefined, }); - const dryRunRequest: MultimodalEmbeddingRequest = stripUndefined({ + const request: MultimodalEmbeddingRequest = stripUndefined({ model: route.model, - input: { contents: dryRunContents }, + input: { contents }, parameters: Object.keys(parameters).length > 0 ? parameters : undefined, }); - if (settings.dryRun) { - ctx.output.result({ endpoint, request: dryRunRequest }); + if (dryRun) { + ctx.output.result({ endpoint, request }); return; } - const contents: MultimodalEmbeddingContent[] = [ - ...texts.map((text) => ({ text })), - ...images.map((image) => ({ - image: resolveImageInput(image, route.spec.maxImageBytes, localize), - })), - ...videos.map((video) => ({ video: assertVideoUrl(video, localize) })), - ]; + if (outPath) assertWritableOutPath(outPath, localize); - const request: MultimodalEmbeddingRequest = stripUndefined({ - model: route.model, - input: { contents }, - parameters: Object.keys(parameters).length > 0 ? parameters : undefined, - }); - - const response = await ctx.client.requestJson({ - path: route.path, - method: "POST", - body: request, - }); - - let saved: string | undefined; - if (flags.out) { - saved = writeResponseFile(flags.out as string, response, localize); + let response: MultimodalEmbeddingResponse; + try { + response = await ctx.client.requestJson({ + path: route.path, + method: "POST", + body: request, + }); + } catch (error) { + rethrowWithQwen3VlRegionHint(error, { + model: route.model, + endpoint, + localize, + }); } - const result = saved ? { ...response, saved } : response; - const text = formatTextSummary({ + emitEmbeddingResult(ctx, { + response, model: route.model, - count: embeddingCount(response), - dimensions: dimensions ?? embeddingDimensions(response), + dimensions, fusion: fuse, - saved, + outPath, }); - ctx.output.result(result, settings.output === "text" ? { text } : undefined); }, }); diff --git a/packages/commands/src/commands/rerank.ts b/packages/commands/src/commands/rerank.ts index 131f9f4e2..f87193f4e 100644 --- a/packages/commands/src/commands/rerank.ts +++ b/packages/commands/src/commands/rerank.ts @@ -1,75 +1,31 @@ import { dirname, isAbsolute, resolve as resolvePath } from "node:path"; -import { existsSync, readFileSync, statSync } from "node:fs"; +import { existsSync, readFileSync } from "node:fs"; import { BailianError, ExitCode, + DEFAULT_RERANK_MODEL, defineCommand, - imageFileToDataUri, - LOCAL_IMAGE_PENDING_ENCODE, + isDataUri, + isLocalMediaPath, redactDataUri, rerankPath, + resolveImageMediaInput, + resolveRerankModel, + rethrowWithQwen3VlRerankUnavailableHint, + RerankRouteError, + assertPublicHttpUrl, stripUndefined, + throwUsage, type FlagsDef, type LocalizedText, type RerankDocumentInput, + type RerankModelSpec, type RerankQueryInput, type RerankRequest, type RerankResponse, type RerankResultItem, } from "bailian-cli-core"; -const DEFAULT_MODEL = "qwen3-rerank"; - -type RerankModelKind = "text" | "vl"; - -interface RerankModelSpec { - model: string; - kind: RerankModelKind; - maxDocuments: number; - maxTextDocuments?: number; - maxImageDocuments?: number; - maxVideoDocuments?: number; - supportsInstruct: boolean; - /** Local image byte limit for Data URI encoding. */ - maxImageBytes: number; -} - -const RERANK_MODELS: readonly RerankModelSpec[] = [ - { - model: "qwen3-rerank", - kind: "text", - maxDocuments: 500, - supportsInstruct: true, - maxImageBytes: 0, - }, - { - model: "gte-rerank-v2", - kind: "text", - maxDocuments: 500, - supportsInstruct: false, - maxImageBytes: 0, - }, - { - model: "qwen3.7-text-rerank", - kind: "text", - maxDocuments: 500, - supportsInstruct: true, - maxImageBytes: 0, - }, - { - model: "qwen3-vl-rerank", - kind: "vl", - maxDocuments: Number.POSITIVE_INFINITY, - maxTextDocuments: 100, - maxImageDocuments: 40, - maxVideoDocuments: 4, - supportsInstruct: true, - maxImageBytes: 10 * 1024 * 1024, - }, -]; - -const RERANK_MODEL_BY_ID = new Map(RERANK_MODELS.map((spec) => [spec.model, spec])); - const RERANK_FLAGS = { query: { type: "string", @@ -150,36 +106,15 @@ const RERANK_FLAGS = { }, } satisfies FlagsDef; -function usageError(localize: (text: LocalizedText) => string, text: LocalizedText): never { - throw new BailianError(localize(text), ExitCode.USAGE); -} - -function isHttpUrl(value: string): boolean { - return /^https?:\/\//i.test(value); -} - -function isDataUri(value: string): boolean { - return /^data:/i.test(value); -} - -function isLocalPathCandidate(value: string): boolean { - if (isHttpUrl(value) || isDataUri(value) || value.startsWith("oss://")) return false; - return true; -} - -function lookupModel(model: string, localize: (text: LocalizedText) => string): RerankModelSpec { - const spec = RERANK_MODEL_BY_ID.get(model); - if (!spec) { - usageError(localize, { - "en-US": `Unknown rerank model "${model}". Supported: ${RERANK_MODELS.map((item) => item.model).join(", ")}.`, - "zh-CN": `未知重排序模型 "${model}"。支持:${RERANK_MODELS.map((item) => item.model).join(", ")}。`, - }); - } - return spec; +function routeError(localize: (text: LocalizedText) => string, error: RerankRouteError): never { + throw new BailianError( + localize({ "en-US": error.message, "zh-CN": error.zhMessage }), + ExitCode.USAGE, + ); } function resolveImageRelativeTo(image: string, baseDir: string | undefined): string { - if (!isLocalPathCandidate(image)) return image; + if (!isLocalMediaPath(image)) return image; if (isAbsolute(image) || baseDir === undefined) return image; return resolvePath(baseDir, image); } @@ -194,43 +129,20 @@ function resolveImageValue( }, ): string { const resolved = resolveImageRelativeTo(image, options.baseDir); - if (isDataUri(resolved)) { - return options.dryRun ? redactDataUri(resolved) : resolved; - } - if (isHttpUrl(resolved)) return resolved; - if (resolved.startsWith("oss://")) { - usageError(options.localize, { + return resolveImageMediaInput(resolved, { + maxImageBytes: options.maxImageBytes, + dryRun: options.dryRun, + localize: options.localize, + ossUnsupported: { "en-US": "oss:// media URLs are not supported for rerank. Use a public HTTP(S) URL, Data URI, or local image path.", "zh-CN": "rerank 不支持 oss:// 媒体 URL。请使用公网 HTTP(S) URL、Data URI 或本地图片路径。", - }); - } - if (options.dryRun) return LOCAL_IMAGE_PENDING_ENCODE; - if (!existsSync(resolved)) { - usageError(options.localize, { - "en-US": `Image file not found: ${resolved}`, - "zh-CN": `找不到图片文件:${resolved}`, - }); - } - const stats = statSync(resolved); - if (!stats.isFile()) { - usageError(options.localize, { - "en-US": `Not a file: ${resolved}`, - "zh-CN": `不是文件:${resolved}`, - }); - } - if (options.maxImageBytes > 0 && stats.size > options.maxImageBytes) { - usageError(options.localize, { - "en-US": `Local image exceeds the ${Math.round(options.maxImageBytes / (1024 * 1024))} MB limit (${resolved}). Prefer a public HTTP(S) URL.`, - "zh-CN": `本地图片超过 ${Math.round(options.maxImageBytes / (1024 * 1024))} MB 上限(${resolved})。请优先使用公网 HTTP(S) URL。`, - }); - } - return imageFileToDataUri(resolved); + }, + }); } function assertVideoUrl(video: string, localize: (text: LocalizedText) => string): string { - if (isHttpUrl(video)) return video; - usageError(localize, { + return assertPublicHttpUrl(video, localize, { "en-US": `Video document must be a public HTTP(S) URL (got "${video}"). Local video paths are not supported.`, "zh-CN": `视频文档必须是公网 HTTP(S) URL(收到 "${video}")。不支持本地视频路径。`, }); @@ -238,7 +150,7 @@ function assertVideoUrl(video: string, localize: (text: LocalizedText) => string function parseDocumentsFile(filePath: string, localize: (text: LocalizedText) => string): unknown { if (!existsSync(filePath)) { - usageError(localize, { + throwUsage(localize, { "en-US": `Documents file not found: ${filePath}`, "zh-CN": `找不到候选文档文件:${filePath}`, }); @@ -248,7 +160,7 @@ function parseDocumentsFile(filePath: string, localize: (text: LocalizedText) => raw = readFileSync(filePath, "utf8"); } catch (error) { const reason = error instanceof Error ? error.message : String(error); - usageError(localize, { + throwUsage(localize, { "en-US": `Failed to read documents file "${filePath}": ${reason}`, "zh-CN": `读取候选文档文件 "${filePath}" 失败:${reason}`, }); @@ -257,7 +169,7 @@ function parseDocumentsFile(filePath: string, localize: (text: LocalizedText) => return JSON.parse(raw); } catch (error) { const reason = error instanceof Error ? error.message : String(error); - usageError(localize, { + throwUsage(localize, { "en-US": `Documents file is not valid JSON: ${reason}`, "zh-CN": `候选文档文件不是合法 JSON:${reason}`, }); @@ -271,7 +183,7 @@ function normalizeDocumentEntry( ): RerankDocumentInput { if (typeof entry === "string") { if (!entry.trim()) { - usageError(localize, { + throwUsage(localize, { "en-US": `Document[${index}] must be a non-empty string.`, "zh-CN": `Document[${index}] 必须为非空字符串。`, }); @@ -279,7 +191,7 @@ function normalizeDocumentEntry( return entry; } if (!entry || typeof entry !== "object" || Array.isArray(entry)) { - usageError(localize, { + throwUsage(localize, { "en-US": `Document[${index}] must be a string or an object with exactly one of text/image/video.`, "zh-CN": `Document[${index}] 必须是字符串,或仅含 text/image/video 之一的对象。`, }); @@ -287,7 +199,7 @@ function normalizeDocumentEntry( const record = entry as Record; const keys = ["text", "image", "video"].filter((key) => record[key] !== undefined); if (keys.length !== 1) { - usageError(localize, { + throwUsage(localize, { "en-US": `Document[${index}] must contain exactly one of text/image/video.`, "zh-CN": `Document[${index}] 必须且只能包含 text/image/video 之一。`, }); @@ -295,7 +207,7 @@ function normalizeDocumentEntry( const key = keys[0]!; const value = record[key]; if (typeof value !== "string" || !value.trim()) { - usageError(localize, { + throwUsage(localize, { "en-US": `Document[${index}].${key} must be a non-empty string.`, "zh-CN": `Document[${index}].${key} 必须为非空字符串。`, }); @@ -327,38 +239,38 @@ function assertDocumentLimits( localize: (text: LocalizedText) => string, ): void { if (documents.length === 0) { - usageError(localize, { + throwUsage(localize, { "en-US": "Provide at least one candidate document.", "zh-CN": "请至少提供一条候选文档。", }); } if (documents.length > spec.maxDocuments) { - usageError(localize, { + throwUsage(localize, { "en-US": `Model "${spec.model}" accepts at most ${spec.maxDocuments} documents; got ${documents.length}.`, "zh-CN": `模型 "${spec.model}" 最多接受 ${spec.maxDocuments} 条候选;当前为 ${documents.length}。`, }); } const counts = countModalities(documents); if (spec.kind === "text" && (counts.image > 0 || counts.video > 0)) { - usageError(localize, { + throwUsage(localize, { "en-US": `Model "${spec.model}" only accepts text documents. Use qwen3-vl-rerank for image/video candidates.`, "zh-CN": `模型 "${spec.model}" 仅接受文本文档。图/视频候选请使用 qwen3-vl-rerank。`, }); } if (spec.maxTextDocuments !== undefined && counts.text > spec.maxTextDocuments) { - usageError(localize, { + throwUsage(localize, { "en-US": `Model "${spec.model}" accepts at most ${spec.maxTextDocuments} text documents; got ${counts.text}.`, "zh-CN": `模型 "${spec.model}" 最多接受 ${spec.maxTextDocuments} 条文本文档;当前为 ${counts.text}。`, }); } if (spec.maxImageDocuments !== undefined && counts.image > spec.maxImageDocuments) { - usageError(localize, { + throwUsage(localize, { "en-US": `Model "${spec.model}" accepts at most ${spec.maxImageDocuments} image documents; got ${counts.image}.`, "zh-CN": `模型 "${spec.model}" 最多接受 ${spec.maxImageDocuments} 张图片文档;当前为 ${counts.image}。`, }); } if (spec.maxVideoDocuments !== undefined && counts.video > spec.maxVideoDocuments) { - usageError(localize, { + throwUsage(localize, { "en-US": `Model "${spec.model}" accepts at most ${spec.maxVideoDocuments} video documents; got ${counts.video}.`, "zh-CN": `模型 "${spec.model}" 最多接受 ${spec.maxVideoDocuments} 个视频文档;当前为 ${counts.video}。`, }); @@ -413,11 +325,23 @@ function summarizeDocument(document: unknown): string { return JSON.stringify(document); } -function formatTextResults(results: RerankResultItem[]): string { +function formatTextResults( + results: RerankResultItem[], + localDocuments?: RerankDocumentInput[], +): string { if (results.length === 0) return "No results."; return results .map((item) => { - const documentSummary = summarizeDocument(item.document); + const fromServer = summarizeDocument(item.document); + const fromLocal = + !fromServer && + localDocuments !== undefined && + Number.isInteger(item.index) && + item.index >= 0 && + item.index < localDocuments.length + ? summarizeDocument(localDocuments[item.index]) + : ""; + const documentSummary = fromServer || fromLocal; const suffix = documentSummary ? ` ${documentSummary}` : ""; return `#${item.index} score=${item.relevance_score}${suffix}`; }) @@ -450,9 +374,9 @@ export default defineCommand({ notes: [ { "en-US": - "relevance_score is comparable only within one request; this CLI never re-sorts or merges scores across batches. Paths in --documents-file are resolved relative to that file's directory; --query-image uses the process cwd. Local video is unsupported. Billed per call (up to 500 candidates). For knowledge-base retrieval / server-side hybrid ranking use knowledge commands, not rerank.", + "relevance_score is comparable only within one request; this CLI never re-sorts or merges scores across batches. Text mode previews documents from local inputs when the server omits them. Paths in --documents-file are resolved relative to that file's directory; --query-image uses the process cwd. If qwen3-vl-rerank is unavailable on the current endpoint, text rerank can fall back to qwen3-rerank. Local video is unsupported. Billed per call (up to 500 candidates). For knowledge-base retrieval / server-side hybrid ranking use knowledge commands, not rerank.", "zh-CN": - "relevance_score 仅可在单次请求内比较;CLI 不会二次排序或跨批合并分数。--documents-file 内相对路径相对该文件目录解析;--query-image 相对进程 cwd。不支持本地视频。按调用计费(最多 500 候选)。建库 / 召回 / 服务侧混排请用 knowledge 命令,不要用 rerank。", + "relevance_score 仅可在单次请求内比较;CLI 不会二次排序或跨批合并分数。text 模式在服务端未返回文档时用本地输入做预览。--documents-file 内相对路径相对该文件目录解析;--query-image 相对进程 cwd。若当前端点未提供 qwen3-vl-rerank,文本重排可改用 qwen3-rerank。不支持本地视频。按调用计费(最多 500 候选)。建库 / 召回 / 服务侧混排请用 knowledge 命令,不要用 rerank。", }, ], validate: (flags) => { @@ -490,19 +414,31 @@ export default defineCommand({ async run(ctx) { const { settings, flags } = ctx; const localize = ctx.localize; - const model = ((flags.model as string | undefined) || DEFAULT_MODEL).trim(); - const spec = lookupModel(model, localize); + const model = ((flags.model as string | undefined) || DEFAULT_RERANK_MODEL).trim(); + let spec: RerankModelSpec; + try { + spec = resolveRerankModel(model); + } catch (error) { + if (error instanceof RerankRouteError) routeError(localize, error); + throw error; + } const queryText = flags.query as string | undefined; const queryImage = flags.queryImage as string | undefined; if (queryText !== undefined && !queryText.trim()) { - usageError(localize, { + throwUsage(localize, { "en-US": "--query must be a non-empty string.", "zh-CN": "--query 必须为非空字符串。", }); } + if (queryImage !== undefined && !queryImage.trim()) { + throwUsage(localize, { + "en-US": "--query-image must be a non-empty string.", + "zh-CN": "--query-image 必须为非空字符串。", + }); + } if (queryImage !== undefined && spec.kind !== "vl") { - usageError(localize, { + throwUsage(localize, { "en-US": `--query-image is only supported by qwen3-vl-rerank (got "${model}").`, "zh-CN": `--query-image 仅 qwen3-vl-rerank 支持(当前为 "${model}")。`, }); @@ -510,8 +446,8 @@ export default defineCommand({ const topN = flags.topN as number | undefined; if (topN !== undefined) { - if (!Number.isInteger(topN) || topN <= 0 || !Number.isFinite(topN)) { - usageError(localize, { + if (!Number.isInteger(topN) || topN <= 0) { + throwUsage(localize, { "en-US": "--top-n must be a positive integer.", "zh-CN": "--top-n 必须为正整数。", }); @@ -521,13 +457,13 @@ export default defineCommand({ const instruct = flags.instruct as string | undefined; if (instruct !== undefined) { if (!instruct.trim()) { - usageError(localize, { + throwUsage(localize, { "en-US": "--instruct must be a non-empty string.", "zh-CN": "--instruct 必须为非空字符串。", }); } if (!spec.supportsInstruct) { - usageError(localize, { + throwUsage(localize, { "en-US": `Model "${model}" does not support --instruct.`, "zh-CN": `模型 "${model}" 不支持 --instruct。`, }); @@ -537,13 +473,13 @@ export default defineCommand({ const fps = flags.fps as number | undefined; if (fps !== undefined) { if (spec.kind !== "vl") { - usageError(localize, { + throwUsage(localize, { "en-US": `--fps is only supported by qwen3-vl-rerank (got "${model}").`, "zh-CN": `--fps 仅 qwen3-vl-rerank 支持(当前为 "${model}")。`, }); } - if (!(fps > 0 && fps <= 5) || !Number.isFinite(fps)) { - usageError(localize, { + if (!(fps > 0 && fps <= 5)) { + throwUsage(localize, { "en-US": "--fps must be in (0, 5].", "zh-CN": "--fps 必须在 (0, 5] 范围内。", }); @@ -556,7 +492,7 @@ export default defineCommand({ const filePath = flags.documentsFile as string; const parsed = parseDocumentsFile(filePath, localize); if (!Array.isArray(parsed) || parsed.length === 0) { - usageError(localize, { + throwUsage(localize, { "en-US": "Documents file must be a non-empty JSON array.", "zh-CN": "候选文档文件必须是非空 JSON 数组。", }); @@ -567,7 +503,7 @@ export default defineCommand({ const documentFlags = flags.document as string[] | undefined; documents = (documentFlags ?? []).map((value, index) => { if (!value.trim()) { - usageError(localize, { + throwUsage(localize, { "en-US": `--document[${index}] must be a non-empty string.`, "zh-CN": `--document[${index}] 必须为非空字符串。`, }); @@ -596,12 +532,26 @@ export default defineCommand({ }), }; } else { - query = queryText!.trim(); + // Preserve original query text; emptiness was checked above via trim(). + query = queryText!; + } + + const returnDocuments = flags.returnDocuments as boolean | undefined; + if (model === "qwen3.7-text-rerank" && returnDocuments === true) { + ctx.output.warning({ + code: "RERANK_RETURN_DOCUMENTS_UNCONFIRMED", + message: { + "en-US": + 'Model "qwen3.7-text-rerank" may not support return_documents; the server response is authoritative. Text mode previews use local inputs.', + "zh-CN": + '模型 "qwen3.7-text-rerank" 可能不支持 return_documents;以服务端响应为准。text 模式会用本地输入做预览。', + }, + }); } const parameters = stripUndefined({ top_n: topN, - return_documents: flags.returnDocuments as boolean | undefined, + return_documents: returnDocuments, instruct: instruct?.trim(), fps, }); @@ -621,16 +571,24 @@ export default defineCommand({ return; } - const response = await ctx.client.requestJson({ - path: rerankPath(), - method: "POST", - body: request, - }); + let response: RerankResponse; + try { + response = await ctx.client.requestJson({ + path: rerankPath(), + method: "POST", + body: request, + }); + } catch (error) { + rethrowWithQwen3VlRerankUnavailableHint(error, { + model, + localize, + }); + } const results = response.output?.results ?? []; ctx.output.result( response, - settings.output === "text" ? { text: formatTextResults(results) } : undefined, + settings.output === "text" ? { text: formatTextResults(results, documents) } : undefined, ); }, }); diff --git a/packages/commands/tests/e2e/embedding-create.e2e.test.ts b/packages/commands/tests/e2e/embedding-create.e2e.test.ts index 5033c5205..426e282d4 100644 --- a/packages/commands/tests/e2e/embedding-create.e2e.test.ts +++ b/packages/commands/tests/e2e/embedding-create.e2e.test.ts @@ -1,4 +1,4 @@ -import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { chmodSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { createServer, type IncomingMessage, type Server, type ServerResponse } from "node:http"; import { tmpdir } from "node:os"; import { join } from "node:path"; @@ -102,6 +102,8 @@ describe("e2e: embedding create", () => { expect(stderr).toMatch(/Embedding dimensions|向量维度/); expect(stderr).toMatch(/text-embedding-v4/); expect(stderr).toMatch(/qwen3-vl-embedding/); + expect(stderr).toMatch(/tongyi-embedding-vision-plus/); + expect(stderr).toMatch(/Beijing-only|仅北京/); }); test("missing inputs → 2", async () => { @@ -145,7 +147,7 @@ describe("e2e: embedding create", () => { expect(stderr).toMatch(/does not accept|--image/); }); - test("unknown model → 2", async () => { + test("unknown model → 2 and lists supported IDs", async () => { const { stderr, exitCode } = await runCommandInProcess( EMBEDDING_ROUTES, ["embedding", "create", "--model", "no-such-embed", "--text", "a", "--dry-run", "--quiet"], @@ -153,9 +155,11 @@ describe("e2e: embedding create", () => { ); expect(exitCode).toBe(2); expect(stderr).toMatch(/Unknown embedding model|未知向量模型/); + expect(stderr).toMatch(/text-embedding-v4/); + expect(stderr).toMatch(/qwen3-vl-embedding/); }); - test("fuse on text model → 2; fuse=false preserved for qwen3", async () => { + test("fuse on text model → 2; fuse=false preserved for qwen3; always models omit enable_fusion", async () => { const rejected = await runCommandInProcess( EMBEDDING_ROUTES, ["embedding", "create", "--text", "a", "--fuse", "true", "--dry-run", "--quiet"], @@ -186,6 +190,69 @@ describe("e2e: embedding create", () => { request?: { parameters?: { enable_fusion?: boolean } }; }>(ok.stdout); expect(data.request?.parameters?.enable_fusion).toBe(false); + + const alwaysFuse = await runCommandInProcess( + EMBEDDING_ROUTES, + [ + "embedding", + "create", + "--model", + "qwen2.5-vl-embedding", + "--text", + "a", + "--fuse", + "true", + "--dry-run", + "--output", + "json", + ], + isolatedEnv({ DASHSCOPE_API_KEY: "sk-e2e-placeholder" }), + ); + expect(alwaysFuse.exitCode, alwaysFuse.stderr).toBe(0); + const alwaysData = parseStdoutJson<{ + request?: { parameters?: { enable_fusion?: boolean } }; + }>(alwaysFuse.stdout); + expect(alwaysData.request?.parameters?.enable_fusion).toBeUndefined(); + }); + + test("preserves --text whitespace; dry-run validates missing local images", async () => { + const spaced = await runCommandInProcess( + EMBEDDING_ROUTES, + ["embedding", "create", "--text", " hello ", "--dry-run", "--output", "json"], + isolatedEnv({ DASHSCOPE_API_KEY: "sk-e2e-placeholder" }), + ); + expect(spaced.exitCode, spaced.stderr).toBe(0); + expect( + parseStdoutJson<{ request?: { input?: string[] } }>(spaced.stdout).request?.input, + ).toEqual([" hello "]); + + const missing = await runCommandInProcess( + EMBEDDING_ROUTES, + [ + "embedding", + "create", + "--model", + "qwen3-vl-embedding", + "--image", + join(isolatedDirectory, "nope.png"), + "--dry-run", + "--quiet", + ], + isolatedEnv(), + ); + expect(missing.exitCode).toBe(2); + expect(missing.stderr).toMatch(/not found|找不到/); + }); + + test("tongyi snapshot input caps reject oversized batches", async () => { + const args = ["embedding", "create", "--model", "tongyi-embedding-vision-plus-2026-03-06"]; + for (let index = 0; index < 21; index += 1) { + args.push("--text", `t${index}`); + } + args.push("--dry-run", "--quiet"); + const { stderr, exitCode } = await runCommandInProcess(EMBEDDING_ROUTES, args, isolatedEnv()); + expect(exitCode).toBe(2); + expect(stderr).toMatch(/at most 20|最多接受 20/); }); test("dry-run text uses dimensions; multimodal uses dimension", async () => { @@ -427,20 +494,29 @@ describe("e2e: embedding create", () => { expect(stderr).toMatch(/boom-embedding/); }); - test("--out writes full response without saved; text summarizes", async () => { - const { origin } = await startServer((_request, response) => { + test("--out writes full response; JSON stdout is summary-only", async () => { + let callCount = 0; + const { origin, requests } = await startServer((_request, response) => { + callCount += 1; response.writeHead(200, { "Content-Type": "application/json" }); + // Compatible text APIs often return `id` instead of `request_id`. + const identity = + callCount === 1 + ? { id: "emb-id-1" } + : callCount === 2 + ? { id: "emb-id-2" } + : { request_id: "save-1" }; response.end( JSON.stringify({ data: [{ embedding: Array.from({ length: 8 }, (_, index) => index), index: 0 }], usage: { total_tokens: 1 }, - request_id: "save-1", + ...identity, }), ); }); const outDir = makeE2eOutputDir("embedding-create-out"); const outPath = join(outDir, "vectors.json"); - const { stdout, stderr, exitCode } = await runCommandE2e( + const textMode = await runCommandE2e( EMBEDDING_ROUTES, [ "embedding", @@ -458,15 +534,114 @@ describe("e2e: embedding create", () => { ], isolatedEnv(), ); - expect(exitCode, stderr).toBe(0); - expect(stdout).toMatch(/model: text-embedding-v4/); - expect(stdout).toMatch(/count: 1/); - expect(stdout).toMatch(/dimensions: 8/); - expect(stdout).toMatch(/saved:/); - expect(stdout).not.toMatch(/0,1,2,3,4,5,6,7/); - const saved = JSON.parse(readFileSync(outPath, "utf8")) as Record; + expect(textMode.exitCode, textMode.stderr).toBe(0); + expect(textMode.stdout).toMatch(/model: text-embedding-v4/); + expect(textMode.stdout).toMatch(/count: 1/); + expect(textMode.stdout).toMatch(/dimensions: 8/); + expect(textMode.stdout).toMatch(/saved:/); + expect(textMode.stdout).not.toMatch(/0,1,2,3,4,5,6,7/); + const saved = JSON.parse(readFileSync(outPath, "utf8")) as { + request_id?: string; + data?: Array<{ embedding?: number[] }>; + saved?: unknown; + }; expect(saved).not.toHaveProperty("saved"); - expect(saved.request_id).toBe("save-1"); + expect(saved).toMatchObject({ id: "emb-id-1" }); + expect(saved.data?.[0]?.embedding).toEqual([0, 1, 2, 3, 4, 5, 6, 7]); + + const jsonMode = await runCommandInProcess( + EMBEDDING_ROUTES, + [ + "embedding", + "create", + "--text", + "hello", + "--api-key", + "sk-e2e", + "--base-url", + origin, + "--out", + join(outDir, "vectors-json.json"), + "--output", + "json", + "--quiet", + ], + isolatedEnv(), + ); + expect(jsonMode.exitCode, jsonMode.stderr).toBe(0); + const summary = parseStdoutJson<{ + model?: string; + count?: number; + dimensions?: number; + usage?: unknown; + request_id?: string; + saved?: string; + data?: unknown; + embedding?: unknown; + }>(jsonMode.stdout); + expect(summary).toMatchObject({ + model: "text-embedding-v4", + count: 1, + dimensions: 8, + request_id: "emb-id-2", + }); + expect(summary.saved).toMatch(/vectors-json\.json$/); + expect(summary).not.toHaveProperty("data"); + expect(JSON.stringify(summary)).not.toMatch(/"embedding"/); + + const blocker = join(isolatedDirectory, "afile"); + writeFileSync(blocker, "not-a-dir"); + const badOut = await runCommandInProcess( + EMBEDDING_ROUTES, + [ + "embedding", + "create", + "--text", + "hello", + "--api-key", + "sk-e2e", + "--base-url", + origin, + "--out", + join(blocker, "x.json"), + "--quiet", + ], + isolatedEnv(), + ); + expect(badOut.exitCode).toBe(2); + expect(badOut.stderr).toMatch(/parent path is not a directory|父路径不是目录/); + expect(requests).toHaveLength(2); + + const readonlyPath = join(outDir, "readonly.json"); + writeFileSync(readonlyPath, "x"); + chmodSync(readonlyPath, 0o444); + const writeFail = await runCommandInProcess( + EMBEDDING_ROUTES, + [ + "embedding", + "create", + "--text", + "hello", + "--api-key", + "sk-e2e", + "--base-url", + origin, + "--out", + readonlyPath, + "--output", + "json", + "--quiet", + ], + isolatedEnv(), + ); + expect(writeFail.exitCode, writeFail.stderr).toBe(0); + expect(writeFail.stderr).toMatch(/Failed to write --out|写入 --out 失败/); + const fallback = parseStdoutJson<{ data?: unknown[]; request_id?: string; id?: string }>( + writeFail.stdout, + ); + expect(fallback.request_id ?? fallback.id).toBe("save-1"); + expect(fallback.data).toHaveLength(1); + expect(requests).toHaveLength(3); }); test("missing image file → 2 via subprocess", async () => { diff --git a/packages/commands/tests/e2e/rerank.e2e.test.ts b/packages/commands/tests/e2e/rerank.e2e.test.ts index 8bcfca539..b30fc3075 100644 --- a/packages/commands/tests/e2e/rerank.e2e.test.ts +++ b/packages/commands/tests/e2e/rerank.e2e.test.ts @@ -96,6 +96,7 @@ describe("e2e: rerank", () => { expect(stderr).toMatch(/qwen3-rerank/); expect(stderr).toMatch(/--top-n/); expect(stderr).toMatch(/--return-documents/); + expect(stderr).toMatch(/unavailable on the current endpoint|当前端点未提供 qwen3-vl-rerank/); }); test("missing query / documents / conflicts → 2", async () => { @@ -143,6 +144,24 @@ describe("e2e: rerank", () => { expect(blank.exitCode).toBe(2); expect(blank.stderr).toMatch(/non-empty|非空/); + const blankImage = await runCommandInProcess( + RERANK_ROUTES, + [ + "rerank", + "--model", + "qwen3-vl-rerank", + "--query-image", + " ", + "--document", + "a", + "--dry-run", + "--quiet", + ], + isolatedEnv(), + ); + expect(blankImage.exitCode).toBe(2); + expect(blankImage.stderr).toMatch(/--query-image must be a non-empty|必须为非空/); + const emptyFile = join(isolatedDirectory, "empty.json"); writeFileSync(emptyFile, "[]"); const empty = await runCommandInProcess( @@ -314,6 +333,82 @@ describe("e2e: rerank", () => { ); expect(localVideo.exitCode).toBe(2); expect(localVideo.stderr).toMatch(/HTTP\(S\)|本地视频/); + + writeFileSync( + join(isolatedDirectory, "missing-image.json"), + JSON.stringify([{ image: "./missing.png" }]), + ); + const missingImage = await runCommandInProcess( + RERANK_ROUTES, + [ + "rerank", + "--model", + "qwen3-vl-rerank", + "--query", + "q", + "--documents-file", + join(isolatedDirectory, "missing-image.json"), + "--dry-run", + "--quiet", + ], + isolatedEnv(), + ); + expect(missingImage.exitCode).toBe(2); + expect(missingImage.stderr).toMatch(/not found|找不到/); + }); + + test("qwen3-vl-rerank rejects mixed total over 100 locally", async () => { + const docs = [ + ...Array.from({ length: 61 }, (_, index) => ({ text: `t${index}` })), + ...Array.from({ length: 40 }, () => ({ image: "https://example.com/a.png" })), + ]; + const docsFile = join(isolatedDirectory, "over-total.json"); + writeFileSync(docsFile, JSON.stringify(docs)); + const overTotal = await runCommandInProcess( + RERANK_ROUTES, + [ + "rerank", + "--model", + "qwen3-vl-rerank", + "--query", + "q", + "--documents-file", + docsFile, + "--dry-run", + "--quiet", + ], + isolatedEnv(), + ); + expect(overTotal.exitCode).toBe(2); + expect(overTotal.stderr).toMatch(/at most 100 documents|最多接受 100/); + + const okDocs = [ + ...Array.from({ length: 60 }, (_, index) => ({ text: `t${index}` })), + ...Array.from({ length: 40 }, () => ({ image: "https://example.com/a.png" })), + ]; + const okFile = join(isolatedDirectory, "total-100.json"); + writeFileSync(okFile, JSON.stringify(okDocs)); + const ok = await runCommandInProcess( + RERANK_ROUTES, + [ + "rerank", + "--model", + "qwen3-vl-rerank", + "--query", + "q", + "--documents-file", + okFile, + "--dry-run", + "--output", + "json", + ], + isolatedEnv({ DASHSCOPE_API_KEY: "sk-e2e" }), + ); + expect(ok.exitCode, ok.stderr).toBe(0); + expect( + parseStdoutJson<{ request?: { input?: { documents?: unknown[] } } }>(ok.stdout).request?.input + ?.documents, + ).toHaveLength(100); }); test("fps bounds and text-model media rejection", async () => { @@ -457,6 +552,72 @@ describe("e2e: rerank", () => { expect(textMode.exitCode, textMode.stderr).toBe(0); expect(textMode.stdout).toMatch(/#1/); expect(textMode.stdout).toMatch(/#0/); + expect(textMode.stdout).toMatch(/霓虹街道与夜空/); + }); + + test("text mode backfills local document preview; qwen3.7 return-documents warns", async () => { + const { origin, requests } = await startServer((_request, response) => { + response.writeHead(200, { "Content-Type": "application/json" }); + response.end( + JSON.stringify({ + output: { + results: [ + { index: 1, relevance_score: 0.9 }, + { index: 0, relevance_score: 0.1 }, + ], + }, + usage: { total_tokens: 3 }, + request_id: "rerank-local-preview", + }), + ); + }); + + const preview = await runCommandInProcess( + RERANK_ROUTES, + [ + "rerank", + "--query", + " city ", + "--document", + "白天的田野", + "--document", + "霓虹街道与夜空", + "--api-key", + "sk-e2e", + "--base-url", + origin, + "--output", + "text", + ], + isolatedEnv(), + ); + expect(preview.exitCode, preview.stderr).toBe(0); + expect(preview.stdout).toMatch(/#1\s+score=0\.9\s+霓虹街道与夜空/); + expect(preview.stdout).toMatch(/#0\s+score=0\.1\s+白天的田野/); + expect(requests[0]?.body).toMatchObject({ + input: { query: " city " }, + }); + + const warned = await runCommandInProcess( + RERANK_ROUTES, + [ + "rerank", + "--model", + "qwen3.7-text-rerank", + "--query", + "q", + "--document", + "a", + "--return-documents", + "true", + "--dry-run", + "--output", + "json", + ], + isolatedEnv({ DASHSCOPE_API_KEY: "sk-e2e" }), + ); + expect(warned.exitCode, warned.stderr).toBe(0); + expect(warned.stderr).toMatch(/return_documents|本地输入做预览/); }); test("server error passed through; missing file subprocess", async () => { diff --git a/packages/core/src/client/embedding-region-hint.ts b/packages/core/src/client/embedding-region-hint.ts new file mode 100644 index 000000000..1346a5377 --- /dev/null +++ b/packages/core/src/client/embedding-region-hint.ts @@ -0,0 +1,55 @@ +import { BailianError } from "../errors/base.ts"; +import { isNonBeijingDashScopeEndpoint } from "../config/model-endpoints.ts"; +import type { LocalizedText } from "../types/command.ts"; +import { + DEFAULT_MULTIMODAL_EMBEDDING_MODEL, + INTL_MULTIMODAL_EMBEDDING_MODEL, +} from "./embedding-routes.ts"; +import { looksLikeModelUnavailable } from "./model-unavailable.ts"; + +/** @deprecated Prefer looksLikeModelUnavailable. */ +export const looksLikeEmbeddingModelUnavailable = looksLikeModelUnavailable; + +export function shouldAttachQwen3VlIntlHint(options: { + model: string; + endpoint: string; + error: BailianError; +}): boolean { + if (options.error.hint) return false; + if (options.model !== DEFAULT_MULTIMODAL_EMBEDDING_MODEL) return false; + if (!isNonBeijingDashScopeEndpoint(options.endpoint)) return false; + return looksLikeModelUnavailable(options.error); +} + +export function qwen3VlIntlHint(localize: (text: LocalizedText) => string): string { + return localize({ + "en-US": `${DEFAULT_MULTIMODAL_EMBEDDING_MODEL} is currently Beijing-only. On international endpoints, retry with --model ${INTL_MULTIMODAL_EMBEDDING_MODEL}.`, + "zh-CN": `${DEFAULT_MULTIMODAL_EMBEDDING_MODEL} 目前仅北京地域可用。国际站请改用 --model ${INTL_MULTIMODAL_EMBEDDING_MODEL} 重试。`, + }); +} + +/** Keep server message; append intl fallback hint when applicable. */ +export function rethrowWithQwen3VlRegionHint( + error: unknown, + options: { + model: string; + endpoint: string; + localize: (text: LocalizedText) => string; + }, +): never { + if (!(error instanceof BailianError)) throw error; + if ( + !shouldAttachQwen3VlIntlHint({ + model: options.model, + endpoint: options.endpoint, + error, + }) + ) { + throw error; + } + throw new BailianError(error.message, error.exitCode, qwen3VlIntlHint(options.localize), { + cause: error, + api: error.api, + rawResponse: error.rawResponse, + }); +} diff --git a/packages/core/src/client/embedding-routes.ts b/packages/core/src/client/embedding-routes.ts index 74ba2177a..2398c75ce 100644 --- a/packages/core/src/client/embedding-routes.ts +++ b/packages/core/src/client/embedding-routes.ts @@ -1,5 +1,8 @@ +import { LOCAL_IMAGE_PENDING_ENCODE } from "../files/media-input.ts"; import { embeddingPath, multimodalEmbeddingPath } from "./endpoints.ts"; +export { LOCAL_IMAGE_PENDING_ENCODE }; + /** Compatible text vs native multimodal embedding protocols. */ export type EmbeddingApiKind = "compatible-text" | "native-multimodal"; @@ -128,13 +131,16 @@ const EMBEDDING_MODELS: readonly EmbeddingModelSpec[] = [ fusion: "none", }, { + // Snapshot docs: total ≤20 elements, images ≤64, videos ≤8; image size ≤10MB. + // Same-object multimodal fusion is a different protocol; this CLI keeps independent mode only. model: "tongyi-embedding-vision-plus-2026-03-06", kind: "native-multimodal", dimensions: [1152, 1024, 512, 256, 128, 64], - maxTexts: Number.POSITIVE_INFINITY, - maxImages: Number.POSITIVE_INFINITY, - maxVideos: Number.POSITIVE_INFINITY, - maxImageBytes: 3 * MB, + maxTexts: 20, + maxImages: 64, + maxVideos: 8, + maxTotal: 20, + maxImageBytes: 10 * MB, fusion: "none", }, { @@ -148,13 +154,15 @@ const EMBEDDING_MODELS: readonly EmbeddingModelSpec[] = [ fusion: "none", }, { + // Same caps as plus-2026-03-06; fusion remains independent-only for current flags. model: "tongyi-embedding-vision-flash-2026-03-06", kind: "native-multimodal", dimensions: [768, 512, 256, 128, 64], - maxTexts: Number.POSITIVE_INFINITY, - maxImages: Number.POSITIVE_INFINITY, - maxVideos: Number.POSITIVE_INFINITY, - maxImageBytes: 3 * MB, + maxTexts: 20, + maxImages: 64, + maxVideos: 8, + maxTotal: 20, + maxImageBytes: 10 * MB, fusion: "none", }, { @@ -175,9 +183,8 @@ const MODEL_BY_ID = new Map(EMBEDDING_MODELS.map((spec) => [spec.model, spec])); export const DEFAULT_TEXT_EMBEDDING_MODEL = "text-embedding-v4"; export const DEFAULT_MULTIMODAL_EMBEDDING_MODEL = "qwen3-vl-embedding"; - -/** Dry-run placeholder for a local image that has not been encoded yet. */ -export const LOCAL_IMAGE_PENDING_ENCODE = ""; +/** Intl-friendly multimodal fallback when Beijing-only defaults are unavailable. */ +export const INTL_MULTIMODAL_EMBEDDING_MODEL = "tongyi-embedding-vision-plus"; /** Look up a known embedding model; unknown IDs return undefined (no prefix guessing). */ export function lookupEmbeddingModel(model: string): EmbeddingModelSpec | undefined { @@ -209,9 +216,10 @@ export function resolveEmbeddingRoute(input: ResolveEmbeddingRouteInput): Embedd (input.hasMedia ? DEFAULT_MULTIMODAL_EMBEDDING_MODEL : DEFAULT_TEXT_EMBEDDING_MODEL); const spec = lookupEmbeddingModel(model); if (!spec) { + const supported = EMBEDDING_MODELS.map((item) => item.model).join(", "); throw new EmbeddingRouteError( - `Unknown embedding model "${model}". Add it to the local embedding route table or use a known model ID.`, - `未知向量模型 "${model}"。请使用已知模型 ID,或将其补充到本地路由表。`, + `Unknown embedding model "${model}". Supported: ${supported}.`, + `未知向量模型 "${model}"。支持:${supported}。`, ); } if (spec.kind === "compatible-text" && input.hasMedia) { @@ -242,7 +250,7 @@ export function assertEmbeddingDimensions( dimensions: number | undefined, ): void { if (dimensions === undefined) return; - if (!Number.isInteger(dimensions) || dimensions <= 0 || !Number.isFinite(dimensions)) { + if (!Number.isInteger(dimensions) || dimensions <= 0) { throw new EmbeddingRouteError( "--dimensions must be a positive integer.", "--dimensions 必须为正整数。", diff --git a/packages/core/src/client/index.ts b/packages/core/src/client/index.ts index 22d34c100..ecbfb06ce 100644 --- a/packages/core/src/client/index.ts +++ b/packages/core/src/client/index.ts @@ -77,6 +77,7 @@ export { DEFAULT_MULTIMODAL_EMBEDDING_MODEL, DEFAULT_TEXT_EMBEDDING_MODEL, EmbeddingRouteError, + INTL_MULTIMODAL_EMBEDDING_MODEL, listEmbeddingModels, LOCAL_IMAGE_PENDING_ENCODE, lookupEmbeddingModel, @@ -87,6 +88,29 @@ export { type EmbeddingRoute, type ResolveEmbeddingRouteInput, } from "./embedding-routes.ts"; +export { + looksLikeEmbeddingModelUnavailable, + qwen3VlIntlHint, + rethrowWithQwen3VlRegionHint, + shouldAttachQwen3VlIntlHint, +} from "./embedding-region-hint.ts"; +export { looksLikeModelUnavailable } from "./model-unavailable.ts"; +export { + DEFAULT_RERANK_MODEL, + MULTIMODAL_RERANK_MODEL, + TEXT_RERANK_FALLBACK_MODEL, + listRerankModels, + lookupRerankModel, + resolveRerankModel, + RerankRouteError, + type RerankModelKind, + type RerankModelSpec, +} from "./rerank-routes.ts"; +export { + qwen3VlRerankUnavailableHint, + rethrowWithQwen3VlRerankUnavailableHint, + shouldAttachQwen3VlRerankUnavailableHint, +} from "./rerank-region-hint.ts"; export { buildAsrContextMessages, buildAsrFlashRequest, diff --git a/packages/core/src/client/model-unavailable.ts b/packages/core/src/client/model-unavailable.ts new file mode 100644 index 000000000..c72b1f879 --- /dev/null +++ b/packages/core/src/client/model-unavailable.ts @@ -0,0 +1,13 @@ +import type { BailianError } from "../errors/base.ts"; + +const MODEL_UNAVAILABLE_API_CODES = new Set(["modelnotfound", "model_not_found", "invalidmodel"]); + +/** Prefer apiCode; fall back to model-unavailable phrasing in the message. */ +export function looksLikeModelUnavailable(error: BailianError): boolean { + const apiCode = error.api?.apiCode?.trim().toLowerCase() ?? ""; + if (apiCode && MODEL_UNAVAILABLE_API_CODES.has(apiCode)) return true; + // Message fallback for servers that omit / rename codes. Avoid permission-only matches. + return /invalid[_ ]?model|model[\s\S]{0,80}not[\s\S]{0,20}(exist|found|available)|模型[\s\S]{0,40}(不存在|不可用|未找到)|(不存在|不可用|未找到)[\s\S]{0,40}模型/i.test( + error.message, + ); +} diff --git a/packages/core/src/client/rerank-region-hint.ts b/packages/core/src/client/rerank-region-hint.ts new file mode 100644 index 000000000..2703dc0ea --- /dev/null +++ b/packages/core/src/client/rerank-region-hint.ts @@ -0,0 +1,49 @@ +import { BailianError } from "../errors/base.ts"; +import type { LocalizedText } from "../types/command.ts"; +import { looksLikeModelUnavailable } from "./model-unavailable.ts"; +import { MULTIMODAL_RERANK_MODEL, TEXT_RERANK_FALLBACK_MODEL } from "./rerank-routes.ts"; + +export function shouldAttachQwen3VlRerankUnavailableHint(options: { + model: string; + error: BailianError; +}): boolean { + if (options.error.hint) return false; + if (options.model !== MULTIMODAL_RERANK_MODEL) return false; + return looksLikeModelUnavailable(options.error); +} + +export function qwen3VlRerankUnavailableHint(localize: (text: LocalizedText) => string): string { + return localize({ + "en-US": `This endpoint currently does not provide ${MULTIMODAL_RERANK_MODEL} (model missing or not activated). For text rerank, retry with --model ${TEXT_RERANK_FALLBACK_MODEL}.`, + "zh-CN": `该端点当前未提供 ${MULTIMODAL_RERANK_MODEL}(模型不存在或未开通);文本重排可改用 --model ${TEXT_RERANK_FALLBACK_MODEL}。`, + }); +} + +/** Keep server message; append endpoint-scoped text-rerank hint when applicable. */ +export function rethrowWithQwen3VlRerankUnavailableHint( + error: unknown, + options: { + model: string; + localize: (text: LocalizedText) => string; + }, +): never { + if (!(error instanceof BailianError)) throw error; + if ( + !shouldAttachQwen3VlRerankUnavailableHint({ + model: options.model, + error, + }) + ) { + throw error; + } + throw new BailianError( + error.message, + error.exitCode, + qwen3VlRerankUnavailableHint(options.localize), + { + cause: error, + api: error.api, + rawResponse: error.rawResponse, + }, + ); +} diff --git a/packages/core/src/client/rerank-routes.ts b/packages/core/src/client/rerank-routes.ts new file mode 100644 index 000000000..a6a44a891 --- /dev/null +++ b/packages/core/src/client/rerank-routes.ts @@ -0,0 +1,88 @@ +export type RerankModelKind = "text" | "vl"; + +export interface RerankModelSpec { + model: string; + kind: RerankModelKind; + maxDocuments: number; + maxTextDocuments?: number; + maxImageDocuments?: number; + maxVideoDocuments?: number; + supportsInstruct: boolean; + /** Local image byte limit for Data URI encoding. */ + maxImageBytes: number; +} + +const MB = 1024 * 1024; + +const RERANK_MODELS: readonly RerankModelSpec[] = [ + { + model: "qwen3-rerank", + kind: "text", + maxDocuments: 500, + supportsInstruct: true, + maxImageBytes: 0, + }, + { + model: "gte-rerank-v2", + kind: "text", + maxDocuments: 500, + supportsInstruct: false, + maxImageBytes: 0, + }, + { + model: "qwen3.7-text-rerank", + kind: "text", + maxDocuments: 500, + supportsInstruct: true, + maxImageBytes: 0, + }, + { + // Live verified: server rejects total documents > 100 ("total documents should not be larger than 100"), + // while still enforcing per-modality caps (text ≤100, image ≤40, video ≤4). + model: "qwen3-vl-rerank", + kind: "vl", + maxDocuments: 100, + maxTextDocuments: 100, + maxImageDocuments: 40, + maxVideoDocuments: 4, + supportsInstruct: true, + maxImageBytes: 10 * MB, + }, +]; + +const RERANK_MODEL_BY_ID = new Map(RERANK_MODELS.map((spec) => [spec.model, spec])); + +export const DEFAULT_RERANK_MODEL = "qwen3-rerank"; +export const MULTIMODAL_RERANK_MODEL = "qwen3-vl-rerank"; +/** Text fallback suggested when multimodal rerank is unavailable on the current endpoint. */ +export const TEXT_RERANK_FALLBACK_MODEL = "qwen3-rerank"; + +export function listRerankModels(): readonly RerankModelSpec[] { + return RERANK_MODELS; +} + +export function lookupRerankModel(model: string): RerankModelSpec | undefined { + return RERANK_MODEL_BY_ID.get(model); +} + +export class RerankRouteError extends Error { + readonly zhMessage: string; + constructor(enMessage: string, zhMessage: string) { + super(enMessage); + this.name = "RerankRouteError"; + this.zhMessage = zhMessage; + } +} + +/** Resolve a known rerank model; unknown IDs throw with the supported list. */ +export function resolveRerankModel(model: string): RerankModelSpec { + const spec = lookupRerankModel(model); + if (!spec) { + const supported = RERANK_MODELS.map((item) => item.model).join(", "); + throw new RerankRouteError( + `Unknown rerank model "${model}". Supported: ${supported}.`, + `未知重排序模型 "${model}"。支持:${supported}。`, + ); + } + return spec; +} diff --git a/packages/core/src/config/index.ts b/packages/core/src/config/index.ts index a3b12ef30..a5c0c74f0 100644 --- a/packages/core/src/config/index.ts +++ b/packages/core/src/config/index.ts @@ -43,6 +43,7 @@ export { KNOWN_MODEL_BASE_URLS, classifyModelHost, hostnameOf, + isNonBeijingDashScopeEndpoint, type OrdinaryWorkspaceRegion, type DomesticWorkspaceRegion, type ApiKeyEndpointKind as ModelEndpointKind, diff --git a/packages/core/src/config/model-endpoints.ts b/packages/core/src/config/model-endpoints.ts index e10610c1f..b54834425 100644 --- a/packages/core/src/config/model-endpoints.ts +++ b/packages/core/src/config/model-endpoints.ts @@ -102,3 +102,8 @@ function classifyWorkspaceRegion(region: string): ModelHostClass { if (INTERNATIONAL_REGION_SET.has(region)) return "international"; return "unknown"; } + +/** True for known official international / non-Beijing model endpoints. */ +export function isNonBeijingDashScopeEndpoint(endpointUrl: string): boolean { + return classifyModelHost(endpointUrl) === "international"; +} diff --git a/packages/core/src/files/index.ts b/packages/core/src/files/index.ts index 692b293f4..e7dcffbc3 100644 --- a/packages/core/src/files/index.ts +++ b/packages/core/src/files/index.ts @@ -7,4 +7,15 @@ export { audioMimeForPath, redactDataUri, } from "./upload.ts"; +export { + LOCAL_IMAGE_PENDING_ENCODE, + assertLocalImageReadable, + assertPublicHttpUrl, + isDataUri, + isHttpUrl, + isLocalMediaPath, + resolveImageMediaInput, + throwUsage, + type LocalizeText, +} from "./media-input.ts"; export { CONSOLE_FILE_URL_API, getConsoleFileUrl } from "./url.ts"; diff --git a/packages/core/src/files/media-input.ts b/packages/core/src/files/media-input.ts new file mode 100644 index 000000000..153332c44 --- /dev/null +++ b/packages/core/src/files/media-input.ts @@ -0,0 +1,88 @@ +import { existsSync, statSync } from "node:fs"; +import { BailianError } from "../errors/base.ts"; +import { ExitCode } from "../errors/codes.ts"; +import type { LocalizedText } from "../types/command.ts"; +import { imageFileToDataUri, redactDataUri } from "./upload.ts"; + +/** Dry-run placeholder for a local image that has not been encoded yet. */ +export const LOCAL_IMAGE_PENDING_ENCODE = ""; + +export type LocalizeText = (text: LocalizedText) => string; + +export function throwUsage(localize: LocalizeText, text: LocalizedText): never { + throw new BailianError(localize(text), ExitCode.USAGE); +} + +export function isHttpUrl(value: string): boolean { + return /^https?:\/\//i.test(value); +} + +export function isDataUri(value: string): boolean { + return /^data:/i.test(value); +} + +/** True when the value should be treated as a local filesystem path. */ +export function isLocalMediaPath(value: string): boolean { + if (isHttpUrl(value) || isDataUri(value) || value.startsWith("oss://")) return false; + return true; +} + +/** Validate a local image exists, is a file, and is within the byte limit. */ +export function assertLocalImageReadable( + image: string, + maxImageBytes: number, + localize: LocalizeText, +): void { + if (!existsSync(image)) { + throwUsage(localize, { + "en-US": `Image file not found: ${image}`, + "zh-CN": `找不到图片文件:${image}`, + }); + } + const stats = statSync(image); + if (!stats.isFile()) { + throwUsage(localize, { + "en-US": `Not a file: ${image}`, + "zh-CN": `不是文件:${image}`, + }); + } + if (maxImageBytes > 0 && stats.size > maxImageBytes) { + throwUsage(localize, { + "en-US": `Local image exceeds the ${Math.round(maxImageBytes / (1024 * 1024))} MB limit (${image}). Prefer a public HTTP(S) URL for large images.`, + "zh-CN": `本地图片超过 ${Math.round(maxImageBytes / (1024 * 1024))} MB 上限(${image})。大图请优先使用公网 HTTP(S) URL。`, + }); + } +} + +/** + * Resolve an image input for embedding/rerank style APIs. + * Local paths are size-checked even in dry-run; encoding is skipped then. + */ +export function resolveImageMediaInput( + image: string, + options: { + maxImageBytes: number; + dryRun: boolean; + localize: LocalizeText; + ossUnsupported: LocalizedText; + }, +): string { + if (isDataUri(image)) return options.dryRun ? redactDataUri(image) : image; + if (isHttpUrl(image)) return image; + if (image.startsWith("oss://")) { + throwUsage(options.localize, options.ossUnsupported); + } + assertLocalImageReadable(image, options.maxImageBytes, options.localize); + if (options.dryRun) return LOCAL_IMAGE_PENDING_ENCODE; + return imageFileToDataUri(image); +} + +/** Require a public HTTP(S) URL; local paths and other schemes are rejected. */ +export function assertPublicHttpUrl( + value: string, + localize: LocalizeText, + error: LocalizedText, +): string { + if (isHttpUrl(value)) return value; + throwUsage(localize, error); +} diff --git a/packages/core/src/types/api.ts b/packages/core/src/types/api.ts index 71aa40772..bbe17d176 100644 --- a/packages/core/src/types/api.ts +++ b/packages/core/src/types/api.ts @@ -174,6 +174,8 @@ export interface TextEmbeddingResponse { }>; model?: string; usage?: Record; + /** OpenAI-compatible responses often use `id` instead of `request_id`. */ + id?: string; request_id?: string; } diff --git a/packages/core/tests/embedding-region-hint.test.ts b/packages/core/tests/embedding-region-hint.test.ts new file mode 100644 index 000000000..5e7b9b159 --- /dev/null +++ b/packages/core/tests/embedding-region-hint.test.ts @@ -0,0 +1,98 @@ +import { expect, test } from "vite-plus/test"; +import { BailianError } from "../src/errors/base.ts"; +import { ExitCode } from "../src/errors/codes.ts"; +import type { LocalizedText } from "../src/types/command.ts"; +import { + looksLikeEmbeddingModelUnavailable, + qwen3VlIntlHint, + rethrowWithQwen3VlRegionHint, + shouldAttachQwen3VlIntlHint, +} from "../src/client/embedding-region-hint.ts"; + +const localize = (text: LocalizedText) => + typeof text === "string" ? text : (text["en-US"] ?? text["zh-CN"] ?? ""); + +test("model-unavailable detection prefers apiCode and avoids permission-only matches", () => { + expect( + looksLikeEmbeddingModelUnavailable( + new BailianError("Access denied", ExitCode.GENERAL, undefined, { + api: { apiCode: "ModelNotFound" }, + }), + ), + ).toBe(true); + expect( + looksLikeEmbeddingModelUnavailable( + new BailianError("Model qwen3-vl-embedding does not exist", ExitCode.GENERAL), + ), + ).toBe(true); + expect( + looksLikeEmbeddingModelUnavailable( + new BailianError("无权限调用该接口", ExitCode.GENERAL, undefined, { + api: { apiCode: "AccessDenied" }, + }), + ), + ).toBe(false); + expect(looksLikeEmbeddingModelUnavailable(new BailianError("无权限", ExitCode.GENERAL))).toBe( + false, + ); +}); + +test("attaches intl hint only for qwen3-vl on non-Beijing endpoints", () => { + const error = new BailianError( + "Model qwen3-vl-embedding does not exist", + ExitCode.GENERAL, + undefined, + { + api: { apiCode: "ModelNotFound" }, + }, + ); + expect( + shouldAttachQwen3VlIntlHint({ + model: "qwen3-vl-embedding", + endpoint: + "https://dashscope-intl.aliyuncs.com/api/v1/services/embeddings/multimodal-embedding/multimodal-embedding", + error, + }), + ).toBe(true); + expect( + shouldAttachQwen3VlIntlHint({ + model: "qwen3-vl-embedding", + endpoint: + "https://dashscope.aliyuncs.com/api/v1/services/embeddings/multimodal-embedding/multimodal-embedding", + error, + }), + ).toBe(false); + expect( + shouldAttachQwen3VlIntlHint({ + model: "tongyi-embedding-vision-plus", + endpoint: "https://dashscope-intl.aliyuncs.com/api/v1/x", + error, + }), + ).toBe(false); +}); + +test("rethrowWithQwen3VlRegionHint keeps message and adds hint", () => { + const error = new BailianError( + "Model qwen3-vl-embedding does not exist", + ExitCode.GENERAL, + undefined, + { + api: { apiCode: "ModelNotFound" }, + }, + ); + try { + rethrowWithQwen3VlRegionHint(error, { + model: "qwen3-vl-embedding", + endpoint: "https://dashscope-intl.aliyuncs.com/api/v1/x", + localize, + }); + } catch (thrown) { + expect(thrown).toBeInstanceOf(BailianError); + const bailianError = thrown as BailianError; + expect(bailianError.message).toBe(error.message); + expect(bailianError.hint).toBe(qwen3VlIntlHint(localize)); + expect(bailianError.hint).toMatch(/tongyi-embedding-vision-plus/); + return; + } + throw new Error("expected rethrow"); +}); diff --git a/packages/core/tests/embedding-routes.test.ts b/packages/core/tests/embedding-routes.test.ts index f3d0a7e7a..32a0b991b 100644 --- a/packages/core/tests/embedding-routes.test.ts +++ b/packages/core/tests/embedding-routes.test.ts @@ -37,9 +37,9 @@ test("text model with media is rejected", () => { ); }); -test("unknown model is rejected without prefix guessing", () => { +test("unknown model is rejected without prefix guessing and lists supported IDs", () => { expect(() => resolveEmbeddingRoute({ model: "text-embedding-v9", hasMedia: false })).toThrow( - /Unknown embedding model/, + /Unknown embedding model[\s\S]*Supported:[\s\S]*text-embedding-v4/, ); expect(lookupEmbeddingModel("text-embedding")).toBeUndefined(); }); @@ -131,4 +131,35 @@ test("input count limits", () => { expect(() => assertEmbeddingInputCounts(qwen25, { texts: 2, images: 0, videos: 0 })).toThrow( /at most 1 text/, ); + + for (const model of [ + "tongyi-embedding-vision-plus-2026-03-06", + "tongyi-embedding-vision-flash-2026-03-06", + ]) { + const snapshot = lookupEmbeddingModel(model)!; + expect(snapshot.maxTexts).toBe(20); + expect(snapshot.maxImages).toBe(64); + expect(snapshot.maxVideos).toBe(8); + expect(snapshot.maxTotal).toBe(20); + expect(snapshot.maxImageBytes).toBe(10 * 1024 * 1024); + expect(() => + assertEmbeddingInputCounts(snapshot, { texts: 20, images: 0, videos: 0 }), + ).not.toThrow(); + expect(() => assertEmbeddingInputCounts(snapshot, { texts: 21, images: 0, videos: 0 })).toThrow( + /at most 20/, + ); + expect(() => assertEmbeddingInputCounts(snapshot, { texts: 0, images: 65, videos: 0 })).toThrow( + /at most 64 image/, + ); + expect(() => assertEmbeddingInputCounts(snapshot, { texts: 0, images: 0, videos: 9 })).toThrow( + /at most 8 video/, + ); + } + + const undatedPlus = lookupEmbeddingModel("tongyi-embedding-vision-plus")!; + expect(undatedPlus.maxTexts).toBe(Number.POSITIVE_INFINITY); + expect(undatedPlus.maxImageBytes).toBe(3 * 1024 * 1024); + expect(() => + assertEmbeddingInputCounts(undatedPlus, { texts: 30, images: 0, videos: 0 }), + ).not.toThrow(); }); diff --git a/packages/core/tests/media-input.test.ts b/packages/core/tests/media-input.test.ts new file mode 100644 index 000000000..5970b56fb --- /dev/null +++ b/packages/core/tests/media-input.test.ts @@ -0,0 +1,71 @@ +import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterEach, expect, test } from "vite-plus/test"; +import { BailianError } from "../src/errors/base.ts"; +import { isNonBeijingDashScopeEndpoint } from "../src/config/model-endpoints.ts"; +import type { LocalizedText } from "../src/types/command.ts"; +import { + assertLocalImageReadable, + isDataUri, + isHttpUrl, + isLocalMediaPath, + LOCAL_IMAGE_PENDING_ENCODE, + resolveImageMediaInput, +} from "../src/files/media-input.ts"; + +const tempDirs: string[] = []; + +afterEach(() => { + for (const directory of tempDirs.splice(0)) { + rmSync(directory, { recursive: true, force: true }); + } +}); + +const localize = (text: LocalizedText) => + typeof text === "string" ? text : (text["en-US"] ?? text["zh-CN"] ?? ""); + +test("media path helpers classify URL / data URI / local", () => { + expect(isHttpUrl("https://example.com/a.png")).toBe(true); + expect(isDataUri("data:image/png;base64,xx")).toBe(true); + expect(isLocalMediaPath("./a.png")).toBe(true); + expect(isLocalMediaPath("oss://bucket/key")).toBe(false); +}); + +test("resolveImageMediaInput dry-run validates local files without encoding", () => { + const directory = mkdtempSync(join(tmpdir(), "media-input-")); + tempDirs.push(directory); + const missing = join(directory, "missing.png"); + expect(() => + resolveImageMediaInput(missing, { + maxImageBytes: 1024, + dryRun: true, + localize, + ossUnsupported: { "en-US": "oss unsupported", "zh-CN": "不支持 oss" }, + }), + ).toThrow(BailianError); + + const imagePath = join(directory, "ok.png"); + writeFileSync(imagePath, Buffer.from("tiny")); + expect( + resolveImageMediaInput(imagePath, { + maxImageBytes: 1024, + dryRun: true, + localize, + ossUnsupported: { "en-US": "oss unsupported", "zh-CN": "不支持 oss" }, + }), + ).toBe(LOCAL_IMAGE_PENDING_ENCODE); + expect(() => assertLocalImageReadable(imagePath, 1, localize)).toThrow(/exceeds|MB limit/); +}); + +test("isNonBeijingDashScopeEndpoint detects known intl hosts only", () => { + expect(isNonBeijingDashScopeEndpoint("https://dashscope.aliyuncs.com/api")).toBe(false); + expect(isNonBeijingDashScopeEndpoint("https://dashscope-intl.aliyuncs.com/api")).toBe(true); + expect(isNonBeijingDashScopeEndpoint("https://dashscope-us.aliyuncs.com/api")).toBe(true); + expect(isNonBeijingDashScopeEndpoint("https://token-plan.ap-southeast-1.maas.aliyuncs.com")).toBe( + true, + ); + // Custom proxy hostnames that merely contain region substrings must not match. + expect(isNonBeijingDashScopeEndpoint("https://proxy-ap-southeast-1.example.com/api")).toBe(false); + expect(isNonBeijingDashScopeEndpoint("https://my-us-east-1-gateway.local/api")).toBe(false); +}); diff --git a/packages/core/tests/rerank-region-hint.test.ts b/packages/core/tests/rerank-region-hint.test.ts new file mode 100644 index 000000000..05ca4073d --- /dev/null +++ b/packages/core/tests/rerank-region-hint.test.ts @@ -0,0 +1,58 @@ +import { expect, test } from "vite-plus/test"; +import { BailianError } from "../src/errors/base.ts"; +import { ExitCode } from "../src/errors/codes.ts"; +import type { LocalizedText } from "../src/types/command.ts"; +import { + qwen3VlRerankUnavailableHint, + rethrowWithQwen3VlRerankUnavailableHint, + shouldAttachQwen3VlRerankUnavailableHint, +} from "../src/client/rerank-region-hint.ts"; + +const localize = (text: LocalizedText) => + typeof text === "string" ? text : (text["en-US"] ?? text["zh-CN"] ?? ""); + +test("attaches unavailable hint for qwen3-vl-rerank on any endpoint", () => { + const error = new BailianError( + "Model qwen3-vl-rerank does not exist", + ExitCode.GENERAL, + undefined, + { api: { apiCode: "ModelNotFound" } }, + ); + expect( + shouldAttachQwen3VlRerankUnavailableHint({ + model: "qwen3-vl-rerank", + error, + }), + ).toBe(true); + expect( + shouldAttachQwen3VlRerankUnavailableHint({ + model: "qwen3-rerank", + error, + }), + ).toBe(false); +}); + +test("rethrow keeps message and uses endpoint-scoped wording", () => { + const error = new BailianError( + "Model qwen3-vl-rerank does not exist", + ExitCode.GENERAL, + undefined, + { api: { apiCode: "ModelNotFound" } }, + ); + try { + rethrowWithQwen3VlRerankUnavailableHint(error, { + model: "qwen3-vl-rerank", + localize, + }); + } catch (thrown) { + expect(thrown).toBeInstanceOf(BailianError); + const bailianError = thrown as BailianError; + expect(bailianError.message).toBe(error.message); + expect(bailianError.hint).toBe(qwen3VlRerankUnavailableHint(localize)); + expect(bailianError.hint).toMatch(/qwen3-rerank/); + expect(bailianError.hint).toMatch(/该端点当前未提供|This endpoint currently does not provide/); + expect(bailianError.hint).not.toMatch(/Beijing-only|仅北京|国际站暂不支持/); + return; + } + throw new Error("expected rethrow"); +}); diff --git a/packages/core/tests/rerank-routes.test.ts b/packages/core/tests/rerank-routes.test.ts new file mode 100644 index 000000000..936ce97b9 --- /dev/null +++ b/packages/core/tests/rerank-routes.test.ts @@ -0,0 +1,30 @@ +import { expect, test } from "vite-plus/test"; +import { + DEFAULT_RERANK_MODEL, + listRerankModels, + lookupRerankModel, + resolveRerankModel, + RerankRouteError, +} from "../src/client/rerank-routes.ts"; + +test("default and known rerank models resolve", () => { + expect(DEFAULT_RERANK_MODEL).toBe("qwen3-rerank"); + expect(lookupRerankModel("qwen3-vl-rerank")?.kind).toBe("vl"); + expect(resolveRerankModel("gte-rerank-v2").supportsInstruct).toBe(false); + expect(listRerankModels().map((item) => item.model)).toContain("qwen3.7-text-rerank"); +}); + +test("qwen3-vl-rerank enforces total ≤100 plus per-modality caps", () => { + const spec = lookupRerankModel("qwen3-vl-rerank")!; + expect(spec.maxDocuments).toBe(100); + expect(spec.maxTextDocuments).toBe(100); + expect(spec.maxImageDocuments).toBe(40); + expect(spec.maxVideoDocuments).toBe(4); +}); + +test("unknown rerank model lists supported IDs", () => { + expect(() => resolveRerankModel("no-such-rerank")).toThrow(RerankRouteError); + expect(() => resolveRerankModel("no-such-rerank")).toThrow( + /Unknown rerank model[\s\S]*Supported:[\s\S]*qwen3-rerank/, + ); +}); diff --git a/skills/bailian-cli/reference/embedding.md b/skills/bailian-cli/reference/embedding.md index ce2c005dd..d3a87d9a5 100644 --- a/skills/bailian-cli/reference/embedding.md +++ b/skills/bailian-cli/reference/embedding.md @@ -24,21 +24,21 @@ Index: [index.md](index.md) #### Flags -| Flag | Type | Required | Description | -| ----------------------- | ------- | -------- | ------------------------------------------------------------------------------------------------------ | -| `--text ` | array | no | Text to embed (repeatable; order preserved among --text values) | -| `--image ` | array | no | Image URL or local path (repeatable; public HTTP(S) URL or Data URI preferred for large files) | -| `--video ` | array | no | Public HTTP(S) video URL only (repeatable; local video paths are not supported) | -| `--model ` | string | no | Embedding model (default: text-embedding-v4 for text-only; qwen3-vl-embedding when media is present) | -| `--dimensions ` | number | no | Embedding dimensions (model-dependent) | -| `--fuse ` | boolean | no | Enable fusion for qwen3-vl-embedding (maps to parameters.enable_fusion); other models reject this flag | -| `--out ` | string | no | Save the full server response JSON to a file | -| `--api-key ` | string | no | API key | -| `--base-url ` | string | no | API base URL | +| Flag | Type | Required | Description | +| ----------------------- | ------- | -------- | ---------------------------------------------------------------------------------------------------------------------------- | +| `--text ` | array | no | Text to embed (repeatable; order preserved among --text values) | +| `--image ` | array | no | Image URL or local path (repeatable; public HTTP(S) URL or Data URI preferred for large files) | +| `--video ` | array | no | Public HTTP(S) video URL only (repeatable; local video paths are not supported) | +| `--model ` | string | no | Embedding model (default: text-embedding-v4 for text-only; qwen3-vl-embedding when media is present) | +| `--dimensions ` | number | no | Embedding dimensions (model-dependent) | +| `--fuse ` | boolean | no | Enable fusion for qwen3-vl-embedding (maps to parameters.enable_fusion); ignored on always-fusion models; rejected elsewhere | +| `--out ` | string | no | Save the full server response JSON to a file; JSON stdout then prints a summary only | +| `--api-key ` | string | no | API key | +| `--base-url ` | string | no | API base URL | #### Notes -- Content order is fixed as text → image → video across flags (repeatable flags keep their own order). Multiple inputs do not imply fusion — use --fuse with qwen3-vl-embedding. Local video is unsupported; prefer public HTTP(S) URLs for large images. Billed per call; this command does not auto-batch. For knowledge-base indexing / retrieval use knowledge commands, not embedding create. +- Content order is fixed as text → image → video across flags (repeatable flags keep their own order). Multiple inputs do not imply fusion — use --fuse with qwen3-vl-embedding. Text embeddings use the OpenAI-compatible API in this release (no text_type / instruct / sparse). Dated tongyi-*-2026-03-06 snapshots stay independent-only here. Default multimodal model qwen3-vl-embedding is Beijing-only; on international endpoints use --model tongyi-embedding-vision-plus. With --out, JSON stdout prints a summary only; --dry-run never writes --out. Local video is unsupported; prefer public HTTP(S) URLs for large images. Billed per call; this command does not auto-batch. For knowledge-base indexing / retrieval use knowledge commands, not embedding create. #### Examples diff --git a/skills/bailian-cli/reference/rerank.md b/skills/bailian-cli/reference/rerank.md index 8e39cf197..f856411af 100644 --- a/skills/bailian-cli/reference/rerank.md +++ b/skills/bailian-cli/reference/rerank.md @@ -40,7 +40,7 @@ Index: [index.md](index.md) #### Notes -- relevance_score is comparable only within one request; this CLI never re-sorts or merges scores across batches. Paths in --documents-file are resolved relative to that file's directory; --query-image uses the process cwd. Local video is unsupported. Billed per call (up to 500 candidates). For knowledge-base retrieval / server-side hybrid ranking use knowledge commands, not rerank. +- relevance_score is comparable only within one request; this CLI never re-sorts or merges scores across batches. Text mode previews documents from local inputs when the server omits them. Paths in --documents-file are resolved relative to that file's directory; --query-image uses the process cwd. If qwen3-vl-rerank is unavailable on the current endpoint, text rerank can fall back to qwen3-rerank. Local video is unsupported. Billed per call (up to 500 candidates). For knowledge-base retrieval / server-side hybrid ranking use knowledge commands, not rerank. #### Examples From b3f8f93c273dcfab7542e4dddeef555fae60cfc5 Mon Sep 17 00:00:00 2001 From: clh02467605 Date: Wed, 2 Dec 2026 15:53:58 +0800 Subject: [PATCH 3/3] fix: update SKILL.md for command table formatting --- skills/bailian-cli/SKILL.md | 100 ++++++++++++++++++------------------ 1 file changed, 50 insertions(+), 50 deletions(-) diff --git a/skills/bailian-cli/SKILL.md b/skills/bailian-cli/SKILL.md index 94a42daf8..f4182b472 100644 --- a/skills/bailian-cli/SKILL.md +++ b/skills/bailian-cli/SKILL.md @@ -70,57 +70,57 @@ Do not guess flags — use the reference files or `--help`. Use this table only after the decision table in [`bailian-protocol`](../bailian-protocol/SKILL.md#provider-selection-and-consent) has routed the request to `bl` (class 4, or class 2 after the user picks Bailian). Hub-owned intents only — for media / fine-tune / agents.yaml / Sandbox, soft hand-off to the domain skill. -| User intent | Command | Notes | -| ----------------------------------------------------- | -------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| Explicit Bailian model chat / text execution | `bl text chat` | Default `qwen3.8-max` | -| Dedicated text translation (Qwen-MT) | `bl text translate --target-lang ` | Default `qwen-mt-flash`; language names are English full names (`Chinese`/`English`), not `zh`/`en`; only user messages; see `reference/text.md` | +| User intent | Command | Notes | +| ----------------------------------------------------- | -------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Explicit Bailian model chat / text execution | `bl text chat` | Default `qwen3.8-max` | +| Dedicated text translation (Qwen-MT) | `bl text translate --target-lang ` | Default `qwen-mt-flash`; language names are English full names (`Chinese`/`English`), not `zh`/`en`; only user messages; see `reference/text.md` | | Create text / multimodal embeddings directly | `bl embedding create` | Default `text-embedding-v4` (text) / `qwen3-vl-embedding` (media); full vectors in JSON/`--out`. For knowledge-base indexing / retrieval → `bailian-knowledge`, not this command. See `reference/embedding.md`. | -| Rerank candidate documents for a query | `bl rerank` | Default `qwen3-rerank`; scores comparable only within one request. For knowledge-base retrieval / server-side hybrid ranking → `bailian-knowledge`, not this command. See `reference/rerank.md`. | -| 百炼异步文件批量推理 / CSV 转换 | `bl batch convert` / `create` / `list` / `get` / `cancel` / `download` | CSV → JSONL → 异步任务 → 原始结果,可额外导出 CSV;格式样例见 `reference/batch.md` | -| 百炼单次同步 Batch Chat | `bl text chat --batch` | 等待单次响应,不创建任务 ID;messages-file 是同一请求的对话上下文,边界见 `reference/text.md` | -| Typed decision model inference | `bl decision` | Workspace endpoint; returns `choice` / `noul` / `score` values and probabilities, not generated text | -| Explicit ParseX parsing / structured field extraction | `bl parsex parse submit` / `result`; `bl parsex extract submit` / `result` | Workspace + API key; submit returns biz_id, result --follow waits. HTTP(S) source URLs; extraction can reuse a parsed document. See `reference/parsex.md`. | -| Bailian agent / workflow | `bl flow-agent call` | Needs `--app-id` | -| Find app by name | `bl flow-agent list` then `bl flow-agent call` | Console auth; `--type workflow` lists workflows | -| Create / update / publish / delete / copy an app | `bl flow-agent create` / `update` / `publish` / `delete` / `copy` / `get` / `versions` | Console auth; agent config via `--model`/`--instructions`/`--config-json`; `delete` needs `--yes`; see [`reference/flow-agent.md`](reference/flow-agent.md) | -| Workflow canvas read / save / publish / export | `bl flow-agent workflow get` / `save` / `publish` / `export` | Console auth; `save` replaces the whole draft canvas; see [`reference/flow-agent.md`](reference/flow-agent.md) | -| Personal memory / Bailian memory resources | → skill `bailian-memory` | User-enabled personal memory; explicit resource operations use `bl memory --help` as fallback. | -| Personal documents / Bailian knowledge workflows | Read skill `bailian-knowledge` | If missing: `bl knowledge --help` or `bl skill init` | -| Resolve a Console file key / error-report URL | `bl file url` | Console auth; use the returned business file key, not a file ID or upload URI. Resolves only; no download or fixed expiry. Existing URLs need no resolution. | -| Upload a file as a step of a Bailian workflow | `bl file upload` | When you need `oss://` URL explicitly; not for generic hosting | -| Bailian model selection / recommendation | `bl advisor recommend` | Intent → candidate recall → LLM ranking | -| Bailian model catalog / pricing / params | `bl model list` | No auth (public catalog); `--model ` for detail, `--enrich` for input params | -| Find a model by keyword / modality | `bl model search` | Weighted ranking; `--input-modality` / `--output-modality`; offline models hidden by default | -| SDK sample code for calling a model | `bl model code` | `--sdk openai\|dashscope`, `--lang`; text output is the snippet alone, safe to redirect | -| Install / list / update / remove registry skills | `bl skill add` / `list` / `update` / `remove` | OSS `--name`, cloud `--code`. `add --all` installs the registry. `update --all` updates installed OSS skills. Filter by `--agent` / `--scope`. [Reference](reference/skill.md) | -| Find cloud skills or inspect local installation paths | `bl skill search` / `bl skill get` | Search the cloud with a Bailian API key. Pass the returned `skill_code` to `get --code`. Use `get --name` for an OSS skill. | -| Find and run a workspace connector tool | `bl connector tools --query` → `schema` → `call` | Use the discovered toolRef and authorized instanceId. Pass the returned traceId to both subsequent commands. | -| Inspect activated MCP servers, details or tools | `bl mcp list` / `get` / `tools` / `call` | — | -| Find MCP tools by task or inspect a server's tools | `bl mcp tool search` / `bl mcp tool list` | Search with `--query` or list with `--server`. Both operations may trigger OneKey activation. Preview with `--dry-run`. | -| Call a tool by server code and tool name | `bl mcp tool call` / `bl mcp call` | Use `--server` and `--tool` for OpenAPI, or `--target ` for an MCP session. | -| Activate or stop MCP servers | `bl mcp activate` / `deactivate` | API key. Use `--server ` to select servers and `--dry-run` to preview the batch. | -| Manage a custom Bailian MCP server | `bl mcp create` / `update` / `delete` | API key. Preview changes with `--dry-run`. Deleting a server requires `--yes`. | -| Register or remove a Bailian MCP in an Agent | `bl mcp connect` / `disconnect` | Choose `--agent` and `--scope user\|project`. Connect previews the workspace endpoint and any activation. Disconnect uses the local registration. | -| Bailian pipeline workflow (a step in a bl flow) | `bl pipeline run` / `validate` | JSON/YAML workflow definitions | -| Bailian rate limits / quota | `bl quota list` / `check` / `request` | Console auth; class 2 — ask which product first if unnamed | -| Bailian free tier / usage stats | `bl usage free` / `stats` / `freetier` | Console auth; class 2 — ask which product first if unnamed | -| Bailian Token Plan quota usage | `bl usage token-plan` | Console auth; class 2 — ask which product first if unnamed | -| Token Plan harness entitlement quota | `bl token-plan harness-quota` | Console auth; issued quota usage + still-issuing harnesses | -| Bailian Coding Plan quota usage | `bl usage coding-plan` | Console auth; class 2 — ask which product first if unnamed | -| Model monitoring (calls, latency, errors, delivery) | `bl monitor overview` / `models` / `metrics` / `errors` / `delivery *` | Console auth; see [`reference/monitor.md`](reference/monitor.md) | -| Model call logs / traces | `bl log audit *` / `bl log inference *` / `bl log status` / `bl log trace *` | Console auth; audit and inference logs have separate APIs and switches; see [`reference/log.md`](reference/log.md) | -| Model alert rules / templates / history | `bl alert list` / `create` / `update` / `delete` / `enable` / `disable` / `history` / `metrics` / `template *` | Console auth; contacts are managed in the CloudMonitor console; see [`reference/alert.md`](reference/alert.md) | -| Console API (advanced) | `bl console call` | Console auth | -| Bailian workspace listing | `bl workspace list` | Console auth | -| Switch CLI Help / Quick Start language | `bl config set --key language --value zh-CN` | Use `en-US` to switch back; follows the active config profile | -| Image / video / speech / omni / vision | → skill `bailian-gen` | Fallback: `bl image\|video\|speech\|omni\|vision --help` | -| Training dataset / fine-tune / deploy | → skill `bailian-finetune` | Fallback: `bl dataset\|finetune\|deploy --help` | -| 百炼模型智能路由 / smart routing / model routing | → skill `bailian-finetune` | 独立于精调流程;fallback: `bl deploy router --help`。 | -| 吞吐预留(PTU)/ ModelCode 容量购买与扩缩容 | → skill `bailian-finetune` | 独立于精调流程;包括容量查询、购买、扩缩容、续费、释放、退订与溢出策略;fallback: `bl deploy --help`。 | -| Guided end-to-end OPD distillation workflow | → skill `bailian-opd` | Authorize → validate → preflight → consent → submit → wait; fallback: `bl finetune opd --help` | -| agents.yaml IaC / managed-agent sessions | → skill `bailian-managed-agent` | Fallback: `bl managed-agent --help`; `apply`/`destroy` need `--yes` after `plan` | -| Bailian Sandbox instance / template lifecycle | → skill `bailian-sandbox` | Fallback: `bl sandbox --help` | -| Web search (mode-aware routing) | → skill `bailian-web-search` | Default model mode vs explicit `--mode mcp` + fallback; fallback: `bl search web --help` | +| Rerank candidate documents for a query | `bl rerank` | Default `qwen3-rerank`; scores comparable only within one request. For knowledge-base retrieval / server-side hybrid ranking → `bailian-knowledge`, not this command. See `reference/rerank.md`. | +| 百炼异步文件批量推理 / CSV 转换 | `bl batch convert` / `create` / `list` / `get` / `cancel` / `download` | CSV → JSONL → 异步任务 → 原始结果,可额外导出 CSV;格式样例见 `reference/batch.md` | +| 百炼单次同步 Batch Chat | `bl text chat --batch` | 等待单次响应,不创建任务 ID;messages-file 是同一请求的对话上下文,边界见 `reference/text.md` | +| Typed decision model inference | `bl decision` | Workspace endpoint; returns `choice` / `noul` / `score` values and probabilities, not generated text | +| Explicit ParseX parsing / structured field extraction | `bl parsex parse submit` / `result`; `bl parsex extract submit` / `result` | Workspace + API key; submit returns biz_id, result --follow waits. HTTP(S) source URLs; extraction can reuse a parsed document. See `reference/parsex.md`. | +| Bailian agent / workflow | `bl flow-agent call` | Needs `--app-id` | +| Find app by name | `bl flow-agent list` then `bl flow-agent call` | Console auth; `--type workflow` lists workflows | +| Create / update / publish / delete / copy an app | `bl flow-agent create` / `update` / `publish` / `delete` / `copy` / `get` / `versions` | Console auth; agent config via `--model`/`--instructions`/`--config-json`; `delete` needs `--yes`; see [`reference/flow-agent.md`](reference/flow-agent.md) | +| Workflow canvas read / save / publish / export | `bl flow-agent workflow get` / `save` / `publish` / `export` | Console auth; `save` replaces the whole draft canvas; see [`reference/flow-agent.md`](reference/flow-agent.md) | +| Personal memory / Bailian memory resources | → skill `bailian-memory` | User-enabled personal memory; explicit resource operations use `bl memory --help` as fallback. | +| Personal documents / Bailian knowledge workflows | Read skill `bailian-knowledge` | If missing: `bl knowledge --help` or `bl skill init` | +| Resolve a Console file key / error-report URL | `bl file url` | Console auth; use the returned business file key, not a file ID or upload URI. Resolves only; no download or fixed expiry. Existing URLs need no resolution. | +| Upload a file as a step of a Bailian workflow | `bl file upload` | When you need `oss://` URL explicitly; not for generic hosting | +| Bailian model selection / recommendation | `bl advisor recommend` | Intent → candidate recall → LLM ranking | +| Bailian model catalog / pricing / params | `bl model list` | No auth (public catalog); `--model ` for detail, `--enrich` for input params | +| Find a model by keyword / modality | `bl model search` | Weighted ranking; `--input-modality` / `--output-modality`; offline models hidden by default | +| SDK sample code for calling a model | `bl model code` | `--sdk openai\|dashscope`, `--lang`; text output is the snippet alone, safe to redirect | +| Install / list / update / remove registry skills | `bl skill add` / `list` / `update` / `remove` | OSS `--name`, cloud `--code`. `add --all` installs the registry. `update --all` updates installed OSS skills. Filter by `--agent` / `--scope`. [Reference](reference/skill.md) | +| Find cloud skills or inspect local installation paths | `bl skill search` / `bl skill get` | Search the cloud with a Bailian API key. Pass the returned `skill_code` to `get --code`. Use `get --name` for an OSS skill. | +| Find and run a workspace connector tool | `bl connector tools --query` → `schema` → `call` | Use the discovered toolRef and authorized instanceId. Pass the returned traceId to both subsequent commands. | +| Inspect activated MCP servers, details or tools | `bl mcp list` / `get` / `tools` / `call` | — | +| Find MCP tools by task or inspect a server's tools | `bl mcp tool search` / `bl mcp tool list` | Search with `--query` or list with `--server`. Both operations may trigger OneKey activation. Preview with `--dry-run`. | +| Call a tool by server code and tool name | `bl mcp tool call` / `bl mcp call` | Use `--server` and `--tool` for OpenAPI, or `--target ` for an MCP session. | +| Activate or stop MCP servers | `bl mcp activate` / `deactivate` | API key. Use `--server ` to select servers and `--dry-run` to preview the batch. | +| Manage a custom Bailian MCP server | `bl mcp create` / `update` / `delete` | API key. Preview changes with `--dry-run`. Deleting a server requires `--yes`. | +| Register or remove a Bailian MCP in an Agent | `bl mcp connect` / `disconnect` | Choose `--agent` and `--scope user\|project`. Connect previews the workspace endpoint and any activation. Disconnect uses the local registration. | +| Bailian pipeline workflow (a step in a bl flow) | `bl pipeline run` / `validate` | JSON/YAML workflow definitions | +| Bailian rate limits / quota | `bl quota list` / `check` / `request` | Console auth; class 2 — ask which product first if unnamed | +| Bailian free tier / usage stats | `bl usage free` / `stats` / `freetier` | Console auth; class 2 — ask which product first if unnamed | +| Bailian Token Plan quota usage | `bl usage token-plan` | Console auth; class 2 — ask which product first if unnamed | +| Token Plan harness entitlement quota | `bl token-plan harness-quota` | Console auth; issued quota usage + still-issuing harnesses | +| Bailian Coding Plan quota usage | `bl usage coding-plan` | Console auth; class 2 — ask which product first if unnamed | +| Model monitoring (calls, latency, errors, delivery) | `bl monitor overview` / `models` / `metrics` / `errors` / `delivery *` | Console auth; see [`reference/monitor.md`](reference/monitor.md) | +| Model call logs / traces | `bl log audit *` / `bl log inference *` / `bl log status` / `bl log trace *` | Console auth; audit and inference logs have separate APIs and switches; see [`reference/log.md`](reference/log.md) | +| Model alert rules / templates / history | `bl alert list` / `create` / `update` / `delete` / `enable` / `disable` / `history` / `metrics` / `template *` | Console auth; contacts are managed in the CloudMonitor console; see [`reference/alert.md`](reference/alert.md) | +| Console API (advanced) | `bl console call` | Console auth | +| Bailian workspace listing | `bl workspace list` | Console auth | +| Switch CLI Help / Quick Start language | `bl config set --key language --value zh-CN` | Use `en-US` to switch back; follows the active config profile | +| Image / video / speech / omni / vision | → skill `bailian-gen` | Fallback: `bl image\|video\|speech\|omni\|vision --help` | +| Training dataset / fine-tune / deploy | → skill `bailian-finetune` | Fallback: `bl dataset\|finetune\|deploy --help` | +| 百炼模型智能路由 / smart routing / model routing | → skill `bailian-finetune` | 独立于精调流程;fallback: `bl deploy router --help`。 | +| 吞吐预留(PTU)/ ModelCode 容量购买与扩缩容 | → skill `bailian-finetune` | 独立于精调流程;包括容量查询、购买、扩缩容、续费、释放、退订与溢出策略;fallback: `bl deploy --help`。 | +| Guided end-to-end OPD distillation workflow | → skill `bailian-opd` | Authorize → validate → preflight → consent → submit → wait; fallback: `bl finetune opd --help` | +| agents.yaml IaC / managed-agent sessions | → skill `bailian-managed-agent` | Fallback: `bl managed-agent --help`; `apply`/`destroy` need `--yes` after `plan` | +| Bailian Sandbox instance / template lifecycle | → skill `bailian-sandbox` | Fallback: `bl sandbox --help` | +| Web search (mode-aware routing) | → skill `bailian-web-search` | Default model mode vs explicit `--mode mcp` + fallback; fallback: `bl search web --help` | Flags, usage, and examples: see hub [`reference/`](reference/index.md) or `bl --help` — do not guess flags. Domain command details live in the owning skill's `reference/`. Examples in `reference/` stay bare; wrap with Call attribution when running.