全部产品
Search
文档中心

向量检索服务 Milvus 版:翻译

更新时间:Aug 03, 2026

AI_TRANSLATE 函数可将文本翻译成指定语言,常见于多语种电商与知识库场景。集成于 Collection 时,可实现“写入即翻译”,自动将源内容译后存入目标 VARCHAR/TEXT 字段,无需额外处理步骤。

命令格式

REST 接口

POST /v2/vectordb/ai/translate
Content-Type: application/json

{
  "model_name": "<模型名>",
  "texts": ["<文本>"],
  "params": {"target_language": "<语言代码>"}
}

Python

schema = MilvusClient.create_schema(auto_id=True, enable_dynamic_field=False)
schema.add_field("id", DataType.INT64, is_primary=True)
schema.add_field("content", DataType.VARCHAR, max_length=4096)
schema.add_field("translated", DataType.VARCHAR, max_length=4096)
schema.add_field("dummy_vector", DataType.FLOAT_VECTOR, dim=2)
schema.add_function(
    Function(
        name="translate_content",
        function_type=texttransform_function_type(),
        input_field_names=["content"],
        output_field_names=["translated"],
        params={
            "provider": "aliyun_milvus",
            "model_name": "<模型名>",
            "task": "ai_translate",
            "target_language": "en",
            "temperature": "0",
        },
    )
)

参数说明

参数

说明

model_name

必填。已配置的文本模型名称;REST 也兼容 model

texts

REST 必填。待翻译文本数组,结果逐条对应。

target_language

必填。目标语言代码:zhenesfrdejakoruarpt

temperature

选填。建议设为 0,获得更稳定的译文。

max_concurrency / timeout_sec

选填。控制单条调用的并发数和超时时间。

provider / task

仅 Collection Function 必填,固定为 aliyun_milvusai_translate

返回值说明

data.output.outputs 返回仅包含译文的字符串数组,逐条对应输入文本。在 Collection 中,译文写入目标 VARCHARTEXT 字段。

使用示例:商品描述自动生成英文版

跨境店铺需要将中文商品描述写入英文展示字段。下面用 REST 批量翻译两条文本,并用 Collection Function 在写入时自动翻译。

REST 接口

#!/usr/bin/env bash
set -euo pipefail

MILVUS_REST_BASE_URL="http://c-xxxx.milvus.aliyuncs.com:19530"
MILVUS_AUTH_TOKEN="<yourUsername>:<yourPassword>"

post_json() {
  local path="$1"
  local body="$2"
  curl -X POST \
    "$MILVUS_REST_BASE_URL$path" \
    -H "Authorization: Bearer $MILVUS_AUTH_TOKEN" \
    -H "Content-Type: application/json" \
    -d "$body"
}

MODEL_NAME="qwen3.7-max"

BODY=$(cat <<JSON
{
  "model_name": "$MODEL_NAME",
  "texts": [
    "Milvus 是一款开源的向量数据库。",
    "AI Function 可以在写入时自动完成翻译。"
  ],
  "params": {
    "target_language": "en",
    "temperature": 0
  }
}
JSON
)

RESPONSE_BODY="$(post_json "/v2/vectordb/ai/translate" "$BODY")"
if command -v jq >/dev/null 2>&1; then
  echo "$RESPONSE_BODY" | jq .
  [ "$(echo "$RESPONSE_BODY" | jq -r '.code // -1')" = "0" ] || exit 1
else
  echo "$RESPONSE_BODY"
fi
# 预期:data.output.outputs =
#   ["Milvus is an open-source vector database.",
#    "The AI Function can automatically translate as you type."]

Python

安装 PyMilvus 后,将 MILVUS_URIMILVUS_TOKEN 占位值替换为实际集群地址和 token 后运行;示例已内联公共辅助函数。

from __future__ import annotations

from typing import Any

from pymilvus import DataType, Function, FunctionType, MilvusClient

