Coverage Report

Created: 2026-09-10 01:11

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/exprs/function/ai/embed.h
Line
Count
Source
1
// Licensed to the Apache Software Foundation (ASF) under one
2
// or more contributor license agreements.  See the NOTICE file
3
// distributed with this work for additional information
4
// regarding copyright ownership.  The ASF licenses this file
5
// to you under the Apache License, Version 2.0 (the
6
// "License"); you may not use this file except in compliance
7
// with the License.  You may obtain a copy of the License at
8
//
9
//   http://www.apache.org/licenses/LICENSE-2.0
10
//
11
// Unless required by applicable law or agreed to in writing,
12
// software distributed under the License is distributed on an
13
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
// KIND, either express or implied.  See the License for the
15
// specific language governing permissions and limitations
16
// under the License.
17
18
#pragma once
19
20
#include <glog/logging.h>
21
#include <rapidjson/document.h>
22
23
#include <string_view>
24
25
#include "core/data_type/data_type_nullable.h"
26
#include "core/data_type/primitive_type.h"
27
#include "exprs/function/ai/ai_functions.h"
28
#include "util/jsonb_utils.h"
29
#include "util/s3_uri.h"
30
#include "util/s3_util.h"
31
32
namespace doris {
33
class FunctionEmbed : public AIFunction<FunctionEmbed> {
34
public:
35
    static constexpr auto name = "embed";
36
37
    static constexpr size_t number_of_arguments = 2;
38
39
    static constexpr auto system_prompt = "";
40
41
5
    DataTypePtr get_nested_return_type_impl(const DataTypes& /*arguments*/) const {
42
5
        return std::make_shared<DataTypeArray>(make_nullable(std::make_shared<DataTypeFloat32>()));
43
5
    }
44
45
    using PreparedFunctionImpl::execute;
46
47
15
    AIResource select_ai_resource(const TAIResource& resource) const {
48
15
        bool has_embed_properties = resource.__isset.embed_endpoint ||
49
15
                resource.__isset.embed_provider_type || resource.__isset.embed_model_name ||
50
15
                resource.__isset.embed_api_key;
51
15
        return has_embed_properties ? AIResource::from_embed(resource) : AIResource(resource);
52
15
    }
53
54
    Status execute(FunctionContext* context, Block& block, const ColumnNumbers& arguments,
55
                   uint32_t result, size_t input_rows_count, const AIResource& config,
56
18
                   std::shared_ptr<AIAdapter>& adapter) const {
57
18
        if (arguments.size() != 2) {
58
1
            return Status::InvalidArgument("Function EMBED expects 2 arguments, but got {}",
59
1
                                           arguments.size());
60
1
        }
61
62
17
        const auto& input = block.get_by_position(arguments[1]);
63
17
        ColumnUInt8::MutablePtr result_null_map;
64
17
        if (input.type->is_nullable()) {
65
4
            const auto& [column, is_const] = unpack_if_const(input.column);
66
4
            const auto& nullable =
67
4
                    assert_cast<const ColumnNullable&, TypeCheckOnRelease::DISABLE>(*column);
68
4
            result_null_map = ColumnUInt8::create(input_rows_count, 0);
69
4
            VectorizedUtils::update_null_map(result_null_map->get_data(),
70
4
                                             nullable.get_null_map_data(), is_const);
71
4
        }
72
73
17
        if (result_null_map &&
74
17
            !simd::contain_zero(result_null_map->get_data().data(), input_rows_count)) {
75
1
            block.get_by_position(result).column =
76
1
                    block.get_by_position(result).type->create_column_const(input_rows_count,
77
1
                                                                            Field());
78
1
            return Status::OK();
79
1
        }
80
81
16
        ColumnPtr input_column =
82
16
                input.unnest_nullable(input.type->is_nullable() ? input.get_nullable_column_info()
83
16
                                                                : NullableColumnInfo {},
84
16
                                      false)
85
16
                        .column;
86
16
        PrimitiveType input_type = remove_nullable(input.type)->get_primitive_type();
87
16
        if (input_type == PrimitiveType::TYPE_JSONB) {
88
9
            return _execute_multimodal_embed(context, block, result, input_rows_count, config,
89
9
                                             adapter, input_column, std::move(result_null_map));
90
9
        }
91
7
        if (input_type == PrimitiveType::TYPE_STRING || input_type == PrimitiveType::TYPE_VARCHAR ||
92
7
            input_type == PrimitiveType::TYPE_CHAR) {
93
6
            return _execute_text_embed(context, block, result, input_rows_count, config, adapter,
94
6
                                       input_column, std::move(result_null_map));
95
6
        }
96
1
        return Status::InvalidArgument(
97
1
                "Function EMBED expects the second argument to be STRING or JSON, but got type {}",
98
1
                input.type->get_name());
99
7
    }
100
101
24
    static FunctionPtr create() { return std::make_shared<FunctionEmbed>(); }
102
103
private:
104
15
    static int32_t _get_embed_max_batch_size(FunctionContext* context) {
105
15
        QueryContext* query_ctx = context->state()->get_query_ctx();
106
15
        DORIS_CHECK(query_ctx != nullptr);
107
108
15
        return query_ctx->query_options().embed_max_batch_size;
109
15
    }
110
111
    Status _execute_text_embed(FunctionContext* context, Block& block, uint32_t result,
112
                               size_t input_rows_count, const AIResource& config,
113
                               std::shared_ptr<AIAdapter>& adapter, const ColumnPtr& input_column,
114
6
                               ColumnUInt8::MutablePtr result_null_map) const {
115
6
        auto col_result = ColumnArray::create(
116
6
                ColumnNullable::create(ColumnFloat32::create(), ColumnUInt8::create()));
117
6
        std::vector<std::string> batch_prompts;
118
6
        size_t current_batch_size = 0;
119
6
        const int32_t max_batch_size = _get_embed_max_batch_size(context);
120
6
        const size_t max_context_window_size =
121
6
                static_cast<size_t>(get_ai_context_window_size(context));
122
6
        const NullMap* null_map = result_null_map ? &result_null_map->get_data() : nullptr;
123
6
        const Columns prompt_columns {input_column};
124
125
29
        for (size_t i = 0; i < input_rows_count; ++i) {
126
23
            if (null_map && (*null_map)[i]) {
127
9
                continue;
128
9
            }
129
130
14
            std::string prompt;
131
14
            RETURN_IF_ERROR(build_prompt(prompt_columns, i, prompt));
132
133
14
            const size_t prompt_size = prompt.size();
134
135
14
            if (prompt_size > max_context_window_size) {
136
                // flush history batch
137
0
                RETURN_IF_ERROR(_flush_text_embedding_batch(batch_prompts, *col_result, config,
138
0
                                                            adapter, context));
139
0
                current_batch_size = 0;
140
141
0
                batch_prompts.emplace_back(std::move(prompt));
142
0
                RETURN_IF_ERROR(_flush_text_embedding_batch(batch_prompts, *col_result, config,
143
0
                                                            adapter, context));
144
0
                continue;
145
0
            }
146
147
14
            if (!batch_prompts.empty() &&
148
14
                (current_batch_size + prompt_size > max_context_window_size ||
149
8
                 batch_prompts.size() >= static_cast<size_t>(max_batch_size))) {
150
3
                RETURN_IF_ERROR(_flush_text_embedding_batch(batch_prompts, *col_result, config,
151
3
                                                            adapter, context));
152
3
                current_batch_size = 0;
153
3
            }
154
155
14
            batch_prompts.emplace_back(std::move(prompt));
156
14
            current_batch_size += prompt_size;
157
14
        }
158
159
6
        RETURN_IF_ERROR(
160
6
                _flush_text_embedding_batch(batch_prompts, *col_result, config, adapter, context));
161
162
6
        block.replace_by_position(result, _expand_and_wrap_nullable_result(
163
6
                                                  std::move(col_result), std::move(result_null_map),
164
6
                                                  input_rows_count));
165
6
        return Status::OK();
166
6
    }
167
168
    Status _execute_multimodal_embed(FunctionContext* context, Block& block, uint32_t result,
169
                                     size_t input_rows_count, const AIResource& config,
170
                                     std::shared_ptr<AIAdapter>& adapter,
171
                                     const ColumnPtr& input_column,
172
9
                                     ColumnUInt8::MutablePtr result_null_map) const {
173
9
        auto col_result = ColumnArray::create(
174
9
                ColumnNullable::create(ColumnFloat32::create(), ColumnUInt8::create()));
175
9
        std::vector<MultimodalType> batch_media_types;
176
9
        std::vector<std::string> batch_media_content_types;
177
9
        std::vector<std::string> batch_media_urls;
178
9
        const NullMap* null_map = result_null_map ? &result_null_map->get_data() : nullptr;
179
180
9
        int64_t ttl_seconds = 3600;
181
9
        QueryContext* query_ctx = context->state()->get_query_ctx();
182
9
        if (query_ctx && query_ctx->query_options().__isset.file_presigned_url_ttl_seconds) {
183
9
            ttl_seconds = query_ctx->query_options().file_presigned_url_ttl_seconds;
184
9
            if (ttl_seconds <= 0) {
185
1
                ttl_seconds = 3600;
186
1
            }
187
9
        }
188
189
9
        const int32_t max_batch_size = _get_embed_max_batch_size(context);
190
191
24
        for (size_t i = 0; i < input_rows_count; ++i) {
192
19
            if (null_map && (*null_map)[i]) {
193
3
                continue;
194
3
            }
195
196
16
            rapidjson::Document file_input;
197
16
            RETURN_IF_ERROR(_parse_file_input(*input_column, i, file_input));
198
199
16
            std::string content_type;
200
16
            MultimodalType media_type;
201
16
            RETURN_IF_ERROR(_infer_media_type(file_input, content_type, media_type));
202
203
14
            std::string media_url;
204
14
            RETURN_IF_ERROR(_resolve_media_url(file_input, ttl_seconds, media_url));
205
206
12
            if (!batch_media_urls.empty() &&
207
12
                batch_media_urls.size() >= static_cast<size_t>(max_batch_size)) {
208
1
                RETURN_IF_ERROR(_flush_multimodal_embedding_batch(
209
1
                        batch_media_types, batch_media_content_types, batch_media_urls, *col_result,
210
1
                        config, adapter, context));
211
1
            }
212
213
12
            batch_media_types.emplace_back(media_type);
214
12
            batch_media_content_types.emplace_back(std::move(content_type));
215
12
            batch_media_urls.emplace_back(std::move(media_url));
216
12
        }
217
218
5
        RETURN_IF_ERROR(_flush_multimodal_embedding_batch(
219
5
                batch_media_types, batch_media_content_types, batch_media_urls, *col_result, config,
220
5
                adapter, context));
221
222
5
        block.replace_by_position(result, _expand_and_wrap_nullable_result(
223
5
                                                  std::move(col_result), std::move(result_null_map),
224
5
                                                  input_rows_count));
225
5
        return Status::OK();
226
5
    }
227
228
    // EMBED-private helper.
229
    // Sends one embedding request with a prebuilt request body and validates returned row count.
230
    Status _execute_prebuilt_embedding_request(const std::string& request_body,
231
                                               std::vector<std::vector<float>>& results,
232
                                               size_t expected_size, const AIResource& config,
233
                                               std::shared_ptr<AIAdapter>& adapter,
234
0
                                               FunctionContext* context) const {
235
0
        std::string response;
236
#ifdef BE_TEST
237
        if (config.provider_type == "MOCK") {
238
            results.clear();
239
            results.reserve(expected_size);
240
            for (size_t i = 0; i < expected_size; ++i) {
241
                results.emplace_back(std::initializer_list<float> {0, 1, 2, 3, 4});
242
            }
243
            return Status::OK();
244
        }
245
#endif
246
247
0
        RETURN_IF_ERROR(
248
0
                this->send_request_to_llm(request_body, response, config, adapter, context));
249
250
0
        RETURN_IF_ERROR(adapter->parse_embedding_response(response, results));
251
0
        if (results.empty()) {
252
0
            return Status::InternalError("AI returned empty result");
253
0
        }
254
0
        if (results.size() != expected_size) [[unlikely]] {
255
0
            return Status::InternalError(
256
0
                    "AI embedding returned {} results, but {} inputs were sent", results.size(),
257
0
                    expected_size);
258
0
        }
259
0
        return Status::OK();
260
0
    }
261
262
    // EMBED-private helper.
263
    // Flushes one accumulated text embedding batch into the output array column.
264
    Status _flush_text_embedding_batch(std::vector<std::string>& batch_prompts,
265
                                       ColumnArray& col_result, const AIResource& config,
266
                                       std::shared_ptr<AIAdapter>& adapter,
267
9
                                       FunctionContext* context) const {
268
9
        if (batch_prompts.empty()) {
269
0
            return Status::OK();
270
0
        }
271
272
9
        std::string request_body;
273
9
        RETURN_IF_ERROR(adapter->build_embedding_request(batch_prompts, request_body));
274
9
        std::vector<std::vector<float>> batch_results;
275
9
        RETURN_IF_ERROR(_execute_prebuilt_embedding_request(
276
9
                request_body, batch_results, batch_prompts.size(), config, adapter, context));
277
14
        for (const auto& batch_result : batch_results) {
278
14
            _insert_embedding_result(col_result, batch_result);
279
14
        }
280
9
        batch_prompts.clear();
281
9
        return Status::OK();
282
9
    }
283
284
    // EMBED-private helper.
285
    // Flushes one accumulated multimodal embedding batch into the output array column.
286
    Status _flush_multimodal_embedding_batch(std::vector<MultimodalType>& batch_media_types,
287
                                             std::vector<std::string>& batch_media_content_types,
288
                                             std::vector<std::string>& batch_media_urls,
289
                                             ColumnArray& col_result, const AIResource& config,
290
                                             std::shared_ptr<AIAdapter>& adapter,
291
6
                                             FunctionContext* context) const {
292
6
        if (batch_media_urls.empty()) {
293
0
            return Status::OK();
294
0
        }
295
296
6
        std::string request_body;
297
6
        RETURN_IF_ERROR(adapter->build_multimodal_embedding_request(
298
6
                batch_media_types, batch_media_urls, batch_media_content_types, request_body));
299
300
6
        std::vector<std::vector<float>> batch_results;
301
6
        RETURN_IF_ERROR(_execute_prebuilt_embedding_request(
302
6
                request_body, batch_results, batch_media_urls.size(), config, adapter, context));
303
12
        for (const auto& batch_result : batch_results) {
304
12
            _insert_embedding_result(col_result, batch_result);
305
12
        }
306
6
        batch_media_types.clear();
307
6
        batch_media_content_types.clear();
308
6
        batch_media_urls.clear();
309
6
        return Status::OK();
310
6
    }
311
312
    static void _insert_embedding_result(ColumnArray& col_array,
313
26
                                         const std::vector<float>& float_result) {
314
26
        auto& offsets = col_array.get_offsets();
315
26
        auto& nested_nullable_col = assert_cast<ColumnNullable&>(col_array.get_data());
316
26
        auto& nested_col =
317
26
                assert_cast<ColumnFloat32&>(*(nested_nullable_col.get_nested_column_ptr()));
318
26
        nested_col.reserve(nested_col.size() + float_result.size());
319
320
26
        size_t current_offset = nested_col.size();
321
26
        nested_col.insert_many_raw_data(reinterpret_cast<const char*>(float_result.data()),
322
26
                                        float_result.size());
323
26
        offsets.push_back(current_offset + float_result.size());
324
26
        auto& null_map = nested_nullable_col.get_null_map_column();
325
26
        null_map.insert_many_vals(0, float_result.size());
326
26
    }
327
328
    static ColumnPtr _expand_and_wrap_nullable_result(ColumnArray::MutablePtr result,
329
                                                      ColumnUInt8::MutablePtr result_null_map,
330
11
                                                      size_t input_rows_count) {
331
11
        if (!result_null_map) {
332
8
            return result;
333
8
        }
334
335
3
        auto& offsets = result->get_offsets();
336
3
        size_t compact_row = offsets.size();
337
3
        offsets.resize(input_rows_count);
338
        // For example, embedding rows 1 and 3 produces compact offsets [5, 10]. Given
339
        // result_null_map [1, 0, 1, 0, 1], expand them to [0, 5, 5, 10, 10], where NULL rows
340
        // reuse the previous offset. Fill backwards to avoid overwriting unread compact offsets.
341
24
        for (size_t row = input_rows_count; row-- > 0;) {
342
21
            if (result_null_map->get_data()[row]) {
343
12
                offsets[row] = compact_row == 0 ? 0 : offsets[compact_row - 1];
344
12
            } else {
345
9
                offsets[row] = offsets[--compact_row];
346
9
            }
347
21
        }
348
3
        return ColumnNullable::create(std::move(result), std::move(result_null_map));
349
11
    }
350
351
52
    static bool _starts_with_ignore_case(std::string_view s, std::string_view prefix) {
352
52
        if (s.size() < prefix.size()) {
353
0
            return false;
354
0
        }
355
243
        return std::equal(prefix.begin(), prefix.end(), s.begin(), [](char a, char b) {
356
243
            return std::tolower(static_cast<unsigned char>(a)) ==
357
243
                   std::tolower(static_cast<unsigned char>(b));
358
243
        });
359
52
    }
360
361
    static Status _infer_media_type(const rapidjson::Value& file_input, std::string& content_type,
362
16
                                    MultimodalType& media_type) {
363
16
        RETURN_IF_ERROR(_get_required_string_field(file_input, "content_type", content_type));
364
365
15
        if (_starts_with_ignore_case(content_type, "image/")) {
366
9
            media_type = MultimodalType::IMAGE;
367
9
            return Status::OK();
368
9
        } else if (_starts_with_ignore_case(content_type, "video/")) {
369
3
            media_type = MultimodalType::VIDEO;
370
3
            return Status::OK();
371
3
        } else if (_starts_with_ignore_case(content_type, "audio/")) {
372
2
            media_type = MultimodalType::AUDIO;
373
2
            return Status::OK();
374
2
        }
375
376
1
        return Status::InvalidArgument("Unsupported content_type for EMBED: {}", content_type);
377
15
    }
378
379
    // Parse the FILE-like JSONB argument into a JSON object for downstream field reads.
380
    static Status _parse_file_input(const IColumn& file_column, size_t row_num,
381
16
                                    rapidjson::Document& file_input) {
382
16
        StringRef file_ref = file_column.get_data_at(row_num);
383
16
        std::string file_json = JsonbToJson::jsonb_to_json_string(file_ref.data, file_ref.size);
384
16
        file_input.Parse(file_json.c_str());
385
16
        DORIS_CHECK(!file_input.HasParseError() && file_input.IsObject());
386
16
        return Status::OK();
387
16
    }
388
389
    // TODO(lzq): After support FILE type, We should use the interface provided by FILE to get the fields
390
    // replacing this function
391
    static Status _get_required_string_field(const rapidjson::Value& obj, const char* field_name,
392
35
                                             std::string& value) {
393
35
        auto iter = obj.FindMember(field_name);
394
35
        if (iter == obj.MemberEnd() || !iter->value.IsString()) {
395
3
            return Status::InvalidArgument(
396
3
                    "EMBED file json field '{}' is required and must be a string", field_name);
397
3
        }
398
32
        value = iter->value.GetString();
399
32
        if (value.empty()) {
400
0
            return Status::InvalidArgument("EMBED file json field '{}' can not be empty",
401
0
                                           field_name);
402
0
        }
403
32
        return Status::OK();
404
32
    }
405
406
    static Status init_s3_client_conf_from_json(const rapidjson::Value& file_input,
407
3
                                                S3ClientConf& s3_client_conf) {
408
3
        std::string endpoint;
409
3
        RETURN_IF_ERROR(_get_required_string_field(file_input, "endpoint", endpoint));
410
2
        std::string region;
411
2
        RETURN_IF_ERROR(_get_required_string_field(file_input, "region", region));
412
413
4
        auto get_optional_string_field = [&](const char* field_name, std::string& value) {
414
4
            auto iter = file_input.FindMember(field_name);
415
4
            if (iter == file_input.MemberEnd() || iter->value.IsNull()) {
416
0
                return;
417
0
            }
418
4
            DORIS_CHECK(iter->value.IsString());
419
4
            value = iter->value.GetString();
420
4
        };
421
422
1
        get_optional_string_field("ak", s3_client_conf.ak);
423
1
        get_optional_string_field("sk", s3_client_conf.sk);
424
1
        get_optional_string_field("role_arn", s3_client_conf.role_arn);
425
1
        get_optional_string_field("external_id", s3_client_conf.external_id);
426
1
        s3_client_conf.endpoint = endpoint;
427
1
        s3_client_conf.region = region;
428
429
1
        return Status::OK();
430
2
    }
431
432
    Status _resolve_media_url(const rapidjson::Value& file_input, int64_t ttl_seconds,
433
14
                              std::string& media_url) const {
434
14
        std::string uri;
435
14
        RETURN_IF_ERROR(_get_required_string_field(file_input, "uri", uri));
436
437
        // If it's a direct http/https URL, use it as-is
438
14
        if (_starts_with_ignore_case(uri, "http://") || _starts_with_ignore_case(uri, "https://")) {
439
11
            media_url = uri;
440
11
            return Status::OK();
441
11
        }
442
443
3
        S3ClientConf s3_client_conf;
444
3
        RETURN_IF_ERROR(init_s3_client_conf_from_json(file_input, s3_client_conf));
445
1
        auto s3_client = DORIS_TRY(S3ClientFactory::instance().create(s3_client_conf));
446
447
1
        S3URI s3_uri(uri);
448
1
        RETURN_IF_ERROR(s3_uri.parse());
449
1
        std::string bucket = s3_uri.get_bucket();
450
1
        std::string key = s3_uri.get_key();
451
1
        DORIS_CHECK(!bucket.empty() && !key.empty());
452
1
        media_url = s3_client->generate_presigned_url({.bucket = bucket, .key = key, .prefix = ""},
453
1
                                                      ttl_seconds);
454
1
        return Status::OK();
455
1
    }
456
};
457
458
}; // namespace doris