github-actions[bot] commented on code in PR #62494:
URL: https://github.com/apache/doris/pull/62494#discussion_r3091879899


##########
be/src/exprs/function/ai/ai_adapter.h:
##########
@@ -137,26 +139,71 @@ class AIAdapter {
 
     virtual Status build_embedding_request(const std::vector<std::string>& 
inputs,
                                            std::string& request_body) const {
-        return Status::NotSupported("{} does not support the Embed feature.",
-                                    _config.provider_type);
+        return embed_not_supported_status();
     }
 
-    virtual Status build_multimodal_embedding_request(MultimodalType 
/*media_type*/,
-                                                      const std::string& 
/*media_url*/,
-                                                      std::string& 
/*request_body*/) const {
+    virtual Status build_multimodal_embedding_request(
+            const std::vector<MultimodalType>& /*media_types*/,
+            const std::vector<std::string>& /*media_urls*/, std::string& 
/*request_body*/) const {
         return Status::NotSupported("{} does not support multimodal Embed 
feature.",
                                     _config.provider_type);
     }
 
     virtual Status parse_embedding_response(const std::string& response_body,
                                             std::vector<std::vector<float>>& 
results) const {
-        return Status::NotSupported("{} does not support the Embed feature.",
-                                    _config.provider_type);
+        return embed_not_supported_status();
     }
 
 protected:
     TAIResource _config;
 
+    Status embed_not_supported_status() const {
+        return Status::NotSupported(
+                "{} does not support the Embed feature. Currently supported 
providers are "
+                "OpenAI, Gemini, Voyage, Jina, Qwen, and Minimax.",
+                _config.provider_type);
+    }
+
+    // Appends one provider-parsed text result to `results`.
+    // The adapter has already parsed the provider's outer response envelope 
before calling here.
+    // Example:
+    // provider response -> choices[0].message.content = "[\"1\",\"0\",\"1\"]"
+    // this helper       -> appends "1", "0", "1" into `results`
+    static Status append_parsed_text_result(std::string_view text,
+                                            std::vector<std::string>& results) 
{
+        size_t begin = 0;
+        size_t end = text.size();
+        while (begin < end && std::isspace(static_cast<unsigned 
char>(text[begin]))) {
+            ++begin;
+        }
+        while (begin < end && std::isspace(static_cast<unsigned char>(text[end 
- 1]))) {
+            --end;
+        }
+

Review Comment:
   `append_parsed_text_result()` only treats the payload as a batch JSON array 
when the character immediately after `[` is `"` or `'`. That rejects valid 
pretty-printed JSON like `[ "1", "0" ]` or `[` followed by 
newlines/indentation, which models commonly emit. In the batched scalar path 
this becomes a false size-mismatch (`expected N items but got 1`) or downstream 
parse error even though the model returned valid JSON. Please parse the trimmed 
payload whenever it starts with `[` and ends with `]`, then validate 
`doc.IsArray()`.



##########
be/src/exprs/function/ai/ai_functions.h:
##########
@@ -211,77 +213,182 @@ class AIFunction : public IFunction {
                                               });
     }
 
-    // Wrapper for executing a single LLM request
-    Status execute_single_request(const std::string& input, std::string& 
result,
-                                  const TAIResource& config, 
std::shared_ptr<AIAdapter>& adapter,
-                                  FunctionContext* context) const {
-        std::vector<std::string> inputs = {input};
-        std::vector<std::string> results;
+    // Provider-reusable helper for string-returning functions.
+    // Estimates one batch entry size using the raw prompt length plus the 
fixed JSON wrapper cost.
+    size_t estimate_batch_entry_size(size_t idx, const std::string& prompt) 
const {
+        static constexpr size_t json_wrapper_size = 20;
+        return prompt.size() + std::to_string(idx).size() + json_wrapper_size;
+    }
+
+    // Provider-reusable helper for string-returning functions.
+    // Executes one batch request and parses the provider result into one 
string per input row.
+    Status execute_batch_request(const std::vector<std::string>& batch_prompts,
+                                 std::vector<std::string>& results, const 
TAIResource& config,
+                                 std::shared_ptr<AIAdapter>& adapter,
+                                 FunctionContext* context) const {
+#ifdef BE_TEST
+        const char* test_result = std::getenv("AI_TEST_RESULT");
+        if (test_result != nullptr) {
+            std::vector<std::string> parsed_test_response;
+            RETURN_IF_ERROR(
+                    adapter->parse_response(std::string(test_result), 
parsed_test_response));
+            if (parsed_test_response.empty()) {
+                return Status::InternalError("AI returned empty result");
+            }
+            if (parsed_test_response.size() != batch_prompts.size()) {
+                return Status::RuntimeError(
+                        "Failed to parse {} batch result, expected {} items 
but got {}", get_name(),
+                        batch_prompts.size(), parsed_test_response.size());
+            }
+            results = std::move(parsed_test_response);
+            return Status::OK();
+        }
+        if (config.provider_type == "MOCK") {
+            results.clear();
+            results.reserve(batch_prompts.size());
+            for (const auto& prompt : batch_prompts) {
+                results.emplace_back("this is a mock response. " + prompt);
+            }
+            return Status::OK();
+        }
+#endif
+
+        std::string batch_prompt;
+        RETURN_IF_ERROR(build_batch_prompt(batch_prompts, batch_prompt));
+
+        std::vector<std::string> inputs = {batch_prompt};
+        std::vector<std::string> parsed_response;
 
         std::string request_body;
         RETURN_IF_ERROR(adapter->build_request_payload(
                 inputs, assert_cast<const Derived&>(*this).system_prompt, 
request_body));
 
         std::string response;
-        if (config.provider_type == "MOCK") {
-            // Mock path for UT
-            response = "this is a mock response. " + input;
-        } else {
-            RETURN_IF_ERROR(send_request_to_llm(request_body, response, 
config, adapter, context));
-        }
-
-        RETURN_IF_ERROR(adapter->parse_response(response, results));
-        if (results.empty()) {
+        RETURN_IF_ERROR(send_request_to_llm(request_body, response, config, 
adapter, context));
+        RETURN_IF_ERROR(adapter->parse_response(response, parsed_response));
+        if (parsed_response.empty()) {
             return Status::InternalError("AI returned empty result");
         }
-
-        result = std::move(results[0]);
+        if (parsed_response.size() != batch_prompts.size()) {
+            return Status::RuntimeError(
+                    "Failed to parse {} batch result, expected {} items but 
got {}", get_name(),
+                    batch_prompts.size(), parsed_response.size());
+        }
+        results = std::move(parsed_response);
         return Status::OK();
     }
 
-    Status execute_single_request(const std::string& input, 
std::vector<float>& result,
-                                  const TAIResource& config, 
std::shared_ptr<AIAdapter>& adapter,
-                                  FunctionContext* context) const {
-        std::vector<std::string> inputs = {input};
-        std::vector<std::vector<float>> results;
+    // Provider-reusable helper for string-returning functions.
+    // Runs the common batch execution flow; derived classes only need to 
define how one batch of
+    // string results is inserted into the final output column.
+    Status execute_batched_prompts(FunctionContext* context, Block& block,
+                                   const ColumnNumbers& arguments, size_t 
input_rows_count,
+                                   const TAIResource& config, 
std::shared_ptr<AIAdapter>& adapter,
+                                   IColumn& col_result) const {
+        std::vector<std::string> batch_prompts;
+        size_t current_batch_size = 2; // []
+        const size_t max_batch_prompt_size =
+                static_cast<size_t>(get_ai_context_window_size(context));
 
-        std::string request_body;
-        RETURN_IF_ERROR(adapter->build_embedding_request(inputs, 
request_body));
+        for (size_t i = 0; i < input_rows_count; ++i) {
+            std::string prompt;
+            RETURN_IF_ERROR(
+                    assert_cast<const Derived&>(*this).build_prompt(block, 
arguments, i, prompt));
 
-        std::string response;
-        if (config.provider_type == "MOCK") {
-            // Mock path for UT
-            response = "{\"embedding\": [0, 1, 2, 3, 4]}";
-        } else {
-            RETURN_IF_ERROR(send_request_to_llm(request_body, response, 
config, adapter, context));
+            size_t entry_size = 
estimate_batch_entry_size(batch_prompts.size(), prompt);
+            if (entry_size > max_batch_prompt_size) {
+                if (!batch_prompts.empty()) {
+                    std::vector<std::string> batch_results;
+                    RETURN_IF_ERROR(this->execute_batch_request(batch_prompts, 
batch_results,
+                                                                config, 
adapter, context));
+                    RETURN_IF_ERROR(assert_cast<const 
Derived&>(*this).append_batch_results(
+                            batch_results, col_result));
+                    batch_prompts.clear();
+                    current_batch_size = 2;
+                }
+
+                std::vector<std::string> single_prompts;
+                single_prompts.emplace_back(std::move(prompt));
+                std::vector<std::string> single_results;
+                RETURN_IF_ERROR(this->execute_batch_request(single_prompts, 
single_results, config,
+                                                            adapter, context));
+                RETURN_IF_ERROR(assert_cast<const 
Derived&>(*this).append_batch_results(
+                        single_results, col_result));
+                continue;
+            }
+
+            size_t additional_size = entry_size + (batch_prompts.empty() ? 0 : 
1);
+            if (!batch_prompts.empty() &&
+                current_batch_size + additional_size > max_batch_prompt_size) {
+                std::vector<std::string> batch_results;
+                RETURN_IF_ERROR(this->execute_batch_request(batch_prompts, 
batch_results, config,
+                                                            adapter, context));
+                RETURN_IF_ERROR(assert_cast<const 
Derived&>(*this).append_batch_results(
+                        batch_results, col_result));
+                batch_prompts.clear();
+                current_batch_size = 2;
+                additional_size = entry_size;
+            }
+
+            batch_prompts.emplace_back(std::move(prompt));
+            current_batch_size += additional_size;
         }
 
-        RETURN_IF_ERROR(adapter->parse_embedding_response(response, results));
-        if (results.empty()) {
-            return Status::InternalError("AI returned empty result");
+        if (!batch_prompts.empty()) {
+            std::vector<std::string> batch_results;
+            RETURN_IF_ERROR(this->execute_batch_request(batch_prompts, 
batch_results, config,
+                                                        adapter, context));
+            RETURN_IF_ERROR(assert_cast<const 
Derived&>(*this).append_batch_results(batch_results,
+                                                                               
     col_result));
         }
+        return Status::OK();
+    }
+
+private:
+    // The ai resource must be literal
+    Status _init_from_resource(FunctionContext* context, const Block& block,
+                               const ColumnNumbers& arguments, TAIResource& 
config,
+                               std::shared_ptr<AIAdapter>& adapter) const {
+        const ColumnWithTypeAndName& resource_column = 
block.get_by_position(arguments[0]);
+        StringRef resource_name_ref = resource_column.column->get_data_at(0);
+        std::string resource_name = std::string(resource_name_ref.data, 
resource_name_ref.size);

Review Comment:
   Using `DORIS_CHECK` here turns ordinary query/config errors into BE crashes. 
Before this patch `_init_from_resource()` returned `Status` for missing AI 
metadata, unknown resource names, or unsupported providers; after this change 
`SELECT ai_sentiment('not_exist_resource', ...)` aborts the process (the new UT 
even expects `ASSERT_DEATH`). These are not invariants, so this path should 
keep returning `Status` instead of asserting.



##########
fe/fe-core/src/main/java/org/apache/doris/qe/SessionVariable.java:
##########
@@ -3463,6 +3465,20 @@ public void setDetailShapePlanNodes(String 
detailShapePlanNodes) {
             })
     public long filePresignedUrlTtlSeconds = 3600;
 

Review Comment:
   These new session variables are forwarded without any FE-side validation, 
but BE silently rewrites invalid values: `_get_embed_max_batch_size()` clamps 
`<= 0` to `1`, and `get_ai_context_window_size()` clamps `<= 0` to `128 * 
1024`. So `SET embed_max_batch_size = 0` or `SET ai_context_window_size = -1` 
is accepted and visible in FE session state, while execution ignores it and 
uses different values. Please add a checker/setter validation here so session 
state matches actual execution.



##########
be/src/exprs/function/ai/ai_functions.h:
##########
@@ -88,81 +88,83 @@ class AIFunction : public IFunction {
     }
 
 protected:
+    // Reads the shared AI context window size from query options. String AI 
batch functions and
+    // ai_agg both use the same byte-based session variable so batching 
behavior stays consistent.
+    static int64_t get_ai_context_window_size(FunctionContext* context) {
+        DORIS_CHECK(context != nullptr);
+        QueryContext* query_ctx = context->state()->get_query_ctx();
+        DORIS_CHECK(query_ctx != nullptr);
+
+        int64_t context_window_size = 
query_ctx->query_options().ai_context_window_size;
+        return context_window_size > 0 ? context_window_size : 128 * 1024;
+    }
+
     // Derived classes can override this method for non-text/default behavior.
-    // The base implementation keeps previous text-oriented processing 
unchanged.
+    // The base implementation handles all string-input/string-output 
batchable functions.
     Status execute_with_adapter(FunctionContext* context, Block& block,
                                 const ColumnNumbers& arguments, uint32_t 
result,
                                 size_t input_rows_count, const TAIResource& 
config,
                                 std::shared_ptr<AIAdapter>& adapter) const {
-        DataTypePtr return_type_impl =
-                assert_cast<const 
Derived&>(*this).get_return_type_impl(DataTypes());
-        if (return_type_impl->get_primitive_type() != 
PrimitiveType::TYPE_STRING) {
-            return Status::InternalError("{} must override execute for 
non-string return type",
-                                         get_name());
-        }
-        MutableColumnPtr col_result = ColumnString::create();
+        auto col_result = assert_cast<const 
Derived&>(*this).create_result_column();
+        RETURN_IF_ERROR(execute_batched_prompts(context, block, arguments, 
input_rows_count, config,
+                                                adapter, *col_result));
 
-        for (size_t i = 0; i < input_rows_count; ++i) {
-            // Build AI prompt text
-            std::string prompt;
-            RETURN_IF_ERROR(
-                    assert_cast<const Derived&>(*this).build_prompt(block, 
arguments, i, prompt));
+        block.replace_by_position(result, std::move(col_result));
+        return Status::OK();
+    }
 
-            std::string string_result;
-            RETURN_IF_ERROR(
-                    execute_single_request(prompt, string_result, config, 
adapter, context));
-            assert_cast<ColumnString&>(*col_result)
-                    .insert_data(string_result.data(), string_result.size());
-        }
+    MutableColumnPtr create_result_column() const { return 
ColumnString::create(); }
 
-        block.replace_by_position(result, std::move(col_result));
+    // Provider-reusable hook for AI functions(string) -> string.
+    Status append_batch_results(const std::vector<std::string>& batch_results,
+                                IColumn& col_result) const {
+        auto& string_col = assert_cast<ColumnString&>(col_result);
+        for (const auto& batch_result : batch_results) {
+            string_col.insert_data(batch_result.data(), batch_result.size());
+        }
         return Status::OK();
     }
 
-    // The endpoint `v1/completions` does not support `system_prompt`.
-    // To ensure a clear structure and stable AI results.
-    // Convert from `v1/completions` to `v1/chat/completions`
     static void normalize_endpoint(TAIResource& config) {
+        // 1. If users configure only the version root like `.../v1` or 
`.../v1beta`, append
+        //    `models/<model>:batchEmbedContents` for `embed`, and 
`models/<model>:generateContent`

Review Comment:
   This normalization only runs through `AIFunction::_init_from_resource()`. 
`AggregateFunctionAIAggData::prepare()` still copies the raw `TAIResource` and 
sends requests without any equivalent rewrite, so the same Gemini resource can 
work for `ai_sentiment`/`embed` after this PR but still fail for `ai_agg` when 
the endpoint is configured as the base version URL (`.../v1` / `.../v1beta`) or 
legacy `.../v1/completions`. Since `ai_agg` is the parallel AI path in BE, it 
should keep the same endpoint-compatibility behavior.



##########
be/src/exprs/function/ai/ai_adapter.h:
##########
@@ -1207,43 +1320,66 @@ class GeminiAdapter : public AIAdapter {
         return Status::OK();
     }
 
-    Status build_multimodal_embedding_request(MultimodalType media_type,
-                                              const std::string& media_url,
+    Status build_multimodal_embedding_request(const 
std::vector<MultimodalType>& media_types,
+                                              const std::vector<std::string>& 
media_urls,
                                               std::string& request_body) const 
override {
-        const char* mime_type = nullptr;
-        switch (media_type) {
-        case MultimodalType::IMAGE:
-            mime_type = "image/png";
-            break;
-        case MultimodalType::AUDIO:
-            mime_type = "audio/mpeg";
-            break;
-        case MultimodalType::VIDEO:
-            mime_type = "video/mp4";
-            break;
-        }
+        RETURN_IF_ERROR(validate_multimodal_embedding_inputs(
+                "Gemini", media_types, media_urls,
+                {MultimodalType::IMAGE, MultimodalType::AUDIO, 
MultimodalType::VIDEO}));
 
         rapidjson::Document doc;
         doc.SetObject();
         auto& allocator = doc.GetAllocator();
 
+        /*{
+          "requests": [
+            {
+              "model": "models/gemini-embedding-2-preview",
+              "content": {
+                "parts": [
+                  {"file_data": {"mime_type": "image/png", "file_uri": 
"<url>"}}
+                ]
+              },
+              "outputDimensionality": 768
+            },
+            {
+              "model": "models/gemini-embedding-2-preview",
+              "content": {
+                "parts": [
+                  {"file_data": {"mime_type": "video/mp4", "file_uri": 
"<url>"}}
+                ]
+              },
+              "outputDimensionality": 768
+            }
+          ]
+        }*/
         std::string model_name = _config.model_name;
         if (!model_name.starts_with("models/")) {
             model_name = "models/" + model_name;
         }
-        doc.AddMember("model", rapidjson::Value(model_name.c_str(), 
allocator), allocator);
-        add_dimension_params(doc, allocator);
 
-        rapidjson::Value content(rapidjson::kObjectType);
-        rapidjson::Value parts(rapidjson::kArrayType);
-        rapidjson::Value part(rapidjson::kObjectType);

Review Comment:
   This hardcodes one MIME type per coarse media category, but `EMBED` already 
reads the real `content_type` from the FILE JSON. For Gemini that means inputs 
like `image/jpeg`, `image/webp`, `audio/wav`, or `video/webm` are all rewritten 
to `image/png` / `audio/mpeg` / `video/mp4`. The request then advertises a 
different media type than the actual object URL, so valid multimodal inputs can 
be rejected or misinterpreted. The adapter needs the original `content_type`, 
not just `MultimodalType`.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to