tortoise-embeddings 0.0.1__tar.gz

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 (24) hide show
  1. tortoise_embeddings-0.0.1/LICENSE +201 -0
  2. tortoise_embeddings-0.0.1/PKG-INFO +170 -0
  3. tortoise_embeddings-0.0.1/README.md +146 -0
  4. tortoise_embeddings-0.0.1/pyproject.toml +63 -0
  5. tortoise_embeddings-0.0.1/setup.cfg +4 -0
  6. tortoise_embeddings-0.0.1/tests/test_gemini.py +93 -0
  7. tortoise_embeddings-0.0.1/tests/test_vector_fields.py +192 -0
  8. tortoise_embeddings-0.0.1/tortoise_embeddings/__init__.py +18 -0
  9. tortoise_embeddings-0.0.1/tortoise_embeddings/aerich_vector_postgres_ddl.py +31 -0
  10. tortoise_embeddings-0.0.1/tortoise_embeddings/fields/__init__.py +156 -0
  11. tortoise_embeddings-0.0.1/tortoise_embeddings/fields/binary_vector_field.py +74 -0
  12. tortoise_embeddings-0.0.1/tortoise_embeddings/fields/half_vector_field.py +54 -0
  13. tortoise_embeddings-0.0.1/tortoise_embeddings/fields/sparse_vector_field.py +85 -0
  14. tortoise_embeddings-0.0.1/tortoise_embeddings/fields/vector_field.py +65 -0
  15. tortoise_embeddings-0.0.1/tortoise_embeddings/postgres_ddl.py +72 -0
  16. tortoise_embeddings-0.0.1/tortoise_embeddings/similarity.py +97 -0
  17. tortoise_embeddings-0.0.1/tortoise_embeddings/vector_asyncpg_db_client.py +110 -0
  18. tortoise_embeddings-0.0.1/tortoise_embeddings/vector_distance.py +66 -0
  19. tortoise_embeddings-0.0.1/tortoise_embeddings/vector_threshold_criterion.py +70 -0
  20. tortoise_embeddings-0.0.1/tortoise_embeddings.egg-info/PKG-INFO +170 -0
  21. tortoise_embeddings-0.0.1/tortoise_embeddings.egg-info/SOURCES.txt +22 -0
  22. tortoise_embeddings-0.0.1/tortoise_embeddings.egg-info/dependency_links.txt +1 -0
  23. tortoise_embeddings-0.0.1/tortoise_embeddings.egg-info/requires.txt +15 -0
  24. tortoise_embeddings-0.0.1/tortoise_embeddings.egg-info/top_level.txt +1 -0
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,170 @@
1
+ Metadata-Version: 2.4
2
+ Name: tortoise-embeddings
3
+ Version: 0.0.1
4
+ Summary: Adds pgvector support to TortoiseORM.
5
+ Author-email: Kaoticz <1812311+Kaoticz@users.noreply.github.com>
6
+ Requires-Python: >=3.14
7
+ Description-Content-Type: text/markdown
8
+ License-File: LICENSE
9
+ Requires-Dist: tortoise-orm<1.0.0,>=0.25.0
10
+ Requires-Dist: aerich>=0.9.0
11
+ Requires-Dist: asyncpg>=0.31.0
12
+ Requires-Dist: pgvector>=0.4.0
13
+ Requires-Dist: numpy>=2.4.0
14
+ Provides-Extra: dev
15
+ Requires-Dist: setuptools==82.0.1; extra == "dev"
16
+ Requires-Dist: build==1.4.2; extra == "dev"
17
+ Requires-Dist: mypy; extra == "dev"
18
+ Requires-Dist: basedpyright; extra == "dev"
19
+ Requires-Dist: pytest>=9.0.2; extra == "dev"
20
+ Requires-Dist: pytest-asyncio>=1.3.0; extra == "dev"
21
+ Requires-Dist: google-genai>=1.70.0; extra == "dev"
22
+ Requires-Dist: python-dotenv>=1.2.2; extra == "dev"
23
+ Dynamic: license-file
24
+
25
+ # Tortoise Embeddings
26
+
27
+ Tortoise Embeddings adds `pgvector` support to TortoiseORM, enabling efficient vector storage and similarity search in PostgreSQL.
28
+
29
+ ## Features
30
+
31
+ - **Four Vector Field Types:**
32
+ - `VectorField`: Supports `vector` type.
33
+ - `HalfVectorField`: Supports `halfvec` type.
34
+ - `BinaryVector`: Supports `bit` type.
35
+ - `SparseVector`: Supports `sparsevec` type.
36
+ - **Aerich Migration Support:** Automatically includes vector-based types from your models into the migration scripts.
37
+ - **Similarity Operations:**
38
+ - **Custom Functions:** `L2Distance`, `CosineDistance`, `InnerProduct`, `L1Distance`, `HammingDistance`, `JaccardDistance`.
39
+ - **Custom Filters:** Convenient filter suffixes - `__l2`, `__cosine`, `__inner`, `__l1`, `__hamming`, and `__jaccard`.
40
+ - Works with `numpy` arrays and standard Python types.
41
+
42
+ ## Installation
43
+
44
+ ```bash
45
+ pip install tortoise-embeddings
46
+ ```
47
+
48
+ Make sure you have `pgvector` installed in your PostgreSQL database.
49
+
50
+ ## Usage
51
+
52
+ ### Define Your Models
53
+
54
+ ```python
55
+ from tortoise.models import Model
56
+ from tortoise.fields import IntField
57
+ from tortoise_embeddings import VectorField, HalfVectorField, BinaryVectorField, SparseVectorField
58
+
59
+ class Item(Model):
60
+ id = IntField(primary_key=True)
61
+ # Define a vector field with 3 dimensions
62
+ embedding = VectorField(dimensions=3)
63
+ # Support for other pgvector types
64
+ half_embedding = HalfVectorField(dimensions=3)
65
+ binary_embedding = BinaryVectorField(dimensions=4)
66
+ sparse_embedding = SparseVectorField(dimensions=3)
67
+ ```
68
+
69
+ ### Initialize with Custom Client
70
+
71
+ To enable binary codecs and migration support, use the provided `AsyncpgDBClient`:
72
+
73
+ ```python
74
+ from tortoise import Tortoise
75
+ import tortoise.backends.asyncpg
76
+ from tortoise_embeddings import VectorAsyncpgDBClient
77
+
78
+ # Override the client class for the asyncpg backend
79
+ tortoise.backends.asyncpg.client_class = VectorAsyncpgDBClient
80
+
81
+ async def init():
82
+ await Tortoise.init(
83
+ db_url='postgres://user:pass@host:port/db',
84
+ modules={'models': ['your_models_module']}
85
+ )
86
+ await Tortoise.generate_schemas()
87
+ ```
88
+
89
+ ### Similarity Search
90
+
91
+ #### Using Custom Filters (Recommended)
92
+
93
+ ```python
94
+ import numpy
95
+
96
+ target_vector = numpy.array([1.0, 0.0, 0.0])
97
+
98
+ # Find items where L2 distance is less than 0.5
99
+ items = await Item.filter(embedding__l2=(target_vector, 0.5))
100
+
101
+ # Find items where Cosine distance is less than 0.1
102
+ items = await Item.filter(embedding__cosine=(target_vector, 0.1))
103
+ ```
104
+
105
+ #### Using Custom Functions
106
+
107
+ ```python
108
+ from tortoise_embeddings.similarity import L2Distance
109
+
110
+ target_vector = [1.0, 0.0, 0.0]
111
+
112
+ # Annotate results with distance and order by it
113
+ items = await Item.all().annotate(
114
+ dist=L2Distance(Item._meta.fields_map['embedding'], target_vector, alias="dist")
115
+ ).order_by("dist")
116
+
117
+ for item in items:
118
+ print(f"Item {item.id} has distance {item.dist}")
119
+ ```
120
+
121
+ ### Aerich Migrations
122
+
123
+ If you use `aerich`, simply use the `AerichVectorPostgresDDL` to ensure the `vector` extension is created:
124
+
125
+ ```python
126
+ # In your project configuration
127
+ from tortoise_embeddings import AerichVectorPostgresDDL
128
+ # This is usually handled automatically if you use the VectorAsyncpgDBClient
129
+ ```
130
+ # Development setup
131
+
132
+ Set the following environment variables:
133
+
134
+ | Variable | Description | How to get? |
135
+ |--------------------------------|-----------------------------------------------|-------------------------------------------------------------------------|
136
+ | PSQL_CONNECTION_STRING | A connection string to a PostgreSQL database. | `postgres://user:password@host:port/database` |
137
+ | GEMINI_API_KEY | An API key to Google GenAI. (optional) | Go to [aistudio.google.com](aistudio.google.com) and create an API key. |
138
+
139
+ ## Dependencies:
140
+
141
+ - tortoise-orm>=0.25.0,<1.0.0
142
+ - aerich>=0.9.0
143
+ - asyncpg>=0.31.0
144
+ - pgvector>=0.4.0
145
+ - numpy>=2.4.0
146
+
147
+ ## Running Tests
148
+
149
+ Tests require a PostgreSQL database with the `pgvector` extension.
150
+
151
+ ```bash
152
+ export PSQL_CONNECTION_STRING="postgres://user:password@host:port/database"
153
+ export GEMINI_API_KEY="your_api_key" # Optional for Gemini integration tests
154
+ pytest tests/
155
+ ```
156
+
157
+ ## License
158
+ Copyright 2026 Kotz
159
+
160
+ Licensed under the Apache License, Version 2.0 (the "License");
161
+ you may not use this file except in compliance with the License.
162
+ You may obtain a copy of the License at
163
+
164
+ > http://www.apache.org/licenses/LICENSE-2.0
165
+
166
+ Unless required by applicable law or agreed to in writing, software
167
+ distributed under the License is distributed on an "AS IS" BASIS,
168
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
169
+ See the License for the specific language governing permissions and
170
+ limitations under the License.
@@ -0,0 +1,146 @@
1
+ # Tortoise Embeddings
2
+
3
+ Tortoise Embeddings adds `pgvector` support to TortoiseORM, enabling efficient vector storage and similarity search in PostgreSQL.
4
+
5
+ ## Features
6
+
7
+ - **Four Vector Field Types:**
8
+ - `VectorField`: Supports `vector` type.
9
+ - `HalfVectorField`: Supports `halfvec` type.
10
+ - `BinaryVector`: Supports `bit` type.
11
+ - `SparseVector`: Supports `sparsevec` type.
12
+ - **Aerich Migration Support:** Automatically includes vector-based types from your models into the migration scripts.
13
+ - **Similarity Operations:**
14
+ - **Custom Functions:** `L2Distance`, `CosineDistance`, `InnerProduct`, `L1Distance`, `HammingDistance`, `JaccardDistance`.
15
+ - **Custom Filters:** Convenient filter suffixes - `__l2`, `__cosine`, `__inner`, `__l1`, `__hamming`, and `__jaccard`.
16
+ - Works with `numpy` arrays and standard Python types.
17
+
18
+ ## Installation
19
+
20
+ ```bash
21
+ pip install tortoise-embeddings
22
+ ```
23
+
24
+ Make sure you have `pgvector` installed in your PostgreSQL database.
25
+
26
+ ## Usage
27
+
28
+ ### Define Your Models
29
+
30
+ ```python
31
+ from tortoise.models import Model
32
+ from tortoise.fields import IntField
33
+ from tortoise_embeddings import VectorField, HalfVectorField, BinaryVectorField, SparseVectorField
34
+
35
+ class Item(Model):
36
+ id = IntField(primary_key=True)
37
+ # Define a vector field with 3 dimensions
38
+ embedding = VectorField(dimensions=3)
39
+ # Support for other pgvector types
40
+ half_embedding = HalfVectorField(dimensions=3)
41
+ binary_embedding = BinaryVectorField(dimensions=4)
42
+ sparse_embedding = SparseVectorField(dimensions=3)
43
+ ```
44
+
45
+ ### Initialize with Custom Client
46
+
47
+ To enable binary codecs and migration support, use the provided `AsyncpgDBClient`:
48
+
49
+ ```python
50
+ from tortoise import Tortoise
51
+ import tortoise.backends.asyncpg
52
+ from tortoise_embeddings import VectorAsyncpgDBClient
53
+
54
+ # Override the client class for the asyncpg backend
55
+ tortoise.backends.asyncpg.client_class = VectorAsyncpgDBClient
56
+
57
+ async def init():
58
+ await Tortoise.init(
59
+ db_url='postgres://user:pass@host:port/db',
60
+ modules={'models': ['your_models_module']}
61
+ )
62
+ await Tortoise.generate_schemas()
63
+ ```
64
+
65
+ ### Similarity Search
66
+
67
+ #### Using Custom Filters (Recommended)
68
+
69
+ ```python
70
+ import numpy
71
+
72
+ target_vector = numpy.array([1.0, 0.0, 0.0])
73
+
74
+ # Find items where L2 distance is less than 0.5
75
+ items = await Item.filter(embedding__l2=(target_vector, 0.5))
76
+
77
+ # Find items where Cosine distance is less than 0.1
78
+ items = await Item.filter(embedding__cosine=(target_vector, 0.1))
79
+ ```
80
+
81
+ #### Using Custom Functions
82
+
83
+ ```python
84
+ from tortoise_embeddings.similarity import L2Distance
85
+
86
+ target_vector = [1.0, 0.0, 0.0]
87
+
88
+ # Annotate results with distance and order by it
89
+ items = await Item.all().annotate(
90
+ dist=L2Distance(Item._meta.fields_map['embedding'], target_vector, alias="dist")
91
+ ).order_by("dist")
92
+
93
+ for item in items:
94
+ print(f"Item {item.id} has distance {item.dist}")
95
+ ```
96
+
97
+ ### Aerich Migrations
98
+
99
+ If you use `aerich`, simply use the `AerichVectorPostgresDDL` to ensure the `vector` extension is created:
100
+
101
+ ```python
102
+ # In your project configuration
103
+ from tortoise_embeddings import AerichVectorPostgresDDL
104
+ # This is usually handled automatically if you use the VectorAsyncpgDBClient
105
+ ```
106
+ # Development setup
107
+
108
+ Set the following environment variables:
109
+
110
+ | Variable | Description | How to get? |
111
+ |--------------------------------|-----------------------------------------------|-------------------------------------------------------------------------|
112
+ | PSQL_CONNECTION_STRING | A connection string to a PostgreSQL database. | `postgres://user:password@host:port/database` |
113
+ | GEMINI_API_KEY | An API key to Google GenAI. (optional) | Go to [aistudio.google.com](aistudio.google.com) and create an API key. |
114
+
115
+ ## Dependencies:
116
+
117
+ - tortoise-orm>=0.25.0,<1.0.0
118
+ - aerich>=0.9.0
119
+ - asyncpg>=0.31.0
120
+ - pgvector>=0.4.0
121
+ - numpy>=2.4.0
122
+
123
+ ## Running Tests
124
+
125
+ Tests require a PostgreSQL database with the `pgvector` extension.
126
+
127
+ ```bash
128
+ export PSQL_CONNECTION_STRING="postgres://user:password@host:port/database"
129
+ export GEMINI_API_KEY="your_api_key" # Optional for Gemini integration tests
130
+ pytest tests/
131
+ ```
132
+
133
+ ## License
134
+ Copyright 2026 Kotz
135
+
136
+ Licensed under the Apache License, Version 2.0 (the "License");
137
+ you may not use this file except in compliance with the License.
138
+ You may obtain a copy of the License at
139
+
140
+ > http://www.apache.org/licenses/LICENSE-2.0
141
+
142
+ Unless required by applicable law or agreed to in writing, software
143
+ distributed under the License is distributed on an "AS IS" BASIS,
144
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
145
+ See the License for the specific language governing permissions and
146
+ limitations under the License.
@@ -0,0 +1,63 @@
1
+ [build-system]
2
+ requires = ['setuptools>=82.0.1', 'wheel>=0.46.3']
3
+ build-backend = 'setuptools.build_meta'
4
+
5
+ [project]
6
+ name = 'tortoise-embeddings'
7
+ version = '0.0.1'
8
+ description = 'Adds pgvector support to TortoiseORM. '
9
+ readme = 'README.md'
10
+ requires-python = '>=3.14'
11
+ authors = [
12
+ {name = 'Kaoticz', email = '1812311+Kaoticz@users.noreply.github.com'},
13
+ ]
14
+ dependencies = [
15
+ 'tortoise-orm>=0.25.0,<1.0.0',
16
+ 'aerich>=0.9.0',
17
+ 'asyncpg>=0.31.0',
18
+ 'pgvector>=0.4.0',
19
+ 'numpy>=2.4.0',
20
+ ]
21
+
22
+ [tool.setuptools.packages.find]
23
+ include = ['tortoise_embeddings', 'tortoise_embeddings.*']
24
+
25
+ [tool.mypy]
26
+ python_version = '3.14'
27
+ files = ['tortoise_embeddings/']
28
+ strict = true
29
+ local_partial_types = true
30
+ exclude = '.venv/'
31
+ disallow_untyped_defs = true
32
+ no_implicit_optional = true
33
+ warn_redundant_casts = true
34
+ warn_unused_ignores = true
35
+ ignore_missing_imports = true
36
+
37
+ [tool.pyright]
38
+ typeCheckingMode = 'standard'
39
+ analyzeUnannotatedFunctions = true
40
+ reportDeprecated = true
41
+ reportUnannotatedClassAttribute = true
42
+ reportImplicitOverride = true
43
+ reportUnknownLambdaType = false
44
+
45
+ [tool.pytest.ini_options]
46
+ testpaths = ['tests']
47
+ addopts = ['-v', '--showlocals']
48
+ asyncio_mode = 'auto'
49
+ filterwarnings = [
50
+ 'ignore:_UnionGenericAlias is deprecated:DeprecationWarning:google.genai.types',
51
+ ]
52
+
53
+ [project.optional-dependencies]
54
+ dev = [
55
+ 'setuptools==82.0.1',
56
+ 'build==1.4.2',
57
+ 'mypy',
58
+ 'basedpyright',
59
+ 'pytest>=9.0.2',
60
+ 'pytest-asyncio>=1.3.0',
61
+ 'google-genai>=1.70.0',
62
+ 'python-dotenv>=1.2.2'
63
+ ]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,93 @@
1
+ from __future__ import annotations
2
+ import os
3
+ import pytest
4
+ import numpy as np
5
+ from typing import Any, cast
6
+ from tests.models import GeminiModel
7
+
8
+ try:
9
+ from google import genai
10
+ from google.genai import types
11
+ except ImportError:
12
+ genai = None # type: ignore
13
+ types = None # type: ignore
14
+
15
+
16
+ GEMINI_KEY: str | None = os.getenv('GEMINI_API_KEY')
17
+
18
+
19
+ @pytest.mark.skipif(genai is None, reason='google-genai not installed')
20
+ @pytest.mark.skipif(not GEMINI_KEY, reason='GEMINI_API_KEY not set')
21
+ async def test_gemini_embeddings() -> None:
22
+ """
23
+ Test generating vectors using Gemini API and storing them.
24
+ """
25
+ if genai is None or types is None:
26
+ return
27
+
28
+ client: Any = genai.Client(api_key=GEMINI_KEY)
29
+
30
+ # Find an embedding model
31
+ models: Any = client.models.list()
32
+ model_name: str | None = None
33
+ for m in models:
34
+ # The new SDK has different attribute names, let's just try to find a known one or first one
35
+ if 'embedding' in m.name:
36
+ model_name = m.name
37
+ if 'embedding-001' in m.name or 'embedding-004' in m.name:
38
+ break
39
+
40
+ if not model_name:
41
+ model_name = 'models/embedding-001'
42
+
43
+ text: str = 'TortoiseORM is an easy-to-use asyncio ORM inspired by Django.'
44
+ try:
45
+ result: Any = client.models.embed_content(
46
+ model=model_name,
47
+ contents=text,
48
+ config=types.EmbedContentConfig(
49
+ task_type='RETRIEVAL_DOCUMENT',
50
+ output_dimensionality=768
51
+ )
52
+ )
53
+ except Exception:
54
+ # Retry without output_dimensionality
55
+ try:
56
+ result = client.models.embed_content(
57
+ model=model_name,
58
+ contents=text,
59
+ config=types.EmbedContentConfig(
60
+ task_type='RETRIEVAL_DOCUMENT'
61
+ )
62
+ )
63
+ except Exception:
64
+ pytest.skip(f'Failed to get embeddings from {model_name}')
65
+ return
66
+
67
+ # In google-genai, result is an EmbedContentResponse object
68
+ embedding_values: Any = result.embeddings[0].values
69
+ embedding: list[float] = cast(list[float], embedding_values)
70
+
71
+ # Check dimensions
72
+ if len(embedding) != 768:
73
+ if len(embedding) > 768:
74
+ embedding = embedding[:768]
75
+ else:
76
+ pytest.skip(f'Model {model_name} returned {len(embedding)} dimensions, expected 768')
77
+ return
78
+
79
+ # Save to database
80
+ obj: GeminiModel = await GeminiModel.create(vec=embedding)
81
+
82
+ # Retrieve and check
83
+ retrieved: GeminiModel | None = await GeminiModel.get(id=obj.id)
84
+ assert retrieved is not None
85
+ assert isinstance(retrieved.vec, np.ndarray)
86
+ assert retrieved.vec.shape == (768,)
87
+
88
+ # Check similarity with itself
89
+ results: list[GeminiModel] = await GeminiModel.filter(
90
+ vec__cosine=(embedding, 0.1)
91
+ )
92
+ assert len(results) >= 1
93
+ assert any(r.id == obj.id for r in results)