zero-agent-core-embeddings 0.1.0__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.
- zero_agent_core_embeddings-0.1.0/.gitignore +16 -0
- zero_agent_core_embeddings-0.1.0/LICENSE +201 -0
- zero_agent_core_embeddings-0.1.0/PKG-INFO +56 -0
- zero_agent_core_embeddings-0.1.0/README.md +24 -0
- zero_agent_core_embeddings-0.1.0/pyproject.toml +67 -0
- zero_agent_core_embeddings-0.1.0/src/agent_core_embeddings/__init__.py +36 -0
- zero_agent_core_embeddings-0.1.0/src/agent_core_embeddings/base.py +159 -0
- zero_agent_core_embeddings-0.1.0/src/agent_core_embeddings/errors.py +23 -0
- zero_agent_core_embeddings-0.1.0/src/agent_core_embeddings/factory.py +72 -0
- zero_agent_core_embeddings-0.1.0/src/agent_core_embeddings/gemini.py +72 -0
- zero_agent_core_embeddings-0.1.0/src/agent_core_embeddings/ollama.py +92 -0
- zero_agent_core_embeddings-0.1.0/src/agent_core_embeddings/openai.py +77 -0
- zero_agent_core_embeddings-0.1.0/src/agent_core_embeddings/py.typed +1 -0
- zero_agent_core_embeddings-0.1.0/tests/test_adapters.py +234 -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 2026 Agent Core contributors
|
|
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,56 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: zero-agent-core-embeddings
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Handwritten Agent Core 的 Embedding Provider 扩展
|
|
5
|
+
Project-URL: Homepage, https://github.com/qiuzixu/agent-core
|
|
6
|
+
Project-URL: Repository, https://github.com/qiuzixu/agent-core
|
|
7
|
+
License-Expression: Apache-2.0
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Classifier: Development Status :: 3 - Alpha
|
|
10
|
+
Classifier: Operating System :: OS Independent
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
13
|
+
Classifier: Typing :: Typed
|
|
14
|
+
Requires-Python: <3.14,>=3.13
|
|
15
|
+
Requires-Dist: zero-agent-core<0.3,>=0.2.0
|
|
16
|
+
Provides-Extra: all
|
|
17
|
+
Requires-Dist: google-genai<2,>=1.0; extra == 'all'
|
|
18
|
+
Requires-Dist: httpx<1,>=0.28; extra == 'all'
|
|
19
|
+
Requires-Dist: openai<2,>=1.0; extra == 'all'
|
|
20
|
+
Provides-Extra: dev
|
|
21
|
+
Requires-Dist: mypy<2,>=1.18; extra == 'dev'
|
|
22
|
+
Requires-Dist: pytest-asyncio<2,>=1.3; extra == 'dev'
|
|
23
|
+
Requires-Dist: pytest<10,>=9; extra == 'dev'
|
|
24
|
+
Requires-Dist: ruff<1,>=0.14; extra == 'dev'
|
|
25
|
+
Provides-Extra: gemini
|
|
26
|
+
Requires-Dist: google-genai<2,>=1.0; extra == 'gemini'
|
|
27
|
+
Provides-Extra: ollama
|
|
28
|
+
Requires-Dist: httpx<1,>=0.28; extra == 'ollama'
|
|
29
|
+
Provides-Extra: openai
|
|
30
|
+
Requires-Dist: openai<2,>=1.0; extra == 'openai'
|
|
31
|
+
Description-Content-Type: text/markdown
|
|
32
|
+
|
|
33
|
+
# Handwritten Agent Core Embeddings
|
|
34
|
+
|
|
35
|
+
`zero-agent-core-embeddings` 为 Agent Core 的 `Embeddings` 协议提供 OpenAI、Gemini 和
|
|
36
|
+
Ollama 实现。Core 的 Retriever 和 VectorStore 不依赖任何厂商 SDK。
|
|
37
|
+
|
|
38
|
+
```bash
|
|
39
|
+
pip install "zero-agent-core-embeddings[openai]"
|
|
40
|
+
pip install "zero-agent-core-embeddings[gemini]"
|
|
41
|
+
pip install "zero-agent-core-embeddings[ollama]"
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
```python
|
|
45
|
+
from agent_core_embeddings import OpenAIEmbeddings
|
|
46
|
+
|
|
47
|
+
embeddings = OpenAIEmbeddings(
|
|
48
|
+
api_key="从安全配置读取",
|
|
49
|
+
model="text-embedding-3-small",
|
|
50
|
+
)
|
|
51
|
+
vectors = await embeddings.embed_documents(["第一段", "第二段"])
|
|
52
|
+
query_vector = await embeddings.embed_query("查询内容")
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
三个适配器共享批处理、并发、有限重试、超时、有限值和维度校验。API Key 和模型选择由应用配置,
|
|
56
|
+
扩展包不读取 `.env`。
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
# Handwritten Agent Core Embeddings
|
|
2
|
+
|
|
3
|
+
`zero-agent-core-embeddings` 为 Agent Core 的 `Embeddings` 协议提供 OpenAI、Gemini 和
|
|
4
|
+
Ollama 实现。Core 的 Retriever 和 VectorStore 不依赖任何厂商 SDK。
|
|
5
|
+
|
|
6
|
+
```bash
|
|
7
|
+
pip install "zero-agent-core-embeddings[openai]"
|
|
8
|
+
pip install "zero-agent-core-embeddings[gemini]"
|
|
9
|
+
pip install "zero-agent-core-embeddings[ollama]"
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
```python
|
|
13
|
+
from agent_core_embeddings import OpenAIEmbeddings
|
|
14
|
+
|
|
15
|
+
embeddings = OpenAIEmbeddings(
|
|
16
|
+
api_key="从安全配置读取",
|
|
17
|
+
model="text-embedding-3-small",
|
|
18
|
+
)
|
|
19
|
+
vectors = await embeddings.embed_documents(["第一段", "第二段"])
|
|
20
|
+
query_vector = await embeddings.embed_query("查询内容")
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
三个适配器共享批处理、并发、有限重试、超时、有限值和维度校验。API Key 和模型选择由应用配置,
|
|
24
|
+
扩展包不读取 `.env`。
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling>=1.27"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "zero-agent-core-embeddings"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Handwritten Agent Core 的 Embedding Provider 扩展"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.13,<3.14"
|
|
11
|
+
license = "Apache-2.0"
|
|
12
|
+
dependencies = ["zero-agent-core>=0.2.0,<0.3"]
|
|
13
|
+
classifiers = [
|
|
14
|
+
"Development Status :: 3 - Alpha",
|
|
15
|
+
"Operating System :: OS Independent",
|
|
16
|
+
"Programming Language :: Python :: 3",
|
|
17
|
+
"Programming Language :: Python :: 3.13",
|
|
18
|
+
"Typing :: Typed",
|
|
19
|
+
]
|
|
20
|
+
|
|
21
|
+
[project.urls]
|
|
22
|
+
Homepage = "https://github.com/qiuzixu/agent-core"
|
|
23
|
+
Repository = "https://github.com/qiuzixu/agent-core"
|
|
24
|
+
|
|
25
|
+
[project.optional-dependencies]
|
|
26
|
+
openai = ["openai>=1.0,<2"]
|
|
27
|
+
gemini = ["google-genai>=1.0,<2"]
|
|
28
|
+
ollama = ["httpx>=0.28,<1"]
|
|
29
|
+
all = [
|
|
30
|
+
"openai>=1.0,<2",
|
|
31
|
+
"google-genai>=1.0,<2",
|
|
32
|
+
"httpx>=0.28,<1",
|
|
33
|
+
]
|
|
34
|
+
dev = [
|
|
35
|
+
"mypy>=1.18,<2",
|
|
36
|
+
"pytest>=9,<10",
|
|
37
|
+
"pytest-asyncio>=1.3,<2",
|
|
38
|
+
"ruff>=0.14,<1",
|
|
39
|
+
]
|
|
40
|
+
|
|
41
|
+
[tool.hatch.build.targets.wheel]
|
|
42
|
+
packages = ["src/agent_core_embeddings"]
|
|
43
|
+
|
|
44
|
+
[tool.uv.sources]
|
|
45
|
+
zero-agent-core = { path = "../..", editable = true }
|
|
46
|
+
|
|
47
|
+
[tool.pytest.ini_options]
|
|
48
|
+
addopts = "-ra"
|
|
49
|
+
asyncio_mode = "auto"
|
|
50
|
+
testpaths = ["tests"]
|
|
51
|
+
|
|
52
|
+
[tool.ruff]
|
|
53
|
+
line-length = 110
|
|
54
|
+
target-version = "py313"
|
|
55
|
+
|
|
56
|
+
[tool.ruff.lint]
|
|
57
|
+
select = ["E", "F", "I", "UP", "B", "ASYNC", "RUF"]
|
|
58
|
+
ignore = ["RUF001", "RUF002", "RUF003"]
|
|
59
|
+
|
|
60
|
+
[tool.mypy]
|
|
61
|
+
python_version = "3.13"
|
|
62
|
+
strict = true
|
|
63
|
+
files = ["src"]
|
|
64
|
+
|
|
65
|
+
[[tool.mypy.overrides]]
|
|
66
|
+
module = ["google.*", "httpx", "openai"]
|
|
67
|
+
ignore_missing_imports = true
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
"""Agent Core 的 Embedding Provider 扩展。"""
|
|
2
|
+
|
|
3
|
+
from agent_core_embeddings.base import BaseProviderEmbeddings, EmbeddingExecutionPolicy
|
|
4
|
+
from agent_core_embeddings.errors import (
|
|
5
|
+
EmbeddingAdapterError,
|
|
6
|
+
EmbeddingConfigurationError,
|
|
7
|
+
EmbeddingInvocationError,
|
|
8
|
+
EmbeddingResponseError,
|
|
9
|
+
UnknownEmbeddingProviderError,
|
|
10
|
+
)
|
|
11
|
+
from agent_core_embeddings.factory import (
|
|
12
|
+
EmbeddingProviderFactory,
|
|
13
|
+
EmbeddingProviderRegistry,
|
|
14
|
+
create_embeddings,
|
|
15
|
+
default_embedding_provider_registry,
|
|
16
|
+
)
|
|
17
|
+
from agent_core_embeddings.gemini import GeminiEmbeddings
|
|
18
|
+
from agent_core_embeddings.ollama import OllamaEmbeddings
|
|
19
|
+
from agent_core_embeddings.openai import OpenAIEmbeddings
|
|
20
|
+
|
|
21
|
+
__all__ = [
|
|
22
|
+
"BaseProviderEmbeddings",
|
|
23
|
+
"EmbeddingAdapterError",
|
|
24
|
+
"EmbeddingConfigurationError",
|
|
25
|
+
"EmbeddingExecutionPolicy",
|
|
26
|
+
"EmbeddingInvocationError",
|
|
27
|
+
"EmbeddingProviderFactory",
|
|
28
|
+
"EmbeddingProviderRegistry",
|
|
29
|
+
"EmbeddingResponseError",
|
|
30
|
+
"GeminiEmbeddings",
|
|
31
|
+
"OllamaEmbeddings",
|
|
32
|
+
"OpenAIEmbeddings",
|
|
33
|
+
"UnknownEmbeddingProviderError",
|
|
34
|
+
"create_embeddings",
|
|
35
|
+
"default_embedding_provider_registry",
|
|
36
|
+
]
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
"""Embedding Provider 共用执行策略和校验。"""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import math
|
|
7
|
+
from abc import ABC, abstractmethod
|
|
8
|
+
from collections.abc import Sequence
|
|
9
|
+
from dataclasses import dataclass, replace
|
|
10
|
+
from typing import Literal
|
|
11
|
+
|
|
12
|
+
from agent_core_embeddings.errors import (
|
|
13
|
+
EmbeddingConfigurationError,
|
|
14
|
+
EmbeddingInvocationError,
|
|
15
|
+
EmbeddingResponseError,
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
EmbeddingTask = Literal["document", "query"]
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@dataclass(frozen=True)
|
|
22
|
+
class EmbeddingExecutionPolicy:
|
|
23
|
+
"""跨 Provider 共用的批处理和调用策略。"""
|
|
24
|
+
|
|
25
|
+
batch_size: int = 64
|
|
26
|
+
max_concurrency: int = 2
|
|
27
|
+
timeout_seconds: float = 60.0
|
|
28
|
+
max_retries: int = 2
|
|
29
|
+
retry_base_seconds: float = 0.5
|
|
30
|
+
expected_dimensions: int | None = None
|
|
31
|
+
|
|
32
|
+
def __post_init__(self) -> None:
|
|
33
|
+
if self.batch_size <= 0:
|
|
34
|
+
raise EmbeddingConfigurationError("batch_size 必须大于 0")
|
|
35
|
+
if self.max_concurrency <= 0:
|
|
36
|
+
raise EmbeddingConfigurationError("max_concurrency 必须大于 0")
|
|
37
|
+
if self.timeout_seconds <= 0:
|
|
38
|
+
raise EmbeddingConfigurationError("timeout_seconds 必须大于 0")
|
|
39
|
+
if self.max_retries < 0:
|
|
40
|
+
raise EmbeddingConfigurationError("max_retries 不能小于 0")
|
|
41
|
+
if self.retry_base_seconds < 0:
|
|
42
|
+
raise EmbeddingConfigurationError("retry_base_seconds 不能小于 0")
|
|
43
|
+
if self.expected_dimensions is not None and self.expected_dimensions <= 0:
|
|
44
|
+
raise EmbeddingConfigurationError("expected_dimensions 必须大于 0")
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class BaseProviderEmbeddings(ABC):
|
|
48
|
+
"""为具体 Provider 提供批处理、重试、超时和向量校验。"""
|
|
49
|
+
|
|
50
|
+
provider_name = "base"
|
|
51
|
+
|
|
52
|
+
def __init__(self, model: str, *, policy: EmbeddingExecutionPolicy | None = None) -> None:
|
|
53
|
+
if not model.strip():
|
|
54
|
+
raise EmbeddingConfigurationError("Embedding model 不能为空")
|
|
55
|
+
self.model = model
|
|
56
|
+
self.policy = policy or EmbeddingExecutionPolicy()
|
|
57
|
+
self._observed_dimensions: int | None = None
|
|
58
|
+
self._dimension_lock = asyncio.Lock()
|
|
59
|
+
|
|
60
|
+
@property
|
|
61
|
+
def dimensions(self) -> int | None:
|
|
62
|
+
"""返回配置或最近一次成功响应的向量维度。"""
|
|
63
|
+
return self.policy.expected_dimensions or self._observed_dimensions
|
|
64
|
+
|
|
65
|
+
async def embed_documents(self, texts: Sequence[str]) -> list[list[float]]:
|
|
66
|
+
values = [str(text) for text in texts]
|
|
67
|
+
if not values:
|
|
68
|
+
return []
|
|
69
|
+
return await self._embed_many(values, task="document")
|
|
70
|
+
|
|
71
|
+
async def embed_query(self, text: str) -> list[float]:
|
|
72
|
+
if not text.strip():
|
|
73
|
+
raise EmbeddingConfigurationError("查询文本不能为空")
|
|
74
|
+
vectors = await self._embed_many([text], task="query")
|
|
75
|
+
return vectors[0]
|
|
76
|
+
|
|
77
|
+
async def _embed_many(self, texts: list[str], *, task: EmbeddingTask) -> list[list[float]]:
|
|
78
|
+
batches = [
|
|
79
|
+
texts[offset : offset + self.policy.batch_size]
|
|
80
|
+
for offset in range(0, len(texts), self.policy.batch_size)
|
|
81
|
+
]
|
|
82
|
+
semaphore = asyncio.Semaphore(self.policy.max_concurrency)
|
|
83
|
+
|
|
84
|
+
async def execute(batch: list[str]) -> list[list[float]]:
|
|
85
|
+
async with semaphore:
|
|
86
|
+
return await self._execute_batch(batch, task=task)
|
|
87
|
+
|
|
88
|
+
results = await asyncio.gather(*(execute(batch) for batch in batches))
|
|
89
|
+
vectors = [vector for batch in results for vector in batch]
|
|
90
|
+
if len(vectors) != len(texts):
|
|
91
|
+
raise EmbeddingResponseError(
|
|
92
|
+
f"{self.provider_name} 返回 {len(vectors)} 个向量,期望 {len(texts)} 个"
|
|
93
|
+
)
|
|
94
|
+
await self._validate_vectors(vectors)
|
|
95
|
+
return vectors
|
|
96
|
+
|
|
97
|
+
async def _execute_batch(self, texts: list[str], *, task: EmbeddingTask) -> list[list[float]]:
|
|
98
|
+
last_error: Exception | None = None
|
|
99
|
+
attempts = self.policy.max_retries + 1
|
|
100
|
+
for attempt in range(attempts):
|
|
101
|
+
try:
|
|
102
|
+
vectors = await asyncio.wait_for(
|
|
103
|
+
self._embed_batch(texts, task=task),
|
|
104
|
+
timeout=self.policy.timeout_seconds,
|
|
105
|
+
)
|
|
106
|
+
if len(vectors) != len(texts):
|
|
107
|
+
raise EmbeddingResponseError(
|
|
108
|
+
f"{self.provider_name} 当前批次返回 {len(vectors)} 个向量,"
|
|
109
|
+
f"期望 {len(texts)} 个"
|
|
110
|
+
)
|
|
111
|
+
return vectors
|
|
112
|
+
except (EmbeddingConfigurationError, EmbeddingResponseError):
|
|
113
|
+
raise
|
|
114
|
+
except Exception as exc:
|
|
115
|
+
last_error = exc
|
|
116
|
+
if attempt + 1 >= attempts:
|
|
117
|
+
break
|
|
118
|
+
delay = self.policy.retry_base_seconds * (2**attempt)
|
|
119
|
+
if delay > 0:
|
|
120
|
+
await asyncio.sleep(delay)
|
|
121
|
+
raise EmbeddingInvocationError(
|
|
122
|
+
f"{self.provider_name} Embedding 调用失败,已尝试 {attempts} 次"
|
|
123
|
+
) from last_error
|
|
124
|
+
|
|
125
|
+
async def _validate_vectors(self, vectors: list[list[float]]) -> None:
|
|
126
|
+
if not vectors:
|
|
127
|
+
raise EmbeddingResponseError(f"{self.provider_name} 没有返回向量")
|
|
128
|
+
async with self._dimension_lock:
|
|
129
|
+
expected = self.policy.expected_dimensions or self._observed_dimensions or len(vectors[0])
|
|
130
|
+
if expected <= 0:
|
|
131
|
+
raise EmbeddingResponseError("Embedding 向量不能为空")
|
|
132
|
+
for vector in vectors:
|
|
133
|
+
if len(vector) != expected:
|
|
134
|
+
raise EmbeddingResponseError(
|
|
135
|
+
f"Embedding 向量维度不一致:期望 {expected},实际 {len(vector)}"
|
|
136
|
+
)
|
|
137
|
+
if not all(math.isfinite(value) for value in vector):
|
|
138
|
+
raise EmbeddingResponseError("Embedding 向量包含 NaN 或 Infinity")
|
|
139
|
+
self._observed_dimensions = expected
|
|
140
|
+
|
|
141
|
+
@abstractmethod
|
|
142
|
+
async def _embed_batch(self, texts: list[str], *, task: EmbeddingTask) -> list[list[float]]:
|
|
143
|
+
"""调用具体 Provider 生成一批向量。"""
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def policy_with_expected_dimensions(
|
|
147
|
+
policy: EmbeddingExecutionPolicy | None,
|
|
148
|
+
dimensions: int | None,
|
|
149
|
+
) -> EmbeddingExecutionPolicy:
|
|
150
|
+
"""把 Provider 的维度参数合并进通用校验策略。"""
|
|
151
|
+
if dimensions is None:
|
|
152
|
+
return policy or EmbeddingExecutionPolicy()
|
|
153
|
+
if dimensions <= 0:
|
|
154
|
+
raise EmbeddingConfigurationError("dimensions 必须大于 0")
|
|
155
|
+
if policy is None:
|
|
156
|
+
return EmbeddingExecutionPolicy(expected_dimensions=dimensions)
|
|
157
|
+
if policy.expected_dimensions not in {None, dimensions}:
|
|
158
|
+
raise EmbeddingConfigurationError("dimensions 与 policy.expected_dimensions 不一致")
|
|
159
|
+
return replace(policy, expected_dimensions=dimensions)
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"""Embedding 扩展错误。"""
|
|
2
|
+
|
|
3
|
+
from agent_core import AgentError
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class EmbeddingAdapterError(AgentError):
|
|
7
|
+
"""Embedding 适配器基础错误。"""
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class EmbeddingConfigurationError(EmbeddingAdapterError):
|
|
11
|
+
"""Embedding Provider 配置无效。"""
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class EmbeddingInvocationError(EmbeddingAdapterError):
|
|
15
|
+
"""Embedding Provider 调用失败。"""
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class EmbeddingResponseError(EmbeddingAdapterError):
|
|
19
|
+
"""Provider 返回的向量数量、维度或数值无效。"""
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class UnknownEmbeddingProviderError(EmbeddingConfigurationError):
|
|
23
|
+
"""请求了尚未注册的 Embedding Provider。"""
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
"""Embedding Provider 注册表和工厂。"""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Callable
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
from agent_core import Embeddings
|
|
9
|
+
|
|
10
|
+
from agent_core_embeddings.errors import (
|
|
11
|
+
EmbeddingConfigurationError,
|
|
12
|
+
UnknownEmbeddingProviderError,
|
|
13
|
+
)
|
|
14
|
+
from agent_core_embeddings.gemini import GeminiEmbeddings
|
|
15
|
+
from agent_core_embeddings.ollama import OllamaEmbeddings
|
|
16
|
+
from agent_core_embeddings.openai import OpenAIEmbeddings
|
|
17
|
+
|
|
18
|
+
type EmbeddingProviderFactory = Callable[..., Embeddings]
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _normalize_provider(name: str) -> str:
|
|
22
|
+
normalized = name.strip().lower().replace("_", "-")
|
|
23
|
+
if not normalized:
|
|
24
|
+
raise EmbeddingConfigurationError("Embedding Provider 名称不能为空")
|
|
25
|
+
return normalized
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class EmbeddingProviderRegistry:
|
|
29
|
+
"""保存 Provider 名称与构造函数,不动态导入配置中的类路径。"""
|
|
30
|
+
|
|
31
|
+
def __init__(self) -> None:
|
|
32
|
+
self._factories: dict[str, EmbeddingProviderFactory] = {}
|
|
33
|
+
|
|
34
|
+
def register(
|
|
35
|
+
self,
|
|
36
|
+
name: str,
|
|
37
|
+
factory: EmbeddingProviderFactory,
|
|
38
|
+
*,
|
|
39
|
+
replace: bool = False,
|
|
40
|
+
) -> None:
|
|
41
|
+
normalized = _normalize_provider(name)
|
|
42
|
+
if normalized in self._factories and not replace:
|
|
43
|
+
raise EmbeddingConfigurationError(f"Embedding Provider 已注册:{normalized}")
|
|
44
|
+
self._factories[normalized] = factory
|
|
45
|
+
|
|
46
|
+
def create(self, name: str, **kwargs: Any) -> Embeddings:
|
|
47
|
+
normalized = _normalize_provider(name)
|
|
48
|
+
factory = self._factories.get(normalized)
|
|
49
|
+
if factory is None:
|
|
50
|
+
raise UnknownEmbeddingProviderError(
|
|
51
|
+
f"未知 Embedding Provider:{name};可用值:{', '.join(self.names())}"
|
|
52
|
+
)
|
|
53
|
+
return factory(**kwargs)
|
|
54
|
+
|
|
55
|
+
def names(self) -> tuple[str, ...]:
|
|
56
|
+
return tuple(sorted(self._factories))
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
default_embedding_provider_registry = EmbeddingProviderRegistry()
|
|
60
|
+
default_embedding_provider_registry.register("openai", OpenAIEmbeddings)
|
|
61
|
+
default_embedding_provider_registry.register("gemini", GeminiEmbeddings)
|
|
62
|
+
default_embedding_provider_registry.register("ollama", OllamaEmbeddings)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def create_embeddings(
|
|
66
|
+
provider: str,
|
|
67
|
+
*,
|
|
68
|
+
registry: EmbeddingProviderRegistry | None = None,
|
|
69
|
+
**kwargs: Any,
|
|
70
|
+
) -> Embeddings:
|
|
71
|
+
"""按注册名创建符合 Core ``Embeddings`` 协议的适配器。"""
|
|
72
|
+
return (registry or default_embedding_provider_registry).create(provider, **kwargs)
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
"""Gemini Embedding 适配器。"""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
from agent_core_embeddings.base import (
|
|
8
|
+
BaseProviderEmbeddings,
|
|
9
|
+
EmbeddingExecutionPolicy,
|
|
10
|
+
EmbeddingTask,
|
|
11
|
+
policy_with_expected_dimensions,
|
|
12
|
+
)
|
|
13
|
+
from agent_core_embeddings.errors import EmbeddingConfigurationError, EmbeddingResponseError
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class GeminiEmbeddings(BaseProviderEmbeddings):
|
|
17
|
+
"""使用 Google Gen AI SDK 生成文档和查询向量。"""
|
|
18
|
+
|
|
19
|
+
provider_name = "gemini"
|
|
20
|
+
|
|
21
|
+
def __init__(
|
|
22
|
+
self,
|
|
23
|
+
*,
|
|
24
|
+
api_key: str | None = None,
|
|
25
|
+
model: str = "gemini-embedding-001",
|
|
26
|
+
dimensions: int | None = None,
|
|
27
|
+
policy: EmbeddingExecutionPolicy | None = None,
|
|
28
|
+
client: Any | None = None,
|
|
29
|
+
) -> None:
|
|
30
|
+
effective_policy = policy_with_expected_dimensions(policy, dimensions)
|
|
31
|
+
super().__init__(model, policy=effective_policy)
|
|
32
|
+
self._requested_dimensions = dimensions
|
|
33
|
+
if client is None:
|
|
34
|
+
try:
|
|
35
|
+
from google import genai
|
|
36
|
+
except ImportError as exc:
|
|
37
|
+
raise ImportError(
|
|
38
|
+
"GeminiEmbeddings 需要 google-genai,请安装 "
|
|
39
|
+
"zero-agent-core-embeddings[gemini]"
|
|
40
|
+
) from exc
|
|
41
|
+
client = genai.Client(api_key=api_key)
|
|
42
|
+
aio = getattr(client, "aio", None)
|
|
43
|
+
models: Any = getattr(aio, "models", None)
|
|
44
|
+
if models is None:
|
|
45
|
+
raise EmbeddingConfigurationError("Gemini client 必须提供 aio.models")
|
|
46
|
+
self._models: Any = models
|
|
47
|
+
|
|
48
|
+
async def _embed_batch(self, texts: list[str], *, task: EmbeddingTask) -> list[list[float]]:
|
|
49
|
+
config: dict[str, Any] = {
|
|
50
|
+
"task_type": "RETRIEVAL_DOCUMENT" if task == "document" else "RETRIEVAL_QUERY"
|
|
51
|
+
}
|
|
52
|
+
if self._requested_dimensions is not None:
|
|
53
|
+
config["output_dimensionality"] = self._requested_dimensions
|
|
54
|
+
response = await self._models.embed_content(
|
|
55
|
+
model=self.model,
|
|
56
|
+
contents=texts,
|
|
57
|
+
config=config,
|
|
58
|
+
)
|
|
59
|
+
embeddings = _read_value(response, "embeddings")
|
|
60
|
+
if not isinstance(embeddings, (list, tuple)):
|
|
61
|
+
raise EmbeddingResponseError("Gemini 响应缺少 embeddings 数组")
|
|
62
|
+
vectors: list[list[float]] = []
|
|
63
|
+
for item in embeddings:
|
|
64
|
+
values = _read_value(item, "values")
|
|
65
|
+
if not isinstance(values, (list, tuple)):
|
|
66
|
+
raise EmbeddingResponseError("Gemini 响应缺少 values 数组")
|
|
67
|
+
vectors.append([float(value) for value in values])
|
|
68
|
+
return vectors
|
|
69
|
+
def _read_value(value: Any, key: str, default: Any = None) -> Any:
|
|
70
|
+
if isinstance(value, dict):
|
|
71
|
+
return value.get(key, default)
|
|
72
|
+
return getattr(value, key, default)
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
"""Ollama Embedding 适配器。"""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Mapping
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
from agent_core_embeddings.base import BaseProviderEmbeddings, EmbeddingExecutionPolicy, EmbeddingTask
|
|
9
|
+
from agent_core_embeddings.errors import EmbeddingInvocationError, EmbeddingResponseError
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class OllamaEmbeddings(BaseProviderEmbeddings):
|
|
13
|
+
"""调用 Ollama 原生 ``/api/embed`` 接口。"""
|
|
14
|
+
|
|
15
|
+
provider_name = "ollama"
|
|
16
|
+
|
|
17
|
+
def __init__(
|
|
18
|
+
self,
|
|
19
|
+
*,
|
|
20
|
+
model: str = "nomic-embed-text",
|
|
21
|
+
base_url: str = "http://127.0.0.1:11434",
|
|
22
|
+
api_key: str | None = None,
|
|
23
|
+
truncate: bool = True,
|
|
24
|
+
keep_alive: str | int | None = None,
|
|
25
|
+
policy: EmbeddingExecutionPolicy | None = None,
|
|
26
|
+
client: Any | None = None,
|
|
27
|
+
) -> None:
|
|
28
|
+
super().__init__(model, policy=policy)
|
|
29
|
+
self._endpoint = f"{base_url.rstrip('/')}/api/embed"
|
|
30
|
+
self._api_key = api_key
|
|
31
|
+
self._truncate = truncate
|
|
32
|
+
self._keep_alive = keep_alive
|
|
33
|
+
self._client = client
|
|
34
|
+
|
|
35
|
+
async def _embed_batch(self, texts: list[str], *, task: EmbeddingTask) -> list[list[float]]:
|
|
36
|
+
del task
|
|
37
|
+
payload: dict[str, Any] = {
|
|
38
|
+
"model": self.model,
|
|
39
|
+
"input": texts,
|
|
40
|
+
"truncate": self._truncate,
|
|
41
|
+
}
|
|
42
|
+
if self._keep_alive is not None:
|
|
43
|
+
payload["keep_alive"] = self._keep_alive
|
|
44
|
+
headers = {"Accept": "application/json"}
|
|
45
|
+
if self._api_key:
|
|
46
|
+
headers["Authorization"] = f"Bearer {self._api_key}"
|
|
47
|
+
|
|
48
|
+
if self._client is not None:
|
|
49
|
+
return await self._post(self._client, payload=payload, headers=headers)
|
|
50
|
+
|
|
51
|
+
try:
|
|
52
|
+
import httpx
|
|
53
|
+
except ImportError as exc:
|
|
54
|
+
raise ImportError(
|
|
55
|
+
"OllamaEmbeddings 需要 httpx,请安装 "
|
|
56
|
+
"zero-agent-core-embeddings[ollama]"
|
|
57
|
+
) from exc
|
|
58
|
+
async with httpx.AsyncClient() as client:
|
|
59
|
+
return await self._post(client, payload=payload, headers=headers)
|
|
60
|
+
|
|
61
|
+
async def _post(
|
|
62
|
+
self,
|
|
63
|
+
client: Any,
|
|
64
|
+
*,
|
|
65
|
+
payload: Mapping[str, Any],
|
|
66
|
+
headers: Mapping[str, str],
|
|
67
|
+
) -> list[list[float]]:
|
|
68
|
+
response = await client.post(
|
|
69
|
+
self._endpoint,
|
|
70
|
+
json=dict(payload),
|
|
71
|
+
headers=dict(headers),
|
|
72
|
+
timeout=self.policy.timeout_seconds,
|
|
73
|
+
)
|
|
74
|
+
status_code = int(getattr(response, "status_code", 0))
|
|
75
|
+
if status_code < 200 or status_code >= 300:
|
|
76
|
+
body = str(getattr(response, "text", ""))[:500]
|
|
77
|
+
raise EmbeddingInvocationError(f"Ollama 返回 HTTP {status_code}:{body}")
|
|
78
|
+
try:
|
|
79
|
+
value = response.json()
|
|
80
|
+
except Exception as exc:
|
|
81
|
+
raise EmbeddingResponseError("Ollama 返回了无效 JSON") from exc
|
|
82
|
+
if not isinstance(value, Mapping):
|
|
83
|
+
raise EmbeddingResponseError("Ollama 响应根节点必须是对象")
|
|
84
|
+
embeddings = value.get("embeddings")
|
|
85
|
+
if not isinstance(embeddings, list):
|
|
86
|
+
raise EmbeddingResponseError("Ollama 响应缺少 embeddings 数组")
|
|
87
|
+
vectors: list[list[float]] = []
|
|
88
|
+
for item in embeddings:
|
|
89
|
+
if not isinstance(item, (list, tuple)):
|
|
90
|
+
raise EmbeddingResponseError("Ollama embedding 必须是数组")
|
|
91
|
+
vectors.append([float(number) for number in item])
|
|
92
|
+
return vectors
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
"""OpenAI Embedding 适配器。"""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
from agent_core_embeddings.base import (
|
|
8
|
+
BaseProviderEmbeddings,
|
|
9
|
+
EmbeddingExecutionPolicy,
|
|
10
|
+
EmbeddingTask,
|
|
11
|
+
policy_with_expected_dimensions,
|
|
12
|
+
)
|
|
13
|
+
from agent_core_embeddings.errors import EmbeddingResponseError
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class OpenAIEmbeddings(BaseProviderEmbeddings):
|
|
17
|
+
"""使用 OpenAI Embeddings API 生成文档和查询向量。"""
|
|
18
|
+
|
|
19
|
+
provider_name = "openai"
|
|
20
|
+
|
|
21
|
+
def __init__(
|
|
22
|
+
self,
|
|
23
|
+
*,
|
|
24
|
+
api_key: str | None = None,
|
|
25
|
+
model: str = "text-embedding-3-small",
|
|
26
|
+
base_url: str | None = None,
|
|
27
|
+
dimensions: int | None = None,
|
|
28
|
+
policy: EmbeddingExecutionPolicy | None = None,
|
|
29
|
+
client: Any | None = None,
|
|
30
|
+
) -> None:
|
|
31
|
+
effective_policy = policy_with_expected_dimensions(policy, dimensions)
|
|
32
|
+
super().__init__(model, policy=effective_policy)
|
|
33
|
+
self._requested_dimensions = dimensions
|
|
34
|
+
if client is None:
|
|
35
|
+
try:
|
|
36
|
+
from openai import AsyncOpenAI
|
|
37
|
+
except ImportError as exc:
|
|
38
|
+
raise ImportError(
|
|
39
|
+
"OpenAIEmbeddings 需要 openai,请安装 "
|
|
40
|
+
"zero-agent-core-embeddings[openai]"
|
|
41
|
+
) from exc
|
|
42
|
+
kwargs: dict[str, Any] = {}
|
|
43
|
+
if api_key is not None:
|
|
44
|
+
kwargs["api_key"] = api_key
|
|
45
|
+
if base_url is not None:
|
|
46
|
+
kwargs["base_url"] = base_url
|
|
47
|
+
client = AsyncOpenAI(**kwargs)
|
|
48
|
+
self._client = client
|
|
49
|
+
|
|
50
|
+
async def _embed_batch(self, texts: list[str], *, task: EmbeddingTask) -> list[list[float]]:
|
|
51
|
+
del task
|
|
52
|
+
kwargs: dict[str, Any] = {
|
|
53
|
+
"model": self.model,
|
|
54
|
+
"input": texts,
|
|
55
|
+
"encoding_format": "float",
|
|
56
|
+
}
|
|
57
|
+
if self._requested_dimensions is not None:
|
|
58
|
+
kwargs["dimensions"] = self._requested_dimensions
|
|
59
|
+
response = await self._client.embeddings.create(**kwargs)
|
|
60
|
+
data = _read_value(response, "data")
|
|
61
|
+
if not isinstance(data, list):
|
|
62
|
+
try:
|
|
63
|
+
data = list(data)
|
|
64
|
+
except TypeError as exc:
|
|
65
|
+
raise EmbeddingResponseError("OpenAI 响应缺少 data 数组") from exc
|
|
66
|
+
ordered = sorted(data, key=lambda item: int(_read_value(item, "index", 0)))
|
|
67
|
+
vectors: list[list[float]] = []
|
|
68
|
+
for item in ordered:
|
|
69
|
+
embedding = _read_value(item, "embedding")
|
|
70
|
+
if not isinstance(embedding, (list, tuple)):
|
|
71
|
+
raise EmbeddingResponseError("OpenAI 响应缺少 embedding 数组")
|
|
72
|
+
vectors.append([float(value) for value in embedding])
|
|
73
|
+
return vectors
|
|
74
|
+
def _read_value(value: Any, key: str, default: Any = None) -> Any:
|
|
75
|
+
if isinstance(value, dict):
|
|
76
|
+
return value.get(key, default)
|
|
77
|
+
return getattr(value, key, default)
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
"""Embedding Provider 扩展契约测试。"""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import math
|
|
7
|
+
import unittest
|
|
8
|
+
from types import SimpleNamespace
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
from agent_core import Embeddings
|
|
12
|
+
|
|
13
|
+
from agent_core_embeddings import (
|
|
14
|
+
BaseProviderEmbeddings,
|
|
15
|
+
EmbeddingConfigurationError,
|
|
16
|
+
EmbeddingExecutionPolicy,
|
|
17
|
+
EmbeddingProviderRegistry,
|
|
18
|
+
EmbeddingResponseError,
|
|
19
|
+
GeminiEmbeddings,
|
|
20
|
+
OllamaEmbeddings,
|
|
21
|
+
OpenAIEmbeddings,
|
|
22
|
+
UnknownEmbeddingProviderError,
|
|
23
|
+
create_embeddings,
|
|
24
|
+
)
|
|
25
|
+
from agent_core_embeddings.base import EmbeddingTask
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class _OpenAIEndpoint:
|
|
29
|
+
def __init__(self) -> None:
|
|
30
|
+
self.calls: list[dict[str, Any]] = []
|
|
31
|
+
|
|
32
|
+
async def create(self, **kwargs: Any) -> Any:
|
|
33
|
+
self.calls.append(kwargs)
|
|
34
|
+
data = [
|
|
35
|
+
SimpleNamespace(index=index, embedding=[float(len(text)), float(index), 1.0])
|
|
36
|
+
for index, text in enumerate(kwargs["input"])
|
|
37
|
+
]
|
|
38
|
+
return SimpleNamespace(data=list(reversed(data)))
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class _OpenAIClient:
|
|
42
|
+
def __init__(self) -> None:
|
|
43
|
+
self.embeddings = _OpenAIEndpoint()
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class _GeminiModels:
|
|
47
|
+
def __init__(self) -> None:
|
|
48
|
+
self.calls: list[dict[str, Any]] = []
|
|
49
|
+
|
|
50
|
+
async def embed_content(self, **kwargs: Any) -> Any:
|
|
51
|
+
self.calls.append(kwargs)
|
|
52
|
+
return SimpleNamespace(
|
|
53
|
+
embeddings=[
|
|
54
|
+
SimpleNamespace(values=[float(len(text)), 1.0, 0.0])
|
|
55
|
+
for text in kwargs["contents"]
|
|
56
|
+
]
|
|
57
|
+
)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
class _GeminiClient:
|
|
61
|
+
def __init__(self) -> None:
|
|
62
|
+
self.models = _GeminiModels()
|
|
63
|
+
self.aio = SimpleNamespace(models=self.models)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
class _HttpResponse:
|
|
67
|
+
def __init__(self, payload: object, *, status_code: int = 200, text: str = "") -> None:
|
|
68
|
+
self.payload = payload
|
|
69
|
+
self.status_code = status_code
|
|
70
|
+
self.text = text
|
|
71
|
+
|
|
72
|
+
def json(self) -> object:
|
|
73
|
+
return self.payload
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
class _HttpClient:
|
|
77
|
+
def __init__(self, response: _HttpResponse) -> None:
|
|
78
|
+
self.response = response
|
|
79
|
+
self.calls: list[dict[str, Any]] = []
|
|
80
|
+
|
|
81
|
+
async def post(self, url: str, **kwargs: Any) -> _HttpResponse:
|
|
82
|
+
self.calls.append({"url": url, **kwargs})
|
|
83
|
+
return self.response
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
class _FlakyEmbeddings(BaseProviderEmbeddings):
|
|
87
|
+
provider_name = "flaky"
|
|
88
|
+
|
|
89
|
+
def __init__(self, failures: int, vectors: list[list[float]], **kwargs: Any) -> None:
|
|
90
|
+
super().__init__("fake", **kwargs)
|
|
91
|
+
self.failures = failures
|
|
92
|
+
self.vectors = vectors
|
|
93
|
+
self.calls = 0
|
|
94
|
+
|
|
95
|
+
async def _embed_batch(self, texts: list[str], *, task: EmbeddingTask) -> list[list[float]]:
|
|
96
|
+
del texts, task
|
|
97
|
+
self.calls += 1
|
|
98
|
+
if self.calls <= self.failures:
|
|
99
|
+
raise RuntimeError("temporary")
|
|
100
|
+
return self.vectors
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
class _SlowEmbeddings(BaseProviderEmbeddings):
|
|
104
|
+
provider_name = "slow"
|
|
105
|
+
|
|
106
|
+
async def _embed_batch(self, texts: list[str], *, task: EmbeddingTask) -> list[list[float]]:
|
|
107
|
+
del texts, task
|
|
108
|
+
await asyncio.sleep(0.1)
|
|
109
|
+
return [[1.0]]
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
class ProviderAdapterTests(unittest.IsolatedAsyncioTestCase):
|
|
113
|
+
async def test_openai_batches_and_restores_response_order(self) -> None:
|
|
114
|
+
client = _OpenAIClient()
|
|
115
|
+
embeddings = OpenAIEmbeddings(
|
|
116
|
+
client=client,
|
|
117
|
+
dimensions=3,
|
|
118
|
+
policy=EmbeddingExecutionPolicy(
|
|
119
|
+
batch_size=2,
|
|
120
|
+
max_concurrency=1,
|
|
121
|
+
expected_dimensions=3,
|
|
122
|
+
),
|
|
123
|
+
)
|
|
124
|
+
|
|
125
|
+
vectors = await embeddings.embed_documents(["a", "bb", "ccc"])
|
|
126
|
+
|
|
127
|
+
self.assertEqual(vectors, [[1.0, 0.0, 1.0], [2.0, 1.0, 1.0], [3.0, 0.0, 1.0]])
|
|
128
|
+
self.assertEqual(len(client.embeddings.calls), 2)
|
|
129
|
+
self.assertTrue(all(call["dimensions"] == 3 for call in client.embeddings.calls))
|
|
130
|
+
self.assertIsInstance(embeddings, Embeddings)
|
|
131
|
+
|
|
132
|
+
async def test_gemini_distinguishes_document_and_query_tasks(self) -> None:
|
|
133
|
+
client = _GeminiClient()
|
|
134
|
+
embeddings = GeminiEmbeddings(client=client, dimensions=3)
|
|
135
|
+
|
|
136
|
+
documents = await embeddings.embed_documents(["文档"])
|
|
137
|
+
query = await embeddings.embed_query("查询")
|
|
138
|
+
|
|
139
|
+
self.assertEqual(len(documents[0]), 3)
|
|
140
|
+
self.assertEqual(len(query), 3)
|
|
141
|
+
self.assertEqual(
|
|
142
|
+
client.models.calls[0]["config"]["task_type"],
|
|
143
|
+
"RETRIEVAL_DOCUMENT",
|
|
144
|
+
)
|
|
145
|
+
self.assertEqual(
|
|
146
|
+
client.models.calls[1]["config"]["task_type"],
|
|
147
|
+
"RETRIEVAL_QUERY",
|
|
148
|
+
)
|
|
149
|
+
|
|
150
|
+
async def test_ollama_uses_native_embed_endpoint(self) -> None:
|
|
151
|
+
client = _HttpClient(_HttpResponse({"embeddings": [[1, 0], [0, 1]]}))
|
|
152
|
+
embeddings = OllamaEmbeddings(
|
|
153
|
+
client=client,
|
|
154
|
+
model="nomic-embed-text",
|
|
155
|
+
base_url="http://ollama.local/",
|
|
156
|
+
api_key="secret",
|
|
157
|
+
policy=EmbeddingExecutionPolicy(expected_dimensions=2),
|
|
158
|
+
)
|
|
159
|
+
|
|
160
|
+
vectors = await embeddings.embed_documents(["one", "two"])
|
|
161
|
+
|
|
162
|
+
self.assertEqual(vectors, [[1.0, 0.0], [0.0, 1.0]])
|
|
163
|
+
call = client.calls[0]
|
|
164
|
+
self.assertEqual(call["url"], "http://ollama.local/api/embed")
|
|
165
|
+
self.assertEqual(call["json"]["input"], ["one", "two"])
|
|
166
|
+
self.assertEqual(call["headers"]["Authorization"], "Bearer secret")
|
|
167
|
+
|
|
168
|
+
async def test_retry_and_observed_dimensions(self) -> None:
|
|
169
|
+
embeddings = _FlakyEmbeddings(
|
|
170
|
+
1,
|
|
171
|
+
[[1.0, 2.0]],
|
|
172
|
+
policy=EmbeddingExecutionPolicy(max_retries=1, retry_base_seconds=0),
|
|
173
|
+
)
|
|
174
|
+
|
|
175
|
+
vector = await embeddings.embed_query("query")
|
|
176
|
+
|
|
177
|
+
self.assertEqual(vector, [1.0, 2.0])
|
|
178
|
+
self.assertEqual(embeddings.calls, 2)
|
|
179
|
+
self.assertEqual(embeddings.dimensions, 2)
|
|
180
|
+
|
|
181
|
+
async def test_invalid_vector_and_timeout_are_rejected(self) -> None:
|
|
182
|
+
invalid = _FlakyEmbeddings(0, [[math.nan]])
|
|
183
|
+
slow = _SlowEmbeddings(
|
|
184
|
+
"slow",
|
|
185
|
+
policy=EmbeddingExecutionPolicy(timeout_seconds=0.01, max_retries=0),
|
|
186
|
+
)
|
|
187
|
+
|
|
188
|
+
with self.assertRaises(EmbeddingResponseError):
|
|
189
|
+
await invalid.embed_query("query")
|
|
190
|
+
with self.assertRaises(Exception) as caught:
|
|
191
|
+
await slow.embed_query("query")
|
|
192
|
+
self.assertEqual(caught.exception.__class__.__name__, "EmbeddingInvocationError")
|
|
193
|
+
|
|
194
|
+
async def test_dimension_mismatch_is_rejected(self) -> None:
|
|
195
|
+
embeddings = _FlakyEmbeddings(
|
|
196
|
+
0,
|
|
197
|
+
[[1.0, 2.0]],
|
|
198
|
+
policy=EmbeddingExecutionPolicy(expected_dimensions=3),
|
|
199
|
+
)
|
|
200
|
+
|
|
201
|
+
with self.assertRaises(EmbeddingResponseError):
|
|
202
|
+
await embeddings.embed_query("query")
|
|
203
|
+
|
|
204
|
+
with self.assertRaises(EmbeddingConfigurationError):
|
|
205
|
+
OpenAIEmbeddings(
|
|
206
|
+
client=_OpenAIClient(),
|
|
207
|
+
dimensions=2,
|
|
208
|
+
policy=EmbeddingExecutionPolicy(expected_dimensions=3),
|
|
209
|
+
)
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
class FactoryTests(unittest.TestCase):
|
|
213
|
+
def test_default_factory_and_custom_registry(self) -> None:
|
|
214
|
+
adapter = create_embeddings("OPENAI", client=_OpenAIClient())
|
|
215
|
+
self.assertIsInstance(adapter, OpenAIEmbeddings)
|
|
216
|
+
|
|
217
|
+
registry = EmbeddingProviderRegistry()
|
|
218
|
+
registry.register("custom", lambda **_: _FlakyEmbeddings(0, [[1.0]]))
|
|
219
|
+
custom = registry.create("custom")
|
|
220
|
+
self.assertIsInstance(custom, Embeddings)
|
|
221
|
+
|
|
222
|
+
def test_duplicate_unknown_and_invalid_policy_are_explicit(self) -> None:
|
|
223
|
+
registry = EmbeddingProviderRegistry()
|
|
224
|
+
registry.register("custom", lambda **_: _FlakyEmbeddings(0, [[1.0]]))
|
|
225
|
+
with self.assertRaises(EmbeddingConfigurationError):
|
|
226
|
+
registry.register("custom", lambda **_: _FlakyEmbeddings(0, [[1.0]]))
|
|
227
|
+
with self.assertRaises(UnknownEmbeddingProviderError):
|
|
228
|
+
registry.create("missing")
|
|
229
|
+
with self.assertRaises(EmbeddingConfigurationError):
|
|
230
|
+
EmbeddingExecutionPolicy(batch_size=0)
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
if __name__ == "__main__":
|
|
234
|
+
unittest.main()
|