camel-ai 0.2.67__py3-none-any.whl → 0.2.80a2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (224) hide show
  1. camel/__init__.py +1 -1
  2. camel/agents/_types.py +6 -2
  3. camel/agents/_utils.py +38 -0
  4. camel/agents/chat_agent.py +4014 -410
  5. camel/agents/mcp_agent.py +30 -27
  6. camel/agents/repo_agent.py +2 -1
  7. camel/benchmarks/browsecomp.py +6 -6
  8. camel/configs/__init__.py +15 -0
  9. camel/configs/aihubmix_config.py +88 -0
  10. camel/configs/amd_config.py +70 -0
  11. camel/configs/cometapi_config.py +104 -0
  12. camel/configs/minimax_config.py +93 -0
  13. camel/configs/nebius_config.py +103 -0
  14. camel/configs/vllm_config.py +2 -0
  15. camel/data_collectors/alpaca_collector.py +15 -6
  16. camel/datagen/self_improving_cot.py +1 -1
  17. camel/datasets/base_generator.py +39 -10
  18. camel/environments/__init__.py +12 -0
  19. camel/environments/rlcards_env.py +860 -0
  20. camel/environments/single_step.py +28 -3
  21. camel/environments/tic_tac_toe.py +1 -1
  22. camel/interpreters/__init__.py +2 -0
  23. camel/interpreters/docker/Dockerfile +4 -16
  24. camel/interpreters/docker_interpreter.py +3 -2
  25. camel/interpreters/e2b_interpreter.py +34 -1
  26. camel/interpreters/internal_python_interpreter.py +51 -2
  27. camel/interpreters/microsandbox_interpreter.py +395 -0
  28. camel/loaders/__init__.py +11 -2
  29. camel/loaders/base_loader.py +85 -0
  30. camel/loaders/chunkr_reader.py +9 -0
  31. camel/loaders/firecrawl_reader.py +4 -4
  32. camel/logger.py +1 -1
  33. camel/memories/agent_memories.py +84 -1
  34. camel/memories/base.py +34 -0
  35. camel/memories/blocks/chat_history_block.py +122 -4
  36. camel/memories/blocks/vectordb_block.py +8 -1
  37. camel/memories/context_creators/score_based.py +29 -237
  38. camel/memories/records.py +88 -8
  39. camel/messages/base.py +166 -40
  40. camel/messages/func_message.py +32 -5
  41. camel/models/__init__.py +10 -0
  42. camel/models/aihubmix_model.py +83 -0
  43. camel/models/aiml_model.py +1 -16
  44. camel/models/amd_model.py +101 -0
  45. camel/models/anthropic_model.py +117 -18
  46. camel/models/aws_bedrock_model.py +2 -33
  47. camel/models/azure_openai_model.py +205 -91
  48. camel/models/base_audio_model.py +3 -1
  49. camel/models/base_model.py +189 -24
  50. camel/models/cohere_model.py +5 -17
  51. camel/models/cometapi_model.py +83 -0
  52. camel/models/crynux_model.py +1 -16
  53. camel/models/deepseek_model.py +6 -16
  54. camel/models/fish_audio_model.py +6 -0
  55. camel/models/gemini_model.py +71 -20
  56. camel/models/groq_model.py +1 -17
  57. camel/models/internlm_model.py +1 -16
  58. camel/models/litellm_model.py +49 -32
  59. camel/models/lmstudio_model.py +1 -17
  60. camel/models/minimax_model.py +83 -0
  61. camel/models/mistral_model.py +1 -16
  62. camel/models/model_factory.py +27 -1
  63. camel/models/model_manager.py +24 -6
  64. camel/models/modelscope_model.py +1 -16
  65. camel/models/moonshot_model.py +185 -19
  66. camel/models/nebius_model.py +83 -0
  67. camel/models/nemotron_model.py +0 -5
  68. camel/models/netmind_model.py +1 -16
  69. camel/models/novita_model.py +1 -16
  70. camel/models/nvidia_model.py +1 -16
  71. camel/models/ollama_model.py +4 -19
  72. camel/models/openai_compatible_model.py +171 -46
  73. camel/models/openai_model.py +205 -77
  74. camel/models/openrouter_model.py +1 -17
  75. camel/models/ppio_model.py +1 -16
  76. camel/models/qianfan_model.py +1 -16
  77. camel/models/qwen_model.py +1 -16
  78. camel/models/reka_model.py +1 -16
  79. camel/models/samba_model.py +34 -47
  80. camel/models/sglang_model.py +64 -31
  81. camel/models/siliconflow_model.py +1 -16
  82. camel/models/stub_model.py +0 -4
  83. camel/models/togetherai_model.py +1 -16
  84. camel/models/vllm_model.py +1 -16
  85. camel/models/volcano_model.py +0 -17
  86. camel/models/watsonx_model.py +1 -16
  87. camel/models/yi_model.py +1 -16
  88. camel/models/zhipuai_model.py +60 -16
  89. camel/parsers/__init__.py +18 -0
  90. camel/parsers/mcp_tool_call_parser.py +176 -0
  91. camel/retrievers/auto_retriever.py +1 -0
  92. camel/runtimes/configs.py +11 -11
  93. camel/runtimes/daytona_runtime.py +15 -16
  94. camel/runtimes/docker_runtime.py +6 -6
  95. camel/runtimes/remote_http_runtime.py +5 -5
  96. camel/services/agent_openapi_server.py +380 -0
  97. camel/societies/__init__.py +2 -0
  98. camel/societies/role_playing.py +26 -28
  99. camel/societies/workforce/__init__.py +2 -0
  100. camel/societies/workforce/events.py +122 -0
  101. camel/societies/workforce/prompts.py +249 -38
  102. camel/societies/workforce/role_playing_worker.py +82 -20
  103. camel/societies/workforce/single_agent_worker.py +634 -34
  104. camel/societies/workforce/structured_output_handler.py +512 -0
  105. camel/societies/workforce/task_channel.py +169 -23
  106. camel/societies/workforce/utils.py +176 -9
  107. camel/societies/workforce/worker.py +77 -23
  108. camel/societies/workforce/workflow_memory_manager.py +772 -0
  109. camel/societies/workforce/workforce.py +3168 -478
  110. camel/societies/workforce/workforce_callback.py +74 -0
  111. camel/societies/workforce/workforce_logger.py +203 -175
  112. camel/societies/workforce/workforce_metrics.py +33 -0
  113. camel/storages/__init__.py +4 -0
  114. camel/storages/key_value_storages/json.py +15 -2
  115. camel/storages/key_value_storages/mem0_cloud.py +48 -47
  116. camel/storages/object_storages/google_cloud.py +1 -1
  117. camel/storages/vectordb_storages/__init__.py +6 -0
  118. camel/storages/vectordb_storages/chroma.py +731 -0
  119. camel/storages/vectordb_storages/oceanbase.py +13 -13
  120. camel/storages/vectordb_storages/pgvector.py +349 -0
  121. camel/storages/vectordb_storages/qdrant.py +3 -3
  122. camel/storages/vectordb_storages/surreal.py +365 -0
  123. camel/storages/vectordb_storages/tidb.py +8 -6
  124. camel/tasks/task.py +244 -27
  125. camel/toolkits/__init__.py +46 -8
  126. camel/toolkits/aci_toolkit.py +64 -19
  127. camel/toolkits/arxiv_toolkit.py +6 -6
  128. camel/toolkits/base.py +63 -5
  129. camel/toolkits/code_execution.py +28 -1
  130. camel/toolkits/context_summarizer_toolkit.py +684 -0
  131. camel/toolkits/craw4ai_toolkit.py +93 -0
  132. camel/toolkits/dappier_toolkit.py +10 -6
  133. camel/toolkits/dingtalk.py +1135 -0
  134. camel/toolkits/edgeone_pages_mcp_toolkit.py +49 -0
  135. camel/toolkits/excel_toolkit.py +901 -67
  136. camel/toolkits/file_toolkit.py +1402 -0
  137. camel/toolkits/function_tool.py +30 -6
  138. camel/toolkits/github_toolkit.py +107 -20
  139. camel/toolkits/gmail_toolkit.py +1839 -0
  140. camel/toolkits/google_calendar_toolkit.py +38 -4
  141. camel/toolkits/google_drive_mcp_toolkit.py +54 -0
  142. camel/toolkits/human_toolkit.py +34 -10
  143. camel/toolkits/hybrid_browser_toolkit/__init__.py +18 -0
  144. camel/toolkits/hybrid_browser_toolkit/config_loader.py +185 -0
  145. camel/toolkits/hybrid_browser_toolkit/hybrid_browser_toolkit.py +246 -0
  146. camel/toolkits/hybrid_browser_toolkit/hybrid_browser_toolkit_ts.py +1973 -0
  147. camel/toolkits/hybrid_browser_toolkit/installer.py +203 -0
  148. camel/toolkits/hybrid_browser_toolkit/ts/package-lock.json +3749 -0
  149. camel/toolkits/hybrid_browser_toolkit/ts/package.json +32 -0
  150. camel/toolkits/hybrid_browser_toolkit/ts/src/browser-scripts.js +125 -0
  151. camel/toolkits/hybrid_browser_toolkit/ts/src/browser-session.ts +1815 -0
  152. camel/toolkits/hybrid_browser_toolkit/ts/src/config-loader.ts +233 -0
  153. camel/toolkits/hybrid_browser_toolkit/ts/src/hybrid-browser-toolkit.ts +590 -0
  154. camel/toolkits/hybrid_browser_toolkit/ts/src/index.ts +7 -0
  155. camel/toolkits/hybrid_browser_toolkit/ts/src/parent-child-filter.ts +226 -0
  156. camel/toolkits/hybrid_browser_toolkit/ts/src/snapshot-parser.ts +219 -0
  157. camel/toolkits/hybrid_browser_toolkit/ts/src/som-screenshot-injected.ts +543 -0
  158. camel/toolkits/hybrid_browser_toolkit/ts/src/types.ts +130 -0
  159. camel/toolkits/hybrid_browser_toolkit/ts/tsconfig.json +26 -0
  160. camel/toolkits/hybrid_browser_toolkit/ts/websocket-server.js +319 -0
  161. camel/toolkits/hybrid_browser_toolkit/ws_wrapper.py +1032 -0
  162. camel/toolkits/hybrid_browser_toolkit_py/__init__.py +17 -0
  163. camel/toolkits/hybrid_browser_toolkit_py/actions.py +575 -0
  164. camel/toolkits/hybrid_browser_toolkit_py/agent.py +311 -0
  165. camel/toolkits/hybrid_browser_toolkit_py/browser_session.py +787 -0
  166. camel/toolkits/hybrid_browser_toolkit_py/config_loader.py +490 -0
  167. camel/toolkits/hybrid_browser_toolkit_py/hybrid_browser_toolkit.py +2390 -0
  168. camel/toolkits/hybrid_browser_toolkit_py/snapshot.py +233 -0
  169. camel/toolkits/hybrid_browser_toolkit_py/stealth_script.js +0 -0
  170. camel/toolkits/hybrid_browser_toolkit_py/unified_analyzer.js +1043 -0
  171. camel/toolkits/image_generation_toolkit.py +390 -0
  172. camel/toolkits/jina_reranker_toolkit.py +3 -4
  173. camel/toolkits/klavis_toolkit.py +5 -1
  174. camel/toolkits/markitdown_toolkit.py +104 -0
  175. camel/toolkits/math_toolkit.py +64 -10
  176. camel/toolkits/mcp_toolkit.py +370 -45
  177. camel/toolkits/memory_toolkit.py +5 -1
  178. camel/toolkits/message_agent_toolkit.py +608 -0
  179. camel/toolkits/message_integration.py +724 -0
  180. camel/toolkits/minimax_mcp_toolkit.py +195 -0
  181. camel/toolkits/note_taking_toolkit.py +277 -0
  182. camel/toolkits/notion_mcp_toolkit.py +224 -0
  183. camel/toolkits/openbb_toolkit.py +5 -1
  184. camel/toolkits/origene_mcp_toolkit.py +56 -0
  185. camel/toolkits/playwright_mcp_toolkit.py +12 -31
  186. camel/toolkits/pptx_toolkit.py +25 -12
  187. camel/toolkits/resend_toolkit.py +168 -0
  188. camel/toolkits/screenshot_toolkit.py +213 -0
  189. camel/toolkits/search_toolkit.py +437 -142
  190. camel/toolkits/slack_toolkit.py +104 -50
  191. camel/toolkits/sympy_toolkit.py +1 -1
  192. camel/toolkits/task_planning_toolkit.py +3 -3
  193. camel/toolkits/terminal_toolkit/__init__.py +18 -0
  194. camel/toolkits/terminal_toolkit/terminal_toolkit.py +957 -0
  195. camel/toolkits/terminal_toolkit/utils.py +532 -0
  196. camel/toolkits/thinking_toolkit.py +1 -1
  197. camel/toolkits/vertex_ai_veo_toolkit.py +590 -0
  198. camel/toolkits/video_analysis_toolkit.py +106 -26
  199. camel/toolkits/video_download_toolkit.py +17 -14
  200. camel/toolkits/web_deploy_toolkit.py +1219 -0
  201. camel/toolkits/wechat_official_toolkit.py +483 -0
  202. camel/toolkits/zapier_toolkit.py +5 -1
  203. camel/types/__init__.py +2 -2
  204. camel/types/agents/tool_calling_record.py +4 -1
  205. camel/types/enums.py +316 -40
  206. camel/types/openai_types.py +2 -2
  207. camel/types/unified_model_type.py +31 -4
  208. camel/utils/commons.py +36 -5
  209. camel/utils/constants.py +3 -0
  210. camel/utils/context_utils.py +1003 -0
  211. camel/utils/mcp.py +138 -4
  212. camel/utils/mcp_client.py +45 -1
  213. camel/utils/message_summarizer.py +148 -0
  214. camel/utils/token_counting.py +43 -20
  215. camel/utils/tool_result.py +44 -0
  216. {camel_ai-0.2.67.dist-info → camel_ai-0.2.80a2.dist-info}/METADATA +296 -85
  217. {camel_ai-0.2.67.dist-info → camel_ai-0.2.80a2.dist-info}/RECORD +219 -146
  218. camel/loaders/pandas_reader.py +0 -368
  219. camel/toolkits/dalle_toolkit.py +0 -175
  220. camel/toolkits/file_write_toolkit.py +0 -444
  221. camel/toolkits/openai_agent_toolkit.py +0 -135
  222. camel/toolkits/terminal_toolkit.py +0 -1037
  223. {camel_ai-0.2.67.dist-info → camel_ai-0.2.80a2.dist-info}/WHEEL +0 -0
  224. {camel_ai-0.2.67.dist-info → camel_ai-0.2.80a2.dist-info}/licenses/LICENSE +0 -0
