Skip to content

Framework for orchestrating role-playing, autonomous AI agents. By fostering collaborative intelligence, CrewAI empowers agents to work together seamlessly, tackling complex tasks.

Add Oracle Integrations (#6026)

Elif Sema Balcioglu68f82f936d29
diff --git a/lib/crewai-tools/pyproject.toml b/lib/crewai-tools/pyproject.toml
index 5dc578aa1..65b185584 100644
--- a/lib/crewai-tools/pyproject.toml
+++ b/lib/crewai-tools/pyproject.toml
@@ -155,6 +155,9 @@ mongodb = [
# consumers installing crewai-tools[mongodb] get this floor.
"pymongo>=4.18.2"
]
+oracledb = [
+ "oracledb>=2.2.0"
+]
mysql = [
"pymysql>=1.1.1"
]
diff --git a/lib/crewai-tools/src/crewai_tools/__init__.py b/lib/crewai-tools/src/crewai_tools/__init__.py
index c8fd167ef..f28a49ad4 100644
--- a/lib/crewai-tools/src/crewai_tools/__init__.py
+++ b/lib/crewai-tools/src/crewai_tools/__init__.py
@@ -123,6 +123,12 @@ from crewai_tools.tools.multion_tool.multion_tool import MultiOnTool
from crewai_tools.tools.mysql_search_tool.mysql_search_tool import MySQLSearchTool
from crewai_tools.tools.nl2sql.nl2sql_tool import NL2SQLTool
from crewai_tools.tools.ocr_tool.ocr_tool import OCRTool
+from crewai_tools.tools.oracle_vector_search_tool.vector_search import (
+ OracleToolSchema,
+ OracleVectorSearchConfig,
+ OracleVectorSearchQueryConfig,
+ OracleVectorSearchTool,
+)
from crewai_tools.tools.oxylabs_amazon_product_scraper_tool.oxylabs_amazon_product_scraper_tool import (
OxylabsAmazonProductScraperTool,
)
@@ -290,6 +296,10 @@ __all__ = [
"MySQLSearchTool",
"NL2SQLTool",
"OCRTool",
+ "OracleToolSchema",
+ "OracleVectorSearchConfig",
+ "OracleVectorSearchQueryConfig",
+ "OracleVectorSearchTool",
"OxylabsAmazonProductScraperTool",
"OxylabsAmazonSearchScraperTool",
"OxylabsGoogleSearchScraperTool",
diff --git a/lib/crewai-tools/src/crewai_tools/tools/__init__.py b/lib/crewai-tools/src/crewai_tools/tools/__init__.py
index 2653490f7..d8846f718 100644
--- a/lib/crewai-tools/src/crewai_tools/tools/__init__.py
+++ b/lib/crewai-tools/src/crewai_tools/tools/__init__.py
@@ -113,6 +113,12 @@ from crewai_tools.tools.multion_tool.multion_tool import MultiOnTool
from crewai_tools.tools.mysql_search_tool.mysql_search_tool import MySQLSearchTool
from crewai_tools.tools.nl2sql.nl2sql_tool import NL2SQLTool
from crewai_tools.tools.ocr_tool.ocr_tool import OCRTool
+from crewai_tools.tools.oracle_vector_search_tool import (
+ OracleToolSchema,
+ OracleVectorSearchConfig,
+ OracleVectorSearchQueryConfig,
+ OracleVectorSearchTool,
+)
from crewai_tools.tools.oxylabs_amazon_product_scraper_tool.oxylabs_amazon_product_scraper_tool import (
OxylabsAmazonProductScraperTool,
)
@@ -274,6 +280,10 @@ __all__ = [
"MySQLSearchTool",
"NL2SQLTool",
"OCRTool",
+ "OracleToolSchema",
+ "OracleVectorSearchConfig",
+ "OracleVectorSearchQueryConfig",
+ "OracleVectorSearchTool",
"OxylabsAmazonProductScraperTool",
"OxylabsAmazonSearchScraperTool",
"OxylabsGoogleSearchScraperTool",
diff --git a/lib/crewai-tools/src/crewai_tools/tools/oracle_vector_search_tool/README.md b/lib/crewai-tools/src/crewai_tools/tools/oracle_vector_search_tool/README.md
new file mode 100644
index 000000000..d09954772
--- /dev/null
+++ b/lib/crewai-tools/src/crewai_tools/tools/oracle_vector_search_tool/README.md
@@ -0,0 +1,216 @@
+# OracleVectorSearchTool
+
+## Description
+
+This tool is specifically crafted for conducting vector searches within Oracle AI Vector Search tables. Use this tool to find semantically similar documents stored in Oracle Database.
+
+Oracle Database 23ai and later can store vectors natively and query them with `vector_distance(...)`. This tool follows CrewAI's existing vector-search tool shape while using Oracle-native SQL under the hood.
+
+## Installation
+
+Install the CrewAI tools package with Oracle support:
+
+```shell
+pip install crewai-tools[oracledb]
+```
+
+or
+
+```shell
+uv add crewai-tools --extra oracledb
+```
+
+## Example
+
+```python
+import os
+
+from crewai_tools import (
+ OracleVectorSearchConfig,
+ OracleVectorSearchQueryConfig,
+ OracleVectorSearchTool,
+)
+
+tool = OracleVectorSearchTool(
+ oracle_config=OracleVectorSearchConfig(
+ user=os.environ["ORACLE_DB_USERNAME"],
+ password=os.environ["ORACLE_DB_SECRET"],
+ dsn=os.environ["ORACLE_DB_DSN"],
+ table_name="DOCS_VECTORS",
+ limit=3,
+ distance_strategy="COSINE",
+ ),
+ query_config=OracleVectorSearchQueryConfig(
+ score_threshold=0.6,
+ filter={"source": "docs"},
+ ),
+)
+```
+
+Running a search with native JSON numeric filtering:
+
+```python
+results = tool._run(
+ query="oracle vector",
+ filter_by="priority",
+ filter_value=5,
+ score_threshold=0.6,
+)
+```
+
+Using richer Oracle-style filters:
+
+```python
+results = tool._run(
+ query="oracle vector",
+ filters='{"$or":[{"source":"docs"},{"priority":{"$gte":3}}]}',
+)
+```
+
+Using a custom embedding function:
+
+```python
+import os
+
+tool = OracleVectorSearchTool(
+ oracle_config=OracleVectorSearchConfig(
+ user=os.environ["ORACLE_DB_USERNAME"],
+ password=os.environ["ORACLE_DB_SECRET"],
+ dsn=os.environ["ORACLE_DB_DSN"],
+ table_name="DOCS_VECTORS",
+ ),
+ embedding_function=my_embedding_function,
+)
+```
+
+Passing additional `oracledb.connect()` options:
+
+```python
+import os
+
+tool = OracleVectorSearchTool(
+ oracle_config=OracleVectorSearchConfig(
+ user=os.environ["ORACLE_DB_USERNAME"],
+ password=os.environ["ORACLE_DB_SECRET"],
+ dsn=os.environ["ORACLE_DB_DSN"],
+ table_name="DOCS_VECTORS",
+ connection_kwargs={
+ "config_dir": "/path/to/wallet",
+ "wallet_location": "/path/to/wallet",
+ },
+ ),
+ embedding_function=my_embedding_function,
+)
+```
+
+Using a caller-managed connection pool:
+
+```python
+import os
+
+import oracledb
+
+pool = oracledb.create_pool(
+ user=os.environ["ORACLE_DB_USERNAME"],
+ password=os.environ["ORACLE_DB_SECRET"],
+ dsn=os.environ["ORACLE_DB_DSN"],
+ min=1,
+ max=4,
+)
+
+tool = OracleVectorSearchTool(
+ oracle_config=OracleVectorSearchConfig(table_name="DOCS_VECTORS"),
+ client=pool,
+ embedding_function=my_embedding_function,
+)
+```
+
+Preloading data into Oracle:
+
+```python
+tool.create_table()
+tool.add_texts(
+ ["CrewAI integrates with Oracle AI Vector Search."],
+ metadatas=[{"source": "docs"}],
+)
+tool.create_vector_index(
+ idx_type="HNSW",
+ params={"accuracy": 90, "neighbors": 32, "efconstruction": 200, "parallel": 8},
+)
+
+# Or create an IVF index instead.
+tool.create_vector_index(
+ index_name="DOCS_IVF_IDX",
+ idx_type="IVF",
+ params={
+ "accuracy": 90,
+ "neighbor_partitions": 32,
+ "samples_per_partition": 1,
+ "min_vectors_per_partition": 0,
+ "parallel": 8,
+ },
+)
+```
+
+## Arguments
+
+- `oracle_config`: Oracle connection and search settings. Required.
+- `query_config`: Optional default query behavior including `limit`, `score_threshold`, and Oracle-style metadata filters.
+- `embedding_function`: Optional callable used instead of OpenAI embeddings.
+- `embedding_model`: OpenAI embedding model used when `embedding_function` is not provided.
+- `dimensions`: Embedding dimension used when creating tables and validating inserted embeddings.
+
+`oracle_config` supports:
+
+- `user`, `password`, `dsn`: Common Oracle connection fields when a client is not provided.
+- `connection_kwargs`: Optional extra keyword arguments passed to `oracledb.connect()` when the tool creates the connection.
+- `table_name`: Oracle table containing your text, metadata, and vector columns.
+- `limit`: Number of search results to return.
+- `score_threshold`: Optional maximum vector distance. Only rows with `distance <= score_threshold` are returned. Negative thresholds are supported for `DOT`, which returns the negative inner product.
+- `distance_strategy`: One of `COSINE`, `EUCLIDEAN`, or `DOT`.
+- `index_name`: Optional default vector index name used by `create_vector_index()`.
+
+`create_vector_index()` supports:
+
+- `idx_type`: `HNSW` or `IVF`. Defaults to `HNSW`.
+- `params`: Oracle vector index parameters. For `HNSW`, use `accuracy`, `neighbors`, `efconstruction`, and `parallel`. For `IVF`, use `accuracy`, `neighbor_partitions`, `samples_per_partition`, `min_vectors_per_partition`, and `parallel`.
+
+`client` may be a caller-managed `oracledb.Connection` or `oracledb.ConnectionPool`. Pools must be created by the caller and passed through `client`; `OracleVectorSearchConfig` only configures single connections created with `oracledb.connect()`.
+
+Use `vector_index_exists(idx_type="IVF")` to check the default IVF index name;
+the default index type remains `HNSW`. An explicit `index_name` overrides the
+configured name and the generated default name in both creation and lookup.
+Schema-qualified index and table names are resolved independently. Unqualified
+names use the connection's current schema. Identifier casing is preserved.
+
+Metadata operators `$in`, `$nin`, and `$all` require non-empty lists.
+`$in` and `$nin` test membership for scalar fields and array elements.
+Member names containing spaces or commas are quoted in JSON paths; dots
+represent nesting and `[*]` represents an array wildcard.
+Searches exclude rows with null embeddings.
+`$all` checks each requested value independently, so an array must contain
+every requested value to match. Search limits must be positive integers.
+
+If an insertion fails, `add_texts()` rolls back that batch to a savepoint,
+preserving earlier pending work on the same connection. Successful calls
+still commit the connection. Creating a missing table uses Oracle DDL, which
+implicitly commits; create the table before starting unrelated transactions.
+
+The tool creates and expects a fixed Oracle schema:
+- `id`
+- `text`
+- `metadata` as native Oracle `JSON`
+- `embedding`
+
+`_run()` also supports:
+
+- `filters`: JSON string for richer Oracle metadata filters such as `{"$or":[{"source":"docs"},{"topic":{"$eq":"oracle"}}]}`
+- `limit`: Per-call result limit override
+- `score_threshold`: Per-call maximum distance override
+
+Result format:
+
+- `context`: The matched text payload.
+- `metadata`: Oracle JSON metadata decoded back into Python values.
+- `distance`: Raw Oracle `vector_distance(...)` value.
+- `score`: Kept for consistency with other CrewAI vector tools, but currently equal to `distance`.
diff --git a/lib/crewai-tools/src/crewai_tools/tools/oracle_vector_search_tool/__init__.py b/lib/crewai-tools/src/crewai_tools/tools/oracle_vector_search_tool/__init__.py
new file mode 100644
index 000000000..6f08c096d
--- /dev/null
+++ b/lib/crewai-tools/src/crewai_tools/tools/oracle_vector_search_tool/__init__.py
@@ -0,0 +1,14 @@
+from crewai_tools.tools.oracle_vector_search_tool.vector_search import (
+ OracleToolSchema,
+ OracleVectorSearchConfig,
+ OracleVectorSearchQueryConfig,
+ OracleVectorSearchTool,
+)
+
+
+__all__ = [
+ "OracleToolSchema",
+ "OracleVectorSearchConfig",
+ "OracleVectorSearchQueryConfig",
+ "OracleVectorSearchTool",
+]
diff --git a/lib/crewai-tools/src/crewai_tools/tools/oracle_vector_search_tool/vector_search.py b/lib/crewai-tools/src/crewai_tools/tools/oracle_vector_search_tool/vector_search.py
new file mode 100644
index 000000000..5479581fc
--- /dev/null
+++ b/lib/crewai-tools/src/crewai_tools/tools/oracle_vector_search_tool/vector_search.py
@@ -0,0 +1,994 @@
+from __future__ import annotations
+
+import array
+from collections.abc import Callable, Iterable
+from contextlib import contextmanager
+from decimal import Decimal
+import json
+import logging
+import os
+import re
+from typing import Any, Literal, cast
+import uuid
+
+from crewai.tools import BaseTool, EnvVar
+from openai import AzureOpenAI, Client
+from pydantic import BaseModel, ConfigDict, Field, model_validator
+
+
+try:
+ import oracledb
+
+ ORACLEDB_AVAILABLE = True
+except ImportError:
+ ORACLEDB_AVAILABLE = False
+ oracledb = Any # type: ignore[assignment]
+
+
+logger = logging.getLogger(__name__)
+
+_IDENTIFIER_RE = re.compile(
+ r'^(?:"[^"]+"|[A-Za-z_][A-Za-z0-9_$#]*)(?:\.(?:"[^"]+"|[A-Za-z_][A-Za-z0-9_$#]*))*$'
+)
+_JSON_PATH_RE = re.compile(r"^[A-Za-z0-9_]+(?:\.[A-Za-z0-9_]+)*$")
+_ID_COLUMN = "id"
+_TEXT_COLUMN = "text"
+_METADATA_COLUMN = "metadata"
+_EMBEDDING_COLUMN = "embedding"
+LOGICAL_MAP = {
+ "$and": (" AND ", "({0})"),
+ "$or": (" OR ", "({0})"),
+ "$nor": (" OR ", "( NOT ({0}) )"),
+}
+COMPARISON_MAP = {
+ "$exists": "",
+ "$eq": "@ == {0}",
+ "$ne": "@ != {0}",
+ "$gt": "@ > {0}",
+ "$lt": "@ < {0}",
+ "$gte": "@ >= {0}",
+ "$lte": "@ <= {0}",
+ "$between": "",
+ "$startsWith": "@ starts with {0}",
+ "$hasSubstring": "@ has substring {0}",
+ "$instr": "@ has substring {0}",
+ "$regex": "@ like_regex {0}",
+ "$like": "@ like {0}",
+ "$in": "",
+ "$nin": "",
+ "$all": "",
+ "$not": "",
+}
+NOT_OPERS = ["$nin", "$not", "$exists"]
+
+
+def _read_lob_if_needed(value: Any) -> Any:
+ """Read Oracle LOB values eagerly so downstream JSON/text handling works."""
+ if hasattr(value, "read") and callable(value.read):
+ return value.read()
+ return value
+
+
+def _normalize_json_value(value: Any) -> Any:
+ if isinstance(value, Decimal):
+ return int(value) if value == value.to_integral_value() else float(value)
+ if isinstance(value, dict):
+ return {key: _normalize_json_value(item) for key, item in value.items()}
+ if isinstance(value, list):
+ return [_normalize_json_value(item) for item in value]
+ return value
+
+
+def _is_sequence(value: Any) -> bool:
+ return isinstance(value, Iterable) and not isinstance(value, (str, bytes))
+
+
+def _is_nested_sequence(value: Any) -> bool:
+ return _is_sequence(value) and all(_is_sequence(item) for item in value)
+
+
+def _split_identifier_parts(name: str) -> list[str]:
+ parts: list[str] = []
+ current = []
+ in_quotes = False
+ for char in name:
+ if char == '"':
+ in_quotes = not in_quotes
+ current.append(char)
+ continue
+ if char == "." and not in_quotes:
+ parts.append("".join(current))
+ current = []
+ continue
+ current.append(char)
+ if current:
+ parts.append("".join(current))
+ return parts
+
+
+def _quote_identifier(name: str) -> str:
+ name = name.strip()
+ if not _IDENTIFIER_RE.fullmatch(name):
+ raise ValueError(f"Identifier '{name}' is not valid for Oracle SQL.")
+
+ quoted_parts = []
+ for part in _split_identifier_parts(name):
+ stripped = part.strip()
+ if stripped.startswith('"') and stripped.endswith('"'):
+ quoted_parts.append(stripped)
+ else:
+ quoted_parts.append(f'"{stripped}"')
+ return ".".join(quoted_parts)
+
+
+def _validate_metadata_key(metadata_key: str) -> None:
+ if not re.fullmatch(
+ r"[A-Za-z0-9_ ,]+(?:\[\*\])?(?:\.[A-Za-z0-9_ ,]+(?:\[\*\])?)*", metadata_key
+ ):
+ raise ValueError(
+ f"Invalid metadata key '{metadata_key}'. Use member names separated by '.' and optional '[*]' array wildcards."
+ )
+
+
+def _metadata_path_key(metadata_key: str) -> str:
+ """Quote member names requiring JSON path escaping while preserving nesting."""
+ _validate_metadata_key(metadata_key)
+ parts = []
+ for part in metadata_key.split("."):
+ suffix = "[*]" if part.endswith("[*]") else ""
+ name = part[:-3] if suffix else part
+ if not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", name):
+ name = json.dumps(name)
+ parts.append(name + suffix)
+ return ".".join(parts)
+
+
+def _validate_int_param(
+ config: dict[str, Any],
+ key: str,
+ min_value: int,
+ max_value: int | None = None,
+) -> None:
+ if key not in config:
+ return
+
+ value = config[key]
+ if isinstance(value, bool) or not isinstance(value, int):
+ raise ValueError(f"{key} must be an integer.")
+ if value < min_value:
+ raise ValueError(f"{key} must be at least {min_value}.")
+ if max_value is not None and value > max_value:
+ raise ValueError(f"{key} must be at most {max_value}.")
+
+
+def _validate_params(
+ config: dict[str, Any],
+ allowed_keys: set[str],
+) -> None:
+ for key in config:
+ if key not in allowed_keys:
+ raise ValueError(f"Invalid parameter: {key}")
+
+
+@contextmanager
+def _get_connection(client: Any) -> Any:
+ connection_pool_class = getattr(oracledb, "ConnectionPool", None)
+ if connection_pool_class is not None and isinstance(client, connection_pool_class):
+ with client.acquire() as connection:
+ yield connection
+ return
+
+ if hasattr(client, "cursor") and callable(client.cursor):
+ yield client
+ return
+
+ if hasattr(client, "acquire") and callable(client.acquire):
+ with client.acquire() as connection:
+ yield connection
+ return
+
+ raise TypeError(
+ "client must be an oracledb connection or connection pool compatible object."
+ )
+
+
+def _get_comparison_string(
+ oper: str, value: Any, bind_variables: list[Any]
+) -> tuple[str, str]:
+ if oper not in COMPARISON_MAP:
+ raise ValueError(f"Invalid operator: {oper}")
+
+ if COMPARISON_MAP[oper] != "":
+ bind_index = len(bind_variables)
+ bind_variables.append(value)
+ return (
+ COMPARISON_MAP[oper].format(f"$val{bind_index}"),
+ f':value{bind_index} AS "val{bind_index}"',
+ )
+
+ if oper == "$between":
+ if not isinstance(value, list) or len(value) != 2:
+ raise ValueError(
+ f"Invalid value for $between: {value}. It must be a list containing exactly 2 elements."
+ )
+
+ min_val, max_val = value
+ if min_val is None and max_val is None:
+ raise ValueError("At least one bound in $between must be non-null.")
+
+ conditions: list[str] = []
+ passings: list[str] = []
+
+ if min_val is not None:
+ bind_index = len(bind_variables)
+ bind_variables.append(min_val)
+ conditions.append(f"@ >= $val{bind_index}")
+ passings.append(f':value{bind_index} AS "val{bind_index}"')
+
+ if max_val is not None:
+ bind_index = len(bind_variables)
+ bind_variables.append(max_val)
+ conditions.append(f"@ <= $val{bind_index}")
+ passings.append(f':value{bind_index} AS "val{bind_index}"')
+
+ return " && ".join(conditions), ",".join(passings)
+
+ if oper in ["$in", "$nin"]:
+ if not isinstance(value, list) or not value:
+ raise ValueError(
+ f"Invalid value for {oper}: {value}. It must be a non-empty list."
+ )
+
+ value_binds: list[str] = []
+ membership_passings: list[str] = []
+ for current_value in value:
+ bind_index = len(bind_variables)
+ bind_variables.append(current_value)
+ value_binds.append(f"$val{bind_index}")
+ membership_passings.append(f':value{bind_index} AS "val{bind_index}"')
+
+ condition = f"@ in ({','.join(value_binds)})"
+
+ return condition, ",".join(membership_passings)
+
+ raise ValueError(f"Invalid operator: {oper}.")
+
+
+def _generate_condition(
+ metadata_key: str, value: Any, bind_variables: list[Any]
+) -> str:
+ single_mask = (
+ "JSON_EXISTS(metadata, '$.{key}?(@ {oper} $val)' "
+ 'PASSING {value_bind} AS "val")'
+ )
+ multiple_mask = "JSON_EXISTS(metadata, '$.{key}?({filters})' PASSING {passes})"
+
+ path_key = _metadata_path_key(metadata_key)
+
+ if not isinstance(value, (dict, list, tuple)):
+ bind_name = f":value{len(bind_variables)}"
+ bind_variables.append(value)
+ return single_mask.format(key=path_key, oper="==", value_bind=bind_name)
+
+ if isinstance(value, dict):
+ if not value:
+ raise ValueError("Field filters must contain at least one operator.")
+ if not all(value_key.startswith("$") for value_key in value):
+ raise ValueError("Nested metadata objects are not supported in filters.")
+
+ not_dict: dict[str, Any] = {}
+ passing_values: list[str] = []
+ comparison_values: list[str] = []
+ all_conditions: list[str] = []
+
+ for oper, current_value in value.items():
+ if oper == "$in":
+ result, passings = _get_comparison_string(
+ oper, current_value, bind_variables
+ )
+ all_conditions.append(
+ multiple_mask.format(
+ key=path_key + "[*]", filters=result, passes=passings
+ )
+ )
+ continue
+ if oper == "$all":
+ if not isinstance(current_value, list) or not current_value:
+ raise ValueError(
+ "Invalid value for $all: it must be a non-empty list."
+ )
+ for item in current_value:
+ bind_index = len(bind_variables)
+ bind_variables.append(item)
+ all_conditions.append(
+ f"JSON_EXISTS(metadata, '$.{path_key}[*]?(@ == $val)' "
+ f'PASSING :value{bind_index} AS "val")'
+ )
+ continue
+ if (
+ oper in NOT_OPERS
+ or (oper == "$eq" and isinstance(current_value, (list, dict)))
+ or (oper == "$ne" and isinstance(current_value, (list, dict)))
+ ):
+ not_dict[oper] = current_value
+ continue
+
+ result, passings = _get_comparison_string(
+ oper, current_value, bind_variables
+ )
+ comparison_values.append(result)
+ passing_values.append(passings)
+
+ if comparison_values:
+ all_conditions.append(
+ multiple_mask.format(
+ key=path_key,
+ filters=" && ".join(comparison_values),
+ passes=" , ".join(passing_values),
+ )
+ )
+
+ for oper, current_value in not_dict.items():
+ if oper == "$not":
+ all_conditions.append(
+ f"NOT ({_generate_condition(metadata_key, current_value, bind_variables)})"
+ )
+ elif oper == "$exists":
+ if not isinstance(current_value, bool):
+ raise ValueError(
+ f"Invalid value for $exists: {current_value}. It must be a boolean."
+ )
+ if current_value:
+ all_conditions.append(f"JSON_EXISTS(metadata, '$.{path_key}')")
+ else:
+ all_conditions.append(
+ f"NOT (JSON_EXISTS(metadata, '$.{path_key}'))"
+ )
+ elif oper == "$nin":
+ result, passings = _get_comparison_string(
+ oper, current_value, bind_variables
+ )
+ all_conditions.append(
+ " NOT "
+ + multiple_mask.format(
+ key=path_key + "[*]", filters=result, passes=passings
+ )
+ )
+ elif oper == "$eq":
+ bind_index = len(bind_variables)
+ bind_variables.append(json.dumps(current_value))
+ all_conditions.append(
+ f"JSON_EQUAL(JSON_QUERY(metadata, '$.{path_key}'), JSON(:value{bind_index}))"
+ )
+ elif oper == "$ne":
+ bind_index = len(bind_variables)
+ bind_variables.append(json.dumps(current_value))
+ all_conditions.append(
+ f"NOT (JSON_EQUAL(JSON_QUERY(metadata, '$.{path_key}'), JSON(:value{bind_index})))"
+ )
+
+ result = " AND ".join(all_conditions)
+ if len(all_conditions) > 1:
+ return f"({result})"
+ return result
+
+ raise ValueError("Filter format is invalid.")
+
+
+def _generate_where_clause(
+ filter_spec: dict[str, Any], bind_variables: list[Any]
+) -> str:
+ if not isinstance(filter_spec, dict):
+ raise ValueError("Filter syntax is incorrect. Must be a dictionary.")
+ if not filter_spec:
+ raise ValueError("Nested filters must be non-empty dictionaries.")
+
+ all_conditions: list[str] = []
+ for key, value in filter_spec.items():
+ if key.startswith("$"):
+ if key not in LOGICAL_MAP:
+ raise ValueError(f"'{key}' is not a recognized logical operator.")
+ if not isinstance(value, list):
+ raise ValueError("Logical operators require an array of values.")
+ if not value:
+ raise ValueError(
+ "Logical operators require a non-empty array of filters."
+ )
+ joiner, wrapper = LOGICAL_MAP[key]
+ combine_conditions = [
+ _generate_where_clause(item, bind_variables) for item in value
+ ]
+ all_conditions.append(wrapper.format(joiner.join(combine_conditions)))
+ else:
+ all_conditions.append(_generate_condition(key, value, bind_variables))
+
+ result = " AND ".join(all_conditions)
+ if len(all_conditions) > 1:
+ return f"({result})"
+ return result
+
+
+def _build_metadata_filter(
+ filter_by: str | None,
+ filter_value: Any | None,
+ filter_spec: dict[str, Any] | None = None,
+) -> tuple[str, dict[str, Any]]:
+ clauses: list[str] = []
+ bind_variables: list[Any] = []
+
+ if filter_by is None and filter_value is None:
+ simple_params: dict[str, Any] = {}
+ else:
+ if filter_by is None or filter_value is None:
+ raise ValueError("filter_by and filter_value must be provided together.")
+ if not _JSON_PATH_RE.fullmatch(filter_by):
+ raise ValueError(
+ "filter_by must reference a metadata path using letters, numbers, underscores, and dots only."
+ )
+ clauses.append(_generate_condition(filter_by, filter_value, bind_variables))
+ simple_params = {}
+
+ if filter_spec:
+ clauses.append(_generate_where_clause(filter_spec, bind_variables))
+
+ params = dict(simple_params)
+ for i, value in enumerate(bind_variables):
+ params[f"value{i}"] = value
+
+ return " AND ".join(clauses), params
+
+
+def _extract_oracle_error_code(exc: Exception) -> int | None:
+ error = getattr(exc, "args", [None])[0]
+ return getattr(error, "code", None)
+
+
+class OracleToolSchema(BaseModel):
+ query: str = Field(
+ ..., description="Query to search in the Oracle vector store - always required."
+ )
+ filter_by: str | None = Field(
+ default=None,
+ description="Metadata field path to filter by, for example 'source' or 'department.region'.",
+ )
+ filter_value: Any | None = Field(
+ default=None,
+ description="Metadata value to filter by. Must be used together with filter_by.",
+ )
+ filters: str | None = Field(
+ default=None,
+ description="Optional JSON string with Oracle-style metadata filters using operators like $and, $or, $eq, $gt, $in, or $exists.",
+ )
+ limit: int | None = Field(
+ default=None,
+ ge=1,
+ description="Optional result limit overriding the tool default for this search.",
+ )
+ score_threshold: float | None = Field(
+ default=None,
+ description="Optional maximum vector distance. Only rows with distance less than or equal to this value are returned.",
+ )
+
+
+class OracleVectorSearchQueryConfig(BaseModel):
+ """Default query behavior for Oracle vector search."""
+
+ limit: int | None = Field(default=None, ge=1)
+ score_threshold: float | None = Field(default=None)
+ filter: dict[str, Any] | None = Field(
+ default=None,
+ description="Optional Oracle-style metadata filter dictionary.",
+ )
+
+
+class OracleVectorSearchConfig(BaseModel):
+ """Oracle connection and vector search settings."""
+
+ user: str | None = None
+ password: str | None = None
+ dsn: str | None = None
+ table_name: str
+ limit: int = Field(default=3, ge=1)
+ score_threshold: float | None = Field(default=None)
+ distance_strategy: Literal["COSINE", "EUCLIDEAN", "DOT"] = "COSINE"
+ index_name: str | None = None
+ connection_kwargs: dict[str, Any] = Field(default_factory=dict)
+
+
+class OracleVectorSearchTool(BaseTool):
+ """Search Oracle AI Vector Search tables for relevant documents."""
+
+ model_config = ConfigDict(arbitrary_types_allowed=True)
+
+ name: str = "OracleVectorSearchTool"
+ description: str = (
+ "Search Oracle AI Vector Search tables for semantically relevant documents."
+ )
+ args_schema: type[BaseModel] = OracleToolSchema
+ package_dependencies: list[str] = Field(default_factory=lambda: ["oracledb"])
+ env_vars: list[EnvVar] = Field(
+ default_factory=lambda: [
+ EnvVar(
+ name="OPENAI_API_KEY",
+ description="API key for default OpenAI embeddings when embedding_function is not provided",
+ required=False,
+ )
+ ]
+ )
+ oracle_config: OracleVectorSearchConfig
+ query_config: OracleVectorSearchQueryConfig | None = Field(
+ default=None,
+ description="Optional default query behavior including filters and maximum distance threshold.",
+ )
+ embedding_model: str = Field(
+ default="text-embedding-3-large",
+ description="OpenAI embedding model used when embedding_function is not provided.",
+ )
+ dimensions: int = Field(
+ default=3072,
+ description="Embedding dimension used when creating Oracle vector tables and indexes.",
+ )
+ embedding_function: Callable[[str], list[float]] | None = Field(
+ default=None,
+ description="Optional embedding function used instead of OpenAI embeddings.",
+ )
+ client: Any | None = Field(
+ default=None, description="Optional pre-configured Oracle connection."
+ )
+ _openai_client: Any | None = None
+ _owns_client: bool = False
+
+ @model_validator(mode="after")
+ def _setup_oracle(self) -> OracleVectorSearchTool:
+ global ORACLEDB_AVAILABLE, oracledb
+
+ if not ORACLEDB_AVAILABLE:
+ try:
+ import oracledb as installed_oracledb
+ except ImportError as exc:
+ raise ImportError(
+ "The 'oracledb' package is required to use "
+ "OracleVectorSearchTool. Please install it with: uv add oracledb"
+ ) from exc
+
+ oracledb = installed_oracledb
+ ORACLEDB_AVAILABLE = True
+
+ if self.client is None:
+ connect_params = dict(self.oracle_config.connection_kwargs)
+ if self.oracle_config.user is not None:
+ connect_params["user"] = self.oracle_config.user
+ if self.oracle_config.password is not None:
+ connect_params["password"] = self.oracle_config.password
+ if self.oracle_config.dsn is not None:
+ connect_params["dsn"] = self.oracle_config.dsn
+ self.client = oracledb.connect(**connect_params)
+ self._owns_client = True
+
+ if self.embedding_function is None:
+ if "AZURE_OPENAI_ENDPOINT" in os.environ:
+ self._openai_client = AzureOpenAI()
+ elif "OPENAI_API_KEY" in os.environ:
+ self._openai_client = Client()
+ else:
+ raise ValueError(
+ "OPENAI_API_KEY environment variable is required for OracleVectorSearchTool unless embedding_function is provided."
+ )
+
+ return self
+
+ def _embed_texts(self, texts: list[str]) -> list[list[float]]:
+ if self.embedding_function is not None:
+ try:
+ batch_embedder = cast(
+ Callable[[list[str]], list[list[float]]], self.embedding_function
+ )
+ embeddings = batch_embedder(texts)
+ except (AttributeError, TypeError):
+ embeddings = None
+ else:
+ if (
+ embeddings is not None
+ and _is_nested_sequence(embeddings)
+ and len(embeddings) == len(texts)
+ ):
+ return list(embeddings)
+
+ return [self.embedding_function(text) for text in texts]
+ if self._openai_client is None:
+ raise ValueError("No embedding client is configured.")
+ return [
+ item.embedding
+ for item in self._openai_client.embeddings.create(
+ input=texts,
+ model=self.embedding_model,
+ dimensions=self.dimensions,
+ ).data
+ ]
+
+ def _table_exists(self, table_name: str) -> bool:
+ try:
+ with _get_connection(self.client) as connection:
+ with connection.cursor() as cursor:
+ # The caller validates and quotes the table identifier.
+ cursor.execute(f"SELECT 1 FROM {table_name} WHERE ROWNUM < 1") # noqa: S608
+ return True
+ except Exception as exc:
+ if _extract_oracle_error_code(exc) == 942:
+ return False
+ raise
+
+ def _index_exists(
+ self,
+ index_name: str,
+ table_name: str | None = None,
+ owner: str | None = None,
+ ) -> bool:
+ index_parts = _split_identifier_parts(_quote_identifier(index_name))
+ index_name_no_quotes = index_parts[-1].strip('"')
+ table_name_no_quotes = table_name.replace('"', "") if table_name else None
+ owner_no_quotes = owner.replace('"', "") if owner else None
+ query = """
+ SELECT index_name
+ FROM all_indexes
+ WHERE index_name = :idx_name
+ """
+ params = {"idx_name": index_name_no_quotes}
+ if len(index_parts) > 1:
+ query += " AND owner = :idx_owner"
+ params["idx_owner"] = index_parts[0].strip('"')
+ else:
+ query += " AND owner = SYS_CONTEXT('USERENV', 'CURRENT_SCHEMA')"
+ if table_name_no_quotes:
+ query += " AND table_name = :table_name"
+ params["table_name"] = table_name_no_quotes
+ if owner_no_quotes:
+ query += " AND table_owner = :table_owner"
+ params["table_owner"] = owner_no_quotes
+ else:
+ query += " AND table_owner = SYS_CONTEXT('USERENV', 'CURRENT_SCHEMA')"
+
+ with _get_connection(self.client) as connection:
+ with connection.cursor() as cursor:
+ cursor.execute(query, **params)
+ return cursor.fetchone() is not None
+
+ def table_exists(self) -> bool:
+ return self._table_exists(_quote_identifier(self.oracle_config.table_name))
+
+ def _resolve_index_name(self, index_name: str | None, idx_type: str) -> str:
+ if not isinstance(idx_type, str) or idx_type.upper() not in {"HNSW", "IVF"}:
+ raise ValueError("idx_type must be HNSW or IVF.")
+ effective_index_name = index_name or self.oracle_config.index_name
+ if effective_index_name is not None:
+ return effective_index_name
+ table_parts = _split_identifier_parts(
+ _quote_identifier(self.oracle_config.table_name)
+ )
+ base_name = table_parts[-1].strip('"')
+ # Keep dots inside quoted table names as part of the generated index name.
+ name = f"{base_name}_{idx_type.upper()}_IDX"
+ if "." in name or not _IDENTIFIER_RE.fullmatch(name):
+ return f'"{name}"'
+ return name
+
+ def vector_index_exists(
+ self,
+ index_name: str | None = None,
+ *,
+ idx_type: Literal["HNSW", "IVF"] = "HNSW",
+ ) -> bool:
+ """Check an explicit index or the default name for the requested index type."""
+ quoted_table_name = _quote_identifier(self.oracle_config.table_name)
+ table_parts = _split_identifier_parts(quoted_table_name)
+ table_name = table_parts[-1]
+ owner = table_parts[0] if len(table_parts) > 1 else None
+ effective_index_name = self._resolve_index_name(index_name, idx_type)
+ return self._index_exists(
+ _quote_identifier(effective_index_name),
+ table_name,
+ owner,
+ )
+
+ def create_table(self) -> None:
+ table_name = _quote_identifier(self.oracle_config.table_name)
+ if self._table_exists(table_name):
+ return
+
+ ddl = (
+ f"CREATE TABLE {table_name} ("
+ f"{_ID_COLUMN} VARCHAR2(64) PRIMARY KEY, "
+ f"{_TEXT_COLUMN} CLOB, "
+ f"{_METADATA_COLUMN} JSON, "
+ f"{_EMBEDDING_COLUMN} VECTOR({self.dimensions}, FLOAT32)"
+ ")"
+ )
+ with _get_connection(self.client) as connection:
+ with connection.cursor() as cursor:
+ cursor.execute(ddl)
+ connection.commit()
+
+ def create_vector_index(
+ self,
+ *,
+ index_name: str | None = None,
+ idx_type: Literal["HNSW", "IVF"] = "HNSW",
+ params: dict[str, Any] | None = None,
+ ) -> str:
+ table_name = _quote_identifier(self.oracle_config.table_name)
+ effective_index_name = self._resolve_index_name(index_name, idx_type)
+ normalized_idx_type = idx_type.upper()
+ quoted_index_name = _quote_identifier(effective_index_name)
+
+ raw_params = {} if params is None else params
+ if not isinstance(raw_params, dict):
+ raise ValueError("params must be a dictionary.")
+
+ if normalized_idx_type == "HNSW":
+ index_config = {
+ "accuracy": 90,
+ "neighbors": 32,
+ "efconstruction": 200,
+ "parallel": 8,
+ **raw_params,
+ }
+ _validate_params(
+ index_config,
+ {"accuracy", "neighbors", "efconstruction", "parallel"},
+ )
+ _validate_int_param(index_config, "accuracy", 1, 100)
+ _validate_int_param(index_config, "neighbors", 2, 2048)
+ _validate_int_param(index_config, "efconstruction", 1, 65535)
+ _validate_int_param(index_config, "parallel", 1)
+
+ ddl = (
+ f"CREATE VECTOR INDEX {quoted_index_name} "
+ f"ON {table_name}({_EMBEDDING_COLUMN}) "
+ "ORGANIZATION INMEMORY NEIGHBOR GRAPH "
+ f"DISTANCE {self.oracle_config.distance_strategy} "
+ f"WITH TARGET ACCURACY {index_config['accuracy']} "
+ f"PARAMETERS (type HNSW, neighbors {index_config['neighbors']}, "
+ f"efconstruction {index_config['efconstruction']}) "
+ f"PARALLEL {index_config['parallel']}"
+ )
+ else:
+ index_config = {
+ "accuracy": 90,
+ "neighbor_partitions": 32,
+ "parallel": 8,
+ **raw_params,
+ }
+ _validate_params(
+ index_config,
+ {
+ "accuracy",
+ "neighbor_partitions",
+ "samples_per_partition",
+ "min_vectors_per_partition",
+ "parallel",
+ },
+ )
+ _validate_int_param(index_config, "accuracy", 1, 100)
+ _validate_int_param(index_config, "neighbor_partitions", 1, 10000000)
+ _validate_int_param(index_config, "samples_per_partition", 1)
+ _validate_int_param(index_config, "min_vectors_per_partition", 0)
+ _validate_int_param(index_config, "parallel", 1)
+
+ parameters_clause = (
+ "PARAMETERS (type IVF, "
+ f"neighbor partitions {index_config['neighbor_partitions']}"
+ )
+ if "samples_per_partition" in index_config:
+ parameters_clause += (
+ f", samples_per_partition {index_config['samples_per_partition']}"
+ )
+ if "min_vectors_per_partition" in index_config:
+ parameters_clause += f", min_vectors_per_partition {index_config['min_vectors_per_partition']}"
+ parameters_clause += ")"
+
+ ddl = (
+ f"CREATE VECTOR INDEX {quoted_index_name} "
+ f"ON {table_name}({_EMBEDDING_COLUMN}) "
+ "ORGANIZATION NEIGHBOR PARTITIONS "
+ f"DISTANCE {self.oracle_config.distance_strategy} "
+ f"WITH TARGET ACCURACY {index_config['accuracy']} "
+ f"{parameters_clause} "
+ f"PARALLEL {index_config['parallel']}"
+ )
+
+ with _get_connection(self.client) as connection:
+ with connection.cursor() as cursor:
+ cursor.execute(ddl)
+ connection.commit()
+ return effective_index_name
+
+ def add_texts(
+ self,
+ texts: Iterable[str],
+ metadatas: list[dict[str, Any]] | None = None,
+ ids: list[str] | None = None,
+ ) -> list[str]:
+ text_list = list(texts)
+ if not text_list:
+ return []
+
+ metadata_list = metadatas or [{} for _ in text_list]
+ if len(metadata_list) != len(text_list):
+ raise ValueError("metadatas must match the number of texts.")
+
+ id_list = ids or [uuid.uuid4().hex for _ in text_list]
+ if len(id_list) != len(text_list):
+ raise ValueError("ids must match the number of texts.")
+
+ self.create_table()
+ embeddings = self._embed_texts(text_list)
+ if any(len(embedding) != self.dimensions for embedding in embeddings):
+ raise ValueError(
+ "Embedding dimension mismatch. Update dimensions or provide embeddings with consistent length."
+ )
+
+ # Identifiers are validated; all inserted values use bind variables.
+ insert_sql = (
+ f"INSERT INTO {_quote_identifier(self.oracle_config.table_name)} " # noqa: S608
+ f"({_ID_COLUMN}, {_TEXT_COLUMN}, {_METADATA_COLUMN}, {_EMBEDDING_COLUMN}) "
+ "VALUES (:1, :2, :3, :4)"
+ )
+
+ with _get_connection(self.client) as connection:
+ with connection.cursor() as cursor:
+ savepoint = f"crewai_{uuid.uuid4().hex[:20]}"
+ cursor.execute(f"SAVEPOINT {savepoint}")
+ cursor.setinputsizes(
+ None,
+ None,
+ oracledb.DB_TYPE_JSON,
+ oracledb.DB_TYPE_VECTOR,
+ )
+ try:
+ for doc_id, text, metadata, embedding in zip(
+ id_list, text_list, metadata_list, embeddings, strict=False
+ ):
+ cursor.execute(
+ insert_sql,
+ [doc_id, text, metadata, array.array("f", embedding)],
+ )
+ except Exception:
+ try:
+ cursor.execute(f"ROLLBACK TO SAVEPOINT {savepoint}")
+ except Exception:
+ logger.exception("Failed to roll back Oracle insertion batch")
+ raise
+ connection.commit()
+ return id_list
+
+ def _run(
+ self,
+ query: str,
+ filter_by: str | None = None,
+ filter_value: Any | None = None,
+ filters: str | None = None,
+ limit: int | None = None,
+ score_threshold: float | None = None,
+ ) -> str:
+ try:
+ table_name = _quote_identifier(self.oracle_config.table_name)
+ if not self.table_exists():
+ raise ValueError(
+ f"Table '{self.oracle_config.table_name}' does not exist. Create it first or point the tool at an existing Oracle vector table."
+ )
+
+ filter_spec: dict[str, Any] | None = None
+ if self.query_config and self.query_config.filter:
+ filter_spec = self.query_config.filter.copy()
+ if filters:
+ parsed_filters = json.loads(filters)
+ if not isinstance(parsed_filters, dict):
+ raise ValueError("filters must decode to a JSON object.")
+ filter_spec = (
+ {"$and": [filter_spec, parsed_filters]}
+ if filter_spec is not None
+ else parsed_filters
+ )
+
+ where_clause, where_params = _build_metadata_filter(
+ filter_by,
+ filter_value,
+ filter_spec,
+ )
+
+ effective_limit = (
+ limit
+ if limit is not None
+ else self.query_config.limit
+ if self.query_config and self.query_config.limit is not None
+ else self.oracle_config.limit
+ )
+ effective_score_threshold = (
+ score_threshold
+ if score_threshold is not None
+ else self.query_config.score_threshold
+ if self.query_config and self.query_config.score_threshold is not None
+ else self.oracle_config.score_threshold
+ )
+
+ if type(effective_limit) is not int or effective_limit < 1:
+ raise ValueError("limit must be a positive integer.")
+
+ query_vector = array.array("f", self._embed_texts([query])[0])
+ # Identifiers and filters are validated; metric and limit come from
+ # typed config/tool inputs. Vector and metadata values use binds.
+ search_sql = f"""
+ SELECT
+ {_TEXT_COLUMN},
+ {_METADATA_COLUMN},
+ vector_distance(
+ {_EMBEDDING_COLUMN},
+ :embedding,
+ {self.oracle_config.distance_strategy}
+ ) AS distance
+ FROM {table_name}
+ WHERE {_EMBEDDING_COLUMN} IS NOT NULL
+ {"AND (" + where_clause + ")" if where_clause else ""}
+ ORDER BY distance
+ FETCH APPROX FIRST :result_limit ROWS ONLY
+ """ # noqa: S608
+
+ with _get_connection(self.client) as connection:
+ with connection.cursor() as cursor:
+ params = {
+ "embedding": query_vector,
+ "result_limit": effective_limit,
+ **where_params,
+ }
+ cursor.execute(search_sql, params)
+ rows = cursor.fetchall()
+
+ formatted_rows = []
+ for text, metadata, distance in rows:
+ if distance is None:
+ continue
+ text = _read_lob_if_needed(text)
+ metadata = _read_lob_if_needed(metadata)
+ distance_value = float(distance)
+
+ if (
+ effective_score_threshold is not None
+ and distance_value > effective_score_threshold
+ ):
+ continue
+
+ metadata_dict: dict[str, Any]
+ if isinstance(metadata, str) and metadata:
+ metadata_dict = _normalize_json_value(json.loads(metadata))
+ else:
+ metadata_dict = _normalize_json_value(metadata or {})
+
+ formatted_rows.append(
+ {
+ "distance": distance_value,
+ "score": distance_value,
+ "metadata": metadata_dict,
+ "context": text or "",
+ }
+ )
+
+ return json.dumps(formatted_rows, indent=2)
+ except Exception as exc:
+ logger.error("Oracle vector search failed: %s", exc)
+ return ""
+
+ def __del__(self) -> None:
+ try:
+ client = getattr(self, "client", None)
+ if getattr(self, "_owns_client", False) and client is not None:
+ client.close()
+ except Exception as exc:
+ if "DPY-1001" not in str(exc):
+ logger.error("Failed to close Oracle client: %s", exc)
+
+ try:
+ openai_client = getattr(self, "_openai_client", None)
+ if openai_client is not None:
+ openai_client.close()
+ except Exception as exc:
+ logger.error("Failed to close OpenAI client: %s", exc)
diff --git a/lib/crewai-tools/tests/tools/test_oracle_vector_search_tool.py b/lib/crewai-tools/tests/tools/test_oracle_vector_search_tool.py
new file mode 100644
index 000000000..96c7c91a3
--- /dev/null
+++ b/lib/crewai-tools/tests/tools/test_oracle_vector_search_tool.py
@@ -0,0 +1,1521 @@
+import importlib.util
+import json
+from decimal import Decimal
+import os
+from pathlib import Path
+import sys
+from types import SimpleNamespace
+from typing import Any
+import uuid
+
+from crewai_tools import (
+ OracleVectorSearchConfig,
+ OracleVectorSearchQueryConfig,
+ OracleVectorSearchTool,
+)
+import pytest
+
+from crewai_tools.tools.oracle_vector_search_tool import vector_search as vs
+from crewai_tools.tools.oracle_vector_search_tool.vector_search import _quote_identifier
+
+
+ORACLE_USERNAME_ENV = "VECDB_USER"
+ORACLE_PASS_ENV = "VECDB_PASS"
+ORACLE_DSN_ENV = "VECDB_HOST"
+
+
+class FakeOracleError(Exception):
+ def __init__(self, code: int):
+ super().__init__()
+ self.args = [SimpleNamespace(code=code)]
+
+
+class FakeCursor:
+ def __init__(
+ self,
+ fetchall_result=None,
+ fetchone_result=None,
+ execute_side_effects=None,
+ ):
+ self.fetchall_result = fetchall_result or []
+ self.fetchone_result = fetchone_result
+ self.execute_side_effects = list(execute_side_effects or [])
+ self.executed = []
+ self.inputsizes = None
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, exc_type, exc, tb):
+ return False
+
+ def setinputsizes(self, *args):
+ self.inputsizes = args
+
+ def execute(self, sql, params=None, **kwargs):
+ self.executed.append((sql, params, kwargs))
+ if self.execute_side_effects:
+ side_effect = self.execute_side_effects.pop(0)
+ if side_effect is not None:
+ raise side_effect
+
+ def fetchall(self):
+ return self.fetchall_result
+
+ def fetchone(self):
+ return self.fetchone_result
+
+
+class FakeConnection:
+ def __init__(self, cursors=None):
+ self.cursors = list(cursors or [])
+ self.commit_count = 0
+ self.closed = False
+
+ def cursor(self):
+ return self.cursors.pop(0)
+
+ def commit(self):
+ self.commit_count += 1
+
+ def close(self):
+ self.closed = True
+
+
+class FakePoolAcquire:
+ def __init__(self, connection):
+ self.connection = connection
+
+ def __enter__(self):
+ return self.connection
+
+ def __exit__(self, exc_type, exc, tb):
+ return False
+
+
+class FakeConnectionPool:
+ def __init__(self, connection):
+ self.connection = connection
+ self.acquire_count = 0
+ self.closed = False
+
+ def acquire(self):
+ self.acquire_count += 1
+ return FakePoolAcquire(self.connection)
+
+ def close(self):
+ self.closed = True
+
+
+class FakeOracleModule:
+ DB_TYPE_JSON = object()
+ DB_TYPE_VECTOR = object()
+
+ def __init__(self, connection=None):
+ self.connection = connection
+ self.connect_calls = []
+
+ def connect(self, **kwargs):
+ self.connect_calls.append(kwargs)
+ return self.connection or FakeConnection()
+
+
+class FakeEmbeddingsClient:
+ def __init__(self, embeddings):
+ self.embeddings = embeddings
+ self.closed = False
+
+ def close(self):
+ self.closed = True
+
+
+class CloseError:
+ def __init__(self, message: str):
+ self.message = message
+
+ def close(self):
+ raise RuntimeError(self.message)
+
+
+class FakeLob:
+ def __init__(self, value):
+ self.value = value
+
+ def read(self):
+ return self.value
+
+
+def _oracle_env_config() -> tuple[str, str, str] | None:
+ username = os.getenv(ORACLE_USERNAME_ENV)
+ password = os.getenv(ORACLE_PASS_ENV)
+ dsn = os.getenv(ORACLE_DSN_ENV)
+ if not username or not password or not dsn:
+ return None
+ return username, password, dsn
+
+
+def _embed_text(text: str) -> list[float]:
+ lowered = text.lower()
+ return [
+ 1.0 if "oracle" in lowered else 0.0,
+ 1.0 if "crewai" in lowered else 0.0,
+ 1.0 if "vector" in lowered else 0.0,
+ ]
+
+
+def _cleanup_real_tool(tool: OracleVectorSearchTool) -> None:
+ table_name = tool.oracle_config.table_name
+ try:
+ with tool.client.cursor() as cursor:
+ cursor.execute(f'DROP TABLE "{table_name}" PURGE')
+ tool.client.commit()
+ except Exception:
+ pass
+
+ openai_client = getattr(tool, "_openai_client", None)
+ if openai_client is not None:
+ try:
+ openai_client.close()
+ except Exception:
+ pass
+
+ client = getattr(tool, "client", None)
+ if client is not None:
+ try:
+ client.close()
+ except Exception:
+ pass
+
+
+def make_tool(**kwargs):
+ defaults = {
+ "oracle_config": OracleVectorSearchConfig(table_name="docs_vectors"),
+ "client": FakeConnection(),
+ "embedding_function": lambda text: [float(len(text))],
+ "dimensions": 1,
+ }
+ defaults.update(kwargs)
+ return OracleVectorSearchTool(**defaults)
+
+
+def oracle_tool():
+ creds = _oracle_env_config()
+ if creds is not None:
+ username, password, dsn = creds
+ table_name = f"CREWAI_ORACLE_UNIT_{uuid.uuid4().hex[:12].upper()}"
+ tool = OracleVectorSearchTool(
+ oracle_config=OracleVectorSearchConfig(
+ user=username,
+ password=password,
+ dsn=dsn,
+ table_name=table_name,
+ limit=2,
+ distance_strategy="COSINE",
+ ),
+ embedding_function=_embed_text,
+ dimensions=3,
+ )
+ try:
+ tool.create_table()
+ tool.add_texts(
+ [
+ "Oracle vector guide",
+ "CrewAI onboarding",
+ ],
+ metadatas=[
+ {"source": "docs", "priority": 5},
+ {"source": "crew", "priority": 1},
+ ],
+ )
+ yield tool
+ finally:
+ _cleanup_real_tool(tool)
+ return
+
+ existence_cursor = FakeCursor()
+ search_cursor = FakeCursor(
+ fetchall_result=[
+ ("CrewAI docs", '{"source": "docs"}', Decimal("0.12")),
+ ]
+ )
+ client = FakeConnection([existence_cursor, search_cursor])
+ tool = OracleVectorSearchTool(
+ oracle_config=OracleVectorSearchConfig(
+ table_name="docs_vectors",
+ limit=2,
+ ),
+ client=client,
+ embedding_function=lambda _: [0.1, 0.2, 0.3],
+ )
+ yield tool
+
+
+def test_successful_query_execution(oracle_tool):
+ results = json.loads(
+ oracle_tool._run(
+ query="oracle vector search", filter_by="source", filter_value="docs"
+ )
+ )
+
+ assert len(results) >= 1
+ assert results[0]["metadata"]["source"] == "docs"
+ assert results[0]["context"]
+ assert results[0]["score"] == pytest.approx(results[0]["distance"])
+
+ if isinstance(oracle_tool.client, FakeConnection):
+ assert results[0]["context"] == "CrewAI docs"
+ assert results[0]["score"] == pytest.approx(0.12)
+ assert results[0]["distance"] == pytest.approx(0.12)
+
+
+def test_query_config_filters_results_by_score_threshold():
+ creds = _oracle_env_config()
+ if creds is not None:
+ username, password, dsn = creds
+ table_name = f"CREWAI_ORACLE_THRESH_{uuid.uuid4().hex[:12].upper()}"
+ tool = OracleVectorSearchTool(
+ oracle_config=OracleVectorSearchConfig(
+ user=username,
+ password=password,
+ dsn=dsn,
+ table_name=table_name,
+ distance_strategy="COSINE",
+ ),
+ query_config=OracleVectorSearchQueryConfig(score_threshold=0.5),
+ embedding_function=_embed_text,
+ dimensions=3,
+ )
+ try:
+ tool.create_table()
+ tool.add_texts(
+ ["Oracle vector guide", "CrewAI onboarding"],
+ metadatas=[
+ {"source": "docs"},
+ {"source": "crew"},
+ ],
+ )
+ results = json.loads(tool._run(query="oracle vector"))
+ assert len(results) >= 1
+ assert all(result["distance"] <= 0.5 for result in results)
+ assert results[0]["metadata"]["source"] == "docs"
+ finally:
+ _cleanup_real_tool(tool)
+ return
+
+ existence_cursor = FakeCursor()
+ search_cursor = FakeCursor(
+ fetchall_result=[
+ ("CrewAI docs", '{"source": "docs"}', 0.1),
+ ("Low relevance", '{"source": "other"}', 10.0),
+ ]
+ )
+ client = FakeConnection([existence_cursor, search_cursor])
+ tool = OracleVectorSearchTool(
+ oracle_config=OracleVectorSearchConfig(table_name="docs_vectors"),
+ query_config=OracleVectorSearchQueryConfig(score_threshold=0.5),
+ client=client,
+ embedding_function=lambda _: [0.1, 0.2, 0.3],
+ )
+
+ results = json.loads(tool._run(query="oracle vector search"))
+
+ assert len(results) == 1
+ assert results[0]["metadata"]["source"] == "docs"
+ assert results[0]["distance"] <= 0.5
+
+
+def test_simple_filter_preserves_native_json_numeric_type():
+ creds = _oracle_env_config()
+ if creds is not None:
+ username, password, dsn = creds
+ table_name = f"CREWAI_ORACLE_FILTER_{uuid.uuid4().hex[:12].upper()}"
+ tool = OracleVectorSearchTool(
+ oracle_config=OracleVectorSearchConfig(
+ user=username,
+ password=password,
+ dsn=dsn,
+ table_name=table_name,
+ distance_strategy="COSINE",
+ ),
+ embedding_function=_embed_text,
+ dimensions=3,
+ )
+ try:
+ tool.create_table()
+ tool.add_texts(
+ ["Oracle vector guide", "CrewAI onboarding"],
+ metadatas=[
+ {"source": "docs", "priority": 3},
+ {"source": "crew", "priority": 1},
+ ],
+ )
+ results = json.loads(
+ tool._run(
+ query="oracle vector search",
+ filter_by="priority",
+ filter_value=3,
+ )
+ )
+ assert len(results) >= 1
+ assert all(result["metadata"]["priority"] == 3 for result in results)
+ finally:
+ _cleanup_real_tool(tool)
+ return
+
+ existence_cursor = FakeCursor()
+ search_cursor = FakeCursor(fetchall_result=[])
+ client = FakeConnection([existence_cursor, search_cursor])
+ tool = OracleVectorSearchTool(
+ oracle_config=OracleVectorSearchConfig(table_name="docs_vectors"),
+ client=client,
+ embedding_function=lambda _: [0.1, 0.2, 0.3],
+ )
+
+ tool._run(query="oracle vector search", filter_by="priority", filter_value=3)
+
+ executed_sql, params, _ = search_cursor.executed[0]
+ assert "JSON_EXISTS(metadata, '$.priority?(@ == $val)'" in executed_sql
+ assert params["value0"] == 3
+
+
+def test_run_normalizes_decimal_metadata_values():
+ existence_cursor = FakeCursor()
+ search_cursor = FakeCursor(
+ fetchall_result=[
+ ("CrewAI docs", {"priority": Decimal("5"), "ratio": Decimal("0.25")}, 0.1),
+ ]
+ )
+ client = FakeConnection([existence_cursor, search_cursor])
+ tool = OracleVectorSearchTool(
+ oracle_config=OracleVectorSearchConfig(table_name="docs_vectors"),
+ client=client,
+ embedding_function=lambda _: [0.1, 0.2, 0.3],
+ )
+
+ results = json.loads(tool._run(query="oracle vector search"))
+
+ assert results[0]["metadata"]["priority"] == 5
+ assert results[0]["metadata"]["ratio"] == pytest.approx(0.25)
+
+
+def test_per_call_score_threshold_filters_by_max_distance():
+ creds = _oracle_env_config()
+ if creds is not None:
+ username, password, dsn = creds
+ table_name = f"CREWAI_ORACLE_CALLTH_{uuid.uuid4().hex[:12].upper()}"
+ tool = OracleVectorSearchTool(
+ oracle_config=OracleVectorSearchConfig(
+ user=username,
+ password=password,
+ dsn=dsn,
+ table_name=table_name,
+ distance_strategy="COSINE",
+ ),
+ embedding_function=_embed_text,
+ dimensions=3,
+ )
+ try:
+ tool.create_table()
+ tool.add_texts(
+ ["Oracle vector guide", "CrewAI onboarding"],
+ metadatas=[
+ {"source": "docs"},
+ {"source": "crew"},
+ ],
+ )
+ results = json.loads(
+ tool._run(query="oracle vector search", score_threshold=0.5)
+ )
+ assert len(results) >= 1
+ assert all(result["distance"] <= 0.5 for result in results)
+ assert results[0]["metadata"]["source"] == "docs"
+ finally:
+ _cleanup_real_tool(tool)
+ return
+
+ existence_cursor = FakeCursor()
+ search_cursor = FakeCursor(
+ fetchall_result=[
+ ("Near match", '{"source": "docs"}', 0.2),
+ ("Far match", '{"source": "docs"}', 0.8),
+ ]
+ )
+ client = FakeConnection([existence_cursor, search_cursor])
+ tool = OracleVectorSearchTool(
+ oracle_config=OracleVectorSearchConfig(table_name="docs_vectors"),
+ client=client,
+ embedding_function=lambda _: [0.1, 0.2, 0.3],
+ )
+
+ results = json.loads(tool._run(query="oracle vector search", score_threshold=0.5))
+
+ assert [result["context"] for result in results] == ["Near match"]
+ assert results[0]["score"] == pytest.approx(0.2)
+
+
+def test_filters_json_builds_oracle_where_clause():
+ existence_cursor = FakeCursor()
+ search_cursor = FakeCursor(fetchall_result=[])
+ client = FakeConnection([existence_cursor, search_cursor])
+ tool = OracleVectorSearchTool(
+ oracle_config=OracleVectorSearchConfig(table_name="docs_vectors"),
+ client=client,
+ embedding_function=lambda _: [0.1, 0.2, 0.3],
+ )
+
+ tool._run(
+ query="oracle vector search",
+ filters=json.dumps(
+ {
+ "$or": [
+ {"source": "docs"},
+ {"priority": {"$gte": 3}},
+ ]
+ }
+ ),
+ )
+
+ executed_sql, params, _ = search_cursor.executed[0]
+ assert "JSON_EXISTS(metadata, '$.source?(@ == $val)'" in executed_sql
+ assert "JSON_EXISTS(metadata, '$.priority?(@ >= $val" in executed_sql
+ assert 3 in params.values()
+
+
[email protected]("failure_stage", ["create_table", "add_texts"])
+ "case",
+ [
+ "fixture",
+ "test_query_config_filters_results_by_score_threshold",
+ "test_simple_filter_preserves_native_json_numeric_type",
+ "test_per_call_score_threshold_filters_by_max_distance",
+ ],
+)
+def test_real_setup_failure_closes_connection(monkeypatch, failure_stage, case):
+ tool = make_tool(client=FakeConnection())
+
+ def fail(*args, **kwargs):
+ raise RuntimeError("setup failed")
+
+ monkeypatch.setattr(OracleVectorSearchTool, "create_table", lambda self: None)
+ monkeypatch.setattr(OracleVectorSearchTool, "add_texts", lambda *a, **kw: None)
+ monkeypatch.setattr(OracleVectorSearchTool, failure_stage, fail)
+ monkeypatch.setitem(
+ globals(), "_oracle_env_config", lambda: ("user", "pass", "dsn")
+ )
+ monkeypatch.setitem(globals(), "OracleVectorSearchTool", lambda **kw: tool)
+
+ with pytest.raises(RuntimeError, match="setup failed"):
+ if case == "fixture":
+ next(oracle_tool.__wrapped__())
+ else:
+ globals()[case]()
+
+ assert tool.client.closed
+
+
+def test_create_vector_index():
+ index_cursor = FakeCursor()
+ oracle_tool = make_tool(client=FakeConnection([index_cursor]))
+
+ index_name = oracle_tool.create_vector_index(
+ index_name="docs_vec_idx",
+ params={"accuracy": 80, "neighbors": 64, "efconstruction": 300, "parallel": 4},
+ )
+
+ assert index_name == "docs_vec_idx"
+ assert oracle_tool.client.commit_count == 1
+ ddl = index_cursor.executed[0][0]
+ assert "CREATE VECTOR INDEX" in ddl
+ assert "ORGANIZATION INMEMORY NEIGHBOR GRAPH" in ddl
+ assert "WITH TARGET ACCURACY 80" in ddl
+ assert "PARAMETERS (type HNSW, neighbors 64, efconstruction 300)" in ddl
+ assert "PARALLEL 4" in ddl
+
+
+def test_create_vector_index_creates_ivf_index():
+ index_cursor = FakeCursor()
+ client = FakeConnection([index_cursor])
+ tool = make_tool(client=client)
+
+ index_name = tool.create_vector_index(
+ index_name="docs_ivf_idx",
+ idx_type="IVF",
+ params={
+ "accuracy": 70,
+ "neighbor_partitions": 128,
+ "samples_per_partition": 10,
+ "min_vectors_per_partition": 0,
+ "parallel": 2,
+ },
+ )
+
+ assert index_name == "docs_ivf_idx"
+ assert client.commit_count == 1
+ ddl = index_cursor.executed[0][0]
+ assert "CREATE VECTOR INDEX" in ddl
+ assert "ORGANIZATION NEIGHBOR PARTITIONS" in ddl
+ assert "WITH TARGET ACCURACY 70" in ddl
+ assert (
+ "PARAMETERS (type IVF, neighbor partitions 128, "
+ "samples_per_partition 10, min_vectors_per_partition 0)"
+ ) in ddl
+ assert "PARALLEL 2" in ddl
+
+
+ ("idx_type", "params", "message"),
+ [
+ ("HNSW", {"accuracy": 0}, "accuracy must be at least 1"),
+ ("HNSW", {"accuracy": 101}, "accuracy must be at most 100"),
+ ("HNSW", {"accuracy": "90"}, "accuracy must be an integer"),
+ ("HNSW", {"neighbors": 1}, "neighbors must be at least 2"),
+ ("HNSW", {"neighbors": 2049}, "neighbors must be at most 2048"),
+ ("HNSW", {"neighbors": "32"}, "neighbors must be an integer"),
+ ("HNSW", {"efconstruction": 0}, "efconstruction must be at least 1"),
+ ("HNSW", {"efconstruction": 65536}, "efconstruction must be at most 65535"),
+ ("HNSW", {"efconstruction": "200"}, "efconstruction must be an integer"),
+ ("HNSW", {"parallel": 0}, "parallel must be at least 1"),
+ ("HNSW", {"parallel": "8 NOLOGGING"}, "parallel must be an integer"),
+ ("HNSW", {"parallel": True}, "parallel must be an integer"),
+ ("HNSW", {"neighbor_partitions": 32}, "Invalid parameter: neighbor_partitions"),
+ ("HNSW", {"idx_type": "HNSW"}, "Invalid parameter: idx_type"),
+ ("IVF", {"accuracy": 0}, "accuracy must be at least 1"),
+ ("IVF", {"accuracy": 101}, "accuracy must be at most 100"),
+ ("IVF", {"neighbor_partitions": 0}, "neighbor_partitions must be at least 1"),
+ (
+ "IVF",
+ {"neighbor_partitions": 10000001},
+ "neighbor_partitions must be at most 10000000",
+ ),
+ (
+ "IVF",
+ {"neighbor_partitions": "32"},
+ "neighbor_partitions must be an integer",
+ ),
+ (
+ "IVF",
+ {"samples_per_partition": 0},
+ "samples_per_partition must be at least 1",
+ ),
+ (
+ "IVF",
+ {"samples_per_partition": "10"},
+ "samples_per_partition must be an integer",
+ ),
+ (
+ "IVF",
+ {"min_vectors_per_partition": -1},
+ "min_vectors_per_partition must be at least 0",
+ ),
+ (
+ "IVF",
+ {"min_vectors_per_partition": "0"},
+ "min_vectors_per_partition must be an integer",
+ ),
+ ("IVF", {"parallel": 0}, "parallel must be at least 1"),
+ ("IVF", {"neighbors": 32}, "Invalid parameter: neighbors"),
+ ("IVF", {"idx_type": "IVF"}, "Invalid parameter: idx_type"),
+ ],
+)
+def test_create_vector_index_validates_parameters(
+ monkeypatch, idx_type, params, message
+):
+ monkeypatch.setattr(vs, "oracledb", FakeOracleModule())
+ monkeypatch.setattr(vs, "ORACLEDB_AVAILABLE", True)
+ index_cursor = FakeCursor()
+ client = FakeConnection([index_cursor])
+ tool = make_tool(client=client)
+
+ with pytest.raises(ValueError, match=message):
+ tool.create_vector_index(idx_type=idx_type, params=params)
+
+ assert index_cursor.executed == []
+ assert client.commit_count == 0
+
+
+def test_create_vector_index_rejects_invalid_idx_type(monkeypatch):
+ monkeypatch.setattr(vs, "oracledb", FakeOracleModule())
+ monkeypatch.setattr(vs, "ORACLEDB_AVAILABLE", True)
+ tool = make_tool(client=FakeConnection([FakeCursor()]))
+
+ with pytest.raises(ValueError, match="idx_type must be HNSW or IVF"):
+ tool.create_vector_index(idx_type="FLAT")
+
+ with pytest.raises(ValueError, match="idx_type must be HNSW or IVF"):
+ tool.create_vector_index(idx_type=1)
+
+
+def test_create_vector_index_rejects_non_dict_params(monkeypatch):
+ monkeypatch.setattr(vs, "oracledb", FakeOracleModule())
+ monkeypatch.setattr(vs, "ORACLEDB_AVAILABLE", True)
+ index_cursor = FakeCursor()
+ client = FakeConnection([index_cursor])
+ tool = make_tool(client=client)
+
+ with pytest.raises(ValueError, match="params must be a dictionary"):
+ tool.create_vector_index(params=[])
+
+ assert index_cursor.executed == []
+ assert client.commit_count == 0
+
+
+def test_table_and_index_exists_helpers():
+ table_cursor = FakeCursor()
+ index_cursor = FakeCursor(fetchone_result=("DOCS_VEC_IDX",))
+ client = FakeConnection([table_cursor, index_cursor])
+ tool = OracleVectorSearchTool(
+ oracle_config=OracleVectorSearchConfig(
+ table_name="docs_vectors",
+ index_name="DOCS_VEC_IDX",
+ ),
+ client=client,
+ embedding_function=lambda _: [0.1, 0.2, 0.3],
+ )
+
+ assert tool.table_exists() is True
+ assert tool.vector_index_exists() is True
+
+
+def test_add_texts_creates_table_and_inserts_rows(monkeypatch):
+ monkeypatch.setattr(vs, "oracledb", FakeOracleModule())
+ existence_cursor = FakeCursor(execute_side_effects=[FakeOracleError(942)])
+ create_table_cursor = FakeCursor()
+ insert_cursor = FakeCursor()
+ client = FakeConnection([existence_cursor, create_table_cursor, insert_cursor])
+ tool = OracleVectorSearchTool(
+ oracle_config=OracleVectorSearchConfig(table_name="docs_vectors"),
+ client=client,
+ embedding_function=lambda _: [0.1, 0.2, 0.3],
+ dimensions=3,
+ )
+
+ ids = tool.add_texts(["hello"], metadatas=[{"source": "docs"}], ids=["abc"])
+
+ assert ids == ["abc"]
+ assert client.commit_count == 2
+ assert insert_cursor.inputsizes[-1] is FakeOracleModule.DB_TYPE_VECTOR
+ assert "INSERT INTO" in insert_cursor.executed[1][0]
+
+
[email protected]("limit", [0, -1])
+ "model",
+ [vs.OracleToolSchema, OracleVectorSearchConfig, OracleVectorSearchQueryConfig],
+)
+def test_limit_models_reject_nonpositive_values(model, limit):
+ from pydantic import ValidationError
+
+ with pytest.raises(ValidationError):
+ model(query="query", table_name="docs", limit=limit)
+
+
[email protected]("limit", [0, -1, True, 1.5, "1; DROP TABLE docs"])
+def test_direct_run_rejects_invalid_limit(limit, caplog):
+ connection = FakeConnection([FakeCursor()])
+ tool = make_tool(client=connection)
+ assert tool._run(query="query", limit=limit) == ""
+ assert "limit must be a positive integer" in caplog.text
+ assert connection.commit_count == 0
+
+
+def test_all_filter_uses_independent_array_membership_checks():
+ binds = []
+ sql = vs._generate_condition("tags", {"$all": ["red", "blue"]}, binds)
+ assert sql.count("JSON_EXISTS") == 2
+ assert " AND " in sql
+ assert "$.tags[*]" in sql
+ assert binds == ["red", "blue"]
+
+
[email protected]("pooled", [False, True])
+def test_failed_batch_rolls_back_to_its_savepoint(monkeypatch, pooled):
+ error = FakeOracleError(1)
+ cursor = FakeCursor(execute_side_effects=[None, None, error, None])
+ connection = FakeConnection([cursor])
+ tool = make_tool(client=FakeConnectionPool(connection) if pooled else connection)
+ monkeypatch.setattr(OracleVectorSearchTool, "create_table", lambda self: None)
+ with pytest.raises(FakeOracleError) as caught:
+ tool.add_texts(["first", "second"])
+ assert caught.value is error
+ savepoint = cursor.executed[0][0].removeprefix("SAVEPOINT ")
+ assert cursor.executed[-1][0] == f"ROLLBACK TO SAVEPOINT {savepoint}"
+ assert connection.commit_count == 0
+ assert not connection.closed
+
+
+def test_run_returns_empty_string_on_error():
+ missing_table_cursor = FakeCursor(execute_side_effects=[FakeOracleError(942)])
+ client = FakeConnection([missing_table_cursor])
+ tool = OracleVectorSearchTool(
+ oracle_config=OracleVectorSearchConfig(table_name="missing_vectors"),
+ client=client,
+ embedding_function=lambda _: [0.1, 0.2, 0.3],
+ )
+
+ assert tool._run(query="oracle") == ""
+
+
+def test_quote_identifier_preserves_caller_casing():
+ assert _quote_identifier("docs_vectors") == '"docs_vectors"'
+ assert _quote_identifier("MySchema.docs_vectors") == '"MySchema"."docs_vectors"'
+
+
+def test_module_handles_missing_oracledb_import(monkeypatch):
+ import builtins
+
+ module_path = Path(vs.__file__)
+ spec = importlib.util.spec_from_file_location(
+ "vector_search_missing_oracledb", module_path
+ )
+ module = importlib.util.module_from_spec(spec)
+ original_import = builtins.__import__
+
+ def fake_import(name, globals=None, locals=None, fromlist=(), level=0):
+ if name == "oracledb":
+ raise ImportError("missing oracledb")
+ return original_import(name, globals, locals, fromlist, level)
+
+ monkeypatch.setattr(builtins, "__import__", fake_import)
+ assert spec.loader is not None
+ spec.loader.exec_module(module)
+
+ assert module.ORACLEDB_AVAILABLE is False
+ assert module.oracledb is Any
+
+
+def test_setup_oracle_missing_oracledb_raises_without_prompt(monkeypatch):
+ import builtins
+
+ original_import = builtins.__import__
+
+ def fake_import(name, globals=None, locals=None, fromlist=(), level=0):
+ if name == "oracledb":
+ raise ImportError("missing oracledb")
+ return original_import(name, globals, locals, fromlist, level)
+
+ def fail_confirm(*args, **kwargs):
+ raise AssertionError("OracleVectorSearchTool prompted for installation")
+
+ monkeypatch.setattr(vs, "ORACLEDB_AVAILABLE", False)
+ monkeypatch.setitem(sys.modules, "click", SimpleNamespace(confirm=fail_confirm))
+ monkeypatch.setattr(builtins, "__import__", fake_import)
+
+ with pytest.raises(ImportError, match="uv add oracledb"):
+ OracleVectorSearchTool(
+ oracle_config=OracleVectorSearchConfig(table_name="docs_vectors"),
+ client=FakeConnection(),
+ embedding_function=lambda _: [1.0],
+ )
+
+
+def test_helper_functions_cover_error_paths():
+ assert vs._read_lob_if_needed(FakeLob("hello")) == "hello"
+ assert vs._normalize_json_value([{"a": vs.Decimal("1.5")}]) == [{"a": 1.5}]
+
+ with pytest.raises(ValueError, match="Identifier"):
+ vs._quote_identifier("bad-name")
+
+ assert vs._quote_identifier('"Mixed".plain') == '"Mixed"."plain"'
+
+ with pytest.raises(ValueError, match="Invalid metadata key"):
+ vs._validate_metadata_key("bad-key!")
+
+
+def test_get_comparison_string_covers_all_branches(monkeypatch):
+ bind_variables = []
+
+ with pytest.raises(ValueError, match="Invalid operator"):
+ vs._get_comparison_string("$bad", 1, bind_variables)
+
+ with pytest.raises(ValueError, match="exactly 2 elements"):
+ vs._get_comparison_string("$between", [1], bind_variables)
+
+ with pytest.raises(ValueError, match="At least one bound"):
+ vs._get_comparison_string("$between", [None, None], bind_variables)
+
+ assert vs._get_comparison_string("$between", [1, None], bind_variables) == (
+ "@ >= $val0",
+ ':value0 AS "val0"',
+ )
+ assert vs._get_comparison_string("$between", [None, 3], bind_variables) == (
+ "@ <= $val1",
+ ':value1 AS "val1"',
+ )
+
+ with pytest.raises(ValueError, match="must be a non-empty list"):
+ vs._get_comparison_string("$in", "not-a-list", bind_variables)
+
+ assert (
+ vs._get_comparison_string("$in", [4, 5], bind_variables)[0]
+ == "@ in ($val2,$val3)"
+ )
+
+ monkeypatch.setitem(vs.COMPARISON_MAP, "$custom_empty", "")
+ try:
+ with pytest.raises(ValueError, match=r"Invalid operator: \$custom_empty\."):
+ vs._get_comparison_string("$custom_empty", 1, bind_variables)
+ finally:
+ del vs.COMPARISON_MAP["$custom_empty"]
+
+
+def test_generate_condition_covers_dict_branches():
+ bind_variables = []
+ condition = vs._generate_condition(
+ "metadata_field",
+ {
+ "$gt": 1,
+ "$lt": 9,
+ "$not": {"$eq": "blocked"},
+ "$exists": False,
+ "$nin": [10, 11],
+ "$eq": {"a": 1},
+ "$ne": {"a": 2},
+ },
+ bind_variables,
+ )
+
+ assert condition.startswith("(")
+ assert (
+ "JSON_EXISTS(metadata, '$.metadata_field?(@ > $val0 && @ < $val1)'" in condition
+ )
+ assert "NOT (JSON_EXISTS(metadata, '$.metadata_field?(@ == $val2)'" in condition
+ assert "NOT (JSON_EXISTS(metadata, '$.metadata_field'))" in condition
+ assert (
+ "JSON_EQUAL(JSON_QUERY(metadata, '$.metadata_field'), JSON(:value5))"
+ in condition
+ )
+ assert (
+ "NOT (JSON_EQUAL(JSON_QUERY(metadata, '$.metadata_field'), JSON(:value6)))"
+ in condition
+ )
+ assert bind_variables[5] == '{"a": 1}'
+ assert bind_variables[6] == '{"a": 2}'
+
+
+def test_generate_condition_rejects_invalid_shapes():
+ with pytest.raises(ValueError, match="Nested metadata objects"):
+ vs._generate_condition("field", {"nested": 1}, [])
+
+ with pytest.raises(ValueError, match="must be a boolean"):
+ vs._generate_condition("field", {"$exists": "yes"}, [])
+
+ with pytest.raises(ValueError, match="Filter format is invalid"):
+ vs._generate_condition("field", [1, 2], [])
+
+ assert (
+ vs._generate_condition("field", {"$exists": True}, [])
+ == "JSON_EXISTS(metadata, '$.field')"
+ )
+
+
+def test_generate_where_clause_covers_validation_and_logical_branches():
+ with pytest.raises(ValueError, match="Must be a dictionary"):
+ vs._generate_where_clause([], [])
+
+ with pytest.raises(ValueError, match="not a recognized logical operator"):
+ vs._generate_where_clause({"$xor": [{"a": 1}]}, [])
+
+ with pytest.raises(ValueError, match="require an array"):
+ vs._generate_where_clause({"$or": {"a": 1}}, [])
+
+ bind_variables = []
+ condition = vs._generate_where_clause(
+ {
+ "$nor": [{"source": "docs"}, {"priority": {"$gte": 3}}],
+ "tenant": "crew",
+ },
+ bind_variables,
+ )
+
+ assert condition.startswith("(")
+ assert "( NOT (" in condition
+ assert "JSON_EXISTS(metadata, '$.source?(@ == $val)'" in condition
+ assert "JSON_EXISTS(metadata, '$.priority?(@ >= $val1)'" in condition
+ assert "JSON_EXISTS(metadata, '$.tenant?(@ == $val)'" in condition
+
+
+def test_build_metadata_filter_covers_errors_and_combined_filters():
+ with pytest.raises(ValueError, match="provided together"):
+ vs._build_metadata_filter("source", None)
+
+ with pytest.raises(
+ ValueError, match="letters, numbers, underscores, and dots only"
+ ):
+ vs._build_metadata_filter("source-name", "docs")
+
+ clause, params = vs._build_metadata_filter(
+ "priority",
+ 3,
+ {"source": "docs"},
+ )
+
+ assert "JSON_EXISTS(metadata, '$.priority?(@ == $val)'" in clause
+ assert "JSON_EXISTS(metadata, '$.source?(@ == $val)'" in clause
+ assert params == {"value0": 3, "value1": "docs"}
+
+
+def test_extract_oracle_error_code_handles_missing_code():
+ assert vs._extract_oracle_error_code(FakeOracleError(942)) == 942
+ assert vs._extract_oracle_error_code(Exception("boom")) is None
+
+
+def test_setup_oracle_imports_installed_dependency(monkeypatch):
+ original_oracledb = vs.oracledb
+ fake_oracledb = FakeOracleModule()
+ monkeypatch.setitem(sys.modules, "oracledb", fake_oracledb)
+ monkeypatch.setattr(vs, "ORACLEDB_AVAILABLE", False)
+
+ try:
+ tool = OracleVectorSearchTool(
+ oracle_config=OracleVectorSearchConfig(table_name="docs_vectors"),
+ client=FakeConnection(),
+ embedding_function=lambda _: [1.0],
+ dimensions=1,
+ )
+
+ assert tool.client is not None
+ assert vs.oracledb is fake_oracledb
+ assert vs.ORACLEDB_AVAILABLE is True
+ finally:
+ vs.oracledb = original_oracledb
+
+
+def test_setup_oracle_rejects_string_embedding_function():
+ with pytest.raises(ValueError, match="callable"):
+ OracleVectorSearchTool(
+ oracle_config=OracleVectorSearchConfig(table_name="docs_vectors"),
+ client=FakeConnection(),
+ embedding_function="custom.embed",
+ dimensions=1,
+ )
+
+
+def test_setup_oracle_delegates_empty_connection_params_to_oracledb(monkeypatch):
+ fake_oracledb = FakeOracleModule(connection=FakeConnection())
+ monkeypatch.setattr(vs, "oracledb", fake_oracledb)
+ monkeypatch.setattr(vs, "ORACLEDB_AVAILABLE", True)
+
+ OracleVectorSearchTool(
+ oracle_config=OracleVectorSearchConfig(table_name="docs_vectors"),
+ embedding_function=lambda _: [1.0],
+ dimensions=1,
+ )
+
+ assert fake_oracledb.connect_calls == [{}]
+
+
+def test_setup_oracle_connects_when_credentials_are_present(monkeypatch):
+ fake_oracledb = FakeOracleModule(connection=FakeConnection())
+ monkeypatch.setattr(vs, "oracledb", fake_oracledb)
+ monkeypatch.setattr(vs, "ORACLEDB_AVAILABLE", True)
+
+ tool = OracleVectorSearchTool(
+ oracle_config=OracleVectorSearchConfig(
+ user="user",
+ password="pass",
+ dsn="dsn",
+ table_name="docs_vectors",
+ ),
+ embedding_function=lambda _: [1.0],
+ dimensions=1,
+ )
+
+ assert tool._owns_client is True
+ assert fake_oracledb.connect_calls == [
+ {"user": "user", "password": "pass", "dsn": "dsn"}
+ ]
+
+
+def test_setup_oracle_allows_dsn_only_connection(monkeypatch):
+ fake_oracledb = FakeOracleModule(connection=FakeConnection())
+ monkeypatch.setattr(vs, "oracledb", fake_oracledb)
+ monkeypatch.setattr(vs, "ORACLEDB_AVAILABLE", True)
+
+ OracleVectorSearchTool(
+ oracle_config=OracleVectorSearchConfig(
+ dsn="dsn",
+ table_name="docs_vectors",
+ ),
+ embedding_function=lambda _: [1.0],
+ dimensions=1,
+ )
+
+ assert fake_oracledb.connect_calls == [{"dsn": "dsn"}]
+
+
+def test_setup_oracle_passes_connection_kwargs(monkeypatch):
+ fake_oracledb = FakeOracleModule(connection=FakeConnection())
+ monkeypatch.setattr(vs, "oracledb", fake_oracledb)
+ monkeypatch.setattr(vs, "ORACLEDB_AVAILABLE", True)
+
+ OracleVectorSearchTool(
+ oracle_config=OracleVectorSearchConfig(
+ user="user",
+ password="pass",
+ dsn="dsn",
+ table_name="docs_vectors",
+ connection_kwargs={
+ "config_dir": "/wallet",
+ "wallet_location": "/wallet",
+ "retry_count": 3,
+ },
+ ),
+ embedding_function=lambda _: [1.0],
+ dimensions=1,
+ )
+
+ assert fake_oracledb.connect_calls == [
+ {
+ "config_dir": "/wallet",
+ "wallet_location": "/wallet",
+ "retry_count": 3,
+ "user": "user",
+ "password": "pass",
+ "dsn": "dsn",
+ }
+ ]
+
+
+def test_setup_oracle_allows_connection_kwargs_only(monkeypatch):
+ fake_oracledb = FakeOracleModule(connection=FakeConnection())
+ monkeypatch.setattr(vs, "oracledb", fake_oracledb)
+ monkeypatch.setattr(vs, "ORACLEDB_AVAILABLE", True)
+
+ OracleVectorSearchTool(
+ oracle_config=OracleVectorSearchConfig(
+ table_name="docs_vectors",
+ connection_kwargs={
+ "config_dir": "/wallet",
+ "wallet_location": "/wallet",
+ },
+ ),
+ embedding_function=lambda _: [1.0],
+ dimensions=1,
+ )
+
+ assert fake_oracledb.connect_calls == [
+ {
+ "config_dir": "/wallet",
+ "wallet_location": "/wallet",
+ }
+ ]
+
+
+def test_setup_oracle_primary_connection_fields_override_kwargs(monkeypatch):
+ fake_oracledb = FakeOracleModule(connection=FakeConnection())
+ monkeypatch.setattr(vs, "oracledb", fake_oracledb)
+ monkeypatch.setattr(vs, "ORACLEDB_AVAILABLE", True)
+
+ OracleVectorSearchTool(
+ oracle_config=OracleVectorSearchConfig(
+ user="user",
+ password="pass",
+ dsn="dsn",
+ table_name="docs_vectors",
+ connection_kwargs={
+ "user": "other",
+ "password": "other",
+ "dsn": "other",
+ },
+ ),
+ embedding_function=lambda _: [1.0],
+ dimensions=1,
+ )
+
+ assert fake_oracledb.connect_calls == [
+ {"user": "user", "password": "pass", "dsn": "dsn"}
+ ]
+
+
+def test_create_vector_index_uses_connection_pool(monkeypatch):
+ monkeypatch.setattr(vs, "oracledb", FakeOracleModule())
+ monkeypatch.setattr(vs, "ORACLEDB_AVAILABLE", True)
+ index_cursor = FakeCursor()
+ connection = FakeConnection([index_cursor])
+ pool = FakeConnectionPool(connection)
+ tool = make_tool(client=pool)
+
+ index_name = tool.create_vector_index(index_name="docs_vec_idx")
+
+ assert index_name == "docs_vec_idx"
+ assert pool.acquire_count == 1
+ assert connection.commit_count == 1
+ assert "CREATE VECTOR INDEX" in index_cursor.executed[0][0]
+
+
+def test_create_vector_index_uses_ivf_default_name(monkeypatch):
+ monkeypatch.setattr(vs, "oracledb", FakeOracleModule())
+ monkeypatch.setattr(vs, "ORACLEDB_AVAILABLE", True)
+ index_cursor = FakeCursor()
+ client = FakeConnection([index_cursor])
+ tool = make_tool(client=client)
+
+ index_name = tool.create_vector_index(idx_type="IVF")
+
+ assert index_name == "docs_vectors_IVF_IDX"
+ assert "ORGANIZATION NEIGHBOR PARTITIONS" in index_cursor.executed[0][0]
+
+
+def test_caller_supplied_connection_pool_is_not_closed(monkeypatch):
+ monkeypatch.setattr(vs, "oracledb", FakeOracleModule())
+ monkeypatch.setattr(vs, "ORACLEDB_AVAILABLE", True)
+ pool = FakeConnectionPool(FakeConnection())
+ tool = make_tool(client=pool)
+
+ tool.__del__()
+
+ assert pool.closed is False
+
+
+def test_setup_oracle_uses_azure_openai_when_configured(monkeypatch):
+ fake_openai_client = FakeEmbeddingsClient(embeddings=None)
+ monkeypatch.setenv("AZURE_OPENAI_ENDPOINT", "https://example.com")
+ monkeypatch.delenv("OPENAI_API_KEY", raising=False)
+ monkeypatch.setattr(vs, "AzureOpenAI", lambda: fake_openai_client)
+
+ tool = OracleVectorSearchTool(
+ oracle_config=OracleVectorSearchConfig(table_name="docs_vectors"),
+ client=FakeConnection(),
+ dimensions=1,
+ )
+
+ assert tool._openai_client is fake_openai_client
+
+
+def test_setup_oracle_uses_openai_client_when_api_key_present(monkeypatch):
+ fake_openai_client = FakeEmbeddingsClient(embeddings=None)
+ monkeypatch.delenv("AZURE_OPENAI_ENDPOINT", raising=False)
+ monkeypatch.setenv("OPENAI_API_KEY", "test-key")
+ monkeypatch.setattr(vs, "Client", lambda: fake_openai_client)
+
+ tool = OracleVectorSearchTool(
+ oracle_config=OracleVectorSearchConfig(table_name="docs_vectors"),
+ client=FakeConnection(),
+ dimensions=1,
+ )
+
+ assert tool._openai_client is fake_openai_client
+
+
+def test_setup_oracle_requires_embedding_source(monkeypatch):
+ monkeypatch.delenv("AZURE_OPENAI_ENDPOINT", raising=False)
+ monkeypatch.delenv("OPENAI_API_KEY", raising=False)
+
+ with pytest.raises(ValueError, match="OPENAI_API_KEY environment variable"):
+ OracleVectorSearchTool(
+ oracle_config=OracleVectorSearchConfig(table_name="docs_vectors"),
+ client=FakeConnection(),
+ dimensions=1,
+ )
+
+
+def test_embed_texts_uses_openai_client():
+ embeddings = SimpleNamespace(
+ create=lambda **kwargs: SimpleNamespace(
+ data=[
+ SimpleNamespace(embedding=[0.1, 0.2]),
+ SimpleNamespace(embedding=[0.3, 0.4]),
+ ]
+ )
+ )
+ tool = make_tool()
+ tool.embedding_function = None
+ tool._openai_client = FakeEmbeddingsClient(embeddings=embeddings)
+ tool.dimensions = 2
+
+ assert tool._embed_texts(["a", "bb"]) == [[0.1, 0.2], [0.3, 0.4]]
+
+
+def test_embed_texts_accepts_batch_embedding_function():
+ calls = []
+
+ def batch_embed(texts: list[str]) -> list[list[float]]:
+ if isinstance(texts, str):
+ raise TypeError("batch embedding requires a list of texts")
+ calls.append(list(texts))
+ return [[float(len(text))] for text in texts]
+
+ tool = make_tool(embedding_function=batch_embed, dimensions=1)
+
+ assert tool._embed_texts(["a", "bb"]) == [[1.0], [2.0]]
+ assert calls == [["a", "bb"]]
+
+
+def test_table_exists_reraises_non_942_errors():
+ cursor = FakeCursor(execute_side_effects=[FakeOracleError(1111)])
+ tool = make_tool(client=FakeConnection([cursor]))
+
+ with pytest.raises(FakeOracleError):
+ tool._table_exists('"docs_vectors"')
+
+
+def test_index_exists_without_table_name():
+ cursor = FakeCursor(fetchone_result=("IDX",))
+ tool = make_tool(client=FakeConnection([cursor]))
+
+ assert tool._index_exists('"IDX"') is True
+ assert cursor.executed[0][2] == {"idx_name": "IDX"}
+
+
+def test_vector_index_exists_uses_default_name():
+ cursor = FakeCursor(fetchone_result=("DOCS_VECTORS_HNSW_IDX",))
+ tool = make_tool(client=FakeConnection([cursor]))
+
+ assert tool.vector_index_exists() is True
+
+
+def test_vector_index_exists_filters_schema_qualified_table_owner():
+ cursor = FakeCursor(fetchone_result=("DOCS_VEC_IDX",))
+ tool = make_tool(
+ client=FakeConnection([cursor]),
+ oracle_config=OracleVectorSearchConfig(
+ table_name="APP_SCHEMA.docs_vectors",
+ index_name="DOCS_VEC_IDX",
+ ),
+ )
+
+ assert tool.vector_index_exists() is True
+ executed_sql, _, params = cursor.executed[0]
+ assert "table_owner = :table_owner" in executed_sql
+ assert "AND owner = SYS_CONTEXT('USERENV', 'CURRENT_SCHEMA')" in executed_sql
+ assert params == {
+ "idx_name": "DOCS_VEC_IDX",
+ "table_name": "docs_vectors",
+ "table_owner": "APP_SCHEMA",
+ }
+
+
[email protected]("operator", ["$in", "$nin", "$all"])
+def test_empty_list_filters_are_rejected(operator):
+ binds = []
+ with pytest.raises(ValueError, match="must be a non-empty list"):
+ vs._generate_condition("tags", {operator: []}, binds)
+ assert binds == []
+
+
[email protected]("source", ["oracle_config", "query_config", "per_call"])
+def test_negative_dot_threshold_filters_by_max_distance(source):
+ cursor = FakeCursor(fetchall_result=[("near", {}, -0.8), ("far", {}, -0.2)])
+ config = {"table_name": "docs_vectors", "distance_strategy": "DOT"}
+ if source == "oracle_config":
+ config["score_threshold"] = -0.5
+ tool = make_tool(
+ client=FakeConnection([FakeCursor(), cursor]),
+ oracle_config=OracleVectorSearchConfig(**config),
+ query_config=OracleVectorSearchQueryConfig(
+ score_threshold=-0.5 if source == "query_config" else None
+ ),
+ )
+ overrides = {"score_threshold": -0.5} if source == "per_call" else {}
+ results = json.loads(tool._run(query="oracle", **overrides))
+ assert [row["context"] for row in results] == ["near"]
+
+
[email protected]("idx_type", ["HNSW", "IVF", "ivf"])
+ "table_name,base_name",
+ [("docs_vectors", "docs_vectors"), ('"App"."Docs.v1"', "Docs.v1")],
+)
+def test_created_default_index_name_matches_lookup(idx_type, table_name, base_name):
+ create_cursor = FakeCursor()
+ lookup_cursor = FakeCursor(fetchone_result=("index",))
+ tool = make_tool(
+ client=FakeConnection([create_cursor, lookup_cursor]),
+ oracle_config=OracleVectorSearchConfig(table_name=table_name),
+ )
+ name = tool.create_vector_index(idx_type=idx_type)
+ assert tool.vector_index_exists(idx_type=idx_type)
+ expected = f"{base_name}_{idx_type.upper()}_IDX"
+ assert lookup_cursor.executed[0][2]["idx_name"] == expected
+ assert f'CREATE VECTOR INDEX "{expected}"' in create_cursor.executed[0][0]
+ assert name.strip('"') == expected
+
+
[email protected]("explicit", [None, '"IndexOwner"."Custom.idx"'])
+def test_index_owner_is_independent_of_table_owner(explicit):
+ create_cursor = FakeCursor()
+ lookup_cursor = FakeCursor(fetchone_result=("index",))
+ tool = make_tool(
+ client=FakeConnection([create_cursor, lookup_cursor]),
+ oracle_config=OracleVectorSearchConfig(
+ table_name='"TableOwner"."Docs"',
+ index_name='"ConfiguredOwner"."ConfiguredIndex"',
+ ),
+ )
+ name = tool.create_vector_index(index_name=explicit, idx_type="IVF")
+ assert tool.vector_index_exists(explicit, idx_type="IVF")
+ sql, _, binds = lookup_cursor.executed[0]
+ assert binds == {
+ "idx_name": "Custom.idx" if explicit else "ConfiguredIndex",
+ "idx_owner": "IndexOwner" if explicit else "ConfiguredOwner",
+ "table_name": "Docs",
+ "table_owner": "TableOwner",
+ }
+ assert "AND owner = :idx_owner" in sql
+ assert "AND table_owner = :table_owner" in sql
+ assert f"CREATE VECTOR INDEX {name}" in create_cursor.executed[0][0]
+
+
+def test_unqualified_index_lookup_scopes_both_owners():
+ cursor = FakeCursor(fetchone_result=None)
+ tool = make_tool(client=FakeConnection([cursor]))
+ assert not tool.vector_index_exists()
+ sql = cursor.executed[0][0]
+ assert "AND owner = SYS_CONTEXT('USERENV', 'CURRENT_SCHEMA')" in sql
+ assert "AND table_owner = SYS_CONTEXT('USERENV', 'CURRENT_SCHEMA')" in sql
+
+
[email protected]("idx_type", ["invalid", None, 42])
+def test_index_lookup_rejects_invalid_type(idx_type):
+ with pytest.raises(ValueError, match="idx_type must be HNSW or IVF"):
+ make_tool().vector_index_exists(idx_type=idx_type)
+
+
+def test_create_table_returns_early_when_table_exists():
+ tool = make_tool(client=FakeConnection())
+ object.__setattr__(tool, "_table_exists", lambda table_name: True)
+
+ tool.create_table()
+
+ assert tool.client.commit_count == 0
+
+
+def test_create_vector_index_uses_default_name():
+ cursor = FakeCursor()
+ tool = make_tool(client=FakeConnection([cursor]))
+
+ index_name = tool.create_vector_index()
+
+ assert index_name == "docs_vectors_HNSW_IDX"
+ assert "CREATE VECTOR INDEX" in cursor.executed[0][0]
+
+
+def test_add_texts_covers_validation_errors():
+ tool = make_tool()
+
+ assert tool.add_texts([]) == []
+
+ with pytest.raises(ValueError, match="metadatas must match"):
+ tool.add_texts(["a"], metadatas=[{}, {}])
+
+ with pytest.raises(ValueError, match="ids must match"):
+ tool.add_texts(["a"], ids=["id-1", "id-2"])
+
+ object.__setattr__(tool, "create_table", lambda: None)
+ tool.embedding_function = lambda _: [1.0, 2.0]
+ tool.dimensions = 1
+ with pytest.raises(ValueError, match="Embedding dimension mismatch"):
+ tool.add_texts(["a"])
+
+
+def test_run_merges_default_filter_and_rejects_non_object_filters():
+ existence_cursor = FakeCursor()
+ search_cursor = FakeCursor(fetchall_result=[])
+ tool = OracleVectorSearchTool(
+ oracle_config=OracleVectorSearchConfig(table_name="docs_vectors"),
+ query_config=vs.OracleVectorSearchQueryConfig(filter={"tenant": "crew"}),
+ client=FakeConnection([existence_cursor, search_cursor]),
+ embedding_function=lambda _: [1.0],
+ dimensions=1,
+ )
+
+ tool._run(query="oracle", filters='{"source":"docs"}')
+ executed_sql, params, _ = search_cursor.executed[0]
+ assert "JSON_EXISTS(metadata, '$.tenant?(@ == $val)'" in executed_sql
+ assert "JSON_EXISTS(metadata, '$.source?(@ == $val)'" in executed_sql
+ assert params["value0"] == "crew"
+ assert params["value1"] == "docs"
+
+ failing_tool = OracleVectorSearchTool(
+ oracle_config=OracleVectorSearchConfig(table_name="docs_vectors"),
+ client=FakeConnection([FakeCursor()]),
+ embedding_function=lambda _: [1.0],
+ dimensions=1,
+ )
+ assert failing_tool._run(query="oracle", filters="[]") == ""
+
+
+def test_del_logs_cleanup_errors(caplog):
+ tool = make_tool(client=CloseError("client close failed"))
+ tool._owns_client = True
+ tool._openai_client = CloseError("openai close failed")
+
+ with caplog.at_level("ERROR"):
+ tool.__del__()
+
+ assert "Failed to close Oracle client" in caplog.text
+ assert "Failed to close OpenAI client" in caplog.text
+
+
[email protected]("operator", ["$in", "$nin"])
+def test_membership_filters_probe_array_elements(operator):
+ binds = []
+ condition = vs._generate_condition("tags", {operator: ["red", "blue"]}, binds)
+ assert "$.tags[*]?(@ in ($val0,$val1))" in condition
+ assert binds == ["red", "blue"]
+ assert ("NOT" in condition) is (operator == "$nin")
+
+
[email protected]("operator", ["$eq", "$in", "$nin", "$all", "$exists"])
+def test_filters_quote_spaced_member_names(operator):
+ value = (
+ True
+ if operator == "$exists"
+ else ["red"]
+ if operator in {"$in", "$nin", "$all"}
+ else "red"
+ )
+ condition = vs._generate_condition("file name.tags", {operator: value}, [])
+ assert '$."file name".tags' in condition
+
+
[email protected]("key", ["", "*", "a..b", "a[", "a[0]", "a'", 'a"', "a[*]junk"])
+def test_filters_reject_invalid_path_syntax(key):
+ with pytest.raises(ValueError, match="Invalid metadata key"):
+ vs._generate_condition(key, "red", [])
+
+
+def test_null_distances_do_not_hide_valid_matches():
+ cursor = FakeCursor(fetchall_result=[("missing", {}, None), ("valid", {}, 0.2)])
+ tool = make_tool(client=FakeConnection([FakeCursor(fetchone_result=(1,)), cursor]))
+ results = json.loads(tool._run("query", filters=json.dumps({"source": "docs"})))
+ assert [r["context"] for r in results] == ["valid"]
+ sql = cursor.executed[0][0]
+ assert "WHERE embedding IS NOT NULL" in sql
+ assert "AND (" in sql
+
+
[email protected]("operator", ["$and", "$or", "$nor"])
+ "children", [[], [{}], [{"source": "docs"}, {}], [{"$and": []}], [{"source": {}}]]
+)
+def test_empty_logical_and_nested_filters_are_rejected(operator, children):
+ with pytest.raises(ValueError, match="non-empty|at least one"):
+ vs._generate_where_clause({operator: children}, [])
+
+
+def test_top_level_empty_filter_still_means_no_filter():
+ assert vs._build_metadata_filter(None, None, {}) == ("", {})
+
+
+def test_custom_embedding_does_not_declare_openai_key_required(monkeypatch):
+ from crewai_tools.generate_tool_specs import ToolSpecExtractor
+
+ monkeypatch.delenv("OPENAI_API_KEY", raising=False)
+ monkeypatch.delenv("AZURE_OPENAI_ENDPOINT", raising=False)
+ tool = make_tool()
+ assert tool._embed_texts(["hello"]) == [[5.0]]
+ assert all(
+ not env.required for env in tool.env_vars if env.name == "OPENAI_API_KEY"
+ )
+ spec = ToolSpecExtractor._extract_env_vars_from_model_fields(
+ OracleVectorSearchTool.model_fields
+ )
+ assert (
+ next(env for env in spec if env["name"] == "OPENAI_API_KEY")["required"]
+ is False
+ )
+ with pytest.raises(ValueError, match="OPENAI_API_KEY"):
+ make_tool(embedding_function=None)
diff --git a/lib/crewai-tools/tests/tools/test_oracle_vector_search_tool_integration.py b/lib/crewai-tools/tests/tools/test_oracle_vector_search_tool_integration.py
new file mode 100644
index 000000000..0cdc43c45
--- /dev/null
+++ b/lib/crewai-tools/tests/tools/test_oracle_vector_search_tool_integration.py
@@ -0,0 +1,433 @@
+import json
+import os
+import uuid
+
+from crewai_tools import OracleVectorSearchConfig, OracleVectorSearchTool
+import pytest
+
+
+ORACLE_USERNAME_ENV = "VECDB_USER"
+ORACLE_PASSWORD_ENV = "VECDB_PASS"
+ORACLE_DSN_ENV = "VECDB_HOST"
+
+
+def _oracle_env_config() -> tuple[str, str, str] | None:
+ username = os.getenv(ORACLE_USERNAME_ENV)
+ password = os.getenv(ORACLE_PASSWORD_ENV)
+ dsn = os.getenv(ORACLE_DSN_ENV)
+ if not username or not password or not dsn:
+ return None
+ return username, password, dsn
+
+
+def test_oracle_env_config_requires_explicit_credentials(monkeypatch):
+ monkeypatch.delenv(ORACLE_USERNAME_ENV, raising=False)
+ monkeypatch.delenv(ORACLE_PASSWORD_ENV, raising=False)
+ monkeypatch.delenv(ORACLE_DSN_ENV, raising=False)
+
+ assert _oracle_env_config() is None
+
+ monkeypatch.setenv(ORACLE_USERNAME_ENV, "user")
+ monkeypatch.setenv(ORACLE_PASSWORD_ENV, "password")
+ assert _oracle_env_config() is None
+
+ monkeypatch.setenv(ORACLE_DSN_ENV, "host/service")
+ assert _oracle_env_config() == ("user", "password", "host/service")
+
+
+def _embed_text(text: str) -> list[float]:
+ lowered = text.lower()
+ return [
+ 1.0 if "oracle" in lowered else 0.0,
+ 1.0 if "crewai" in lowered else 0.0,
+ 1.0 if "vector" in lowered else 0.0,
+ ]
+
+
+def _embed_texts(texts: list[str]) -> list[list[float]]:
+ if isinstance(texts, str):
+ raise TypeError("batch embedding requires a list of texts")
+ return [_embed_text(text) for text in texts]
+
+
+def test_all_filters_limits_and_failed_batch_with_real_connection():
+ creds = _oracle_env_config()
+ if creds is None:
+ pytest.skip("Set VECDB_USER, VECDB_PASS, and VECDB_HOST for Oracle tests")
+ oracledb = pytest.importorskip("oracledb")
+ username, password, dsn = creds
+ connection = oracledb.connect(user=username, password=password, dsn=dsn)
+ table_name = f"CREWAI_ORACLE_REVIEW_{uuid.uuid4().hex[:12].upper()}"
+ tool = OracleVectorSearchTool(
+ oracle_config=OracleVectorSearchConfig(table_name=table_name),
+ client=connection,
+ embedding_function=_embed_text,
+ dimensions=3,
+ )
+ try:
+ tool.add_texts(
+ [
+ "Oracle vector both",
+ "Oracle vector one",
+ "Oracle vector missing",
+ "Oracle vector empty",
+ ],
+ metadatas=[{"tags": ["red", "blue"]}, {"tags": ["red"]}, {}, {"tags": []}],
+ ids=["both", "one", "missing", "empty"],
+ )
+ results = json.loads(
+ tool._run(
+ "Oracle vector",
+ filters=json.dumps({"tags": {"$all": ["red", "blue"]}}),
+ limit=10,
+ )
+ )
+ assert [row["context"] for row in results] == ["Oracle vector both"]
+ for requested, expected in [
+ (["red"], {"Oracle vector both", "Oracle vector one"}),
+ (["red", "red"], {"Oracle vector both", "Oracle vector one"}),
+ (["red", "absent"], set()),
+ ]:
+ rows = json.loads(
+ tool._run(
+ "Oracle vector",
+ filters=json.dumps({"tags": {"$all": requested}}),
+ limit=10,
+ )
+ )
+ assert {row["context"] for row in rows} == expected
+ for operator, expected in [
+ ("$in", {"Oracle vector both", "Oracle vector one"}),
+ ("$nin", {"Oracle vector missing", "Oracle vector empty"}),
+ ]:
+ rows = json.loads(
+ tool._run(
+ "Oracle vector",
+ filters=json.dumps({"tags": {operator: ["red"]}}),
+ limit=10,
+ )
+ )
+ assert {row["context"] for row in rows} == expected
+ tool.add_texts(
+ ["Oracle vector scalar"],
+ metadatas=[{"tags": "red", "file name": "guide"}],
+ ids=["scalar"],
+ )
+ rows = json.loads(
+ tool._run(
+ "Oracle vector",
+ filters=json.dumps({"tags": {"$in": ["red"]}}),
+ limit=10,
+ )
+ )
+ assert {row["context"] for row in rows} == {
+ "Oracle vector both",
+ "Oracle vector one",
+ "Oracle vector scalar",
+ }
+ rows = json.loads(
+ tool._run(
+ "Oracle vector", filters=json.dumps({"file name": "guide"}), limit=10
+ )
+ )
+ assert [row["context"] for row in rows] == ["Oracle vector scalar"]
+ assert len(json.loads(tool._run("Oracle vector", limit=1))) == 1
+
+ # A failed batch must preserve work already pending on this connection.
+ with connection.cursor() as cursor:
+ cursor.execute(
+ f'INSERT INTO "{table_name}" (id, text) VALUES (:1, :2)',
+ ["pending", "unrelated"],
+ )
+ with pytest.raises(oracledb.IntegrityError):
+ tool.add_texts(["Oracle first", "Oracle duplicate"], ids=["batch", "both"])
+ connection.commit()
+ rows = json.loads(tool._run("Oracle vector", limit=10))
+ assert len(rows) == 5
+ assert "unrelated" not in {row["context"] for row in rows}
+ with connection.cursor() as cursor:
+ cursor.execute(
+ f'SELECT id FROM "{table_name}" WHERE id IN (:1, :2)',
+ ["pending", "batch"],
+ )
+ assert cursor.fetchall() == [("pending",)]
+ finally:
+ _drop_table(tool, table_name)
+ connection.close()
+
+
+def _drop_table(tool: OracleVectorSearchTool, table_name: str) -> None:
+ try:
+ with tool.client.cursor() as cursor:
+ cursor.execute(f'DROP TABLE "{table_name}" PURGE')
+ tool.client.commit()
+ except Exception:
+ pass
+
+
+def test_oracle_vector_search_tool_with_real_connection(
+ pytestconfig: pytest.Config,
+) -> None:
+ creds = _oracle_env_config()
+ if creds is None:
+ pytest.skip(
+ f"Set {ORACLE_USERNAME_ENV}, {ORACLE_PASSWORD_ENV}, and {ORACLE_DSN_ENV} to run Oracle integration tests."
+ )
+
+ if getattr(pytestconfig.option, "block_network", False):
+ pytest.skip(
+ "Network access is blocked by pytest addopts. Re-run this test without --block-network to use a real Oracle connection."
+ )
+
+ username, password, dsn = creds
+ oracledb = pytest.importorskip("oracledb")
+ try:
+ connection = oracledb.connect(user=username, password=password, dsn=dsn)
+ except Exception as exc:
+ pytest.skip(f"Database connection failed: {exc}")
+ else:
+ connection.close()
+
+ table_name = f"CREWAI_ORACLE_TOOL_{uuid.uuid4().hex[:12].upper()}"
+
+ tool = OracleVectorSearchTool(
+ oracle_config=OracleVectorSearchConfig(
+ user=username,
+ password=password,
+ dsn=dsn,
+ table_name=table_name,
+ limit=2,
+ distance_strategy="COSINE",
+ ),
+ embedding_function=_embed_text,
+ dimensions=3,
+ )
+
+ try:
+ tool.create_table()
+ inserted_ids = tool.add_texts(
+ [
+ "CrewAI integrates with Oracle vector search.",
+ "This reference note mentions vector indexing only.",
+ ],
+ metadatas=[
+ {"source": "docs", "topic": "oracle", "priority": 5},
+ {"source": "kitchen", "topic": "food", "priority": 1},
+ ],
+ )
+
+ assert len(inserted_ids) == 2
+ assert tool.table_exists() is True
+ assert tool.vector_index_exists() is False
+
+ unfiltered_results = json.loads(tool._run(query="oracle vector"))
+ assert len(unfiltered_results) >= 1
+ assert unfiltered_results[0]["metadata"]["source"] == "docs"
+ assert "Oracle vector search" in unfiltered_results[0]["context"]
+ assert unfiltered_results[0]["score"] == pytest.approx(
+ unfiltered_results[0]["distance"]
+ )
+
+ filtered_results = json.loads(
+ tool._run(
+ query="oracle vector",
+ filter_by="source",
+ filter_value="docs",
+ )
+ )
+ assert len(filtered_results) >= 1
+ assert all(row["metadata"]["source"] == "docs" for row in filtered_results)
+
+ numeric_filter_results = json.loads(
+ tool._run(
+ query="oracle vector",
+ filter_by="priority",
+ filter_value=5,
+ )
+ )
+ assert len(numeric_filter_results) >= 1
+ assert all(
+ result["metadata"]["priority"] == 5 for result in numeric_filter_results
+ )
+
+ json_filter_results = json.loads(
+ tool._run(
+ query="oracle vector",
+ filters=json.dumps(
+ {
+ "$or": [
+ {"source": "docs"},
+ {"topic": {"$eq": "oracle"}},
+ ]
+ }
+ ),
+ score_threshold=0.5,
+ )
+ )
+ assert len(json_filter_results) >= 1
+ assert all(result["distance"] <= 0.5 for result in json_filter_results)
+
+ created_index_name = tool.create_vector_index()
+ assert created_index_name
+ assert tool.vector_index_exists() is True
+ finally:
+ _drop_table(tool, table_name)
+
+ openai_client = getattr(tool, "_openai_client", None)
+ if openai_client is not None:
+ openai_client.close()
+
+ client = getattr(tool, "client", None)
+ if client is not None:
+ client.close()
+
+
+def test_oracle_vector_search_tool_with_real_connection_batch_embedding(
+ pytestconfig: pytest.Config,
+) -> None:
+ creds = _oracle_env_config()
+ if creds is None:
+ pytest.skip(
+ f"Set {ORACLE_USERNAME_ENV}, {ORACLE_PASSWORD_ENV}, and {ORACLE_DSN_ENV} to run Oracle integration tests."
+ )
+
+ if getattr(pytestconfig.option, "block_network", False):
+ pytest.skip(
+ "Network access is blocked by pytest addopts. Re-run this test without --block-network to use a real Oracle connection."
+ )
+
+ username, password, dsn = creds
+ oracledb = pytest.importorskip("oracledb")
+ try:
+ connection = oracledb.connect(user=username, password=password, dsn=dsn)
+ except Exception as exc:
+ pytest.skip(f"Database connection failed: {exc}")
+ else:
+ connection.close()
+
+ table_name = f"CREWAI_ORACLE_BATCH_{uuid.uuid4().hex[:12].upper()}"
+ tool = OracleVectorSearchTool(
+ oracle_config=OracleVectorSearchConfig(
+ user=username,
+ password=password,
+ dsn=dsn,
+ table_name=table_name,
+ limit=2,
+ distance_strategy="COSINE",
+ ),
+ embedding_function=_embed_texts,
+ dimensions=3,
+ )
+
+ try:
+ tool.create_table()
+ tool.add_texts(
+ [
+ "CrewAI integrates with Oracle vector search.",
+ "This reference note mentions vector indexing only.",
+ ],
+ metadatas=[
+ {"source": "docs"},
+ {"source": "kitchen"},
+ ],
+ )
+
+ results = json.loads(tool._run(query="oracle vector"))
+ assert len(results) >= 1
+ assert results[0]["metadata"]["source"] == "docs"
+ finally:
+ _drop_table(tool, table_name)
+ client = getattr(tool, "client", None)
+ if client is not None:
+ client.close()
+
+
+ ("idx_type", "params", "expected_parameter_text"),
+ [
+ ("HNSW", {"neighbors": 32, "efconstruction": 200}, "HNSW"),
+ (
+ "IVF",
+ {
+ "neighbor_partitions": 32,
+ "samples_per_partition": 1,
+ "min_vectors_per_partition": 0,
+ },
+ "IVF",
+ ),
+ ],
+)
+def test_oracle_vector_search_tool_creates_vector_index_type(
+ pytestconfig: pytest.Config,
+ idx_type: str,
+ params: dict[str, int],
+ expected_parameter_text: str,
+) -> None:
+ creds = _oracle_env_config()
+ if creds is None:
+ pytest.skip(
+ f"Set {ORACLE_USERNAME_ENV}, {ORACLE_PASSWORD_ENV}, and {ORACLE_DSN_ENV} to run Oracle integration tests."
+ )
+
+ if getattr(pytestconfig.option, "block_network", False):
+ pytest.skip(
+ "Network access is blocked by pytest addopts. Re-run this test without --block-network to use a real Oracle connection."
+ )
+
+ username, password, dsn = creds
+ oracledb = pytest.importorskip("oracledb")
+ try:
+ connection = oracledb.connect(user=username, password=password, dsn=dsn)
+ except Exception as exc:
+ pytest.skip(f"Database connection failed: {exc}")
+ else:
+ connection.close()
+
+ table_name = f"CREWAI_ORACLE_{idx_type}_{uuid.uuid4().hex[:12].upper()}"
+ index_name = f"{table_name}_IDX"
+ tool = OracleVectorSearchTool(
+ oracle_config=OracleVectorSearchConfig(
+ user=username,
+ password=password,
+ dsn=dsn,
+ table_name=table_name,
+ distance_strategy="COSINE",
+ ),
+ embedding_function=_embed_text,
+ dimensions=3,
+ )
+
+ try:
+ tool.create_table()
+ tool.add_texts(["CrewAI Oracle vector index type test."])
+
+ created_index_name = tool.create_vector_index(
+ index_name=index_name,
+ idx_type=idx_type,
+ params=params,
+ )
+
+ assert created_index_name == index_name
+ assert tool.vector_index_exists(index_name=index_name) is True
+ with tool.client.cursor() as cursor:
+ cursor.execute(
+ """
+ SELECT index_type, index_subtype
+ FROM user_indexes
+ WHERE index_name = :index_name
+ """,
+ index_name=index_name,
+ )
+ row = cursor.fetchone()
+ assert row is not None
+ assert row[0] == "VECTOR"
+ assert expected_parameter_text in (row[1] or "").upper()
+ finally:
+ _drop_table(tool, table_name)
+ client = getattr(tool, "client", None)
+ if client is not None:
+ client.close()
diff --git a/lib/crewai/src/crewai/rag/embeddings/factory.py b/lib/crewai/src/crewai/rag/embeddings/factory.py
index cbaede7ac..bb551e3f4 100644
--- a/lib/crewai/src/crewai/rag/embeddings/factory.py
+++ b/lib/crewai/src/crewai/rag/embeddings/factory.py
@@ -75,6 +75,10 @@ if TYPE_CHECKING:
from crewai.rag.embeddings.providers.openai.types import OpenAIProviderSpec
from crewai.rag.embeddings.providers.openclip.types import OpenCLIPProviderSpec
from crewai.rag.embeddings.providers.openrouter.types import OpenRouterProviderSpec
+ from crewai.rag.embeddings.providers.oracle.embedding_callable import (
+ OracleEmbeddingFunction,
+ )
+ from crewai.rag.embeddings.providers.oracle.types import OracleProviderSpec
from crewai.rag.embeddings.providers.roboflow.types import RoboflowProviderSpec
from crewai.rag.embeddings.providers.sentence_transformer.types import (
SentenceTransformerProviderSpec,
@@ -104,6 +108,7 @@ PROVIDER_PATHS = {
"openai": "crewai.rag.embeddings.providers.openai.openai_provider.OpenAIProvider",
"openclip": "crewai.rag.embeddings.providers.openclip.openclip_provider.OpenCLIPProvider",
"openrouter": "crewai.rag.embeddings.providers.openrouter.openrouter_provider.OpenRouterProvider",
+ "oracle": "crewai.rag.embeddings.providers.oracle.oracle_provider.OracleProvider",
"roboflow": "crewai.rag.embeddings.providers.roboflow.roboflow_provider.RoboflowProvider",
"sentence-transformer": "crewai.rag.embeddings.providers.sentence_transformer.sentence_transformer_provider.SentenceTransformerProvider",
"text2vec": "crewai.rag.embeddings.providers.text2vec.text2vec_provider.Text2VecProvider",
@@ -160,6 +165,10 @@ def build_embedder_from_dict(
def build_embedder_from_dict(spec: OllamaProviderSpec) -> OllamaEmbeddingFunction: ...
+@overload
+def build_embedder_from_dict(spec: OracleProviderSpec) -> OracleEmbeddingFunction: ...
+
+
@overload
def build_embedder_from_dict(spec: OpenAIProviderSpec) -> OpenAIEmbeddingFunction: ...
@@ -305,6 +314,10 @@ def build_embedder(spec: HuggingFaceProviderSpec) -> HuggingFaceEmbeddingFunctio
def build_embedder(spec: OllamaProviderSpec) -> OllamaEmbeddingFunction: ...
+@overload
+def build_embedder(spec: OracleProviderSpec) -> OracleEmbeddingFunction: ...
+
+
@overload
def build_embedder(spec: OpenAIProviderSpec) -> OpenAIEmbeddingFunction: ...
diff --git a/lib/crewai/src/crewai/rag/embeddings/providers/oracle/__init__.py b/lib/crewai/src/crewai/rag/embeddings/providers/oracle/__init__.py
new file mode 100644
index 000000000..495e2506f
--- /dev/null
+++ b/lib/crewai/src/crewai/rag/embeddings/providers/oracle/__init__.py
@@ -0,0 +1,20 @@
+"""Oracle embedding providers."""
+
+from crewai.rag.embeddings.providers.oracle.embedding_callable import (
+ OracleEmbeddingFunction,
+)
+from crewai.rag.embeddings.providers.oracle.oracle_provider import (
+ OracleProvider,
+)
+from crewai.rag.embeddings.providers.oracle.types import (
+ OracleProviderConfig,
+ OracleProviderSpec,
+)
+
+
+__all__ = [
+ "OracleEmbeddingFunction",
+ "OracleProvider",
+ "OracleProviderConfig",
+ "OracleProviderSpec",
+]
diff --git a/lib/crewai/src/crewai/rag/embeddings/providers/oracle/embedding_callable.py b/lib/crewai/src/crewai/rag/embeddings/providers/oracle/embedding_callable.py
new file mode 100644
index 000000000..3e1c28f7c
--- /dev/null
+++ b/lib/crewai/src/crewai/rag/embeddings/providers/oracle/embedding_callable.py
@@ -0,0 +1,121 @@
+"""Oracle embedding function implementation."""
+
+from __future__ import annotations
+
+from contextlib import suppress
+import json
+from typing import Any
+
+import numpy as np
+
+from crewai.rag.core.base_embeddings_callable import EmbeddingFunction
+from crewai.rag.core.types import Documents, Embeddings
+
+
+class OracleEmbeddingFunction(EmbeddingFunction[Documents]):
+ """Embedding function backed by Oracle Database calls."""
+
+ def __init__(
+ self,
+ *,
+ conn: Any | None = None,
+ connection_params: dict[str, Any] | None = None,
+ embedding_params: dict[str, Any],
+ proxy: str | None = None,
+ ) -> None:
+ try:
+ import oracledb
+ except ImportError as e:
+ raise ImportError(
+ "oracledb is required for oracle embeddings. Install it with: uv add oracledb"
+ ) from e
+
+ self._oracledb = oracledb
+ self._embedding_params = embedding_params
+ self._proxy = proxy
+ self._owns_connection = conn is None
+ self._conn = conn or oracledb.connect(**(connection_params or {}))
+
+ @staticmethod
+ def name() -> str:
+ """Return the name of the embedding function for ChromaDB compatibility."""
+ return "oracle"
+
+ def __call__(self, input: Documents) -> Embeddings:
+ """Embed documents of at most 4000 characters, aligned by Oracle embed_id.
+
+ Missing, duplicate, or unexpected result IDs raise ValueError. LOB
+ payloads are read locally without changing process-wide driver defaults.
+ """
+ if isinstance(input, str):
+ input = [input]
+ if not input:
+ raise ValueError("Oracle embeddings input cannot be empty.")
+
+ if any(len(text) > 4000 for text in input):
+ raise ValueError(
+ "Oracle embedding documents must not exceed 4000 characters."
+ )
+
+ cursor = None
+ try:
+ cursor = self._conn.cursor()
+
+ if self._proxy:
+ cursor.execute(
+ "begin utl_http.set_proxy(:proxy); end;", proxy=self._proxy
+ )
+
+ chunks = [
+ json.dumps({"chunk_id": i, "chunk_data": text})
+ for i, text in enumerate(input, start=1)
+ ]
+ vector_array_type = self._conn.gettype("SYS.VECTOR_ARRAY_T")
+ inputs = vector_array_type.newobject(chunks)
+
+ cursor.setinputsizes(None, self._oracledb.DB_TYPE_JSON)
+ cursor.execute(
+ "select t.* from dbms_vector_chain.utl_to_embeddings(:1, json(:2)) t",
+ [inputs, self._embedding_params],
+ )
+
+ embeddings_by_id: dict[int, list[float]] = {}
+ for row in cursor:
+ if row is None:
+ raise ValueError("Oracle embeddings returned an empty row.")
+ payload = row[0]
+ if hasattr(payload, "read"):
+ payload = payload.read()
+ parsed = json.loads(payload)
+ embed_id = parsed.get("embed_id")
+ if (
+ type(embed_id) is not int
+ or not 1 <= embed_id <= len(input)
+ or embed_id in embeddings_by_id
+ ):
+ raise ValueError(
+ "Oracle embeddings returned an invalid or duplicate embed_id."
+ )
+ embeddings_by_id[embed_id] = json.loads(parsed["embed_vector"])
+ if len(embeddings_by_id) != len(input):
+ raise ValueError(
+ "Oracle embeddings count does not match the input documents."
+ )
+ return [
+ np.asarray(embeddings_by_id[i], dtype=np.float32)
+ for i in range(1, len(input) + 1)
+ ]
+ finally:
+ if cursor is not None:
+ if self._proxy and not self._owns_connection:
+ with suppress(Exception):
+ cursor.execute("begin utl_http.set_proxy(NULL); end;")
+ cursor.close()
+
+ def __del__(self) -> None:
+ # Destructors must tolerate partially initialized or closed connections.
+ with suppress(Exception):
+ if getattr(self, "_owns_connection", False):
+ conn = getattr(self, "_conn", None)
+ if conn is not None:
+ conn.close()
diff --git a/lib/crewai/src/crewai/rag/embeddings/providers/oracle/oracle_provider.py b/lib/crewai/src/crewai/rag/embeddings/providers/oracle/oracle_provider.py
new file mode 100644
index 000000000..bab4bc9ae
--- /dev/null
+++ b/lib/crewai/src/crewai/rag/embeddings/providers/oracle/oracle_provider.py
@@ -0,0 +1,74 @@
+"""Oracle embeddings provider."""
+
+from __future__ import annotations
+
+from typing import Any
+
+from pydantic import Field, model_validator
+from pydantic_settings import (
+ BaseSettings,
+ EnvSettingsSource,
+ PydanticBaseSettingsSource,
+ SettingsConfigDict,
+)
+
+from crewai.rag.core.base_embeddings_provider import BaseEmbeddingsProvider
+from crewai.rag.embeddings.providers.oracle.embedding_callable import (
+ OracleEmbeddingFunction,
+)
+
+
+class OracleProvider(BaseEmbeddingsProvider[OracleEmbeddingFunction]):
+ """Oracle embeddings provider."""
+
+ model_config = SettingsConfigDict(env_prefix="ORACLE_")
+
+ embedding_callable: type[OracleEmbeddingFunction] = Field(
+ default=OracleEmbeddingFunction,
+ description="Oracle embedding function class",
+ )
+ conn: Any | None = Field(
+ default=None,
+ description="Existing Oracle connection object to reuse.",
+ )
+ connection_params: dict[str, Any] | None = Field(
+ default=None,
+ description="Keyword arguments forwarded to oracledb.connect(**connection_params).",
+ )
+ embedding_params: dict[str, Any] = Field(
+ ...,
+ description="Parameters forwarded to dbms_vector_chain.utl_to_embeddings.",
+ )
+ proxy: str | None = Field(
+ default=None,
+ description="Optional proxy value passed to utl_http.set_proxy before embedding requests.",
+ )
+
+ @classmethod
+ def settings_customise_sources(
+ cls,
+ settings_cls: type[BaseSettings],
+ init_settings: PydanticBaseSettingsSource,
+ env_settings: PydanticBaseSettingsSource,
+ dotenv_settings: PydanticBaseSettingsSource,
+ file_secret_settings: PydanticBaseSettingsSource,
+ ) -> tuple[PydanticBaseSettingsSource, ...]:
+ # A live connection must be supplied by the caller, never as env text.
+ for source in (env_settings, dotenv_settings):
+ if isinstance(source, EnvSettingsSource):
+ source.env_vars = {
+ key: value
+ for key, value in source.env_vars.items()
+ if key.lower() not in {"conn", "oracle_conn"}
+ }
+ return init_settings, env_settings, dotenv_settings, file_secret_settings
+
+ @model_validator(mode="after")
+ def validate_connection_source(self) -> OracleProvider:
+ has_conn = self.conn is not None
+ has_connection_params = self.connection_params is not None
+ if has_conn == has_connection_params:
+ raise ValueError(
+ "Provide exactly one of 'conn' or 'connection_params' for oracle embeddings."
+ )
+ return self
diff --git a/lib/crewai/src/crewai/rag/embeddings/providers/oracle/types.py b/lib/crewai/src/crewai/rag/embeddings/providers/oracle/types.py
new file mode 100644
index 000000000..8ec629637
--- /dev/null
+++ b/lib/crewai/src/crewai/rag/embeddings/providers/oracle/types.py
@@ -0,0 +1,21 @@
+"""Type definitions for Oracle embedding providers."""
+
+from typing import Any, Literal
+
+from typing_extensions import Required, TypedDict
+
+
+class OracleProviderConfig(TypedDict, total=False):
+ """Configuration for Oracle provider."""
+
+ conn: Any
+ connection_params: dict[str, Any]
+ embedding_params: dict[str, Any]
+ proxy: str
+
+
+class OracleProviderSpec(TypedDict, total=False):
+ """Oracle provider specification."""
+
+ provider: Required[Literal["oracle"]]
+ config: OracleProviderConfig
diff --git a/lib/crewai/src/crewai/rag/embeddings/types.py b/lib/crewai/src/crewai/rag/embeddings/types.py
index 2135eb89f..b983ddd36 100644
--- a/lib/crewai/src/crewai/rag/embeddings/types.py
+++ b/lib/crewai/src/crewai/rag/embeddings/types.py
@@ -22,6 +22,7 @@ from crewai.rag.embeddings.providers.onnx.types import ONNXProviderSpec
from crewai.rag.embeddings.providers.openai.types import OpenAIProviderSpec
from crewai.rag.embeddings.providers.openclip.types import OpenCLIPProviderSpec
from crewai.rag.embeddings.providers.openrouter.types import OpenRouterProviderSpec
+from crewai.rag.embeddings.providers.oracle.types import OracleProviderSpec
from crewai.rag.embeddings.providers.roboflow.types import RoboflowProviderSpec
from crewai.rag.embeddings.providers.sentence_transformer.types import (
SentenceTransformerProviderSpec,
@@ -44,6 +45,7 @@ ProviderSpec: TypeAlias = (
| OpenAIProviderSpec
| OpenCLIPProviderSpec
| OpenRouterProviderSpec
+ | OracleProviderSpec
| RoboflowProviderSpec
| SentenceTransformerProviderSpec
| Text2VecProviderSpec
@@ -67,6 +69,7 @@ AllowedEmbeddingProviders = Literal[
"openai",
"openclip",
"openrouter",
+ "oracle",
"roboflow",
"sentence-transformer",
"text2vec",
diff --git a/lib/crewai/tests/rag/embeddings/test_oracle_memory_integration.py b/lib/crewai/tests/rag/embeddings/test_oracle_memory_integration.py
new file mode 100644
index 000000000..94f456e1d
--- /dev/null
+++ b/lib/crewai/tests/rag/embeddings/test_oracle_memory_integration.py
@@ -0,0 +1,84 @@
+"""Live integration tests for Oracle embeddings with Crew memory."""
+
+from __future__ import annotations
+
+import os
+
+import pytest
+
+from crewai.memory.unified_memory import Memory
+from crewai.rag.embeddings.factory import build_embedder
+
+
+ORACLE_USERNAME_ENV = "VECDB_USER"
+ORACLE_PASSWORD_ENV = "VECDB_PASS"
+ORACLE_DSN_ENV = "VECDB_HOST"
+ORACLE_MODEL_ENV = "ORACLE_EMBEDDING_MODEL"
+
+
+def _oracle_env_config() -> tuple[str, str, str] | None:
+ username = os.getenv(ORACLE_USERNAME_ENV, "")
+ password = os.getenv(ORACLE_PASSWORD_ENV, "")
+ dsn = os.getenv(ORACLE_DSN_ENV, "")
+ if not username or not password or not dsn:
+ return None
+ return username, password, dsn
+
+
+def test_oracle_embedder_and_memory_with_real_connection(
+ pytestconfig: pytest.Config,
+) -> None:
+ creds = _oracle_env_config()
+ if creds is None:
+ pytest.skip(
+ f"Set {ORACLE_USERNAME_ENV}, {ORACLE_PASSWORD_ENV}, and {ORACLE_DSN_ENV} to run Oracle integration tests."
+ )
+
+ if getattr(pytestconfig.option, "block_network", False):
+ pytest.skip(
+ "Network access is blocked by pytest addopts. Re-run this test without --block-network to use a real Oracle connection."
+ )
+
+ pytest.importorskip("oracledb")
+ username, password, dsn = creds
+ model_name = os.getenv(ORACLE_MODEL_ENV, "ALL_MINILM_L12_V2")
+ embedder_config = {
+ "provider": "oracle",
+ "config": {
+ "connection_params": {
+ "user": username,
+ "password": password,
+ "dsn": dsn,
+ },
+ "embedding_params": {
+ "provider": "database",
+ "model": model_name,
+ },
+ },
+ }
+
+ embedder = build_embedder(embedder_config)
+ vectors = embedder(["database tablespace", "kitchen recipes"])
+ assert len(vectors) == 2
+ assert len(vectors[0]) > 0
+ assert len(vectors[0]) == len(vectors[1])
+
+ memory = Memory(embedder=embedder_config)
+ record = memory.remember(
+ content="A tablespace can be online or offline whenever the database is open.",
+ scope="/oracle",
+ categories=["oracle", "storage"],
+ importance=0.8,
+ )
+ assert record is not None
+ assert record.scope == "/oracle"
+
+ results = memory.recall(
+ "tablespace online offline database",
+ scope="/oracle",
+ depth="shallow",
+ limit=3,
+ )
+ assert results, "Expected shallow recall to return at least one Oracle-embedded memory"
+ assert "tablespace" in results[0].record.content.lower()
diff --git a/lib/crewai/tests/rag/embeddings/test_oracle_provider.py b/lib/crewai/tests/rag/embeddings/test_oracle_provider.py
new file mode 100644
index 000000000..c3b8d187a
--- /dev/null
+++ b/lib/crewai/tests/rag/embeddings/test_oracle_provider.py
@@ -0,0 +1,452 @@
+"""Tests for Oracle embedding provider and callable."""
+
+from __future__ import annotations
+
+import json
+import sys
+from types import SimpleNamespace
+from typing import Any
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+from crewai.rag.embeddings.factory import build_embedder
+from crewai.rag.embeddings.providers.oracle.embedding_callable import (
+ OracleEmbeddingFunction,
+)
+from crewai.rag.embeddings.providers.oracle.oracle_provider import OracleProvider
+
+
+class FakeCursor:
+ """Minimal Oracle cursor test double."""
+
+ def __init__(
+ self,
+ rows: list[tuple[str]] | None = None,
+ execute_side_effects: list[Exception | None] | None = None,
+ ):
+ self.rows = rows or []
+ self.execute_side_effects = list(execute_side_effects or [])
+ self.executed: list[tuple[str, Any, dict[str, Any]]] = []
+ self.closed = False
+ self.inputsizes: tuple[Any, ...] | None = None
+
+ def execute(self, sql: str, params: Any = None, **kwargs: Any) -> None:
+ self.executed.append((sql, params, kwargs))
+ if self.execute_side_effects:
+ side_effect = self.execute_side_effects.pop(0)
+ if side_effect is not None:
+ raise side_effect
+
+ def setinputsizes(self, *args: Any) -> None:
+ self.inputsizes = args
+
+ def close(self) -> None:
+ self.closed = True
+
+ def __iter__(self):
+ return iter(self.rows)
+
+
+class FakeVectorArrayType:
+ """Minimal Oracle named type test double."""
+
+ def __init__(self):
+ self.newobject_calls: list[list[str]] = []
+
+ def newobject(self, values: list[str]) -> list[str]:
+ self.newobject_calls.append(values)
+ return values
+
+
+class FakeConnection:
+ """Minimal Oracle connection test double."""
+
+ def __init__(self, cursor: FakeCursor | None = None):
+ self._cursor = cursor or FakeCursor()
+ self.vector_array_type = FakeVectorArrayType()
+ self.closed = False
+
+ def cursor(self) -> FakeCursor:
+ return self._cursor
+
+ def gettype(self, name: str) -> FakeVectorArrayType:
+ assert name == "SYS.VECTOR_ARRAY_T"
+ return self.vector_array_type
+
+ def close(self) -> None:
+ self.closed = True
+
+
+class FakeOracleModule:
+ """Minimal oracledb module test double."""
+
+ DB_TYPE_JSON = object()
+
+ def __init__(self, connection: FakeConnection | None = None):
+ self.defaults = SimpleNamespace(fetch_lobs=True)
+ self._connection = connection or FakeConnection()
+ self.connect_calls: list[dict[str, Any]] = []
+
+ def connect(self, **kwargs: Any) -> FakeConnection:
+ self.connect_calls.append(kwargs)
+ return self._connection
+
+
+def _embedding_row(vector: list[float], embed_id: int = 1) -> tuple[str]:
+ return (json.dumps({"embed_id": embed_id, "embed_vector": json.dumps(vector)}),)
+
+
+class TestOracleProvider:
+ """Unit tests for the Oracle provider."""
+
+ @patch("crewai.rag.embeddings.factory.import_and_validate_definition")
+ def test_build_embedder_oracle_routes_to_provider(self, mock_import: MagicMock):
+ mock_provider_class = MagicMock()
+ mock_provider_instance = MagicMock()
+ mock_embedding_function = MagicMock()
+
+ mock_import.return_value = mock_provider_class
+ mock_provider_class.return_value = mock_provider_instance
+ mock_provider_instance.embedding_callable.return_value = mock_embedding_function
+
+ config = {
+ "provider": "oracle",
+ "config": {
+ "connection_params": {"user": "u", "password": "p", "dsn": "db"},
+ "embedding_params": {"provider": "database", "model": "demo_model"},
+ },
+ }
+
+ result = build_embedder(config)
+
+ assert result == mock_embedding_function
+ mock_import.assert_called_once_with(
+ "crewai.rag.embeddings.providers.oracle.oracle_provider.OracleProvider"
+ )
+ call_kwargs = mock_provider_class.call_args.kwargs
+ assert call_kwargs["connection_params"] == {
+ "user": "u",
+ "password": "p",
+ "dsn": "db",
+ }
+ assert call_kwargs["embedding_params"] == {
+ "provider": "database",
+ "model": "demo_model",
+ }
+
+ def test_provider_requires_exactly_one_connection_source(self):
+ with pytest.raises(ValueError, match="exactly one of 'conn' or 'connection_params'"):
+ OracleProvider(embedding_params={"provider": "database", "model": "m"})
+
+ with pytest.raises(ValueError, match="exactly one of 'conn' or 'connection_params'"):
+ OracleProvider(
+ conn=object(),
+ connection_params={"user": "u", "password": "p", "dsn": "db"},
+ embedding_params={"provider": "database", "model": "m"},
+ )
+
+ def test_build_embedder_with_existing_connection_reuses_it(self, monkeypatch: pytest.MonkeyPatch):
+ fake_conn = FakeConnection(
+ cursor=FakeCursor(rows=[_embedding_row([0.1, 0.2]), _embedding_row([0.3, 0.4], 2)])
+ )
+ fake_oracledb = FakeOracleModule()
+ monkeypatch.setitem(sys.modules, "oracledb", fake_oracledb)
+
+ embedder = build_embedder(
+ {
+ "provider": "oracle",
+ "config": {
+ "conn": fake_conn,
+ "embedding_params": {"provider": "database", "model": "demo_model"},
+ "proxy": "http://proxy.example:8080",
+ },
+ }
+ )
+
+ embeddings = embedder(["hello", "world"])
+
+ assert fake_oracledb.connect_calls == []
+ assert len(embeddings) == 2
+ assert embeddings[0].tolist() == pytest.approx([0.1, 0.2])
+ assert embeddings[1].tolist() == pytest.approx([0.3, 0.4])
+ assert fake_oracledb.defaults.fetch_lobs is True
+ assert fake_conn.vector_array_type.newobject_calls
+ proxy_call, embed_call, cleanup_call = fake_conn.cursor().executed
+ assert "utl_http.set_proxy" in proxy_call[0]
+ assert "dbms_vector_chain.utl_to_embeddings" in embed_call[0]
+ assert "utl_http.set_proxy(NULL)" in cleanup_call[0]
+ assert fake_conn.cursor().inputsizes == (None, fake_oracledb.DB_TYPE_JSON)
+ assert fake_conn.cursor().closed is True
+
+ def test_oracle_embedding_restores_fetch_lobs_when_call_fails(
+ self, monkeypatch: pytest.MonkeyPatch
+ ):
+ fake_cursor = FakeCursor(execute_side_effects=[RuntimeError("embedding failed")])
+ fake_conn = FakeConnection(cursor=fake_cursor)
+ fake_oracledb = FakeOracleModule()
+ monkeypatch.setitem(sys.modules, "oracledb", fake_oracledb)
+
+ embedder = OracleEmbeddingFunction(
+ conn=fake_conn,
+ embedding_params={"provider": "database", "model": "demo_model"},
+ )
+
+ with pytest.raises(RuntimeError, match="embedding failed"):
+ embedder(["hello"])
+
+ assert fake_oracledb.defaults.fetch_lobs is True
+ assert fake_cursor.closed is True
+
+ def test_oracle_embedding_proxy_cleanup_error_preserves_original_error(
+ self, monkeypatch: pytest.MonkeyPatch
+ ):
+ fake_cursor = FakeCursor(
+ execute_side_effects=[
+ None,
+ RuntimeError("embedding failed"),
+ RuntimeError("cleanup failed"),
+ ]
+ )
+ fake_conn = FakeConnection(cursor=fake_cursor)
+ fake_oracledb = FakeOracleModule()
+ monkeypatch.setitem(sys.modules, "oracledb", fake_oracledb)
+
+ embedder = OracleEmbeddingFunction(
+ conn=fake_conn,
+ embedding_params={"provider": "database", "model": "demo_model"},
+ proxy="http://proxy.example:8080",
+ )
+
+ with pytest.raises(RuntimeError, match="embedding failed"):
+ embedder(["hello"])
+
+ assert "utl_http.set_proxy(NULL)" in fake_cursor.executed[-1][0]
+ assert fake_cursor.closed is True
+
+ def test_build_embedder_connects_with_connection_params(self, monkeypatch: pytest.MonkeyPatch):
+ fake_cursor = FakeCursor(rows=[_embedding_row([1.0, 2.0, 3.0])])
+ fake_conn = FakeConnection(cursor=fake_cursor)
+ fake_oracledb = FakeOracleModule(connection=fake_conn)
+ monkeypatch.setitem(sys.modules, "oracledb", fake_oracledb)
+
+ embedder = build_embedder(
+ {
+ "provider": "oracle",
+ "config": {
+ "connection_params": {
+ "user": "oracle_user",
+ "password": "oracle_pass",
+ "dsn": "dbhost/service",
+ "config_dir": "/wallet",
+ },
+ "embedding_params": {"provider": "database", "model": "demo_model"},
+ },
+ }
+ )
+
+ embeddings = embedder(["database"])
+
+ assert fake_oracledb.connect_calls == [
+ {
+ "user": "oracle_user",
+ "password": "oracle_pass",
+ "dsn": "dbhost/service",
+ "config_dir": "/wallet",
+ }
+ ]
+ assert len(embeddings) == 1
+ assert embeddings[0].tolist() == pytest.approx([1.0, 2.0, 3.0])
+
+ def test_build_embedder_without_oracledb_raises(self, monkeypatch: pytest.MonkeyPatch):
+ monkeypatch.delitem(sys.modules, "oracledb", raising=False)
+
+ real_import = __import__
+
+ def _import(name: str, *args: Any, **kwargs: Any):
+ if name == "oracledb":
+ raise ImportError("missing")
+ return real_import(name, *args, **kwargs)
+
+ with patch("builtins.__import__", side_effect=_import):
+ with pytest.raises(ImportError, match="oracledb is required for oracle embeddings"):
+ build_embedder(
+ {
+ "provider": "oracle",
+ "config": {
+ "connection_params": {"user": "u", "password": "p", "dsn": "db"},
+ "embedding_params": {"provider": "database", "model": "demo_model"},
+ },
+ }
+ )
+
+ def test_embedding_callable_name(self):
+ assert OracleEmbeddingFunction.name() == "oracle"
+
+ def test_build_embedder_with_string_input_and_none_row_raises(
+ self, monkeypatch: pytest.MonkeyPatch
+ ):
+ fake_cursor = FakeCursor(rows=[None, _embedding_row([0.5, 0.6])])
+ fake_conn = FakeConnection(cursor=fake_cursor)
+ fake_oracledb = FakeOracleModule()
+ monkeypatch.setitem(sys.modules, "oracledb", fake_oracledb)
+
+ embedder = build_embedder(
+ {
+ "provider": "oracle",
+ "config": {
+ "conn": fake_conn,
+ "embedding_params": {"provider": "database", "model": "demo_model"},
+ },
+ }
+ )
+
+ with pytest.raises(ValueError, match="empty row"):
+ embedder("hello")
+
+ assert len(fake_conn.vector_array_type.newobject_calls[0]) == 1
+ assert fake_conn.vector_array_type.newobject_calls[0][0] == json.dumps(
+ {"chunk_id": 1, "chunk_data": "hello"}
+ )
+
+ def test_build_embedder_with_empty_input_raises_without_db_call(
+ self, monkeypatch: pytest.MonkeyPatch
+ ):
+ fake_cursor = FakeCursor()
+ fake_conn = FakeConnection(cursor=fake_cursor)
+ fake_oracledb = FakeOracleModule()
+ monkeypatch.setitem(sys.modules, "oracledb", fake_oracledb)
+
+ embedder = build_embedder(
+ {
+ "provider": "oracle",
+ "config": {
+ "conn": fake_conn,
+ "embedding_params": {"provider": "database", "model": "demo_model"},
+ },
+ }
+ )
+
+ with pytest.raises(ValueError, match="input cannot be empty"):
+ embedder([])
+
+ assert fake_cursor.executed == []
+
+ def test_owned_connection_is_closed_on_delete(self, monkeypatch: pytest.MonkeyPatch):
+ fake_conn = FakeConnection(cursor=FakeCursor(rows=[_embedding_row([1.0])]))
+ fake_oracledb = FakeOracleModule(connection=fake_conn)
+ monkeypatch.setitem(sys.modules, "oracledb", fake_oracledb)
+
+ embedder = build_embedder(
+ {
+ "provider": "oracle",
+ "config": {
+ "connection_params": {"user": "u", "password": "p", "dsn": "db"},
+ "embedding_params": {"provider": "database", "model": "demo_model"},
+ },
+ }
+ )
+ assert fake_conn.closed is False
+
+ embedder.__del__()
+
+ assert fake_conn.closed is True
+
+ def test_delete_swallows_connection_close_error(self, monkeypatch: pytest.MonkeyPatch):
+ class BrokenConnection(FakeConnection):
+ def close(self) -> None:
+ raise RuntimeError("boom")
+
+ fake_oracledb = FakeOracleModule(connection=BrokenConnection())
+ monkeypatch.setitem(sys.modules, "oracledb", fake_oracledb)
+
+ embedder = build_embedder(
+ {
+ "provider": "oracle",
+ "config": {
+ "connection_params": {"user": "u", "password": "p", "dsn": "db"},
+ "embedding_params": {"provider": "database", "model": "demo_model"},
+ },
+ }
+ )
+
+ embedder.__del__()
+
[email protected]("fetch_lobs", [True, False])
+def test_embedding_orders_rows_and_reads_lobs_without_changing_defaults(
+ monkeypatch, fetch_lobs
+):
+ from unittest.mock import Mock
+
+ lob = Mock()
+ lob.read.return_value = _embedding_row([2.0], 2)[0]
+ cursor = FakeCursor(rows=[(lob,), _embedding_row([1.0], 1)])
+ driver = FakeOracleModule()
+
+ class ReadOnlyDefaults:
+ @property
+ def fetch_lobs(self):
+ return fetch_lobs
+
+ driver.defaults = ReadOnlyDefaults()
+ monkeypatch.setitem(sys.modules, "oracledb", driver)
+ embedder = OracleEmbeddingFunction(conn=FakeConnection(cursor), embedding_params={})
+ assert [vector.tolist() for vector in embedder(["first", "second"])] == [
+ [1.0],
+ [2.0],
+ ]
+ assert driver.defaults.fetch_lobs is fetch_lobs
+ assert cursor.closed
+
+
[email protected]("ids", [[], [1], [1, 1], [1, 3], [0, 2], [True, 2], [None, 2]])
+def test_embedding_rejects_missing_duplicate_and_invalid_ids(monkeypatch, ids):
+ cursor = FakeCursor(rows=[_embedding_row([1.0], i) for i in ids])
+ monkeypatch.setitem(sys.modules, "oracledb", FakeOracleModule())
+ embedder = OracleEmbeddingFunction(conn=FakeConnection(cursor), embedding_params={})
+ with pytest.raises(ValueError, match="count|embed_id"):
+ embedder(["first", "second"])
+ assert cursor.closed
+
+
+def test_embedding_rejects_long_documents_before_database_call(monkeypatch):
+ cursor = FakeCursor()
+ monkeypatch.setitem(sys.modules, "oracledb", FakeOracleModule())
+ embedder = OracleEmbeddingFunction(conn=FakeConnection(cursor), embedding_params={})
+ with pytest.raises(ValueError, match="4000"):
+ embedder(["x" * 4001])
+ assert cursor.executed == []
+
+
+def test_proxy_environment_is_provider_specific(monkeypatch):
+ monkeypatch.setenv("PROXY", "generic-proxy")
+ kwargs = {"conn": object(), "embedding_params": {"provider": "database"}}
+ assert OracleProvider(**kwargs).proxy is None
+ monkeypatch.setenv("ORACLE_PROXY", "oracle-proxy")
+ assert OracleProvider(**kwargs).proxy == "oracle-proxy"
+ assert OracleProvider(**kwargs, proxy="explicit-proxy").proxy == "explicit-proxy"
+
+
[email protected]("source", ["environment", "dotenv"])
+def test_connection_object_is_not_loaded_from_settings(monkeypatch, tmp_path, source):
+ if source == "environment":
+ monkeypatch.setenv("ORACLE_CONN", "not-a-connection")
+ monkeypatch.setenv("ORACLE_PROXY", "oracle-proxy")
+ env_file = None
+ else:
+ env_file = tmp_path / ".env"
+ env_file.write_text(
+ "ORACLE_CONN=not-a-connection\nCONN=also-not-a-connection\nORACLE_PROXY=oracle-proxy\n"
+ )
+ params = {"user": "u", "dsn": "db"}
+ provider = OracleProvider(
+ connection_params=params, embedding_params={}, _env_file=env_file
+ )
+ assert provider.conn is None
+ assert provider.connection_params == params
+ assert provider.proxy == "oracle-proxy"
+ connection = object()
+ provider = OracleProvider(conn=connection, embedding_params={}, _env_file=env_file)
+ assert provider.conn is connection
+ with pytest.raises(ValueError, match="exactly one"):
+ OracleProvider(embedding_params={}, _env_file=env_file)
diff --git a/uv.lock b/uv.lock
index 4bc756edf..39724ac50 100644
--- a/uv.lock
+++ b/uv.lock
@@ -1797,6 +1797,9 @@ multion = [
mysql = [
{ name = "pymysql" },
]
+oracledb = [
+ { name = "oracledb" },
+]
oxylabs = [
{ name = "oxylabs" },
]
@@ -1885,6 +1888,7 @@ requires-dist = [
{ name = "nest-asyncio", marker = "extra == 'bedrock'", specifier = ">=1.6.0" },
{ name = "nest-asyncio", marker = "extra == 'contextual'", specifier = ">=1.6.0" },
{ name = "nltk", marker = "extra == 'xml'", specifier = ">=3.10.3" },
+ { name = "oracledb", marker = "extra == 'oracledb'", specifier = ">=2.2.0" },
{ name = "oxylabs", marker = "extra == 'oxylabs'", specifier = ">=2.0.0,<4" },
{ name = "patronus", marker = "extra == 'patronus'", specifier = ">=0.0.16" },
{ name = "playwright", marker = "extra == 'bedrock'", specifier = ">=1.52.0" },
@@ -1916,7 +1920,7 @@ requires-dist = [
{ name = "weaviate-client", marker = "extra == 'weaviate-client'", specifier = ">=4.10.2" },
{ name = "youtube-transcript-api", specifier = "~=1.2.2" },
]
-provides-extras = ["apify", "beautifulsoup4", "bedrock", "browserbase", "composio-core", "contextual", "couchbase", "databricks-sdk", "daytona", "e2b", "exa-py", "firecrawl-py", "github", "hyperbrowser", "linkup-sdk", "mcp", "mongodb", "multion", "mysql", "oxylabs", "patronus", "postgresql", "qdrant-client", "rag", "scrapegraph-py", "scrapfly-sdk", "selenium", "serpapi", "singlestore", "snowflake", "spider-client", "sqlalchemy", "stagehand", "tavily-python", "weaviate-client", "xml"]
+provides-extras = ["apify", "beautifulsoup4", "bedrock", "browserbase", "composio-core", "contextual", "couchbase", "databricks-sdk", "daytona", "e2b", "exa-py", "firecrawl-py", "github", "hyperbrowser", "linkup-sdk", "mcp", "mongodb", "multion", "mysql", "oracledb", "oxylabs", "patronus", "postgresql", "qdrant-client", "rag", "scrapegraph-py", "scrapfly-sdk", "selenium", "serpapi", "singlestore", "snowflake", "spider-client", "sqlalchemy", "stagehand", "tavily-python", "weaviate-client", "xml"]
[[package]]
name = "cryptography"
@@ -5985,6 +5989,49 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/cb/7a/7fe66f5f3682b1dd47d88cc4e11f1c6c0966b737de2d16671146e23c39a5/opentelemetry_semantic_conventions-0.63b1-py3-none-any.whl", hash = "sha256:dfe5ef4dee82586b746f522b818ceb298d00b3d59f660042bd79404bff8d0682", size = 203713, upload-time = "2026-05-21T16:32:47.016Z" },
]
+[[package]]
+name = "oracledb"
+version = "4.0.1"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "cryptography" },
+ { name = "typing-extensions" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/f3/01/203599755aaff4f79683c2d61d2e6dc9d30f6228485d9e0280cc358cede3/oracledb-4.0.1.tar.gz", hash = "sha256:34bbea44423ed8b24093aa859ca7ee9b6e76ea490f9acdc5f6ff01aa1083e343", size = 879077, upload-time = "2026-05-19T18:14:34.881Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/4f/4e/d1a16f398963eb41a6a1024030bf6c5ead34df2f9e558fbf24759effa703/oracledb-4.0.1-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:dbe8b44fea57385617838f2acfce8cc19f6c95cd9e65e7235e86b5932af1acd9", size = 4374567, upload-time = "2026-05-19T18:14:41.043Z" },
+ { url = "https://files.pythonhosted.org/packages/db/da/849e06ddd29f5d8807ba9fb93ebdf210958273eeb12ca08f72d9f07f87cb/oracledb-4.0.1-cp310-cp310-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e3d54b624748cfe42248c4bc62c3f788632a2077058485a9acb3150312b1c396", size = 2499287, upload-time = "2026-05-19T18:14:43.321Z" },
+ { url = "https://files.pythonhosted.org/packages/fe/b6/d6df13f297ccf64396867da84bed8529e2c1755839207746e5ac2cc6abc2/oracledb-4.0.1-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:29ae0ff517a3241060eeee15a321b710c3f83a688cf2da7d5729adbe212e2b00", size = 2689995, upload-time = "2026-05-19T18:14:44.832Z" },
+ { url = "https://files.pythonhosted.org/packages/01/98/5dec7011c2c26c8c3c2f9ea76783e2bc6cd6ad5f0489782f9cf4637e733f/oracledb-4.0.1-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:73ba32597fe1da72e0824aaa4b1900ec08a3b77268cb4eb45c733ae7e7043e70", size = 2540194, upload-time = "2026-05-19T18:14:46.615Z" },
+ { url = "https://files.pythonhosted.org/packages/09/ef/21049e705a5dbac0011e647a4dcaf1746a501e8e19da98bd1674b21206d7/oracledb-4.0.1-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:ce3f25552fe58df5c266874f8b13f0a8ab7fcd09ab4b476bc15520a67527ca4b", size = 2714751, upload-time = "2026-05-19T18:14:48.09Z" },
+ { url = "https://files.pythonhosted.org/packages/4f/c1/0e02cc9f84b92a2fc8cbcb48be22b43076c511392b6ec36795e8a9ebc424/oracledb-4.0.1-cp310-cp310-win32.whl", hash = "sha256:7db5a43c29a23ed23923a29816c65c7a81fe00f2abfe6bf36d83ad952abd9b89", size = 1546877, upload-time = "2026-05-19T18:14:50.081Z" },
+ { url = "https://files.pythonhosted.org/packages/b9/4a/d14ac7ed4e2f87f77807eaed88d8a2e787219407f170e80546cbebc466dd/oracledb-4.0.1-cp310-cp310-win_amd64.whl", hash = "sha256:03afeda85bec3eca983ebf3ad9910d0f217d99300258366d287e015a041d6c13", size = 1894743, upload-time = "2026-05-19T18:14:52.038Z" },
+ { url = "https://files.pythonhosted.org/packages/88/46/f38813e076a43cfa632db2b80761c0b1aa1c85dca7b89720d4984b3b2e17/oracledb-4.0.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:86a06d0afb3bb3a24bace0e72fb9abca2093efe0fa3457c65c13ba4eb5000b0b", size = 4351657, upload-time = "2026-05-19T18:14:53.834Z" },
+ { url = "https://files.pythonhosted.org/packages/0f/e6/8ad2592ae4d5657882b900bad1b1286f1b29befa0f418df8550d8f7defd6/oracledb-4.0.1-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:416b324cd7715073cf5f3d577330387ffd59741463995c25bdc2d82b3e80b88e", size = 2492515, upload-time = "2026-05-19T18:14:55.834Z" },
+ { url = "https://files.pythonhosted.org/packages/08/4e/eaab1183a2ba63e7f8673e3305f5382488c773d8f51d9a705e90d8b8b3e1/oracledb-4.0.1-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:ce6319ee01dcbb4d74f0e2a5794c6a566f339958ecac9830c67c7070521620e2", size = 2680701, upload-time = "2026-05-19T18:14:57.418Z" },
+ { url = "https://files.pythonhosted.org/packages/44/f5/824b419dc3758c86ddcb1d8f69d1e7957882e58e99a3907a45a063ed0878/oracledb-4.0.1-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:873fcca53306e2b3b445a7d657cddc19e415a7aa7e392c473dfd1a3ae3970989", size = 2542151, upload-time = "2026-05-19T18:14:59.173Z" },
+ { url = "https://files.pythonhosted.org/packages/be/5c/35b60bb1c85be5607913a24467052d6496eed9493793989de2a6b9b71147/oracledb-4.0.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:b09eec35681d72c9476e6d715b89bb775724a31e7363df6beba7470494ea8040", size = 2709740, upload-time = "2026-05-19T18:15:01.03Z" },
+ { url = "https://files.pythonhosted.org/packages/79/22/d4639df519c7cca02f45b3404c9e7934970f50a0296f704be7b1805b1ce7/oracledb-4.0.1-cp311-cp311-win32.whl", hash = "sha256:08e84a6af1b6e5921dba088dd9fc0738927206eafe5ce9763c34195f87556849", size = 1543018, upload-time = "2026-05-19T18:15:02.516Z" },
+ { url = "https://files.pythonhosted.org/packages/20/88/7304ff7d512f45d6804501e404ceb7e567eb15661cd7d06c9ffaa6025cb5/oracledb-4.0.1-cp311-cp311-win_amd64.whl", hash = "sha256:3b5ef1676a27b7e0a7ec55be27fd8f6d28d1601f5e8dfdae78705909f25b7c0a", size = 1901166, upload-time = "2026-05-19T18:15:04.096Z" },
+ { url = "https://files.pythonhosted.org/packages/2d/b5/079fe8aa90cb769c68a54dde7591b374c64260d3d448c086acf4585cb8fc/oracledb-4.0.1-cp311-cp311-win_arm64.whl", hash = "sha256:90586b3c7729b9cf3d40df902e81257f01e15e3408d8b6b9dbf91e939b64f72c", size = 1586727, upload-time = "2026-05-19T18:15:05.523Z" },
+ { url = "https://files.pythonhosted.org/packages/53/1a/237ddaa33fe9576e1bb1ee9008eba2269fe49dee974a581465589eac658e/oracledb-4.0.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:c05a01d6ad610a88c2aa1a43b1dc0a8485f5fbd4374d2b36908859d4205de192", size = 4345951, upload-time = "2026-05-19T18:15:07.482Z" },
+ { url = "https://files.pythonhosted.org/packages/d8/bd/2ee10e0bd4d7a44db68a3f10d8941a5ea762bdb9dcff9b37739b2554e011/oracledb-4.0.1-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:cf61e42b9ef723dbdd0b23032b695e872009ed7341003df59d9a97cd960df977", size = 2290431, upload-time = "2026-05-19T18:15:09.041Z" },
+ { url = "https://files.pythonhosted.org/packages/80/54/98fac98c9c1e2461512dcad81d2bd491fb7fe779d5044614867b2e827a78/oracledb-4.0.1-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:c2d394453f669858bec942ff0da18b6ebade296ece823d582ad2b464ed5c6c90", size = 2493620, upload-time = "2026-05-19T18:15:10.635Z" },
+ { url = "https://files.pythonhosted.org/packages/58/71/ebeade4753fd20b6d9cc7568c3853bec44425f24982def220835544008ca/oracledb-4.0.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:d7cd278d59780e22e0a7451d208460756d779dc62b55bdbd95652f9640fbf8c3", size = 2329161, upload-time = "2026-05-19T18:15:12.158Z" },
+ { url = "https://files.pythonhosted.org/packages/21/1d/4ec3ef256633126b669b99bf14e1c2af264ecb25c28f80f5365ea279c39a/oracledb-4.0.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:b73820521eccd290506af94e1ffb9a8a5941b4018e3861df9b040652a7cef123", size = 2513518, upload-time = "2026-05-19T18:15:14.863Z" },
+ { url = "https://files.pythonhosted.org/packages/7c/7a/4506477b52bb2db61a114202beab19bf24859f9fdc0979b8031042582477/oracledb-4.0.1-cp312-cp312-win32.whl", hash = "sha256:8fcad6d9628923281bf21e48a391ac2f87ec6950dc63381d8fea470e3128aef0", size = 1498632, upload-time = "2026-05-19T18:15:16.361Z" },
+ { url = "https://files.pythonhosted.org/packages/dd/66/3d2246e5473b85c61d4b206ea9fcf50619db6b60a1425e34a3a1c1f64c44/oracledb-4.0.1-cp312-cp312-win_amd64.whl", hash = "sha256:523b3356cde9d588ba250cefafdfc34869233d65c179f805ea6e4d3d6b209a7f", size = 1846730, upload-time = "2026-05-19T18:15:18.532Z" },
+ { url = "https://files.pythonhosted.org/packages/dd/95/70420ebc1f051cff48cffb48f720540446d3fc497f7d9ba6f2e63337cb3f/oracledb-4.0.1-cp312-cp312-win_arm64.whl", hash = "sha256:10204432f0eea8707a79c75bdccb84071e43fd19c658cb3b34d1746b12c6e7fe", size = 1518529, upload-time = "2026-05-19T18:15:19.916Z" },
+ { url = "https://files.pythonhosted.org/packages/e3/52/c95031186ddec3788ee72708df406a6b7bafa308bd04722b7d5857942366/oracledb-4.0.1-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:443b2f03461e873ccd73dff3d8541fcf974c05e13e296a6687ffbb0c4a72c0a1", size = 4331008, upload-time = "2026-05-19T18:15:21.762Z" },
+ { url = "https://files.pythonhosted.org/packages/ae/c3/7aaf12fe0f8b8323bce4647762722268da6b3b04ab1ff2349e4b43d30515/oracledb-4.0.1-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:ae894ca2705929eb0ac228329336fd03388ad6e3b54002be6f5d4400a8feaf52", size = 2284457, upload-time = "2026-05-19T18:15:23.727Z" },
+ { url = "https://files.pythonhosted.org/packages/db/1e/48af5b2c559ee2fbee2ad13372858f34f2260cd9727b8ccad6cbe26e09b8/oracledb-4.0.1-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:4b42725337f80d433a3bd2928c08667e5b89da9ce05cf9ae3a4189c4fc4805ea", size = 2506136, upload-time = "2026-05-19T18:15:26.057Z" },
+ { url = "https://files.pythonhosted.org/packages/1f/79/50cb8f7a3bc7ef9edc61db5fbf0ee2af9a4f487f4967eb54cc9f330ea908/oracledb-4.0.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:8e13ff1e6f28fdb863180d23fa94cb42c619c29d2981e24992431e51b97caa54", size = 2332705, upload-time = "2026-05-19T18:15:27.632Z" },
+ { url = "https://files.pythonhosted.org/packages/48/7d/6eea9e9ffece7d270a7d3caf364b5033fa8c73a0f377c10750eca8760a6e/oracledb-4.0.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:e36581bb10e719d928dad12018c2d42606db2c34f49d6665b06f701f049255f0", size = 2528849, upload-time = "2026-05-19T18:15:29.437Z" },
+ { url = "https://files.pythonhosted.org/packages/97/5c/553afdf90a144e25c5ee9825fbbc0c88d52bcf2b1dd7c5b509cad1022a60/oracledb-4.0.1-cp313-cp313-win32.whl", hash = "sha256:86ac65cbc8d29626b1d9d203f9151566c26a78e55bdfc030c06169ae8017f458", size = 1503094, upload-time = "2026-05-19T18:15:30.838Z" },
+ { url = "https://files.pythonhosted.org/packages/b9/73/9305fa2755b234352e29dd5ed6063d017a661ccb08c06da5e14db90b143d/oracledb-4.0.1-cp313-cp313-win_amd64.whl", hash = "sha256:a029dcee759bca56a8c95e952040c3d3f57e5ec05965355293b21930a66967fb", size = 1846068, upload-time = "2026-05-19T18:15:32.475Z" },
+ { url = "https://files.pythonhosted.org/packages/fd/d8/6995a755dbdeee1eab1a6cb77283e3ab6634631512c47e2c3a64efcb515f/oracledb-4.0.1-cp313-cp313-win_arm64.whl", hash = "sha256:20a10f903c8da59e9689a98bd68012f78fa19bed950ad9f19cd8f5b8b97e73a0", size = 1518345, upload-time = "2026-05-19T18:15:34.156Z" },
+]
+
[[package]]
name = "orjson"
version = "3.11.9"