- Add heading and paragraph-preserving chunking algorithms with bounded overlap - Implement OpenAI embeddings client adapter with explicit token limits and batching - Implement stage_document pipeline with strict operational limits and memory protections - Add unit and integration tests covering chunking boundaries, timeouts, and vector generation
317 lines
14 KiB
Python
317 lines
14 KiB
Python
"""One-call OpenAI-compatible REST adapter. No SDK or provider auto retries."""
|
|
from collections.abc import Sequence
|
|
from copy import deepcopy
|
|
from http.client import HTTPException
|
|
import json
|
|
import math
|
|
from queue import Queue, Empty
|
|
import re
|
|
from threading import BoundedSemaphore, Thread
|
|
import time
|
|
from urllib.error import HTTPError, URLError
|
|
from urllib.parse import urlsplit
|
|
from urllib.request import Request, HTTPRedirectHandler, build_opener
|
|
|
|
from app.modules.documents.embeddings import (
|
|
EmbeddingError, EmbeddingProviderError, EmbeddingLimits, packed_vector,
|
|
validate_embedding_profile, validate_counter, validated_limits,
|
|
is_representable_timeout, validate_endpoint_hostname,
|
|
)
|
|
|
|
_CAPACITY = BoundedSemaphore(1)
|
|
_ERROR_BODY_LIMIT = 64 * 1024
|
|
# Current official OpenAI codes + the broader/legacy quota category.
|
|
_PERMANENT_QUOTA_CODES = frozenset({
|
|
"credit_balance_exhausted", "organization_spend_limit_exceeded",
|
|
"project_spend_limit_exceeded", "organization_usage_limit_exceeded",
|
|
"insufficient_quota",
|
|
})
|
|
|
|
|
|
class TiktokenCounter:
|
|
"""Explicit encoding. Deployment must establish endpoint/model compatibility."""
|
|
def __init__(self, encoding):
|
|
import tiktoken
|
|
self.identity = "tiktoken:" + encoding
|
|
self._encoding = tiktoken.get_encoding(encoding)
|
|
|
|
def count(self, text):
|
|
return len(self._encoding.encode(text, disallowed_special=()))
|
|
|
|
|
|
def _bounded_json(content):
|
|
"""Limit structural depth before decoding; reject ambiguous/nonstandard JSON."""
|
|
text = content.decode("utf-8-sig")
|
|
depth, quoted, escaped = 0, False, False
|
|
for character in text:
|
|
if quoted:
|
|
if escaped:
|
|
escaped = False
|
|
elif character == "\\":
|
|
escaped = True
|
|
elif character == '"':
|
|
quoted = False
|
|
elif character == '"':
|
|
quoted = True
|
|
elif character in "[{":
|
|
depth += 1
|
|
if depth > 64:
|
|
raise ValueError("Excessive JSON nesting")
|
|
elif character in "]}":
|
|
depth -= 1
|
|
|
|
def unique_fields(pairs):
|
|
result = {}
|
|
for key, value in pairs:
|
|
if key in result:
|
|
raise ValueError("Duplicate JSON field")
|
|
result[key] = value
|
|
return result
|
|
|
|
def invalid_constant(value):
|
|
raise ValueError("Nonstandard JSON number")
|
|
|
|
return json.loads(text, object_pairs_hook=unique_fields, parse_constant=invalid_constant)
|
|
|
|
|
|
def _quota_exhausted(content):
|
|
if content is None:
|
|
return False
|
|
try:
|
|
native = _bounded_json(content)
|
|
error = native.get("error") if isinstance(native, dict) else None
|
|
if isinstance(error, dict):
|
|
return any(isinstance(error.get(field), str) and error[field] in _PERMANENT_QUOTA_CODES
|
|
for field in ("code", "type"))
|
|
except (ValueError, TypeError, RecursionError):
|
|
pass
|
|
return False
|
|
|
|
|
|
class _NoRedirect(HTTPRedirectHandler):
|
|
def redirect_request(self, *args, **kwargs):
|
|
return None
|
|
|
|
|
|
class _ResponseLimit(EmbeddingError):
|
|
pass
|
|
|
|
|
|
class OpenAICompatibleEmbeddings:
|
|
def __init__(self, *, profile, api_key, limits, timeout_seconds=60,
|
|
send_dimensions=False, max_response_bytes=16 * 1024 * 1024,
|
|
token_counter=None):
|
|
validate_embedding_profile(profile)
|
|
invalid = False
|
|
try:
|
|
endpoint = profile.endpoint
|
|
endpoint.encode("ascii")
|
|
parsed = urlsplit(endpoint)
|
|
is_local = parsed.scheme == "http" and parsed.hostname in ("localhost", "127.0.0.1", "::1")
|
|
if ((parsed.scheme != "https" and not is_local) or not parsed.hostname or parsed.username or parsed.password
|
|
or parsed.query or parsed.fragment or parsed.port == 0 or parsed.netloc.endswith(":")
|
|
or (":" in parsed.hostname and not parsed.netloc.startswith("["))
|
|
or not validate_endpoint_hostname(parsed.hostname)
|
|
or not re.fullmatch(r"/[A-Za-z0-9._~/-]*|", parsed.path)
|
|
or any(c.isspace() or ord(c) < 32 for c in endpoint)
|
|
or any(c in endpoint for c in ("@", "?", "#", "%", "\\", ";"))):
|
|
invalid = True
|
|
if not is_representable_timeout(timeout_seconds):
|
|
invalid = True
|
|
else:
|
|
timeout_seconds = float(timeout_seconds)
|
|
except (ValueError, TypeError, UnicodeError, OverflowError):
|
|
invalid = True
|
|
if invalid:
|
|
raise EmbeddingError("Invalid hosted embedding endpoint or timeout")
|
|
if (not isinstance(api_key, str) or not api_key
|
|
or any(not 33 <= ord(c) <= 126 for c in api_key)):
|
|
raise EmbeddingError("Embedding credentials require visible ASCII header characters")
|
|
# http.client encodes headers as Latin-1; visible ASCII is compatible and
|
|
# excludes control/header injection before any provider work.
|
|
("Bearer " + api_key).encode("ascii")
|
|
if type(max_response_bytes) is not int or max_response_bytes <= 0:
|
|
raise EmbeddingError("Bounded embedding response limit required")
|
|
if type(send_dimensions) is not bool:
|
|
raise EmbeddingError("Dimension capability must be explicit")
|
|
self._profile = deepcopy(profile)
|
|
self._key = api_key
|
|
self.limits = validated_limits(limits)
|
|
self.timeout = timeout_seconds
|
|
self.send_dimensions = send_dimensions
|
|
self.response_limit = max_response_bytes
|
|
self.counter = token_counter
|
|
validate_counter(self.counter, self.limits)
|
|
|
|
@property
|
|
def profile(self):
|
|
return self._profile
|
|
|
|
@property
|
|
def request_policy(self):
|
|
return dict(limits=self.limits.model_dump(), timeout_seconds=self.timeout,
|
|
send_dimensions=self.send_dimensions, max_response_bytes=self.response_limit)
|
|
|
|
@classmethod
|
|
def from_settings(cls, settings, *, token_counter=None):
|
|
from pydantic import SecretStr
|
|
from app.modules.documents.settings import IngestionSettings
|
|
if not isinstance(settings, IngestionSettings):
|
|
raise EmbeddingError("Valid ingestion settings required")
|
|
if not isinstance(settings.embedding_api_key, SecretStr):
|
|
raise EmbeddingError("INGEST_EMBEDDING_API_KEY is required for a hosted adapter")
|
|
if settings.embedding_limits is None:
|
|
raise EmbeddingError("Explicit endpoint-specific embedding limits required")
|
|
invalid = False
|
|
try:
|
|
profile = settings.embedding_profile
|
|
except (ValueError, TypeError, AttributeError, OverflowError):
|
|
invalid = True
|
|
if invalid:
|
|
raise EmbeddingError("Invalid configured embedding profile")
|
|
return cls(profile=profile, api_key=settings.embedding_api_key.get_secret_value(),
|
|
limits=settings.embedding_limits, timeout_seconds=settings.embedding_timeout_seconds,
|
|
send_dimensions=settings.embedding_send_dimensions,
|
|
max_response_bytes=settings.embedding_max_response_bytes, token_counter=token_counter)
|
|
|
|
def embed(self, texts):
|
|
# The port takes a bounded sequence. Do not consume an arbitrary iterator.
|
|
if not isinstance(texts, Sequence) or isinstance(texts, (str, bytes, bytearray)):
|
|
raise EmbeddingError("Embedding inputs require a bounded text sequence")
|
|
if not texts or len(texts) > self.limits.max_batch_inputs:
|
|
raise EmbeddingError("Embedding batch input limit exceeded")
|
|
identity, policy = deepcopy(self.profile), deepcopy(self.request_policy)
|
|
bounded_texts = []
|
|
for text in texts:
|
|
if len(bounded_texts) >= self.limits.max_batch_inputs:
|
|
raise EmbeddingError("Embedding batch input limit exceeded")
|
|
bounded_texts.append(text)
|
|
texts = tuple(bounded_texts)
|
|
self.limits.validate_batch(texts, self.counter)
|
|
if self.profile != identity or self.request_policy != policy:
|
|
raise EmbeddingError("Embedding profile changed during input validation")
|
|
body = dict(model=identity.model, input=texts, encoding_format="float")
|
|
if self.send_dimensions:
|
|
body["dimensions"] = identity.dimensions
|
|
request = Request(identity.endpoint.rstrip("/") + "/embeddings",
|
|
data=json.dumps(body, allow_nan=False).encode("utf-8"),
|
|
headers={"Authorization": "Bearer " + self._key, "Content-Type": "application/json"})
|
|
content = self._request_once(request)
|
|
if self.profile != identity or self.request_policy != policy:
|
|
raise EmbeddingError("Embedding profile changed during provider work")
|
|
invalid = False
|
|
try:
|
|
native = _bounded_json(content)
|
|
if native["model"] != identity.model:
|
|
raise ValueError()
|
|
data = native["data"]
|
|
if not isinstance(data, list) or len(data) != len(texts):
|
|
raise ValueError()
|
|
ordered = [None] * len(texts)
|
|
for item in data:
|
|
index = item["index"]
|
|
if type(index) is not int or not 0 <= index < len(texts) or ordered[index] is not None:
|
|
raise ValueError()
|
|
vector = item["embedding"]
|
|
if not isinstance(vector, list):
|
|
raise ValueError()
|
|
captured_vec = tuple(vector)
|
|
packed_vector(captured_vec, identity.dimensions)
|
|
ordered[index] = captured_vec
|
|
if any(v is None for v in ordered):
|
|
raise ValueError()
|
|
except (KeyError, TypeError, ValueError, OverflowError, RecursionError):
|
|
invalid = True
|
|
if invalid:
|
|
raise EmbeddingError("Invalid embedding provider response")
|
|
return tuple(ordered)
|
|
|
|
def _request_once(self, request):
|
|
deadline = time.monotonic() + self.timeout
|
|
|
|
def remaining():
|
|
left = deadline - time.monotonic()
|
|
if left <= 0:
|
|
raise EmbeddingProviderError("Embedding deadline exceeded", retryable=True)
|
|
return left
|
|
|
|
def read_body(stream, limit):
|
|
expected = getattr(stream, "length", None)
|
|
content = bytearray()
|
|
while True:
|
|
remaining()
|
|
part = stream.read(min(65536, limit + 1 - len(content)))
|
|
remaining()
|
|
if not part:
|
|
if expected is not None and len(content) != expected:
|
|
raise EmbeddingProviderError("Incomplete embedding HTTP response", retryable=True)
|
|
return bytes(content)
|
|
content.extend(part)
|
|
if len(content) > limit:
|
|
raise _ResponseLimit("Embedding response byte limit exceeded")
|
|
|
|
def collect():
|
|
failure = None
|
|
try:
|
|
with build_opener(_NoRedirect()).open(request, timeout=remaining()) as response:
|
|
return read_body(response, self.response_limit)
|
|
except HTTPError as error:
|
|
code = error.code
|
|
body = None
|
|
cleanup_failed = False
|
|
try:
|
|
if code == 429 and error.fp is not None:
|
|
try:
|
|
body = read_body(error, min(self.response_limit, _ERROR_BODY_LIMIT))
|
|
except (_ResponseLimit, EmbeddingProviderError, HTTPException, URLError, TimeoutError, OSError):
|
|
# Partial/oversized/unavailable evidence cannot establish
|
|
# a billing code. Preserve the safe status fallback.
|
|
body = None
|
|
retryable = (code in (408, 429) or 500 <= code < 600)
|
|
if code == 429 and _quota_exhausted(body):
|
|
retryable = False
|
|
finally:
|
|
try:
|
|
error.close()
|
|
except OSError:
|
|
cleanup_failed = True
|
|
remaining() # Includes error parsing and response cleanup.
|
|
failure = EmbeddingProviderError(
|
|
"Embedding provider cleanup failed" if cleanup_failed else "Embedding provider request failed",
|
|
retryable=retryable)
|
|
except (HTTPException, URLError, TimeoutError, OSError):
|
|
failure = EmbeddingProviderError("Embedding transport failed", retryable=True)
|
|
# Raise after leaving the raw exception handler so URLs, bodies and
|
|
# secret-bearing transport exceptions are not retained as context.
|
|
raise failure
|
|
|
|
outcome = Queue(maxsize=1)
|
|
def run():
|
|
try:
|
|
result = (True, collect())
|
|
except Exception as error:
|
|
# Carry unexpected programming failures to the caller unchanged;
|
|
# normalization occurs only at known transport/input boundaries.
|
|
result = (False, error)
|
|
finally:
|
|
_CAPACITY.release()
|
|
outcome.put(result)
|
|
|
|
if not _CAPACITY.acquire(blocking=False):
|
|
raise EmbeddingProviderError("Embedding transport capacity occupied", retryable=True)
|
|
try:
|
|
Thread(target=run, daemon=True, name="embedding-request").start()
|
|
except Exception as error:
|
|
_CAPACITY.release()
|
|
if isinstance(error, (OSError, RuntimeError)):
|
|
raise EmbeddingProviderError("Embedding transport unavailable", retryable=True) from None
|
|
raise
|
|
try:
|
|
success, result = outcome.get(timeout=remaining())
|
|
except Empty:
|
|
raise EmbeddingProviderError("Embedding deadline exceeded", retryable=True) from None
|
|
remaining()
|
|
if not success:
|
|
raise result
|
|
return result
|