/* * DBMS_VECTOR / DBMS_VECTOR_CHAIN shared text core (see * dbms_vector_text.hpp): the UTL_TO_CHUNKS chunker engine. Port of the * Oracle VECTOR_CHUNKS parameter grammar (SPLITBY_VECTOR_CHUNKERS / * GET_SQL_SPLITBY_VECTOR_CHUNKERS, pls:1548-1813) over a native engine. */ #include "dbms_vector_text.hpp" #include "dbms_vector_common.hpp" #include "dbms_vector_rest.hpp" #include #include #include #include #include #include extern "C" { #include "fmgr.h" #include "mb/pg_wchar.h" #include "utils/builtins.h" } // extern "C" /// Oracle VECTOR_CHUNKS defaults (UTL_TO_CHUNKS docs): by chars, max 1000, /// overlap 0, split recursively, normalize none. #define DBMS_VECTOR_CHUNKS_DEFAULT_MAX 1000 enum DbmsVectorChunkSplit { CHUNK_SPLIT_NONE, CHUNK_SPLIT_BLANKLINE, CHUNK_SPLIT_NEWLINE, CHUNK_SPLIT_SPACE, CHUNK_SPLIT_RECURSIVELY, CHUNK_SPLIT_SENTENCE, CHUNK_SPLIT_CUSTOM, }; struct DbmsVectorChunkParams { bool by_words = false; int64_t max = DBMS_VECTOR_CHUNKS_DEFAULT_MAX; int64_t overlap = 0; DbmsVectorChunkSplit split = CHUNK_SPLIT_RECURSIVELY; std::vector custom_list; bool norm_whitespace = false; bool norm_punctuation = false; bool norm_widechar = false; bool extended = false; }; /* * Numeric param with Oracle's HAS()/GET_NUMBER() semantics: a present * value that is not a whole number, or is out of the accepted range, is * the parity error (message without the offending value, pls:1703-1711). */ static int64_t dbms_vector_chunks_int_param(JsonbContainer *container, const char *key, const char *param_name, int64_t min_value, bool &present) { present = false; JsonbValue buffer; JsonbValue *found = dbms_vector_getobjectfield(container, key, &buffer); if (found == nullptr || found->type == jbvNull) return 0; if (found->type != jbvNumeric) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid value for %s parameter", param_name), errdetail("Oracle error: ORA-20003 (EXCP_GU_ERR)."))); int64_t value; PG_TRY(); { value = DatumGetInt64(DirectFunctionCall1( numeric_int8, NumericGetDatum(found->val.numeric))); } PG_CATCH(); { FlushErrorState(); ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid value for %s parameter", param_name), errdetail("Oracle error: ORA-20003 (EXCP_GU_ERR)."))); } PG_END_TRY(); present = true; if (value < min_value) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid value for %s parameter", param_name), errdetail("Oracle error: ORA-20003 (EXCP_GU_ERR)."))); return value; } /* * String-array param (custom_list / norm_options): must be a non-empty * JSON array; the caller validates the elements. */ static JsonbContainer * dbms_vector_chunks_array_param(JsonbContainer *container, const char *key, const char *missing_message) { JsonbValue buffer; JsonbValue *found = dbms_vector_getobjectfield(container, key, &buffer); if (found == nullptr || found->type != jbvBinary || !JsonContainerIsArray(found->val.binary.data) || JsonContainerSize(found->val.binary.data) == 0) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("%s", missing_message), errdetail("Oracle error: ORA-20003 (EXCP_GU_ERR)."))); return found->val.binary.data; } static bool dbms_vector_chunks_is_space_byte(char c) { return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f' || c == '\v'; } /* * Parse and validate the chunking params, keeping the Oracle validation * order (by, max, overlap, split, custom_list, vocabulary, language, * normalize, norm_options, extended; pls:1680-1800). */ static void dbms_vector_chunks_parse_params(Jsonb *params, DbmsVectorChunkParams &out) { out = DbmsVectorChunkParams(); if (params == nullptr) return; JsonbContainer *container = ¶ms->root; if (!JsonContainerIsObject(container)) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("params must be a JSON object"), errdetail("Oracle error: ORA-20003 (EXCP_GU_ERR)."))); std::string by; if (dbms_vector_param_string(container, "by", "BY", by)) { by = dbms_vector_ascii_lower(by); if (by == "words") out.by_words = true; else if (by != "chars" && by != "characters" && by != "vocabulary") ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid value %s for BY parameter", by.c_str()), errdetail("Oracle error: ORA-20003 (EXCP_GU_ERR)."))); } bool present = false; int64_t max = dbms_vector_chunks_int_param(container, "max", "MAX", 1, present); if (present) out.max = max; int64_t overlap = dbms_vector_chunks_int_param(container, "overlap", "OVERLAP", 0, present); if (present) out.overlap = overlap; if (out.overlap >= out.max) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid value for OVERLAP parameter"), errdetail("Oracle error: ORA-20003 (EXCP_GU_ERR)."))); std::string split; if (dbms_vector_param_string(container, "split", "SPLIT", split)) { split = dbms_vector_ascii_lower(split); if (split == "none") out.split = CHUNK_SPLIT_NONE; else if (split == "blankline") out.split = CHUNK_SPLIT_BLANKLINE; else if (split == "newline") out.split = CHUNK_SPLIT_NEWLINE; else if (split == "space") out.split = CHUNK_SPLIT_SPACE; else if (split == "recursively") out.split = CHUNK_SPLIT_RECURSIVELY; else if (split == "sentence") out.split = CHUNK_SPLIT_SENTENCE; else if (split == "custom") out.split = CHUNK_SPLIT_CUSTOM; else ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid value %s for SPLIT parameter", split.c_str()), errdetail("Oracle error: ORA-20003 (EXCP_GU_ERR)."))); } if (out.split == CHUNK_SPLIT_CUSTOM) { JsonbContainer *list = dbms_vector_chunks_array_param( container, "custom_list", "missing CUSTOM_LIST parameter"); for (uint32_t i = 0; i < JsonContainerSize(list); i++) { JsonbValue *element = getIthJsonbValueFromContainer(list, i); if (element == nullptr || element->type != jbvString) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid value for CUSTOM_LIST parameter"), errdetail("Oracle error: ORA-20003 " "(EXCP_GU_ERR)."))); std::string delimiter(element->val.string.val, element->val.string.len); if (!delimiter.empty()) out.custom_list.push_back(delimiter); } if (out.custom_list.empty()) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("missing CUSTOM_LIST parameter"), errdetail("Oracle error: ORA-20003 (EXCP_GU_ERR)."))); } /* * Vocabulary chunking needs Oracle vocabulary storage, which has no * counterpart here; the name is validated for parity before the * capability is reported as missing. */ if (by == "vocabulary") { std::string vocabulary; if (!dbms_vector_param_string(container, "vocabulary", "VOCABULARY", vocabulary)) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("missing VOCABULARY parameter"), errdetail("Oracle error: ORA-20003 (EXCP_GU_ERR)."))); dbms_vector_check_simple_name(vocabulary, "vocabulary name"); ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("chunking by vocabulary is not supported in this " "port"), errdetail("Vocabulary storage is not ported; use " "\"by\": \"chars\" or \"by\": \"words\"."))); } /* * Recognized for grammar parity; the tokenizer is language-agnostic, * so multi-word language names cannot be validated against the Oracle * LANG_NAMES list and are accepted as-is. */ std::string language; dbms_vector_param_string(container, "language", "LANGUAGE", language); std::string normalize; if (dbms_vector_param_string(container, "normalize", "NORMALIZE", normalize)) { normalize = dbms_vector_ascii_lower(normalize); if (normalize == "all") { out.norm_whitespace = true; out.norm_punctuation = true; out.norm_widechar = true; } else if (normalize == "none") { /* defaults */ } else if (normalize == "options") { JsonbContainer *options = dbms_vector_chunks_array_param( container, "norm_options", "missing NORM_OPTIONS parameter"); for (uint32_t i = 0; i < JsonContainerSize(options); i++) { JsonbValue *element = getIthJsonbValueFromContainer(options, i); if (element == nullptr || element->type != jbvString) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid value for NORM_OPTIONS " "parameter"), errdetail("Oracle error: ORA-20003 " "(EXCP_GU_ERR)."))); std::string option(element->val.string.val, element->val.string.len); option = dbms_vector_ascii_lower(option); if (option == "whitespace") out.norm_whitespace = true; else if (option == "punctuation") out.norm_punctuation = true; else if (option == "widechar") out.norm_widechar = true; else ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid value %s for NORM_OPTIONS " "parameter", option.c_str()), errdetail("Oracle error: ORA-20003 " "(EXCP_GU_ERR)."))); } } else { ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid value %s for NORMALIZE parameter", normalize.c_str()), errdetail("Oracle error: ORA-20003 (EXCP_GU_ERR)."))); } } JsonbValue buffer; JsonbValue *found = dbms_vector_getobjectfield(container, "extended", &buffer); if (found != nullptr && found->type != jbvNull) { if (found->type != jbvBool) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid value for EXTENDED parameter"), errdetail("Oracle error: ORA-20003 (EXCP_GU_ERR)."))); out.extended = found->val.boolean; } } /* * Decode one UTF-8 code point starting at s (cap len bytes); returns the * code point and stores its byte length, or (uint32_t) -1 for an invalid * or truncated sequence. */ static uint32_t dbms_vector_text_utf8_decode(const unsigned char *s, size_t cap, int &bytes) { if (cap == 0) return (uint32_t) -1; unsigned char lead = s[0]; if (lead < 0x80) { bytes = 1; return lead; } int len; uint32_t cp; if ((lead & 0xE0) == 0xC0) { len = 2; cp = lead & 0x1F; } else if ((lead & 0xF0) == 0xE0) { len = 3; cp = lead & 0x0F; } else if ((lead & 0xF8) == 0xF0) { len = 4; cp = lead & 0x07; } else return (uint32_t) -1; if ((size_t) len > cap) return (uint32_t) -1; for (int i = 1; i < len; i++) { if ((s[i] & 0xC0) != 0x80) return (uint32_t) -1; cp = (cp << 6) | (uint32_t) (s[i] & 0x3F); } bytes = len; return cp; } /* * Normalization pipeline (before splitting): widechar maps the fullwidth * block U+FF01..U+FF5E to ASCII 0x21..0x7E and U+3000 to a plain space; * punctuation drops ASCII punctuation; whitespace collapses ASCII * whitespace runs to a single space and trims the ends. Runs only in * UTF-8 databases; single-byte encodings get the ASCII parts only. */ static std::string dbms_vector_text_normalize(const std::string &input, bool widechar, bool punctuation, bool whitespace) { std::string wide; if (widechar) { bool utf8 = pg_database_encoding_max_length() > 1; wide.reserve(input.size()); for (size_t i = 0; i < input.size();) { if (utf8 && (unsigned char) input[i] >= 0x80) { int bytes = 0; uint32_t cp = dbms_vector_text_utf8_decode( (const unsigned char *) input.c_str() + i, input.size() - i, bytes); if (cp != (uint32_t) -1) { if (cp >= 0xFF01 && cp <= 0xFF5E) wide.push_back((char) (cp - 0xFF01 + 0x21)); else if (cp == 0x3000) wide.push_back(' '); else { i += bytes; wide.append(input, i - bytes, bytes); continue; } i += bytes; continue; } } wide.push_back(input[i]); i++; } } else wide = input; std::string stripped; if (punctuation) { stripped.reserve(wide.size()); for (char c : wide) if (!ispunct((unsigned char) c)) stripped.push_back(c); } else stripped = wide; if (!whitespace) return stripped; std::string collapsed; collapsed.reserve(stripped.size()); bool pending_space = false; for (char c : stripped) { if (dbms_vector_chunks_is_space_byte(c)) pending_space = true; else { if (pending_space && !collapsed.empty()) collapsed.push_back(' '); pending_space = false; collapsed.push_back(c); } } return collapsed; } /* * Unit arithmetic over the processed text: "chars" counts characters of * the database encoding, "words" counts maximal non-whitespace runs. * Spans are byte ranges; word boundaries never split a word. */ struct DbmsVectorChunkUnits { bool by_words = false; const std::string *text = nullptr; std::vector word_starts; std::vector word_ends; void load(const std::string &input, bool words) { text = &input; by_words = words; if (!words) return; size_t i = 0; while (i < input.size()) { while (i < input.size() && dbms_vector_chunks_is_space_byte(input[i])) i++; size_t start = i; while (i < input.size() && !dbms_vector_chunks_is_space_byte(input[i])) i++; if (i > start) { word_starts.push_back(start); word_ends.push_back(i); } } } /* Number of units fully inside [b, e). */ size_t count(size_t b, size_t e) const { if (e <= b) return 0; if (!by_words) { size_t n = 0; size_t i = b; while (i < e) { i += (size_t) pg_mblen(text->c_str() + i); n++; } return n; } size_t n = 0; for (size_t k = 0; k < word_starts.size(); k++) if (word_starts[k] >= b && word_ends[k] <= e) n++; return n; } /* * Byte position of the boundary n units forward from b (never past * the end of the text). */ size_t advance(size_t b, size_t n) const { size_t limit = text->size(); if (!by_words) { size_t i = b; while (i < limit && n > 0) { i += (size_t) pg_mblen(text->c_str() + i); n--; } return i; } for (size_t k = 0; k < word_starts.size(); k++) { if (word_starts[k] < b) continue; if (n == 0) return word_starts[k]; n--; } return limit; } /* * Byte position where the tail of n units ending at e starts, never * before floor_at. With fewer than n units available the floor wins. */ size_t retreat(size_t floor_at, size_t e, size_t n) const { size_t total = count(floor_at, e); if (total <= n) return floor_at; size_t skip = total - n; if (!by_words) { size_t i = floor_at; while (skip > 0) { i += (size_t) pg_mblen(text->c_str() + i); skip--; } return i; } for (size_t k = 0; k < word_starts.size(); k++) { if (word_starts[k] < floor_at || word_ends[k] > e) continue; if (skip == 0) return word_starts[k]; skip--; } return floor_at; } }; /* * Segmentation of [from, to) into atoms by the split mode. Atoms tile the * span (delimiters stay with the segment they close); zero-length atoms * are never produced. */ static void dbms_vector_text_segment_newline(const std::string &s, size_t from, size_t to, std::vector> &out) { size_t start = from; for (size_t i = from; i < to; i++) { if (s[i] == '\n') { out.emplace_back(start, i + 1); start = i + 1; } } if (start < to) out.emplace_back(start, to); } static void dbms_vector_text_segment_blankline(const std::string &s, size_t from, size_t to, std::vector> &out) { size_t start = from; size_t i = from; while (i < to) { if (s[i] == '\n') { size_t j = i + 1; while (j < to && (s[j] == ' ' || s[j] == '\t')) j++; if (j < to && s[j] == '\n') { out.emplace_back(start, j + 1); start = j + 1; i = j + 1; continue; } } i++; } if (start < to) out.emplace_back(start, to); } static void dbms_vector_text_segment_space(const std::string &s, size_t from, size_t to, std::vector> &out) { size_t start = from; while (start < to && dbms_vector_chunks_is_space_byte(s[start])) start++; if (start >= to) { /* Whitespace-only span: keep it as a single atom. */ if (from < to) out.emplace_back(from, to); return; } size_t i = start; while (i < to) { if (!dbms_vector_chunks_is_space_byte(s[i])) { i++; continue; } /* Whitespace run: the atom ends where the next word begins. */ size_t j = i; while (j < to && dbms_vector_chunks_is_space_byte(s[j])) j++; if (j >= to) break; out.emplace_back(start, j); start = j; i = j; } out.emplace_back(start, to); } static void dbms_vector_text_segment_sentence(const std::string &s, size_t from, size_t to, std::vector> &out) { static const char *terminators = ".!?"; static const char *closers = "\"')]}" ; size_t start = from; size_t i = from; while (i < to) { if (strchr(terminators, s[i]) != nullptr && s[i] != '\0') { size_t j = i + 1; while (j < to && strchr(closers, s[j]) != nullptr && s[j] != '\0') j++; bool boundary = false; if (j >= to) boundary = true; else { size_t k = j; while (k < to && dbms_vector_chunks_is_space_byte(s[k])) k++; if (k > j) { out.emplace_back(start, k); start = k; i = k; continue; } } if (boundary) { out.emplace_back(start, j); start = j; i = j; continue; } i = j; continue; } i++; } if (start < to) out.emplace_back(start, to); } static void dbms_vector_text_segment_custom(const std::string &s, size_t from, size_t to, const std::vector &delimiters, std::vector> &out) { std::vector sorted = delimiters; std::sort(sorted.begin(), sorted.end(), [](const std::string &a, const std::string &b) { return a.size() > b.size(); }); size_t start = from; size_t i = from; while (i < to) { bool matched = false; for (const std::string &delimiter : sorted) { size_t len = delimiter.size(); if (len == 0 || i + len > to) continue; if (memcmp(s.c_str() + i, delimiter.c_str(), len) == 0) { out.emplace_back(start, i + len); start = i + len; i += len; matched = true; break; } } if (!matched) i++; } if (start < to) out.emplace_back(start, to); } /* * Fixed windows of max units stepping by (max - overlap) inside [b, e): * the fallback cut for atoms that exceed max in any split mode (and the * whole engine for "split": "none"). */ static void dbms_vector_text_windows(const DbmsVectorChunkUnits &units, size_t b, size_t e, const DbmsVectorChunkParams ¶ms, std::vector> &out) { size_t step = (size_t) (params.max - params.overlap); size_t start = b; while (start < e) { size_t end = units.advance(start, (size_t) params.max); if (end > e) end = e; out.emplace_back(start, end); if (end >= e) break; size_t next = units.advance(start, step); if (next <= start || next >= e) break; start = next; } } /* * Recursive splitting (the default): blank lines first, then newlines, * then word boundaries, and fixed windows as the last resort. */ static void dbms_vector_text_split_recursive(const std::string &s, size_t from, size_t to, const DbmsVectorChunkUnits &units, const DbmsVectorChunkParams ¶ms, int level, std::vector> &out) { if (from >= to) return; if (units.count(from, to) <= (size_t) params.max) { out.emplace_back(from, to); return; } std::vector> pieces; if (level == 0) dbms_vector_text_segment_blankline(s, from, to, pieces); else if (level == 1) dbms_vector_text_segment_newline(s, from, to, pieces); else if (level == 2) dbms_vector_text_segment_space(s, from, to, pieces); else { dbms_vector_text_windows(units, from, to, params, out); return; } for (const auto &piece : pieces) dbms_vector_text_split_recursive(s, piece.first, piece.second, units, params, level + 1, out); } /* * Greedy packing of atoms into chunks of at most max units, with the tail * of the previous chunk (overlap units) prepended to every following * chunk while the max invariant holds. Each pass consumes at least one * atom, so the loop always advances. */ static void dbms_vector_text_pack(const DbmsVectorChunkUnits &units, std::vector> &atoms, const DbmsVectorChunkParams ¶ms, std::vector> &chunks) { size_t i = 0; bool have_prev = false; size_t prev_start = 0; size_t prev_end = 0; while (i < atoms.size()) { size_t start = atoms[i].first; size_t end = atoms[i].second; size_t j = i + 1; while (j < atoms.size() && units.count(start, atoms[j].second) <= (size_t) params.max) { end = atoms[j].second; j++; } if (have_prev && params.overlap > 0) { size_t want = units.retreat(prev_start, prev_end, (size_t) params.overlap); if (want < start && units.count(want, end) <= (size_t) params.max) start = want; } chunks.emplace_back(start, end); prev_start = start; prev_end = end; have_prev = true; i = j; } } extern "C" char * dbms_vector_text_chunks(const char *data, size_t len, Jsonb *params) { DbmsVectorChunkParams chunk_params; dbms_vector_chunks_parse_params(params, chunk_params); std::string input(data == nullptr ? "" : data, len); std::string text = dbms_vector_text_normalize( input, chunk_params.norm_widechar, chunk_params.norm_punctuation, chunk_params.norm_whitespace); std::vector> atoms; std::vector> chunks; if (!text.empty()) { DbmsVectorChunkUnits units; units.load(text, chunk_params.by_words); switch (chunk_params.split) { case CHUNK_SPLIT_NONE: atoms.emplace_back(0, text.size()); break; case CHUNK_SPLIT_BLANKLINE: dbms_vector_text_segment_blankline(text, 0, text.size(), atoms); break; case CHUNK_SPLIT_NEWLINE: dbms_vector_text_segment_newline(text, 0, text.size(), atoms); break; case CHUNK_SPLIT_SPACE: dbms_vector_text_segment_space(text, 0, text.size(), atoms); break; case CHUNK_SPLIT_SENTENCE: dbms_vector_text_segment_sentence(text, 0, text.size(), atoms); break; case CHUNK_SPLIT_CUSTOM: dbms_vector_text_segment_custom(text, 0, text.size(), chunk_params.custom_list, atoms); break; case CHUNK_SPLIT_RECURSIVELY: dbms_vector_text_split_recursive(text, 0, text.size(), units, chunk_params, 0, atoms); break; } /* Cut oversized atoms into fixed windows first. */ std::vector> bounded; for (const auto &atom : atoms) { if (units.count(atom.first, atom.second) > (size_t) chunk_params.max) dbms_vector_text_windows(units, atom.first, atom.second, chunk_params, bounded); else bounded.push_back(atom); } dbms_vector_text_pack(units, bounded, chunk_params, chunks); } JsonbInState state; JsonbValue key; JsonbValue value; memset(&state, 0, sizeof(state)); memset(&key, 0, sizeof(key)); memset(&value, 0, sizeof(value)); pushJsonbValue(&state, WJB_BEGIN_ARRAY, nullptr); DbmsVectorChunkUnits char_units; char_units.load(text, false); for (size_t i = 0; i < chunks.size(); i++) { pushJsonbValue(&state, WJB_BEGIN_OBJECT, nullptr); key.type = jbvString; key.val.string.val = (char *) "chunk_id"; key.val.string.len = strlen("chunk_id"); pushJsonbValue(&state, WJB_KEY, &key); value.type = jbvNumeric; value.val.numeric = DatumGetNumeric(DirectFunctionCall1( int8_numeric, Int64GetDatum((int64_t) (i + 1)))); pushJsonbValue(&state, WJB_VALUE, &value); key.val.string.val = (char *) "chunk_data"; key.val.string.len = strlen("chunk_data"); pushJsonbValue(&state, WJB_KEY, &key); value.type = jbvString; value.val.string.val = (char *) text.c_str() + chunks[i].first; value.val.string.len = chunks[i].second - chunks[i].first; pushJsonbValue(&state, WJB_VALUE, &value); key.val.string.val = (char *) "chunk_length"; key.val.string.len = strlen("chunk_length"); pushJsonbValue(&state, WJB_KEY, &key); if (chunk_params.extended) { value.type = jbvNumeric; value.val.numeric = DatumGetNumeric(DirectFunctionCall1( int8_numeric, Int64GetDatum((int64_t) char_units.count( chunks[i].first, chunks[i].second)))); } else value.type = jbvNull; pushJsonbValue(&state, WJB_VALUE, &value); key.val.string.val = (char *) "chunk_offset"; key.val.string.len = strlen("chunk_offset"); pushJsonbValue(&state, WJB_KEY, &key); if (chunk_params.extended) { value.type = jbvNumeric; value.val.numeric = DatumGetNumeric(DirectFunctionCall1( int8_numeric, Int64GetDatum((int64_t) char_units.count( 0, chunks[i].first) + 1))); } else value.type = jbvNull; pushJsonbValue(&state, WJB_VALUE, &value); pushJsonbValue(&state, WJB_END_OBJECT, nullptr); } pushJsonbValue(&state, WJB_END_ARRAY, nullptr); Jsonb *result = JsonbValueToJsonb(state.result); return JsonbToCString(nullptr, &result->root, 0); } /* * palloc'd NUL-terminated copy of a counted string (jsonb string values * are not NUL-terminated). */ static char * dbms_vector_text_pstrn(const char *s, size_t len) { char *copy = (char *) palloc(len + 1); memcpy(copy, s, len); copy[len] = '\0'; return copy; } /* * UTL_TO_GENERATE_TEXT core (see dbms_vector_text.hpp): the openai * generate-text path over the shared REST/credential core. The body * shape follows the url: "v1/completions" sends {"prompt": data}, every * other url sends the chat messages with the fixed system message * (Oracle TO_OPENAI_GENERATE_TEXT parity, pls:3099-3113). Non-reserved * params keys pass through into the body (REMOVE_ORACLE_KEYS analog) and * are overwritten by the core keys when they collide. */ static char * dbms_vector_text_generate_openai(const char *data, size_t len, Jsonb *params) { DbmsVectorRestParams rest_params; dbms_vector_rest_parse_params(params, rest_params); dbms_vector_rest_check_params(rest_params); Jsonb *credential = dbms_vector_credential_lookup(rest_params.credential_name); std::string api_key = dbms_vector_rest_credential_key( credential, rest_params.credential_name); bool legacy_completions = rest_params.url.find("v1/completions") != std::string::npos; JsonbInState state; JsonbValue key; JsonbValue value; memset(&state, 0, sizeof(state)); memset(&key, 0, sizeof(key)); memset(&value, 0, sizeof(value)); pushJsonbValue(&state, WJB_BEGIN_OBJECT, nullptr); dbms_vector_rest_push_passthrough(&state, params); key.type = jbvString; key.val.string.val = (char *) "model"; key.val.string.len = strlen("model"); pushJsonbValue(&state, WJB_KEY, &key); value.type = jbvString; value.val.string.val = (char *) rest_params.model.c_str(); value.val.string.len = rest_params.model.size(); pushJsonbValue(&state, WJB_VALUE, &value); if (legacy_completions) { key.type = jbvString; key.val.string.val = (char *) "prompt"; key.val.string.len = strlen("prompt"); pushJsonbValue(&state, WJB_KEY, &key); value.type = jbvString; value.val.string.val = (char *) data; value.val.string.len = len; pushJsonbValue(&state, WJB_VALUE, &value); } else { key.type = jbvString; key.val.string.val = (char *) "messages"; key.val.string.len = strlen("messages"); pushJsonbValue(&state, WJB_KEY, &key); pushJsonbValue(&state, WJB_BEGIN_ARRAY, nullptr); pushJsonbValue(&state, WJB_BEGIN_OBJECT, nullptr); key.val.string.val = (char *) "role"; key.val.string.len = strlen("role"); pushJsonbValue(&state, WJB_KEY, &key); value.val.string.val = (char *) "system"; value.val.string.len = strlen("system"); pushJsonbValue(&state, WJB_VALUE, &value); key.val.string.val = (char *) "content"; key.val.string.len = strlen("content"); pushJsonbValue(&state, WJB_KEY, &key); value.val.string.val = (char *) "You are a helpful assistant"; value.val.string.len = strlen("You are a helpful assistant"); pushJsonbValue(&state, WJB_VALUE, &value); pushJsonbValue(&state, WJB_END_OBJECT, nullptr); pushJsonbValue(&state, WJB_BEGIN_OBJECT, nullptr); key.val.string.val = (char *) "role"; key.val.string.len = strlen("role"); pushJsonbValue(&state, WJB_KEY, &key); value.val.string.val = (char *) "user"; value.val.string.len = strlen("user"); pushJsonbValue(&state, WJB_VALUE, &value); key.val.string.val = (char *) "content"; key.val.string.len = strlen("content"); pushJsonbValue(&state, WJB_KEY, &key); value.val.string.val = (char *) data; value.val.string.len = len; pushJsonbValue(&state, WJB_VALUE, &value); pushJsonbValue(&state, WJB_END_OBJECT, nullptr); pushJsonbValue(&state, WJB_END_ARRAY, nullptr); } pushJsonbValue(&state, WJB_END_OBJECT, nullptr); Jsonb *body_jsonb = JsonbValueToJsonb(state.result); char *body = JsonbToCString(nullptr, &body_jsonb->root, 0); DbmsVectorRestResponse response = dbms_vector_rest_call(rest_params, api_key, body); pfree(body); /* * $.choices[0].text, else $.choices[0].message.content, else the * provider error (pls:3132-3139). Compute the message before * ereport: the provider-error helper may run a PG_CATCH whose * FlushErrorState would drop this ereport's frame. */ Jsonb *parsed = nullptr; PG_TRY(); { parsed = DatumGetJsonbP(DirectFunctionCall1( jsonb_in, CStringGetDatum(response.body.c_str()))); } PG_CATCH(); { FlushErrorState(); parsed = nullptr; } PG_END_TRY(); if (parsed != nullptr && JsonContainerIsObject(&parsed->root)) { JsonbValue buffer; JsonbValue *found = dbms_vector_getobjectfield(&parsed->root, "choices", &buffer); if (found != nullptr && found->type == jbvBinary && JsonContainerIsArray(found->val.binary.data)) { JsonbValue *first = getIthJsonbValueFromContainer( found->val.binary.data, 0); if (first != nullptr && first->type == jbvBinary && JsonContainerIsObject(first->val.binary.data)) { JsonbContainer *choice = first->val.binary.data; found = dbms_vector_getobjectfield(choice, "text", &buffer); if (found != nullptr && found->type == jbvString) return dbms_vector_text_pstrn(found->val.string.val, found->val.string.len); found = dbms_vector_getobjectfield(choice, "message", &buffer); if (found != nullptr && found->type == jbvBinary && JsonContainerIsObject(found->val.binary.data)) { JsonbValue content; if (dbms_vector_getobjectfield(found->val.binary.data, "content", &content) != nullptr && content.type == jbvString) return dbms_vector_text_pstrn(content.val.string.val, content.val.string.len); } } } } std::string provider_error = dbms_vector_rest_provider_error(response.body.c_str()); ereport(ERROR, (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION), errmsg("The provider returned an error: %s", provider_error.c_str()), errdetail("Oracle error: ORA-20002 (EXCP_PROVIDER_ERR)."))); return nullptr; /* not reached */ } /* * UTL_TO_GENERATE_TEXT entry: provider dispatch (pls:2943-2979). Unlike * the embedding APIs the provider is required - a missing provider is * Oracle's "You did not specify a value for the parameter provider". */ extern "C" char * dbms_vector_text_generate(const char *data, size_t len, Jsonb *params) { if (params != nullptr && !JsonContainerIsObject(¶ms->root)) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("params must be a JSON object"), errdetail("Oracle error: ORA-20003 (EXCP_GU_ERR)."))); std::string provider; if (params == nullptr || !dbms_vector_param_string(¶ms->root, "provider", "PROVIDER", provider)) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("You did not specify a value for the parameter " "provider"), errdetail("Oracle error: ORA-20003 (EXCP_GU_ERR)."))); provider = dbms_vector_ascii_lower(provider); if (provider != "openai") ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("An unsupported provider was specified: %s", provider.c_str()), errdetail("Oracle error: ORA-20003 (EXCP_GU_ERR)."), errhint("Supported providers: openai."))); return dbms_vector_text_generate_openai(data, len, params); }