Knowledge Bases API
KnowledgeBase
Bases: SynalinksSaveable
A knowledge base for storing and retrieving structured data.
The KnowledgeBase provides a unified interface for storing structured data with support for full-text search and optional vector similarity search. It uses DuckDB as the underlying storage engine.
Basic Usage
import synalinks
class Document(synalinks.DataModel):
id: str
title: str
content: str
# Create a knowledge base without embeddings (full-text search only)
knowledge_base = synalinks.KnowledgeBase(
uri="duckdb://my_database.db",
data_models=[Document],
)
# Store a document
doc = Document(id="1", title="Hello", content="Hello World!")
await knowledge_base.update(doc.to_json_data_model())
# Retrieve by ID
result = await knowledge_base.get("1", [Document.to_symbolic_data_model()])
# Full-text search
results = await knowledge_base.fulltext_search("Hello", k=10)
With Vector Similarity Search
embedding_model = synalinks.EmbeddingModel(
model="ollama/mxbai-embed-large"
)
knowledge_base = synalinks.KnowledgeBase(
uri="duckdb://./my_database.db",
data_models=[Document],
embedding_model=embedding_model,
metric="cosine",
)
# Hybrid search (combines full-text and vector similarity)
results = await knowledge_base.hybrid_search("semantic query", k=10)
Retrieving Table Definitions
# Get all symbolic data models (table definitions) from the database
symbolic_models = knowledge_base.get_symbolic_data_models()
for model in symbolic_models:
print(model.get_schema())
# {'title': 'Document', 'type': 'object', 'properties': {...}, ...}
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
uri
|
str
|
The database connection URI. Use "duckdb://path/to/db.db" for DuckDB. If not provided, uses an in-memory database. |
None
|
data_models
|
list
|
Optional list of DataModel or SymbolicDataModel classes to create tables for. |
None
|
embedding_model
|
EmbeddingModel
|
Optional embedding model for vector similarity search. |
None
|
metric
|
str
|
The distance metric for vector search. Options: "cosine", "l2seq", "ip" (default: "cosine"). |
'cosine'
|
wipe_on_start
|
bool
|
Whether to clear the database on initialization (default: False). |
False
|
name
|
str
|
Optional name for the knowledge base (used for serialization). |
None
|
Source code in synalinks/src/knowledge_bases/knowledge_base.py
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 | |
fulltext_search(text_or_texts, data_models=None, k=10, threshold=None)
async
Perform full-text search using BM25 ranking.
Searches text fields (description, text, content, message, name, query, question) for matching documents.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text_or_texts
|
Union[str, List[str]]
|
Query text or list of query texts. |
required |
data_models
|
Optional[List[Any]]
|
Optional list of SymbolicDataModels to search in. |
None
|
k
|
int
|
Maximum number of results to return (default: 10). |
10
|
threshold
|
Optional[float]
|
Optional minimum BM25 score threshold. |
None
|
Returns:
| Type | Description |
|---|---|
List[Dict[str, Any]]
|
List of matching records with relevance scores. |
Source code in synalinks/src/knowledge_bases/knowledge_base.py
get(id_or_ids, data_models=None)
async
Retrieve a record by its primary key.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
id_or_ids
|
Any
|
The primary key value to look up. |
required |
data_models
|
Optional[List[Any]]
|
Optional list of SymbolicDataModels to search in. If not provided, searches all tables. |
None
|
Returns:
| Type | Description |
|---|---|
Optional[Any]
|
JsonDataModel if found, None otherwise. |
Source code in synalinks/src/knowledge_bases/knowledge_base.py
get_symbolic_data_models()
Retrieve all symbolic data models (table definitions) from the database.
Returns a list of SymbolicDataModel objects representing each table in the database. This is useful for introspecting the database schema or for passing to search methods to limit the search scope.
Returns:
| Name | Type | Description |
|---|---|---|
list |
List[Any]
|
List of symbolic data models representing the database tables. |
Example
Source code in synalinks/src/knowledge_bases/knowledge_base.py
getall(data_model, limit=50, offset=0)
async
Retrieve all records from a table with pagination.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data_model
|
Any
|
The SymbolicDataModel representing the table to query. |
required |
limit
|
int
|
Maximum number of records to return (default: 50). |
50
|
offset
|
int
|
Number of records to skip (default: 0). |
0
|
Returns:
| Type | Description |
|---|---|
List[Any]
|
List of JsonDataModels. |
Source code in synalinks/src/knowledge_bases/knowledge_base.py
hybrid_search(text_or_texts, data_models=None, k=10, k_rank=60, similarity_threshold=None, fulltext_threshold=None)
async
Perform hybrid search combining vector similarity and full-text.
Uses Reciprocal Rank Fusion (RRF) to combine results from both similarity search and full-text search. Falls back to full-text search only if no embedding model is configured.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text_or_texts
|
Union[str, List[str]]
|
Query text or list of query texts. |
required |
data_models
|
Optional[List[Any]]
|
Optional list of SymbolicDataModels to search in. |
None
|
k
|
int
|
Maximum number of results to return (default: 10). |
10
|
k_rank
|
int
|
RRF smoothing constant. Lower values emphasize top ranks more strongly (default: 60). |
60
|
similarity_threshold
|
Optional[float]
|
Optional threshold for vector similarity. |
None
|
fulltext_threshold
|
Optional[float]
|
Optional threshold for full-text relevance. |
None
|
Returns:
| Type | Description |
|---|---|
List[Dict[str, Any]]
|
List of matching records with combined scores. |
Source code in synalinks/src/knowledge_bases/knowledge_base.py
query(query, params=None, **kwargs)
async
Execute a raw SQL query against the knowledge base.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
query
|
str
|
The SQL query to execute. |
required |
params
|
dict
|
Optional list of parameters for parameterized queries. |
None
|
**kwargs
|
Any
|
Additional options (e.g., read_only=True/False). |
{}
|
Returns:
| Type | Description |
|---|---|
List[Dict[str, Any]]
|
List of result dictionaries. |
Source code in synalinks/src/knowledge_bases/knowledge_base.py
similarity_search(text_or_texts, data_models=None, k=10, threshold=None)
async
Perform vector similarity search using embeddings.
Requires an embedding_model to be configured.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text_or_texts
|
Union[str, List[str]]
|
Query text or list of query texts. |
required |
data_models
|
Optional[List[Any]]
|
Optional list of SymbolicDataModels to search in. |
None
|
k
|
int
|
Maximum number of results to return (default: 10). |
10
|
threshold
|
Optional[float]
|
Optional maximum distance threshold for filtering. |
None
|
Returns:
| Type | Description |
|---|---|
List[Dict[str, Any]]
|
List of matching records with similarity scores. |
Source code in synalinks/src/knowledge_bases/knowledge_base.py
update(data_model_or_data_models)
async
Insert or update records in the knowledge base.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data_model_or_data_models
|
JsonDataModel | List[JsonDataModel]
|
A single JsonDataModel or a list of JsonDataModels to insert or update. Uses the first field as the primary key for upserts. |
required |
Returns:
| Type | Description |
|---|---|
Union[Any, List[Any]]
|
The primary key value(s) of the inserted/updated records. |