@@ -0,0 +1,365 @@
1
+ # ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========
2
+ # Licensed under the Apache License, Version 2.0 (the "License");
3
+ # you may not use this file except in compliance with the License.
4
+ # You may obtain a copy of the License at
5
+ #
6
+ # http://www.apache.org/licenses/LICENSE-2.0
7
+ #
8
+ # Unless required by applicable law or agreed to in writing, software
9
+ # distributed under the License is distributed on an "AS IS" BASIS,
10
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11
+ # See the License for the specific language governing permissions and
12
+ # limitations under the License.
13
+ # ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========
14
+ import re
15
+ from typing import TYPE_CHECKING, Any, Dict, List, Optional
16
+
17
+ from camel.logger import get_logger
18
+ from camel.storages.vectordb_storages import (
19
+ BaseVectorStorage,
20
+ VectorDBQuery,
21
+ VectorDBQueryResult,
22
+ VectorDBStatus,
23
+ VectorRecord,
24
+ )
25
+ from camel.types import VectorDistance
26
+ from camel.utils import dependencies_required
27
+
28
+ if TYPE_CHECKING:
29
+ from surrealdb import Surreal # type: ignore[import-not-found]
30
+
31
+ logger = get_logger(__name__)
32
+
33
+
34
+ class SurrealStorage(BaseVectorStorage):
35
+ r"""An implementation of the `BaseVectorStorage` using SurrealDB,
36
+ a scalable, distributed database with WebSocket support, for
37
+ efficient vector storage and similarity search.
38
+
39
+ SurrealDB official site and documentation can be found at:
40
+ `SurrealDB <https://surrealdb.com>`_
41
+
42
+ Args:
43
+ url (str): WebSocket URL for connecting to SurrealDB
44
+ (default: "ws://localhost:8000/rpc").
45
+ table (str): Name of the table used for storing vectors
46
+ (default: "vector_store").
47
+ vector_dim (int): Dimensionality of the stored vectors.
48
+ distance (VectorDistance): Distance metric used for similarity
49
+ comparisons (default: VectorDistance.COSINE).
50
+ namespace (str): SurrealDB namespace to use (default: "default").
51
+ database (str): SurrealDB database name (default: "demo").
52
+ user (str): Username for authentication (default: "root").
53
+ password (str): Password for authentication (default: "root").
54
+
55
+ Notes:
56
+ - SurrealDB supports flexible schema and powerful querying capabilities
57
+ via SQL-like syntax over WebSocket.
58
+ - This implementation manages connection setup and ensures the target
59
+ table exists.
60
+ - Suitable for applications requiring distributed vector storage and
61
+ search with real-time updates.
62
+ """
63
+
64
+ @dependencies_required('surrealdb')
65
+ def __init__(
66
+ self,
67
+ *,
68
+ url: str = "ws://localhost:8000/rpc",
69
+ table: str = "vector_store",
70
+ vector_dim: int = 786,
71
+ vector_type: str = "F64",
72
+ distance: VectorDistance = VectorDistance.COSINE,
73
+ hnsw_effort: int = 40,
74
+ namespace: str = "default",
75
+ database: str = "demo",
76
+ user: str = "root",
77
+ password: str = "root",
78
+ ) -> None:
79
+ r"""Initialize SurrealStorage with connection settings and ensure
80
+ the target table exists.
81
+
82
+ Args:
83
+ url (str): WebSocket URL for connecting to SurrealDB.
84
+ (default: :obj:`"ws://localhost:8000/rpc"`)
85
+ table (str): Name of the table used for vector storage.
86
+ (default: :obj:`"vector_store"`)
87
+ vector_dim (int): Dimensionality of the stored vectors.
88
+ (default: :obj:`786`)
89
+ distance (VectorDistance): Distance metric for similarity
90
+ searches. (default: :obj:`VectorDistance.COSINE`)
91
+ namespace (str): SurrealDB namespace to use.
92
+ (default: :obj:`"default"`)
93
+ database (str): SurrealDB database name.
94
+ (default: :obj:`"demo"`)
95
+ user (str): Username for authentication.
96
+ (default: :obj:`"root"`)
97
+ password (str): Password for authentication.
98
+ (default: :obj:`"root"`)
99
+ """
100
+
101
+ from surrealdb import Surreal
102
+
103
+ self.url = url
104
+ self.table = table
105
+ self.ns = namespace
106
+ self.db = database
107
+ self.user = user
108
+ self.password = password
109
+ self.vector_dim = vector_dim
110
+ self.vector_type = vector_type
111
+ self.distance = distance
112
+ self._hnsw_effort = hnsw_effort
113
+ self._surreal_client = Surreal(self.url)
114
+ self._surreal_client.signin({"username": user, "password": password})
115
+ self._surreal_client.use(namespace, database)
116
+
117
+ self._check_and_create_table()
118
+
119
+ def _table_exists(self) -> bool:
120
+ r"""Check whether the target table exists in the database.
121
+
122
+ Returns:
123
+ bool: True if the table exists, False otherwise.
124
+ """
125
+ res = self._surreal_client.query("INFO FOR DB;")
126
+ tables = res.get('tables', {})
127
+ logger.debug(f"_table_exists: {res}")
128
+ return self.table in tables
129
+
130
+ def _get_table_info(self) -> dict[str, int | None]:
131
+ r"""Retrieve dimension and record count from the table metadata.
132
+
133
+ Returns:
134
+ Dict[str, int]: A dictionary with 'dim' and 'count' keys.
135
+ """
136
+ if not self._table_exists():
137
+ return {"dim": self.vector_dim, "count": 0}
138
+ res = self._surreal_client.query(f"INFO FOR TABLE {self.table};")
139
+ logger.debug(f"_get_table_info: {res}")
140
+ indexes = res.get("indexes", {})
141
+
142
+ dim = self.vector_dim
143
+ idx_def = indexes.get("hnsw_idx")
144
+ if idx_def and isinstance(idx_def, str):
145
+ m = re.search(r"DIMENSION\s+(\d+)", idx_def)
146
+ if m:
147
+ dim = int(m.group(1))
148
+ cnt = self._surreal_client.query(
149
+ f"SELECT COUNT() FROM ONLY {self.table} GROUP ALL LIMIT 1;"
150
+ )
151
+ count = cnt.get("count", 0)
152
+ return {"dim": dim, "count": count}
153
+
154
+ def _create_table(self):
155
+ r"""Define and create the vector storage table with HNSW index.
156
+
157
+ Documentation: https://surrealdb.com/docs/surrealdb/reference-guide/
158
+ vector-search#vector-search-cheat-sheet
159
+ """
160
+ if self.distance.value not in ["cosine", "euclidean", "manhattan"]:
161
+ raise ValueError(
162
+ f"Unsupported distance metric: {self.distance.value}"
163
+ )
164
+ surql_query = f"""
165
+ DEFINE TABLE {self.table} SCHEMALESS;
166
+ DEFINE FIELD payload ON {self.table} FLEXIBLE TYPE object;
167
+ DEFINE FIELD embedding ON {self.table} TYPE array<float>;
168
+ DEFINE INDEX hnsw_idx ON {self.table}
169
+ FIELDS embedding
170
+ HNSW DIMENSION {self.vector_dim}
171
+ DIST {self.distance.value}
172
+ TYPE {self.vector_type}
173
+ EFC 150 M 12 M0 24;
174
+ """
175
+ logger.debug(f"_create_table query: {surql_query}")
176
+ res = self._surreal_client.query_raw(surql_query)
177
+ logger.debug(f"_create_table response: {res}")
178
+ if "error" in res:
179
+ raise ValueError(f"Failed to create table: {res['error']}")
180
+ logger.info(f"Table '{self.table}' created successfully.")
181
+
182
+ def _drop_table(self):
183
+ r"""Drop the vector storage table if it exists."""
184
+ self._surreal_client.query_raw(f"REMOVE TABLE IF EXISTS {self.table};")
185
+ logger.info(f"Table '{self.table}' deleted successfully.")
186
+
187
+ def _check_and_create_table(self):
188
+ r"""Check if the table exists and matches the expected vector
189
+ dimension. If not, create a new table.
190
+ """
191
+ if self._table_exists():
192
+ in_dim = self._get_table_info()["dim"]
193
+ if in_dim != self.vector_dim:
194
+ raise ValueError(
195
+ f"Table {self.table} exists with dimension {in_dim}, "
196
+ f"expected {self.vector_dim}"
197
+ )
198
+ else:
199
+ self._create_table()
200
+
201
+ def _validate_and_convert_records(
202
+ self, records: List[VectorRecord]
203
+ ) -> List[Dict]:
204
+ r"""Validate and convert VectorRecord instances into
205
+ SurrealDB-compatible dictionaries.
206
+
207
+ Args:
208
+ records (List[VectorRecord]): List of vector records to insert.
209
+
210
+ Returns:
211
+ List[Dict]: Transformed list of dicts ready for insertion.
212
+ """
213
+ validate_data = []
214
+ for record in records:
215
+ if len(record.vector) != self.vector_dim:
216
+ raise ValueError(
217
+ f"Vector dimension mismatch: expected {self.vector_dim}, "
218
+ f"got {len(record.vector)}"
219
+ )
220
+ record_dict = {
221
+ "payload": record.payload if record.payload else {},
222
+ "embedding": record.vector,
223
+ }
224
+ validate_data.append(record_dict)
225
+
226
+ return validate_data
227
+
228
+ def query(
229
+ self,
230
+ query: VectorDBQuery,
231
+ **kwargs: Any,
232
+ ) -> List[VectorDBQueryResult]:
233
+ r"""Perform a top-k similarity search using the configured distance
234
+ metric.
235
+
236
+ Args:
237
+ query (VectorDBQuery): Query containing the query vector
238
+ and top_k value.
239
+
240
+ Returns:
241
+ List[VectorDBQueryResult]: Ranked list of matching records
242
+ with similarity scores.
243
+ """
244
+ surql_query = f"""
245
+ SELECT id, embedding, payload, vector::distance::knn() AS dist
246
+ FROM {self.table}
247
+ WHERE embedding <|{query.top_k},{self._hnsw_effort}|> $vector
248
+ ORDER BY dist;
249
+ """
250
+ logger.debug(
251
+ f"query surql: {surql_query} with $vector = {query.query_vector}"
252
+ )
253
+
254
+ response = self._surreal_client.query(
255
+ surql_query, {"vector": query.query_vector}
256
+ )
257
+ logger.debug(f"query response: {response}")
258
+
259
+ return [
260
+ VectorDBQueryResult(
261
+ record=VectorRecord(
262
+ id=row["id"].id,
263
+ vector=row["embedding"],
264
+ payload=row["payload"],
265
+ ),
266
+ similarity=1.0 - row["dist"]
267
+ if self.distance == VectorDistance.COSINE
268
+ else -row["score"],
269
+ )
270
+ for row in response
271
+ ]
272
+
273
+ def add(self, records: List[VectorRecord], **kwargs) -> None:
274
+ r"""Insert validated vector records into the SurrealDB table.
275
+
276
+ Args:
277
+ records (List[VectorRecord]): List of vector records to add.
278
+ """
279
+ logger.info(
280
+ "Adding %d records to table '%s'.", len(records), self.table
281
+ )
282
+ try:
283
+ validated_records = self._validate_and_convert_records(records)
284
+ for record in validated_records:
285
+ self._surreal_client.create(self.table, record)
286
+
287
+ logger.info(
288
+ "Successfully added %d records to table '%s'.",
289
+ len(records),
290
+ self.table,
291
+ )
292
+ except Exception as e:
293
+ logger.error(
294
+ "Failed to add records to table '%s': %s",
295
+ self.table,
296
+ str(e),
297
+ exc_info=True,
298
+ )
299
+ raise
300
+
301
+ def delete(
302
+ self, ids: Optional[List[str]] = None, if_all: bool = False, **kwargs
303
+ ) -> None:
304
+ r"""Delete specific records by ID or clear the entire table.
305
+
306
+ Args:
307
+ ids (Optional[List[str]]): List of record IDs to delete.
308
+ if_all (bool): Whether to delete all records in the table.
309
+ """
310
+ from surrealdb.data.types.record_id import RecordID
311
+
312
+ try:
313
+ if if_all:
314
+ self._surreal_client.delete(self.table, **kwargs)
315
+ logger.info(f"Deleted all records from table '{self.table}'")
316
+ return
317
+
318
+ if not ids:
319
+ raise ValueError(
320
+ "Either `ids` must be provided or `if_all=True`"
321
+ )
322
+
323
+ for id_str in ids:
324
+ rec = RecordID(self.table, id_str)
325
+ self._surreal_client.delete(rec, **kwargs)
326
+ logger.info(f"Deleted record {rec}")
327
+
328
+ except Exception as e:
329
+ logger.exception("Error deleting records from SurrealDB")
330
+ raise RuntimeError(f"Failed to delete records {ids!r}") from e
331
+
332
+ def status(self) -> VectorDBStatus:
333
+ r"""Retrieve the status of the vector table including dimension and
334
+ count.
335
+
336
+ Returns:
337
+ VectorDBStatus: Object containing vector table metadata.
338
+ """
339
+ status = self._get_table_info()
340
+
341
+ dim = status.get("dim")
342
+ count = status.get("count")
343
+
344
+ if dim is None or count is None:
345
+ raise ValueError("Vector dimension and count cannot be None")
346
+
347
+ return VectorDBStatus(
348
+ vector_dim=dim,
349
+ vector_count=count,
350
+ )
351
+
352
+ def clear(self) -> None:
353
+ r"""Reset the vector table by dropping and recreating it."""
354
+ self._drop_table()
355
+ self._create_table()
356
+
357
+ def load(self) -> None:
358
+ r"""Load the collection hosted on cloud service."""
359
+ # SurrealDB doesn't require explicit loading
360
+ raise NotImplementedError("SurrealDB does not support loading")
361
+
362
+ @property
363
+ def client(self) -> "Surreal":
364
+ r"""Provides access to the underlying SurrealDB client."""
365
+ return self._surreal_client
@@ -44,7 +44,7 @@ class TiDBStorage(BaseVectorStorage):
44
44
  r"""An implementation of the `BaseVectorStorage` for interacting with TiDB.
45
45
 
46
46
  The detailed information about TiDB is available at:
47
- `TiDB Vector Search <https://ai.pingcap.com/>`_
47
+ `TiDB Vector Search <https://pingcap.com/ai>`_
48
48
 
49
49
  Args:
50
50
  vector_dim (int): The dimension of storing vectors.
@@ -107,10 +107,10 @@ class TiDBStorage(BaseVectorStorage):
107
107
  )
108
108
 
109
109
  def _get_table_model(self, collection_name: str) -> Any:
110
+ from pytidb.datatype import JSON
110
111
  from pytidb.schema import Field, TableModel, VectorField
111
- from sqlalchemy import JSON
112
112
 
113
- class VectorDBRecord(TableModel):
113
+ class VectorDBRecordBase(TableModel, table=False):
114
114
  id: Optional[str] = Field(None, primary_key=True)
115
115
  vector: list[float] = VectorField(self.vector_dim)
116
116
  payload: Optional[dict[str, Any]] = Field(None, sa_type=JSON)
@@ -119,7 +119,7 @@ class TiDBStorage(BaseVectorStorage):
119
119
  # class names.
120
120
  return type(
121
121
  f"VectorDBRecord_{collection_name}",
122
- (VectorDBRecord,),
122
+ (VectorDBRecordBase,),
123
123
  {"__tablename__": collection_name},
124
124
  table=True,
125
125
  )
@@ -128,8 +128,9 @@ class TiDBStorage(BaseVectorStorage):
128
128
  r"""Opens an existing table or creates a new table in TiDB."""
129
129
  table = self._client.open_table(self.collection_name)
130
130
  if table is None:
131
+ table_model = self._get_table_model(self.collection_name)
131
132
  table = self._client.create_table(
132
- schema=self._get_table_model(self.collection_name)
133
+ schema=table_model, if_exists="skip"
133
134
  )
134
135
  return table
135
136
 
@@ -166,6 +167,7 @@ class TiDBStorage(BaseVectorStorage):
166
167
  table.
167
168
  """
168
169
  vector_count = self._table.rows()
170
+
169
171
  # Get vector dimension from table schema
170
172
  columns = self._table.columns()
171
173
  dim_value = None
@@ -303,7 +305,7 @@ class TiDBStorage(BaseVectorStorage):
303
305
  for row in rows:
304
306
  query_results.append(
305
307
  VectorDBQueryResult.create(
306
- similarity=float(row['similarity_score']),
308
+ similarity=float(row['_score']),
307
309
  id=str(row['id']),
308
310
  payload=row['payload'],
309
311
  vector=row['vector'],