flowllm 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- flowllm-0.1.0.dist-info/METADATA +597 -0
- flowllm-0.1.0.dist-info/RECORD +66 -0
- flowllm-0.1.0.dist-info/WHEEL +5 -0
- flowllm-0.1.0.dist-info/entry_points.txt +3 -0
- flowllm-0.1.0.dist-info/licenses/LICENSE +201 -0
- flowllm-0.1.0.dist-info/top_level.txt +1 -0
- llmflow/__init__.py +0 -0
- llmflow/app.py +53 -0
- llmflow/config/__init__.py +0 -0
- llmflow/config/config_parser.py +80 -0
- llmflow/config/mock_config.yaml +58 -0
- llmflow/embedding_model/__init__.py +5 -0
- llmflow/embedding_model/base_embedding_model.py +104 -0
- llmflow/embedding_model/openai_compatible_embedding_model.py +95 -0
- llmflow/enumeration/__init__.py +0 -0
- llmflow/enumeration/agent_state.py +8 -0
- llmflow/enumeration/chunk_enum.py +9 -0
- llmflow/enumeration/http_enum.py +9 -0
- llmflow/enumeration/role.py +8 -0
- llmflow/llm/__init__.py +5 -0
- llmflow/llm/base_llm.py +138 -0
- llmflow/llm/openai_compatible_llm.py +283 -0
- llmflow/mcp_server.py +110 -0
- llmflow/op/__init__.py +10 -0
- llmflow/op/base_op.py +125 -0
- llmflow/op/mock_op.py +40 -0
- llmflow/op/prompt_mixin.py +74 -0
- llmflow/op/react/__init__.py +0 -0
- llmflow/op/react/react_v1_op.py +88 -0
- llmflow/op/react/react_v1_prompt.yaml +28 -0
- llmflow/op/vector_store/__init__.py +13 -0
- llmflow/op/vector_store/recall_vector_store_op.py +48 -0
- llmflow/op/vector_store/update_vector_store_op.py +28 -0
- llmflow/op/vector_store/vector_store_action_op.py +46 -0
- llmflow/pipeline/__init__.py +0 -0
- llmflow/pipeline/pipeline.py +94 -0
- llmflow/pipeline/pipeline_context.py +37 -0
- llmflow/schema/__init__.py +0 -0
- llmflow/schema/app_config.py +69 -0
- llmflow/schema/experience.py +144 -0
- llmflow/schema/message.py +68 -0
- llmflow/schema/request.py +32 -0
- llmflow/schema/response.py +29 -0
- llmflow/schema/vector_node.py +11 -0
- llmflow/service/__init__.py +0 -0
- llmflow/service/llmflow_service.py +96 -0
- llmflow/tool/__init__.py +9 -0
- llmflow/tool/base_tool.py +80 -0
- llmflow/tool/code_tool.py +43 -0
- llmflow/tool/dashscope_search_tool.py +162 -0
- llmflow/tool/mcp_tool.py +77 -0
- llmflow/tool/tavily_search_tool.py +109 -0
- llmflow/tool/terminate_tool.py +23 -0
- llmflow/utils/__init__.py +0 -0
- llmflow/utils/common_utils.py +17 -0
- llmflow/utils/file_handler.py +25 -0
- llmflow/utils/http_client.py +156 -0
- llmflow/utils/op_utils.py +102 -0
- llmflow/utils/registry.py +33 -0
- llmflow/utils/singleton.py +9 -0
- llmflow/utils/timer.py +53 -0
- llmflow/vector_store/__init__.py +7 -0
- llmflow/vector_store/base_vector_store.py +136 -0
- llmflow/vector_store/chroma_vector_store.py +188 -0
- llmflow/vector_store/es_vector_store.py +227 -0
- llmflow/vector_store/file_vector_store.py +163 -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 2024 Alibaba Group
|
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 @@
|
|
1
|
+
llmflow
|
llmflow/__init__.py
ADDED
File without changes
|
llmflow/app.py
ADDED
@@ -0,0 +1,53 @@
|
|
1
|
+
import sys
|
2
|
+
|
3
|
+
import uvicorn
|
4
|
+
from dotenv import load_dotenv
|
5
|
+
from fastapi import FastAPI
|
6
|
+
|
7
|
+
from llmflow.schema.request import RetrieverRequest, SummarizerRequest, VectorStoreRequest, AgentRequest
|
8
|
+
from llmflow.schema.response import RetrieverResponse, SummarizerResponse, VectorStoreResponse, AgentResponse
|
9
|
+
from llmflow.service.llmflow_service import LLMFlowService
|
10
|
+
|
11
|
+
load_dotenv()
|
12
|
+
|
13
|
+
app = FastAPI()
|
14
|
+
service = LLMFlowService(sys.argv[1:])
|
15
|
+
|
16
|
+
|
17
|
+
@app.post('/retriever', response_model=RetrieverResponse)
|
18
|
+
def call_retriever(request: RetrieverRequest):
|
19
|
+
return service(api="retriever", request=request)
|
20
|
+
|
21
|
+
|
22
|
+
@app.post('/summarizer', response_model=SummarizerResponse)
|
23
|
+
def call_summarizer(request: SummarizerRequest):
|
24
|
+
return service(api="summarizer", request=request)
|
25
|
+
|
26
|
+
|
27
|
+
@app.post('/vector_store', response_model=VectorStoreResponse)
|
28
|
+
def call_vector_store(request: VectorStoreRequest):
|
29
|
+
return service(api="vector_store", request=request)
|
30
|
+
|
31
|
+
|
32
|
+
@app.post('/agent', response_model=AgentResponse)
|
33
|
+
def call_agent(request: AgentRequest):
|
34
|
+
return service(api="agent", request=request)
|
35
|
+
|
36
|
+
|
37
|
+
def main():
|
38
|
+
uvicorn.run(app=app,
|
39
|
+
host=service.http_service_config.host,
|
40
|
+
port=service.http_service_config.port,
|
41
|
+
timeout_keep_alive=service.http_service_config.timeout_keep_alive,
|
42
|
+
limit_concurrency=service.http_service_config.limit_concurrency)
|
43
|
+
|
44
|
+
|
45
|
+
if __name__ == "__main__":
|
46
|
+
main()
|
47
|
+
|
48
|
+
# start with:
|
49
|
+
# llmflow \
|
50
|
+
# http_service.port=8001 \
|
51
|
+
# llm.default.model_name=qwen3-32b \
|
52
|
+
# embedding_model.default.model_name=text-embedding-v4 \
|
53
|
+
# vector_store.default.backend=local_file
|
File without changes
|
@@ -0,0 +1,80 @@
|
|
1
|
+
import json
|
2
|
+
from pathlib import Path
|
3
|
+
|
4
|
+
from loguru import logger
|
5
|
+
from omegaconf import OmegaConf, DictConfig
|
6
|
+
|
7
|
+
from llmflow.schema.app_config import AppConfig
|
8
|
+
|
9
|
+
|
10
|
+
class ConfigParser:
|
11
|
+
"""
|
12
|
+
Configuration parser that handles loading and merging configurations from multiple sources.
|
13
|
+
|
14
|
+
The configuration loading priority (from lowest to highest):
|
15
|
+
1. Default configuration from AppConfig schema
|
16
|
+
2. YAML configuration file
|
17
|
+
3. Command line arguments
|
18
|
+
4. Runtime keyword arguments
|
19
|
+
"""
|
20
|
+
|
21
|
+
def __init__(self, args: list):
|
22
|
+
"""
|
23
|
+
Initialize the configuration parser with command line arguments.
|
24
|
+
|
25
|
+
Args:
|
26
|
+
args: List of command line arguments in dotlist format (e.g., ['key=value'])
|
27
|
+
"""
|
28
|
+
# Step 1: Initialize with default configuration from AppConfig schema
|
29
|
+
self.app_config: DictConfig = OmegaConf.structured(AppConfig)
|
30
|
+
|
31
|
+
# Step 2: Load configuration from YAML file
|
32
|
+
# First, parse CLI arguments to check if custom config path is specified
|
33
|
+
cli_config: DictConfig = OmegaConf.from_dotlist(args)
|
34
|
+
temp_config: AppConfig = OmegaConf.to_object(OmegaConf.merge(self.app_config, cli_config))
|
35
|
+
|
36
|
+
# Determine config file path: either from CLI args or use predefined config
|
37
|
+
if temp_config.config_path:
|
38
|
+
# Use custom config path if provided
|
39
|
+
config_path = Path(temp_config.config_path)
|
40
|
+
else:
|
41
|
+
# Use predefined config name from the config directory
|
42
|
+
pre_defined_config = temp_config.pre_defined_config
|
43
|
+
if not pre_defined_config.endswith(".yaml"):
|
44
|
+
pre_defined_config += ".yaml"
|
45
|
+
config_path = Path(__file__).parent / pre_defined_config
|
46
|
+
|
47
|
+
logger.info(f"load config from path={config_path}")
|
48
|
+
yaml_config = OmegaConf.load(config_path)
|
49
|
+
# Merge YAML config with default config
|
50
|
+
self.app_config = OmegaConf.merge(self.app_config, yaml_config)
|
51
|
+
|
52
|
+
# Step 3: Merge CLI arguments (highest priority)
|
53
|
+
self.app_config = OmegaConf.merge(self.app_config, cli_config)
|
54
|
+
|
55
|
+
# Log the final merged configuration
|
56
|
+
app_config_dict = OmegaConf.to_container(self.app_config, resolve=True)
|
57
|
+
logger.info(f"app_config=\n{json.dumps(app_config_dict, indent=2, ensure_ascii=False)}")
|
58
|
+
|
59
|
+
def get_app_config(self, **kwargs) -> AppConfig:
|
60
|
+
"""
|
61
|
+
Get the application configuration with optional runtime overrides.
|
62
|
+
|
63
|
+
Args:
|
64
|
+
**kwargs: Additional configuration parameters to override at runtime
|
65
|
+
|
66
|
+
Returns:
|
67
|
+
AppConfig: The final application configuration object
|
68
|
+
"""
|
69
|
+
# Create a copy of the current configuration
|
70
|
+
app_config = self.app_config.copy()
|
71
|
+
|
72
|
+
# Apply runtime overrides if provided
|
73
|
+
if kwargs:
|
74
|
+
# Convert kwargs to dotlist format for OmegaConf
|
75
|
+
kwargs_list = [f"{k}={v}" for k, v in kwargs.items()]
|
76
|
+
update_config = OmegaConf.from_dotlist(kwargs_list)
|
77
|
+
app_config = OmegaConf.merge(app_config, update_config)
|
78
|
+
|
79
|
+
# Convert OmegaConf DictConfig to structured AppConfig object
|
80
|
+
return OmegaConf.to_object(app_config)
|
@@ -0,0 +1,58 @@
|
|
1
|
+
# demo config.yaml
|
2
|
+
|
3
|
+
http_service:
|
4
|
+
host: "0.0.0.0"
|
5
|
+
port: 8001
|
6
|
+
timeout_keep_alive: 600
|
7
|
+
limit_concurrency: 64
|
8
|
+
|
9
|
+
thread_pool:
|
10
|
+
max_workers: 10
|
11
|
+
|
12
|
+
api:
|
13
|
+
retriever: mock1_op->[mock4_op->mock2_op|mock5_op]->[mock3_op|mock6_op]
|
14
|
+
summarizer: mock1_op->[mock4_op->mock2_op|mock5_op]->mock3_op
|
15
|
+
vector_store: mock6_op
|
16
|
+
|
17
|
+
op:
|
18
|
+
mock1_op:
|
19
|
+
backend: mock1_op
|
20
|
+
llm: default
|
21
|
+
vector_store: default
|
22
|
+
params:
|
23
|
+
a: 1
|
24
|
+
b: 2
|
25
|
+
mock2_op:
|
26
|
+
backend: mock2_op
|
27
|
+
params:
|
28
|
+
a: 1
|
29
|
+
mock3_op:
|
30
|
+
backend: mock3_op
|
31
|
+
mock4_op:
|
32
|
+
backend: mock4_op
|
33
|
+
mock5_op:
|
34
|
+
backend: mock5_op
|
35
|
+
mock6_op:
|
36
|
+
backend: mock6_op
|
37
|
+
|
38
|
+
llm:
|
39
|
+
default:
|
40
|
+
backend: openai_compatible
|
41
|
+
model_name: qwen3-32b
|
42
|
+
params:
|
43
|
+
temperature: 0.6
|
44
|
+
|
45
|
+
embedding_model:
|
46
|
+
default:
|
47
|
+
backend: openai_compatible
|
48
|
+
model_name: text-embedding-v4
|
49
|
+
params:
|
50
|
+
dimensions: 1024
|
51
|
+
|
52
|
+
vector_store:
|
53
|
+
default:
|
54
|
+
backend: elasticsearch
|
55
|
+
embedding_model: default
|
56
|
+
params:
|
57
|
+
hosts: "http://localhost:9200"
|
58
|
+
|
@@ -0,0 +1,104 @@
|
|
1
|
+
from abc import ABC
|
2
|
+
from typing import List
|
3
|
+
|
4
|
+
from loguru import logger
|
5
|
+
from pydantic import BaseModel, Field
|
6
|
+
|
7
|
+
from llmflow.schema.vector_node import VectorNode
|
8
|
+
|
9
|
+
|
10
|
+
class BaseEmbeddingModel(BaseModel, ABC):
|
11
|
+
"""
|
12
|
+
Abstract base class for embedding models.
|
13
|
+
|
14
|
+
This class provides a common interface for various embedding model implementations,
|
15
|
+
including retry logic, error handling, and batch processing capabilities.
|
16
|
+
"""
|
17
|
+
# Model configuration fields
|
18
|
+
model_name: str = Field(default=..., description="Name of the embedding model")
|
19
|
+
dimensions: int = Field(default=..., description="Dimensionality of the embedding vectors")
|
20
|
+
max_retries: int = Field(default=3, description="Maximum number of retry attempts on failure")
|
21
|
+
raise_exception: bool = Field(default=True, description="Whether to raise exceptions after max retries")
|
22
|
+
max_batch_size: int = Field(default=10,
|
23
|
+
description="Maximum batch size for processing (text-embedding-v4 should not exceed 10)")
|
24
|
+
|
25
|
+
def _get_embeddings(self, input_text: str | List[str]):
|
26
|
+
"""
|
27
|
+
Abstract method to get embeddings from the model.
|
28
|
+
|
29
|
+
This method must be implemented by concrete subclasses to provide
|
30
|
+
the actual embedding functionality.
|
31
|
+
|
32
|
+
Args:
|
33
|
+
input_text: Single text string or list of text strings to embed
|
34
|
+
|
35
|
+
Returns:
|
36
|
+
Embedding vector(s) corresponding to the input text(s)
|
37
|
+
"""
|
38
|
+
raise NotImplementedError
|
39
|
+
|
40
|
+
def get_embeddings(self, input_text: str | List[str]):
|
41
|
+
"""
|
42
|
+
Get embeddings with retry logic and error handling.
|
43
|
+
|
44
|
+
This method wraps the _get_embeddings method with automatic retry
|
45
|
+
functionality in case of failures.
|
46
|
+
|
47
|
+
Args:
|
48
|
+
input_text: Single text string or list of text strings to embed
|
49
|
+
|
50
|
+
Returns:
|
51
|
+
Embedding vector(s) or None if all retries failed and raise_exception is False
|
52
|
+
"""
|
53
|
+
# Retry loop with exponential backoff potential
|
54
|
+
for i in range(self.max_retries):
|
55
|
+
try:
|
56
|
+
return self._get_embeddings(input_text)
|
57
|
+
|
58
|
+
except Exception as e:
|
59
|
+
logger.exception(f"embedding model name={self.model_name} encounter error with e={e.args}")
|
60
|
+
# If this is the last retry and raise_exception is True, re-raise the exception
|
61
|
+
if i == self.max_retries - 1 and self.raise_exception:
|
62
|
+
raise e
|
63
|
+
|
64
|
+
# Return None if all retries failed and raise_exception is False
|
65
|
+
return None
|
66
|
+
|
67
|
+
def get_node_embeddings(self, nodes: VectorNode | List[VectorNode]):
|
68
|
+
"""
|
69
|
+
Generate embeddings for VectorNode objects and update their vector fields.
|
70
|
+
|
71
|
+
This method handles both single nodes and lists of nodes, with automatic
|
72
|
+
batching for efficient processing of large node lists.
|
73
|
+
|
74
|
+
Args:
|
75
|
+
nodes: Single VectorNode or list of VectorNode objects to embed
|
76
|
+
|
77
|
+
Returns:
|
78
|
+
The same node(s) with updated vector fields containing embeddings
|
79
|
+
|
80
|
+
Raises:
|
81
|
+
RuntimeError: If unsupported node type is provided
|
82
|
+
"""
|
83
|
+
# Handle single VectorNode
|
84
|
+
if isinstance(nodes, VectorNode):
|
85
|
+
nodes.vector = self.get_embeddings(nodes.content)
|
86
|
+
return nodes
|
87
|
+
|
88
|
+
# Handle list of VectorNodes with batch processing
|
89
|
+
elif isinstance(nodes, list):
|
90
|
+
# Process nodes in batches to respect max_batch_size limits
|
91
|
+
embeddings = [emb for i in range(0, len(nodes), self.max_batch_size) for emb in
|
92
|
+
self.get_embeddings(input_text=[node.content for node in nodes[i:i + self.max_batch_size]])]
|
93
|
+
|
94
|
+
# Validate that we got the expected number of embeddings
|
95
|
+
if len(embeddings) != len(nodes):
|
96
|
+
logger.warning(f"embeddings.size={len(embeddings)} <> nodes.size={len(nodes)}")
|
97
|
+
else:
|
98
|
+
# Assign embeddings to corresponding nodes
|
99
|
+
for node, embedding in zip(nodes, embeddings):
|
100
|
+
node.vector = embedding
|
101
|
+
return nodes
|
102
|
+
|
103
|
+
else:
|
104
|
+
raise RuntimeError(f"unsupported type={type(nodes)}")
|
@@ -0,0 +1,95 @@
|
|
1
|
+
import os
|
2
|
+
from typing import Literal, List
|
3
|
+
|
4
|
+
from dotenv import load_dotenv
|
5
|
+
from openai import OpenAI
|
6
|
+
from pydantic import Field, PrivateAttr, model_validator
|
7
|
+
|
8
|
+
from llmflow.embedding_model import EMBEDDING_MODEL_REGISTRY
|
9
|
+
from llmflow.embedding_model.base_embedding_model import BaseEmbeddingModel
|
10
|
+
|
11
|
+
|
12
|
+
@EMBEDDING_MODEL_REGISTRY.register("openai_compatible")
|
13
|
+
class OpenAICompatibleEmbeddingModel(BaseEmbeddingModel):
|
14
|
+
"""
|
15
|
+
OpenAI-compatible embedding model implementation.
|
16
|
+
|
17
|
+
This class provides an implementation of BaseEmbeddingModel that works with
|
18
|
+
OpenAI-compatible embedding APIs, including OpenAI's official API and
|
19
|
+
other services that follow the same interface.
|
20
|
+
"""
|
21
|
+
# API configuration fields
|
22
|
+
api_key: str = Field(default_factory=lambda: os.getenv("EMBEDDING_API_KEY"),
|
23
|
+
description="API key for authentication")
|
24
|
+
base_url: str = Field(default_factory=lambda: os.getenv("EMBEDDING_BASE_URL"),
|
25
|
+
description="Base URL for the API endpoint")
|
26
|
+
model_name: str = Field(default="", description="Name of the embedding model to use")
|
27
|
+
dimensions: int = Field(default=1024, description="Dimensionality of the embedding vectors")
|
28
|
+
encoding_format: Literal["float", "base64"] = Field(default="float", description="Encoding format for embeddings")
|
29
|
+
|
30
|
+
# Private OpenAI client instance
|
31
|
+
_client: OpenAI = PrivateAttr()
|
32
|
+
|
33
|
+
@model_validator(mode="after")
|
34
|
+
def init_client(self):
|
35
|
+
"""
|
36
|
+
Initialize the OpenAI client after model validation.
|
37
|
+
|
38
|
+
This method is called automatically after Pydantic model validation
|
39
|
+
to set up the OpenAI client with the provided API key and base URL.
|
40
|
+
|
41
|
+
Returns:
|
42
|
+
self: The model instance for method chaining
|
43
|
+
"""
|
44
|
+
self._client = OpenAI(api_key=self.api_key, base_url=self.base_url)
|
45
|
+
return self
|
46
|
+
|
47
|
+
def _get_embeddings(self, input_text: str | List[str]):
|
48
|
+
"""
|
49
|
+
Get embeddings from the OpenAI-compatible API.
|
50
|
+
|
51
|
+
This method implements the abstract _get_embeddings method from BaseEmbeddingModel
|
52
|
+
by calling the OpenAI-compatible embeddings API.
|
53
|
+
|
54
|
+
Args:
|
55
|
+
input_text: Single text string or list of text strings to embed
|
56
|
+
|
57
|
+
Returns:
|
58
|
+
Embedding vector(s) corresponding to the input text(s)
|
59
|
+
|
60
|
+
Raises:
|
61
|
+
RuntimeError: If unsupported input type is provided
|
62
|
+
"""
|
63
|
+
completion = self._client.embeddings.create(
|
64
|
+
model=self.model_name,
|
65
|
+
input=input_text,
|
66
|
+
dimensions=self.dimensions,
|
67
|
+
encoding_format=self.encoding_format
|
68
|
+
)
|
69
|
+
|
70
|
+
if isinstance(input_text, str):
|
71
|
+
return completion.data[0].embedding
|
72
|
+
|
73
|
+
elif isinstance(input_text, list):
|
74
|
+
result_emb = [[] for _ in range(len(input_text))]
|
75
|
+
for emb in completion.data:
|
76
|
+
result_emb[emb.index] = emb.embedding
|
77
|
+
return result_emb
|
78
|
+
|
79
|
+
else:
|
80
|
+
raise RuntimeError(f"unsupported type={type(input_text)}")
|
81
|
+
|
82
|
+
|
83
|
+
def main():
|
84
|
+
load_dotenv()
|
85
|
+
model = OpenAICompatibleEmbeddingModel(dimensions=64, model_name="text-embedding-v4")
|
86
|
+
res1 = model.get_embeddings(
|
87
|
+
"The clothes are of good quality and look good, definitely worth the wait. I love them.")
|
88
|
+
res2 = model.get_embeddings(["aa", "bb"])
|
89
|
+
print(res1)
|
90
|
+
print(res2)
|
91
|
+
|
92
|
+
|
93
|
+
if __name__ == "__main__":
|
94
|
+
main()
|
95
|
+
# launch with: python -m llmflow.model.openai_compatible_embedding_model
|
File without changes
|