cmem-plugin-llm 0.5.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.
|
@@ -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 2021 CMEM
|
|
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,65 @@
|
|
|
1
|
+
Metadata-Version: 2.3
|
|
2
|
+
Name: cmem-plugin-llm
|
|
3
|
+
Version: 0.5.0
|
|
4
|
+
Summary: Interact with Large Language Models.
|
|
5
|
+
License: Apache-2.0
|
|
6
|
+
Keywords: eccenca Corporate Memory,plugin
|
|
7
|
+
Author: eccenca GmbH
|
|
8
|
+
Author-email: cmempy-developer@eccenca.com
|
|
9
|
+
Requires-Python: >=3.11,<4.0
|
|
10
|
+
Classifier: Development Status :: 4 - Beta
|
|
11
|
+
Classifier: Environment :: Plugins
|
|
12
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
17
|
+
Requires-Dist: cmem-plugin-base (>=4.7.0,<5.0.0)
|
|
18
|
+
Requires-Dist: langchain-community (>=0.3.0,<0.4.0)
|
|
19
|
+
Requires-Dist: langchain-openai (>=0.2.0,<0.3.0)
|
|
20
|
+
Requires-Dist: pydantic (>=2.8.2,<3.0.0)
|
|
21
|
+
Description-Content-Type: text/markdown
|
|
22
|
+
|
|
23
|
+
# cmem-plugin-llm
|
|
24
|
+
|
|
25
|
+
Interact with Large Language Models.
|
|
26
|
+
|
|
27
|
+
[![eccenca Corporate Memory][cmem-shield]][cmem-link]
|
|
28
|
+
|
|
29
|
+
This is a plugin for [eccenca](https://eccenca.com) [Corporate Memory](https://documentation.eccenca.com). You can install it with the [cmemc](https://eccenca.com/go/cmemc) command line clients like this:
|
|
30
|
+
|
|
31
|
+
```
|
|
32
|
+
cmemc admin workspace python install cmem-plugin-llm
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
[![poetry][poetry-shield]][poetry-link] [![ruff][ruff-shield]][ruff-link] [![mypy][mypy-shield]][mypy-link] [![copier][copier-shield]][copier]
|
|
36
|
+
|
|
37
|
+
[cmem-link]: https://documentation.eccenca.com
|
|
38
|
+
[cmem-shield]: https://img.shields.io/endpoint?url=https://dev.documentation.eccenca.com/badge.json
|
|
39
|
+
[poetry-link]: https://python-poetry.org/
|
|
40
|
+
[poetry-shield]: https://img.shields.io/endpoint?url=https://python-poetry.org/badge/v0.json
|
|
41
|
+
[ruff-link]: https://docs.astral.sh/ruff/
|
|
42
|
+
[ruff-shield]: https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json&label=Code%20Style
|
|
43
|
+
[mypy-link]: https://mypy-lang.org/
|
|
44
|
+
[mypy-shield]: https://www.mypy-lang.org/static/mypy_badge.svg
|
|
45
|
+
[copier]: https://copier.readthedocs.io/
|
|
46
|
+
[copier-shield]: https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/copier-org/copier/master/img/badge/badge-grayscale-inverted-border-purple.json
|
|
47
|
+
|
|
48
|
+
This plugin contain the following capabilitities:
|
|
49
|
+
|
|
50
|
+
- create embeddings: it allows to create embeddings from an arbitrary data point or from specified data point paths (properties/columns).
|
|
51
|
+
After being processed each data point receive two additional paths the ```embedding``` path and the ```text``` path.
|
|
52
|
+
- The ```text``` path contain the paths utilized for generate the embeddings in text format.
|
|
53
|
+
- If the original data contain already a path named ```text```, this path is used for embeddings generation.
|
|
54
|
+
- The ```embedding``` path contain the generated embedding.
|
|
55
|
+
|
|
56
|
+
# Parameters
|
|
57
|
+
|
|
58
|
+
- ```url```: openAI compatible endpoint, default ```https://api.openai.com/v1```
|
|
59
|
+
- ```model```: embedding model, default ```text-embedding-3-small```
|
|
60
|
+
- ```api_key```: api key of the endpoint, default blank
|
|
61
|
+
- ```timout_single_request```: the request timenout in milliseconds, default ```10000```
|
|
62
|
+
- ```entries_processing_buffer```: number of processed entries per request, default ```1000```
|
|
63
|
+
- ```embedding_paths```: specify which paths should be used for embedding generation, default all
|
|
64
|
+
- ```embedding_output_text```: output path that will contain the embedding text, default ```text```
|
|
65
|
+
- ```embedding_output_path```: output path that will contain the generated embedding, default ```embedding```
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
# cmem-plugin-llm
|
|
2
|
+
|
|
3
|
+
Interact with Large Language Models.
|
|
4
|
+
|
|
5
|
+
[![eccenca Corporate Memory][cmem-shield]][cmem-link]
|
|
6
|
+
|
|
7
|
+
This is a plugin for [eccenca](https://eccenca.com) [Corporate Memory](https://documentation.eccenca.com). You can install it with the [cmemc](https://eccenca.com/go/cmemc) command line clients like this:
|
|
8
|
+
|
|
9
|
+
```
|
|
10
|
+
cmemc admin workspace python install cmem-plugin-llm
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
[![poetry][poetry-shield]][poetry-link] [![ruff][ruff-shield]][ruff-link] [![mypy][mypy-shield]][mypy-link] [![copier][copier-shield]][copier]
|
|
14
|
+
|
|
15
|
+
[cmem-link]: https://documentation.eccenca.com
|
|
16
|
+
[cmem-shield]: https://img.shields.io/endpoint?url=https://dev.documentation.eccenca.com/badge.json
|
|
17
|
+
[poetry-link]: https://python-poetry.org/
|
|
18
|
+
[poetry-shield]: https://img.shields.io/endpoint?url=https://python-poetry.org/badge/v0.json
|
|
19
|
+
[ruff-link]: https://docs.astral.sh/ruff/
|
|
20
|
+
[ruff-shield]: https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json&label=Code%20Style
|
|
21
|
+
[mypy-link]: https://mypy-lang.org/
|
|
22
|
+
[mypy-shield]: https://www.mypy-lang.org/static/mypy_badge.svg
|
|
23
|
+
[copier]: https://copier.readthedocs.io/
|
|
24
|
+
[copier-shield]: https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/copier-org/copier/master/img/badge/badge-grayscale-inverted-border-purple.json
|
|
25
|
+
|
|
26
|
+
This plugin contain the following capabilitities:
|
|
27
|
+
|
|
28
|
+
- create embeddings: it allows to create embeddings from an arbitrary data point or from specified data point paths (properties/columns).
|
|
29
|
+
After being processed each data point receive two additional paths the ```embedding``` path and the ```text``` path.
|
|
30
|
+
- The ```text``` path contain the paths utilized for generate the embeddings in text format.
|
|
31
|
+
- If the original data contain already a path named ```text```, this path is used for embeddings generation.
|
|
32
|
+
- The ```embedding``` path contain the generated embedding.
|
|
33
|
+
|
|
34
|
+
# Parameters
|
|
35
|
+
|
|
36
|
+
- ```url```: openAI compatible endpoint, default ```https://api.openai.com/v1```
|
|
37
|
+
- ```model```: embedding model, default ```text-embedding-3-small```
|
|
38
|
+
- ```api_key```: api key of the endpoint, default blank
|
|
39
|
+
- ```timout_single_request```: the request timenout in milliseconds, default ```10000```
|
|
40
|
+
- ```entries_processing_buffer```: number of processed entries per request, default ```1000```
|
|
41
|
+
- ```embedding_paths```: specify which paths should be used for embedding generation, default all
|
|
42
|
+
- ```embedding_output_text```: output path that will contain the embedding text, default ```text```
|
|
43
|
+
- ```embedding_output_path```: output path that will contain the generated embedding, default ```embedding```
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""cmem-plugin-llm"""
|
|
@@ -0,0 +1,313 @@
|
|
|
1
|
+
"""Create Embeddings via OpenAI embeddings API endpoint"""
|
|
2
|
+
|
|
3
|
+
from collections.abc import Generator, Sequence
|
|
4
|
+
from typing import Any, ClassVar
|
|
5
|
+
|
|
6
|
+
from cmem_plugin_base.dataintegration.context import (
|
|
7
|
+
ExecutionContext,
|
|
8
|
+
ExecutionReport,
|
|
9
|
+
PluginContext,
|
|
10
|
+
)
|
|
11
|
+
from cmem_plugin_base.dataintegration.description import Plugin, PluginParameter
|
|
12
|
+
from cmem_plugin_base.dataintegration.entity import (
|
|
13
|
+
Entities,
|
|
14
|
+
Entity,
|
|
15
|
+
EntityPath,
|
|
16
|
+
EntitySchema,
|
|
17
|
+
)
|
|
18
|
+
from cmem_plugin_base.dataintegration.parameter.password import Password, PasswordParameterType
|
|
19
|
+
from cmem_plugin_base.dataintegration.plugins import WorkflowPlugin
|
|
20
|
+
from cmem_plugin_base.dataintegration.ports import (
|
|
21
|
+
FixedNumberOfInputs,
|
|
22
|
+
FixedSchemaPort,
|
|
23
|
+
FlexibleSchemaPort,
|
|
24
|
+
UnknownSchemaPort,
|
|
25
|
+
)
|
|
26
|
+
from cmem_plugin_base.dataintegration.types import Autocompletion, StringParameterType
|
|
27
|
+
from langchain_core.utils.utils import convert_to_secret_str
|
|
28
|
+
from langchain_openai import OpenAIEmbeddings
|
|
29
|
+
from openai import AuthenticationError, OpenAI
|
|
30
|
+
|
|
31
|
+
DEFAULT_EMBEDDING_PATH = "_embedding"
|
|
32
|
+
DEFAULT_EMBEDDING_SOURCE_PATH = "_embedding_source"
|
|
33
|
+
MODEL_EXAMPLE = "text-embedding-3-small"
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class SamePathError(ValueError):
|
|
37
|
+
"""Same Path Exception"""
|
|
38
|
+
|
|
39
|
+
def __init__(self, path: str):
|
|
40
|
+
super().__init__(f"Path '{path}' can not be input AND output path.")
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class OpenAPIModel(StringParameterType):
|
|
44
|
+
"""OpenAPI Model Type"""
|
|
45
|
+
|
|
46
|
+
autocompletion_depends_on_parameters: ClassVar[list[str]] = ["url", "api_key"]
|
|
47
|
+
|
|
48
|
+
# auto complete for values
|
|
49
|
+
allow_only_autocompleted_values: bool = True
|
|
50
|
+
# auto complete for labels
|
|
51
|
+
autocomplete_value_with_labels: bool = True
|
|
52
|
+
|
|
53
|
+
def autocomplete(
|
|
54
|
+
self,
|
|
55
|
+
query_terms: list[str],
|
|
56
|
+
depend_on_parameter_values: list[Any],
|
|
57
|
+
context: PluginContext,
|
|
58
|
+
) -> list[Autocompletion]:
|
|
59
|
+
"""Return all results that match ALL provided query terms."""
|
|
60
|
+
_ = context
|
|
61
|
+
url = depend_on_parameter_values[0]
|
|
62
|
+
api_key = depend_on_parameter_values[1]
|
|
63
|
+
api_key = api_key if isinstance(api_key, str) else api_key.decrypt()
|
|
64
|
+
result = []
|
|
65
|
+
try:
|
|
66
|
+
api = OpenAI(api_key=api_key, base_url=url)
|
|
67
|
+
models = api.models.list()
|
|
68
|
+
filtered_models = set()
|
|
69
|
+
if query_terms:
|
|
70
|
+
for term in query_terms:
|
|
71
|
+
for model in models:
|
|
72
|
+
if term in model.id:
|
|
73
|
+
filtered_models.add(model.id)
|
|
74
|
+
else:
|
|
75
|
+
filtered_models = {_.id for _ in models}
|
|
76
|
+
result = [Autocompletion(value=f"{_}", label=f"{_}") for _ in filtered_models]
|
|
77
|
+
except AuthenticationError as error:
|
|
78
|
+
raise ValueError(
|
|
79
|
+
"Failed to authenticate with OpenAI API, Please check URL and API key."
|
|
80
|
+
) from error
|
|
81
|
+
|
|
82
|
+
result.sort(key=lambda x: x.label)
|
|
83
|
+
return result
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
@Plugin(
|
|
87
|
+
label="Create Embeddings",
|
|
88
|
+
description="Fetch embeddings from OpenAI embeddings API endpoint.",
|
|
89
|
+
parameters=[
|
|
90
|
+
PluginParameter(
|
|
91
|
+
name="url",
|
|
92
|
+
label="URL",
|
|
93
|
+
description="URL of the OpenAI API (without endpoint path and without trailing slash)",
|
|
94
|
+
default_value="https://api.openai.com/v1",
|
|
95
|
+
),
|
|
96
|
+
PluginParameter(
|
|
97
|
+
name="api_key",
|
|
98
|
+
label="The OpenAI API key",
|
|
99
|
+
param_type=PasswordParameterType(),
|
|
100
|
+
description="Fill the OpenAI API key if needed "
|
|
101
|
+
"(or give a dummy value in case you access an unsecured endpoint).",
|
|
102
|
+
),
|
|
103
|
+
PluginParameter(
|
|
104
|
+
name="model",
|
|
105
|
+
label=f"The embeddings model, e.g. {MODEL_EXAMPLE}",
|
|
106
|
+
param_type=OpenAPIModel(),
|
|
107
|
+
),
|
|
108
|
+
PluginParameter(
|
|
109
|
+
name="timout_single_request",
|
|
110
|
+
label="Timeout (Single Request, in Milliseconds)",
|
|
111
|
+
advanced=True,
|
|
112
|
+
default_value=10000,
|
|
113
|
+
),
|
|
114
|
+
PluginParameter(
|
|
115
|
+
name="entries_processing_buffer",
|
|
116
|
+
label="Entries Processing Buffer",
|
|
117
|
+
description="How many input values do you want to send per request?",
|
|
118
|
+
advanced=True,
|
|
119
|
+
default_value=100,
|
|
120
|
+
),
|
|
121
|
+
PluginParameter(
|
|
122
|
+
name="embedding_output_path",
|
|
123
|
+
label="Entity Embedding path (output)",
|
|
124
|
+
description=f"Changing this value will change the output schema accordingly. "
|
|
125
|
+
f"Default: {DEFAULT_EMBEDDING_PATH}",
|
|
126
|
+
advanced=True,
|
|
127
|
+
default_value=DEFAULT_EMBEDDING_PATH,
|
|
128
|
+
),
|
|
129
|
+
PluginParameter(
|
|
130
|
+
name="embedding_output_text",
|
|
131
|
+
label="Entity Embedding text (output)",
|
|
132
|
+
description=f"Changing this value will change the output schema accordingly. "
|
|
133
|
+
f"Default: {DEFAULT_EMBEDDING_SOURCE_PATH}",
|
|
134
|
+
advanced=True,
|
|
135
|
+
default_value=DEFAULT_EMBEDDING_SOURCE_PATH,
|
|
136
|
+
),
|
|
137
|
+
PluginParameter(
|
|
138
|
+
name="embedding_paths",
|
|
139
|
+
label="Used entity paths (comma-separated list)",
|
|
140
|
+
description="Changing this value will change, which input paths are used by the "
|
|
141
|
+
"workflow task. A blank value means, all paths are used.",
|
|
142
|
+
advanced=True,
|
|
143
|
+
default_value="text",
|
|
144
|
+
),
|
|
145
|
+
],
|
|
146
|
+
)
|
|
147
|
+
class CreateEmbeddings(WorkflowPlugin):
|
|
148
|
+
"""Fetch embeddings from OpenAI embeddings API endpoint"""
|
|
149
|
+
|
|
150
|
+
execution_context: ExecutionContext
|
|
151
|
+
embeddings: OpenAIEmbeddings
|
|
152
|
+
entries_processing_buffer: int
|
|
153
|
+
embedding_output_text: str
|
|
154
|
+
embedding_output_path: str
|
|
155
|
+
embedding_paths: list[str]
|
|
156
|
+
embedding_report: ExecutionReport
|
|
157
|
+
|
|
158
|
+
def __init__( # noqa: PLR0913
|
|
159
|
+
self,
|
|
160
|
+
url: str,
|
|
161
|
+
api_key: Password | str = "",
|
|
162
|
+
model: str = MODEL_EXAMPLE,
|
|
163
|
+
timout_single_request: int = 10000,
|
|
164
|
+
entries_processing_buffer: int = 100,
|
|
165
|
+
embedding_paths: str = "",
|
|
166
|
+
embedding_output_text: str = DEFAULT_EMBEDDING_SOURCE_PATH,
|
|
167
|
+
embedding_output_path: str = DEFAULT_EMBEDDING_PATH,
|
|
168
|
+
) -> None:
|
|
169
|
+
self.base_url = url
|
|
170
|
+
self.timout_single_request = timout_single_request
|
|
171
|
+
self.api_key = api_key if isinstance(api_key, str) else api_key.decrypt()
|
|
172
|
+
if self.api_key == "":
|
|
173
|
+
self.api_key = "dummy-key"
|
|
174
|
+
self.embeddings = OpenAIEmbeddings(
|
|
175
|
+
base_url=url,
|
|
176
|
+
api_key=convert_to_secret_str(self.api_key),
|
|
177
|
+
model=model,
|
|
178
|
+
timeout=timout_single_request,
|
|
179
|
+
)
|
|
180
|
+
self.entries_processing_buffer = entries_processing_buffer
|
|
181
|
+
self.embedding_output_text = embedding_output_text
|
|
182
|
+
self.embedding_output_path = embedding_output_path
|
|
183
|
+
self.embedding_paths = self.input_paths_to_list(embedding_paths)
|
|
184
|
+
self.embedding_report = ExecutionReport()
|
|
185
|
+
self.embedding_report.operation = "create"
|
|
186
|
+
self.embedding_report.operation_desc = "embeddings created"
|
|
187
|
+
self._setup_ports()
|
|
188
|
+
if self.embedding_output_text in self.embedding_paths:
|
|
189
|
+
raise SamePathError(self.embedding_output_text)
|
|
190
|
+
if self.embedding_output_path in self.embedding_paths:
|
|
191
|
+
raise SamePathError(self.embedding_output_path)
|
|
192
|
+
|
|
193
|
+
@staticmethod
|
|
194
|
+
def input_paths_to_list(paths: str) -> list[str]:
|
|
195
|
+
"""Convert a comma-separated list of strings to a python list of strings."""
|
|
196
|
+
return [] if paths == "" else [_.strip() for _ in paths.split(",")]
|
|
197
|
+
|
|
198
|
+
def _setup_ports(self) -> None:
|
|
199
|
+
"""Configure input and output ports depending on the configuration"""
|
|
200
|
+
if len(self.embedding_paths) == 0:
|
|
201
|
+
self.input_ports = FixedNumberOfInputs([FlexibleSchemaPort()])
|
|
202
|
+
self.output_port = UnknownSchemaPort()
|
|
203
|
+
return
|
|
204
|
+
|
|
205
|
+
input_paths = [EntityPath(path=_) for _ in self.embedding_paths]
|
|
206
|
+
input_schema = EntitySchema(type_uri="entity", paths=input_paths)
|
|
207
|
+
self.input_ports = FixedNumberOfInputs(ports=[FixedSchemaPort(schema=input_schema)])
|
|
208
|
+
|
|
209
|
+
output_paths = [
|
|
210
|
+
EntityPath(path=_)
|
|
211
|
+
for _ in [*self.embedding_paths, self.embedding_output_path, self.embedding_output_text]
|
|
212
|
+
]
|
|
213
|
+
output_schema = EntitySchema(type_uri="entity", paths=output_paths)
|
|
214
|
+
self.output_port = FixedSchemaPort(schema=output_schema)
|
|
215
|
+
|
|
216
|
+
def _generate_output_schema(self, input_schema: EntitySchema) -> EntitySchema:
|
|
217
|
+
"""Get output schema"""
|
|
218
|
+
paths = list(input_schema.paths).copy()
|
|
219
|
+
paths.append(EntityPath(self.embedding_output_path))
|
|
220
|
+
paths.append(EntityPath(self.embedding_output_text))
|
|
221
|
+
return EntitySchema(type_uri=input_schema.type_uri, paths=paths)
|
|
222
|
+
|
|
223
|
+
def workflow_canceling(self) -> bool:
|
|
224
|
+
"""Check if the workflow is canceling / cancelled"""
|
|
225
|
+
try:
|
|
226
|
+
if self.execution_context.workflow.status() == "Canceling":
|
|
227
|
+
self.log.info("End task (Cancelled Workflow).")
|
|
228
|
+
return True
|
|
229
|
+
except AttributeError:
|
|
230
|
+
pass
|
|
231
|
+
return False
|
|
232
|
+
|
|
233
|
+
def _embedding_report_update(self, n: int) -> None:
|
|
234
|
+
if hasattr(self.execution_context, "report"):
|
|
235
|
+
self.embedding_report.entity_count += n
|
|
236
|
+
self.execution_context.report.update(self.embedding_report)
|
|
237
|
+
|
|
238
|
+
@staticmethod
|
|
239
|
+
def chunker(seq: Sequence, size: int) -> Generator[Sequence]:
|
|
240
|
+
"""Split a sequence into chunks"""
|
|
241
|
+
chunk = []
|
|
242
|
+
for entry in seq:
|
|
243
|
+
chunk.append(entry)
|
|
244
|
+
if len(chunk) == size:
|
|
245
|
+
yield chunk.copy()
|
|
246
|
+
chunk.clear()
|
|
247
|
+
if len(chunk) > 0:
|
|
248
|
+
yield chunk.copy()
|
|
249
|
+
|
|
250
|
+
@staticmethod
|
|
251
|
+
def _entity_to_dict(paths: Sequence[EntityPath], entity: Entity) -> dict[str, list[str]]:
|
|
252
|
+
"""Create a dict representation of an entity"""
|
|
253
|
+
entity_dic = {}
|
|
254
|
+
for key, value in zip(paths, entity.values, strict=False):
|
|
255
|
+
entity_dic[key.path] = list(value)
|
|
256
|
+
return entity_dic
|
|
257
|
+
|
|
258
|
+
def _process_entities(self, entities: Entities) -> Generator[Entity]:
|
|
259
|
+
"""Process an entity list (chunked), yielding new entity objects"""
|
|
260
|
+
self._embedding_report_update(0)
|
|
261
|
+
for entity_chunk in self.chunker(entities.entities, self.entries_processing_buffer):
|
|
262
|
+
embeddings_sources: list[str] = [] # a list of embedding source texts
|
|
263
|
+
entity_dicts: list[dict[str, list[str]]] = [] # a list of entity dictionaries
|
|
264
|
+
entity: Entity
|
|
265
|
+
if self.workflow_canceling():
|
|
266
|
+
break
|
|
267
|
+
for entity in entity_chunk:
|
|
268
|
+
entity_dic = self._entity_to_dict(entities.schema.paths, entity)
|
|
269
|
+
entity_dicts.append(entity_dic)
|
|
270
|
+
if len(entity.values) == 1 and len(entity.values[0]) == 1:
|
|
271
|
+
embedding_source = entity.values[0][0]
|
|
272
|
+
else:
|
|
273
|
+
embedding_source = str(entity_dic)
|
|
274
|
+
embeddings_sources.append(embedding_source)
|
|
275
|
+
embeddings: list[list[float]] = self.embeddings.embed_documents(embeddings_sources)
|
|
276
|
+
self._embedding_report_update(len(embeddings_sources))
|
|
277
|
+
|
|
278
|
+
# looping over list of embeddings, entity dicts, sources and entities
|
|
279
|
+
for (
|
|
280
|
+
entity_embedding,
|
|
281
|
+
entity_dict,
|
|
282
|
+
embedding_source,
|
|
283
|
+
original_entity,
|
|
284
|
+
) in zip(
|
|
285
|
+
embeddings,
|
|
286
|
+
entity_dicts,
|
|
287
|
+
embeddings_sources,
|
|
288
|
+
entity_chunk,
|
|
289
|
+
strict=False,
|
|
290
|
+
):
|
|
291
|
+
# add string repr of the embedding as a single value list
|
|
292
|
+
entity_dict[self.embedding_output_path] = [str(entity_embedding)]
|
|
293
|
+
# add string repr of the embedding source as a single value list
|
|
294
|
+
entity_dict[self.embedding_output_text] = [embedding_source]
|
|
295
|
+
values = list(entity_dict.values())
|
|
296
|
+
yield Entity(uri=original_entity.uri, values=values)
|
|
297
|
+
|
|
298
|
+
def execute(
|
|
299
|
+
self,
|
|
300
|
+
inputs: Sequence[Entities],
|
|
301
|
+
context: ExecutionContext,
|
|
302
|
+
) -> Entities:
|
|
303
|
+
"""Run the workflow operator."""
|
|
304
|
+
self.log.info("Start")
|
|
305
|
+
self.execution_context = context
|
|
306
|
+
first_input: Entities = inputs[0]
|
|
307
|
+
for input_path in [_.path for _ in first_input.schema.paths]:
|
|
308
|
+
if input_path in [self.embedding_output_path, self.embedding_output_text]:
|
|
309
|
+
raise SamePathError(input_path)
|
|
310
|
+
entities = self._process_entities(first_input)
|
|
311
|
+
schema = self._generate_output_schema(first_input.schema)
|
|
312
|
+
self.log.info("End")
|
|
313
|
+
return Entities(entities=entities, schema=schema)
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
[tool.poetry]
|
|
2
|
+
name = "cmem-plugin-llm"
|
|
3
|
+
version = "0.5.0"
|
|
4
|
+
license = "Apache-2.0"
|
|
5
|
+
description = "Interact with Large Language Models."
|
|
6
|
+
authors = ["eccenca GmbH <cmempy-developer@eccenca.com>"]
|
|
7
|
+
classifiers = [
|
|
8
|
+
"Development Status :: 4 - Beta","Environment :: Plugins",
|
|
9
|
+
]
|
|
10
|
+
readme = "README-public.md"
|
|
11
|
+
keywords = [
|
|
12
|
+
"eccenca Corporate Memory", "plugin"
|
|
13
|
+
]
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
[tool.poetry.dependencies]# if you need to change python version here, change it also in .python-version
|
|
17
|
+
python = "^3.11"
|
|
18
|
+
langchain-openai = "^0.2.0"
|
|
19
|
+
langchain-community = "^0.3.0"
|
|
20
|
+
pydantic = "^2.8.2"
|
|
21
|
+
|
|
22
|
+
[tool.poetry.dependencies.cmem-plugin-base]
|
|
23
|
+
version = "^4.7.0"
|
|
24
|
+
allow-prereleases = false
|
|
25
|
+
|
|
26
|
+
[tool.poetry.group.dev.dependencies.cmem-cmemc]
|
|
27
|
+
version = "^24.2.0"
|
|
28
|
+
|
|
29
|
+
[tool.poetry.group.dev.dependencies]
|
|
30
|
+
genbadge = {extras = ["coverage"], version = "^1.1.1"}
|
|
31
|
+
mypy = "^1.11.1"
|
|
32
|
+
pip = "^24"
|
|
33
|
+
pytest = "^8.3.2"
|
|
34
|
+
pytest-cov = "^5.0.0"
|
|
35
|
+
pytest-dotenv = "^0.5.2"
|
|
36
|
+
pytest-html = "^4.1.1"
|
|
37
|
+
pytest-memray = { version = "^1.7.0", markers = "platform_system != 'Windows'" }
|
|
38
|
+
ruff = "^0.6.1"
|
|
39
|
+
safety = "^1.10.3"
|
|
40
|
+
types-requests = "^2.32.0.20240712"
|
|
41
|
+
|
|
42
|
+
[build-system]
|
|
43
|
+
requires = ["poetry-core>=1.0.0", "poetry-dynamic-versioning"]
|
|
44
|
+
build-backend = "poetry_dynamic_versioning.backend"
|
|
45
|
+
|
|
46
|
+
[tool.poetry-dynamic-versioning]
|
|
47
|
+
enable = false
|
|
48
|
+
vcs = "git"
|
|
49
|
+
dirty = true
|
|
50
|
+
bump = true
|
|
51
|
+
|
|
52
|
+
[tool.mypy]
|
|
53
|
+
warn_return_any = true
|
|
54
|
+
ignore_missing_imports = true
|
|
55
|
+
|
|
56
|
+
[tool.pytest.ini_options]
|
|
57
|
+
addopts = ""
|
|
58
|
+
|
|
59
|
+
[tool.coverage.report]
|
|
60
|
+
exclude_also = [
|
|
61
|
+
"def __repr__",
|
|
62
|
+
"if self.debug:",
|
|
63
|
+
"if settings.DEBUG",
|
|
64
|
+
"raise AssertionError",
|
|
65
|
+
"raise NotImplementedError",
|
|
66
|
+
"if TYPE_CHECKING:",
|
|
67
|
+
"class .*\\bProtocol\\):",
|
|
68
|
+
"@(abc\\.)?abstractmethod",
|
|
69
|
+
]
|
|
70
|
+
|
|
71
|
+
[tool.ruff]
|
|
72
|
+
line-length = 100
|
|
73
|
+
target-version = "py311"
|
|
74
|
+
|
|
75
|
+
[tool.ruff.format]
|
|
76
|
+
line-ending = "lf" # Use `\n` line endings for all files
|
|
77
|
+
|
|
78
|
+
[tool.ruff.lint]
|
|
79
|
+
select = ["ALL"]
|
|
80
|
+
ignore = [
|
|
81
|
+
"ANN101", # Missing type annotation for self in method
|
|
82
|
+
"ANN204", # Missing return type annotation for special method `__init__`
|
|
83
|
+
"COM812", # missing-trailing-comma
|
|
84
|
+
"D107", # Missing docstring in __init__
|
|
85
|
+
"D203", # [*] 1 blank line required before class docstring
|
|
86
|
+
"D211", # No blank lines allowed before class docstring
|
|
87
|
+
"D213", # Multi-line docstring summary should start at the second line
|
|
88
|
+
"D400", # First line should end with a period
|
|
89
|
+
"D415", # First line should end with a period, question mark, or exclamation point
|
|
90
|
+
"EM", # Exception texts - https://docs.astral.sh/ruff/rules/#flake8-errmsg-em
|
|
91
|
+
"FBT", # The Boolean Trap - https://docs.astral.sh/ruff/rules/#flake8-boolean-trap-fbt
|
|
92
|
+
"FIX002", # Allow to add TODO notes in the code
|
|
93
|
+
"G004", # Logging statement uses f-string
|
|
94
|
+
"ISC001", # single-line-implicit-string-concatenation
|
|
95
|
+
"PD", # opinionated linting for pandas code
|
|
96
|
+
"S101", # use of assert detected
|
|
97
|
+
"TRY003", # Avoid specifying long messages outside the exception class
|
|
98
|
+
]
|
|
99
|
+
|