|
| 1 | +--- |
| 2 | +title: Db2 Vector Search Tool |
| 3 | +description: Semantic vector search for CrewAI agents using IBM Db2 native VECTOR_DISTANCE capabilities. |
| 4 | +icon: database |
| 5 | +mode: "wide" |
| 6 | +--- |
| 7 | + |
| 8 | +# `DB2VectorSearchTool` |
| 9 | + |
| 10 | +## Description |
| 11 | + |
| 12 | +Perform semantic vector similarity searches against IBM Db2 tables using the native `VECTOR_DISTANCE` function. |
| 13 | +Supports configurable distance metrics, OpenAI or custom embeddings, metadata filtering, and result shaping. |
| 14 | + |
| 15 | +## Installation |
| 16 | + |
| 17 | +```bash |
| 18 | +pip install ibm_db openai |
| 19 | +``` |
| 20 | + |
| 21 | +Or with uv: |
| 22 | + |
| 23 | +```bash |
| 24 | +uv add ibm_db openai |
| 25 | +``` |
| 26 | + |
| 27 | +## Environment Variables |
| 28 | + |
| 29 | +```bash |
| 30 | +OPENAI_API_KEY=your_openai_key # Required when using default OpenAI embeddings |
| 31 | +DB2_CONNECTION_STRING=DATABASE=TESTDB;HOSTNAME=localhost;PORT=50000;PROTOCOL=TCPIP;UID=db2user;PWD=password; |
| 32 | +``` |
| 33 | + |
| 34 | +## Basic Usage |
| 35 | + |
| 36 | +```python |
| 37 | +from crewai import Agent |
| 38 | +from crewai_tools import DB2VectorSearchTool |
| 39 | + |
| 40 | +tool = DB2VectorSearchTool( |
| 41 | + connection_string="DATABASE=TESTDB;HOSTNAME=localhost;PORT=50000;PROTOCOL=TCPIP;UID=db2user;PWD=password;", |
| 42 | + table_name="documents", |
| 43 | + vector_column="embedding", |
| 44 | +) |
| 45 | + |
| 46 | +agent = Agent( |
| 47 | + role="Research Assistant", |
| 48 | + goal="Find relevant information in documents", |
| 49 | + tools=[tool], |
| 50 | +) |
| 51 | +``` |
| 52 | + |
| 53 | +## Full Semantic Search Workflow |
| 54 | + |
| 55 | +```python |
| 56 | +import os |
| 57 | +from dotenv import load_dotenv |
| 58 | +from crewai import Agent, Task, Crew, Process |
| 59 | +from crewai_tools import DB2VectorSearchTool |
| 60 | + |
| 61 | +load_dotenv() |
| 62 | + |
| 63 | +db2_tool = DB2VectorSearchTool( |
| 64 | + connection_string=os.getenv("DB2_CONNECTION_STRING"), |
| 65 | + table_name="documents", |
| 66 | + vector_column="embedding", |
| 67 | + return_columns=["content", "category"], |
| 68 | + limit=3, |
| 69 | + distance_metric="COSINE", |
| 70 | + max_distance=0.35, |
| 71 | +) |
| 72 | + |
| 73 | +search_agent = Agent( |
| 74 | + role="Senior Semantic Search Agent", |
| 75 | + goal="Find and analyse documents based on semantic search", |
| 76 | + backstory="You are an expert research assistant who can find relevant information using semantic search in a Db2 database.", |
| 77 | + tools=[db2_tool], |
| 78 | + verbose=True, |
| 79 | +) |
| 80 | + |
| 81 | +answer_agent = Agent( |
| 82 | + role="Senior Answer Assistant", |
| 83 | + goal="Generate answers based on retrieved context", |
| 84 | + backstory="You are an expert assistant who generates answers from provided context.", |
| 85 | + tools=[db2_tool], |
| 86 | + verbose=True, |
| 87 | +) |
| 88 | + |
| 89 | +search_task = Task( |
| 90 | + description="""Search for relevant documents about {query}. |
| 91 | + Include the relevant information found, vector distances, and returned fields.""", |
| 92 | + agent=search_agent, |
| 93 | +) |
| 94 | + |
| 95 | +answer_task = Task( |
| 96 | + description="Given the retrieved Db2 context, generate a final answer.", |
| 97 | + agent=answer_agent, |
| 98 | +) |
| 99 | + |
| 100 | +crew = Crew( |
| 101 | + agents=[search_agent, answer_agent], |
| 102 | + tasks=[search_task, answer_task], |
| 103 | + process=Process.sequential, |
| 104 | + verbose=True, |
| 105 | +) |
| 106 | + |
| 107 | +result = crew.kickoff(inputs={"query": "What is the role of X in the document?"}) |
| 108 | +print(result) |
| 109 | +``` |
| 110 | + |
| 111 | +## Tool Parameters |
| 112 | + |
| 113 | +| Parameter | Type | Default | Description | |
| 114 | +|---|---|---|---| |
| 115 | +| `connection_string` | `str` | required | Db2 connection string. Format: `DATABASE=x;HOSTNAME=x;PORT=50000;PROTOCOL=TCPIP;UID=x;PWD=x;` | |
| 116 | +| `table_name` | `str` | `"documents"` | Table to search. Supports `schema.table` notation. | |
| 117 | +| `vector_column` | `str` | `"embedding"` | Column storing the vector embeddings. | |
| 118 | +| `embedding_model` | `str` | `"text-embedding-3-large"` | OpenAI model used when no custom embedding function is provided. | |
| 119 | +| `return_columns` | `list[str]` | `["content"]` | Columns to include in each result. Must contain at least one entry. | |
| 120 | +| `limit` | `int` | `3` | Maximum number of results (1–100). | |
| 121 | +| `distance_metric` | `str` | `"COSINE"` | Db2 distance metric. See supported values below. | |
| 122 | +| `max_distance` | `float \| None` | `None` | Drop results whose distance exceeds this value. | |
| 123 | +| `custom_embedding_fn` | `Callable[[str], list[float]] \| None` | `None` | Custom embedding function. Overrides OpenAI when provided. | |
| 124 | + |
| 125 | +## Supported Distance Metrics |
| 126 | + |
| 127 | +The following values map directly to the Db2 `VECTOR_DISTANCE` function: |
| 128 | + |
| 129 | +- `COSINE` |
| 130 | +- `EUCLIDEAN` |
| 131 | +- `EUCLIDEAN_SQUARED` |
| 132 | +- `DOT` |
| 133 | +- `HAMMING` |
| 134 | +- `MANHATTAN` |
| 135 | + |
| 136 | +Reference: [IBM Db2 VECTOR_DISTANCE documentation](https://www.ibm.com/docs/en/db2/12.1.x?topic=functions-vector-distance) |
| 137 | + |
| 138 | +## Schema Parameters (per query) |
| 139 | + |
| 140 | +| Parameter | Type | Required | Description | |
| 141 | +|---|---|---|---| |
| 142 | +| `query` | `str` | ✅ | The search query. | |
| 143 | +| `filter_by` | `str \| None` | ❌ | Column name for metadata filtering. Must be paired with `filter_value`. | |
| 144 | +| `filter_value` | `Any \| None` | ❌ | Value to filter on. Must be paired with `filter_by`. | |
| 145 | + |
| 146 | +## Return Format |
| 147 | + |
| 148 | +```json |
| 149 | +{ |
| 150 | + "success": true, |
| 151 | + "results": [ |
| 152 | + { |
| 153 | + "distance": 0.1401, |
| 154 | + "data": { |
| 155 | + "content": "Document content here", |
| 156 | + "category": "research" |
| 157 | + } |
| 158 | + } |
| 159 | + ] |
| 160 | +} |
| 161 | +``` |
| 162 | + |
| 163 | +On error: |
| 164 | + |
| 165 | +```json |
| 166 | +{ |
| 167 | + "success": false, |
| 168 | + "error": "Description of what went wrong", |
| 169 | + "error_type": "ExceptionClassName" |
| 170 | +} |
| 171 | +``` |
| 172 | + |
| 173 | +## Metadata Filtering |
| 174 | + |
| 175 | +```python |
| 176 | +result = db2_tool.run( |
| 177 | + query="machine learning", |
| 178 | + filter_by="category", |
| 179 | + filter_value="research", |
| 180 | +) |
| 181 | +``` |
| 182 | + |
| 183 | +`filter_by` and `filter_value` must always be provided together. Providing only one raises a validation error. |
| 184 | + |
| 185 | +## Custom Embeddings |
| 186 | + |
| 187 | +Use any embedding model by supplying a `custom_embedding_fn`: |
| 188 | + |
| 189 | +```python |
| 190 | +from sentence_transformers import SentenceTransformer |
| 191 | +from crewai_tools import DB2VectorSearchTool |
| 192 | + |
| 193 | +model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2") |
| 194 | + |
| 195 | +def custom_embeddings(text: str) -> list[float]: |
| 196 | + return model.encode(text).tolist() |
| 197 | + |
| 198 | +tool = DB2VectorSearchTool( |
| 199 | + connection_string="DATABASE=TESTDB;HOSTNAME=localhost;PORT=50000;PROTOCOL=TCPIP;UID=db2user;PWD=password;", |
| 200 | + table_name="documents", |
| 201 | + custom_embedding_fn=custom_embeddings, |
| 202 | +) |
| 203 | +``` |
| 204 | + |
| 205 | +When `custom_embedding_fn` is provided, `OPENAI_API_KEY` is not required. |
| 206 | + |
| 207 | +## Security Features |
| 208 | + |
| 209 | +- SQL identifier validation (table, column names must match `^[A-Za-z][A-Za-z0-9_]*(\.[A-Za-z][A-Za-z0-9_]*)?$`) |
| 210 | +- Parameterised SQL queries — values never interpolated into SQL strings |
| 211 | +- Distance metric whitelist — only valid Db2 metric names accepted |
0 commit comments