MILVUS_URI = "http://c-xxxx.milvus.aliyuncs.com:19530"
MILVUS_TOKEN = "<yourUsername>:<yourPassword>"

DUMMY_VECTOR_DIM = 2
TEXTTRANSFORM_FUNCTION_TYPE = 9

def texttransform_function_type() -> Any:
    for type_name in ("TEXTTRANSFORM", "TEXT_TRANSFORM", "TextTransform"):
        function_type = getattr(FunctionType, type_name, None)
        if function_type is not None:
            return function_type
    # 阿里云 Milvus 将 TEXTTRANSFORM 作为托管扩展(函数类型值 9)提供;
    # 部分 pymilvus 版本尚未内置该枚举成员,而 Function(...) 通过 FunctionType(...) 校验。
    existing = getattr(FunctionType, "_value2member_map_", {}).get(TEXTTRANSFORM_FUNCTION_TYPE)
    if existing is not None:
        return existing
    extension = int.__new__(FunctionType, TEXTTRANSFORM_FUNCTION_TYPE)
    extension._name_ = "TEXTTRANSFORM"
    extension._value_ = TEXTTRANSFORM_FUNCTION_TYPE
    FunctionType._value2member_map_[TEXTTRANSFORM_FUNCTION_TYPE] = extension
    FunctionType._member_map_["TEXTTRANSFORM"] = extension
    return extension

def add_id(schema: Any) -> None:
    schema.add_field("id", DataType.INT64, is_primary=True)

def add_dummy_vector(schema: Any) -> None:
    schema.add_field("dummy_vector", DataType.FLOAT_VECTOR, dim=DUMMY_VECTOR_DIM)

def run_texttransform_example(*, client, collection_name, input_fields, output_field, function_name, function_params, rows) -> None:
    if client.has_collection(collection_name):
        client.drop_collection(collection_name)
    schema = MilvusClient.create_schema(auto_id=True, enable_dynamic_field=False)
    add_id(schema)
    for name, data_type, max_length in input_fields:
        field_params = {"max_length": max_length} if max_length is not None else {}
        schema.add_field(name, data_type, **field_params)
    output_name, output_data_type, output_max_length = output_field
    output_params = {"max_length": output_max_length} if output_max_length is not None else {}
    schema.add_field(output_name, output_data_type, **output_params)
    add_dummy_vector(schema)
    schema.add_function(
        Function(
            name=function_name,
            function_type=texttransform_function_type(),
            input_field_names=[name for name, _, _ in input_fields],
            output_field_names=[output_name],
            params=function_params,
        )
    )
    index_params = client.prepare_index_params()
    index_params.add_index(field_name="dummy_vector", index_type="AUTOINDEX", metric_type="COSINE")
    client.create_collection(collection_name=collection_name, schema=schema, index_params=index_params)
    client.insert(collection_name, rows)
    client.flush(collection_name)
    fields = [name for name, _, _ in input_fields] + [output_name]
    for row in client.query(collection_name, filter="", output_fields=fields, limit=len(rows)):
        print(row)

MODEL_NAME = "qwen3.7-max"
client = MilvusClient(uri=MILVUS_URI, token=MILVUS_TOKEN)

run_texttransform_example(
    client=client,
    collection_name="simple_ai_translate",
    input_fields=[("content", DataType.VARCHAR, 4096)],
    output_field=("translated", DataType.VARCHAR, 4096),
    function_name="translate_content",
    function_params={"provider": "aliyun_milvus", "model_name": MODEL_NAME, "task": "ai_translate", "target_language": "en", "temperature": "0"},
    rows=[{"content": "Milvus 是一款开源的向量数据库。", "dummy_vector": [0.1, 0.2]}],
)
# 预期:query 返回 {'content': 'Milvus 是一款开源的向量数据库。',
#            'translated': 'Milvus is an open-source vector database.', 'id': ...}

预期结果:translated 字段得到 Milvus is an open-source vector database.