Text generation
AI_TEXT_GENERATE generates content for each input entry based on a prompt, making it suitable for product titles, marketing copy, and field completion. You can call this function through the REST API to batch-generate text, or integrate it into a collection as a Collection Function to automatically generate and write results to a target field at write time.
Syntax
The following sections show the request format for the REST API and the Collection Function schema definition in Python.
REST API
REST API
POST /v2/vectordb/ai/text_generate
Content-Type: application/json
{
"model_name": "<model name>",
"texts": ["<text>"],
"params": {"prompt": "<prompt>"}
}Python
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("generated", DataType.VARCHAR, max_length=1024)
schema.add_field("dummy_vector", DataType.FLOAT_VECTOR, dim=2)
schema.add_function(
Function(
name="generate_content",
function_type=texttransform_function_type(),
input_field_names=["content"],
output_field_names=["generated"],
params={
"provider": "aliyun_milvus",
"model_name": "<model name>",
"task": "ai_text_generate",
"prompt": "Write a concise marketing sentence: ${content}",
"temperature": "0.3",
"enable_thinking": "false",
},
)
)Parameters
| Parameter | Description |
model_name | Required. Name of the configured text model, for example qwen3.7-max. The REST API also accepts model. |
texts | Required for REST. Array of texts to generate content for. Each entry corresponds to one generated result. |
prompt | Required for Schema, optional for REST. When omitted in REST, defaults to ${text}. In Schema, must reference all input fields. |
temperature / enable_thinking | Optional. Control generation randomness and thinking mode respectively. |
max_concurrency / timeout_sec | Optional. Control the concurrency limit and timeout for a single call. |
output_mapping | Optional, Schema only. Maps model-returned JSON to multiple VARCHAR, TEXT, or JSON output fields. |
provider / task | Required for Collection Function only. Fixed to aliyun_milvus and ai_text_generate respectively. |
Return values
REST returns generated text in data.output.outputs in the same order as texts. When output_mapping is not configured in Schema, the result is written to a single text field. When output_mapping is configured, the model must return valid JSON.
Usage example: Generate titles from product descriptions
An e-commerce operator wants to automatically generate a concise product title when a product is written to the collection. The following example uses the REST API to batch-generate two marketing sentences, and uses a Collection Function to automatically generate text at write time.
REST API
REST API
#!/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": [
"A lightweight laptop with a titanium alloy shell.",
"An ergonomic mechanical keyboard designed for programmers."
],
"params": {
"prompt": "Write a concise marketing sentence for this product: \${text}",
"temperature": 0.3,
"enable_thinking": false
}
}
JSON
)
RESPONSE_BODY="$(post_json "/v2/vectordb/ai/text_generate" "$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
# Expected: data.output.outputs returns two marketing sentences in the same order as textsPython
Python
After installing PyMilvus, replace the MILVUS_URI and MILVUS_TOKEN placeholder values with your actual cluster address and token, then run the script. Common helper functions are inlined within the example.
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
# Alibaba Cloud Milvus provides TEXTTRANSFORM as a managed extension (function type value 9);
# some pymilvus versions do not have this enum member built in, yet Function(...) validates through 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_text_generate",
input_fields=[("content", DataType.VARCHAR, 4096)],
output_field=("generated", DataType.VARCHAR, 1024),
function_name="generate_content",
function_params={"provider": "aliyun_milvus", "model_name": MODEL_NAME, "task": "ai_text_generate", "prompt": "Write a concise marketing sentence: ${content}", "temperature": "0.3", "enable_thinking": "false"},
rows=[{"content": "A lightweight laptop with a titanium alloy shell.", "dummy_vector": [0.1, 0.2]}],
)
# Expected: query returns records containing content and generated, where generated is a marketing sentenceExpected result: REST returns two marketing sentences; Python prints the inserted records containing content and generated, where generated is a marketing sentence.