mseep-txtai 9.1.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (251) hide show
  1. mseep_txtai-9.1.1.dist-info/METADATA +262 -0
  2. mseep_txtai-9.1.1.dist-info/RECORD +251 -0
  3. mseep_txtai-9.1.1.dist-info/WHEEL +5 -0
  4. mseep_txtai-9.1.1.dist-info/licenses/LICENSE +190 -0
  5. mseep_txtai-9.1.1.dist-info/top_level.txt +1 -0
  6. txtai/__init__.py +16 -0
  7. txtai/agent/__init__.py +12 -0
  8. txtai/agent/base.py +54 -0
  9. txtai/agent/factory.py +39 -0
  10. txtai/agent/model.py +107 -0
  11. txtai/agent/placeholder.py +16 -0
  12. txtai/agent/tool/__init__.py +7 -0
  13. txtai/agent/tool/embeddings.py +69 -0
  14. txtai/agent/tool/factory.py +130 -0
  15. txtai/agent/tool/function.py +49 -0
  16. txtai/ann/__init__.py +7 -0
  17. txtai/ann/base.py +153 -0
  18. txtai/ann/dense/__init__.py +11 -0
  19. txtai/ann/dense/annoy.py +72 -0
  20. txtai/ann/dense/factory.py +76 -0
  21. txtai/ann/dense/faiss.py +233 -0
  22. txtai/ann/dense/hnsw.py +104 -0
  23. txtai/ann/dense/numpy.py +164 -0
  24. txtai/ann/dense/pgvector.py +323 -0
  25. txtai/ann/dense/sqlite.py +303 -0
  26. txtai/ann/dense/torch.py +38 -0
  27. txtai/ann/sparse/__init__.py +7 -0
  28. txtai/ann/sparse/factory.py +61 -0
  29. txtai/ann/sparse/ivfsparse.py +377 -0
  30. txtai/ann/sparse/pgsparse.py +56 -0
  31. txtai/api/__init__.py +18 -0
  32. txtai/api/application.py +134 -0
  33. txtai/api/authorization.py +53 -0
  34. txtai/api/base.py +159 -0
  35. txtai/api/cluster.py +295 -0
  36. txtai/api/extension.py +19 -0
  37. txtai/api/factory.py +40 -0
  38. txtai/api/responses/__init__.py +7 -0
  39. txtai/api/responses/factory.py +30 -0
  40. txtai/api/responses/json.py +56 -0
  41. txtai/api/responses/messagepack.py +51 -0
  42. txtai/api/route.py +41 -0
  43. txtai/api/routers/__init__.py +25 -0
  44. txtai/api/routers/agent.py +38 -0
  45. txtai/api/routers/caption.py +42 -0
  46. txtai/api/routers/embeddings.py +280 -0
  47. txtai/api/routers/entity.py +42 -0
  48. txtai/api/routers/extractor.py +28 -0
  49. txtai/api/routers/labels.py +47 -0
  50. txtai/api/routers/llm.py +61 -0
  51. txtai/api/routers/objects.py +42 -0
  52. txtai/api/routers/openai.py +191 -0
  53. txtai/api/routers/rag.py +61 -0
  54. txtai/api/routers/reranker.py +46 -0
  55. txtai/api/routers/segmentation.py +42 -0
  56. txtai/api/routers/similarity.py +48 -0
  57. txtai/api/routers/summary.py +46 -0
  58. txtai/api/routers/tabular.py +42 -0
  59. txtai/api/routers/textractor.py +42 -0
  60. txtai/api/routers/texttospeech.py +33 -0
  61. txtai/api/routers/transcription.py +42 -0
  62. txtai/api/routers/translation.py +46 -0
  63. txtai/api/routers/upload.py +36 -0
  64. txtai/api/routers/workflow.py +28 -0
  65. txtai/app/__init__.py +5 -0
  66. txtai/app/base.py +821 -0
  67. txtai/archive/__init__.py +9 -0
  68. txtai/archive/base.py +104 -0
  69. txtai/archive/compress.py +51 -0
  70. txtai/archive/factory.py +25 -0
  71. txtai/archive/tar.py +49 -0
  72. txtai/archive/zip.py +35 -0
  73. txtai/cloud/__init__.py +8 -0
  74. txtai/cloud/base.py +106 -0
  75. txtai/cloud/factory.py +70 -0
  76. txtai/cloud/hub.py +101 -0
  77. txtai/cloud/storage.py +125 -0
  78. txtai/console/__init__.py +5 -0
  79. txtai/console/__main__.py +22 -0
  80. txtai/console/base.py +264 -0
  81. txtai/data/__init__.py +10 -0
  82. txtai/data/base.py +138 -0
  83. txtai/data/labels.py +42 -0
  84. txtai/data/questions.py +135 -0
  85. txtai/data/sequences.py +48 -0
  86. txtai/data/texts.py +68 -0
  87. txtai/data/tokens.py +28 -0
  88. txtai/database/__init__.py +14 -0
  89. txtai/database/base.py +342 -0
  90. txtai/database/client.py +227 -0
  91. txtai/database/duckdb.py +150 -0
  92. txtai/database/embedded.py +76 -0
  93. txtai/database/encoder/__init__.py +8 -0
  94. txtai/database/encoder/base.py +37 -0
  95. txtai/database/encoder/factory.py +56 -0
  96. txtai/database/encoder/image.py +43 -0
  97. txtai/database/encoder/serialize.py +28 -0
  98. txtai/database/factory.py +77 -0
  99. txtai/database/rdbms.py +569 -0
  100. txtai/database/schema/__init__.py +6 -0
  101. txtai/database/schema/orm.py +99 -0
  102. txtai/database/schema/statement.py +98 -0
  103. txtai/database/sql/__init__.py +8 -0
  104. txtai/database/sql/aggregate.py +178 -0
  105. txtai/database/sql/base.py +189 -0
  106. txtai/database/sql/expression.py +404 -0
  107. txtai/database/sql/token.py +342 -0
  108. txtai/database/sqlite.py +57 -0
  109. txtai/embeddings/__init__.py +7 -0
  110. txtai/embeddings/base.py +1107 -0
  111. txtai/embeddings/index/__init__.py +14 -0
  112. txtai/embeddings/index/action.py +15 -0
  113. txtai/embeddings/index/autoid.py +92 -0
  114. txtai/embeddings/index/configuration.py +71 -0
  115. txtai/embeddings/index/documents.py +86 -0
  116. txtai/embeddings/index/functions.py +155 -0
  117. txtai/embeddings/index/indexes.py +199 -0
  118. txtai/embeddings/index/indexids.py +60 -0
  119. txtai/embeddings/index/reducer.py +104 -0
  120. txtai/embeddings/index/stream.py +67 -0
  121. txtai/embeddings/index/transform.py +205 -0
  122. txtai/embeddings/search/__init__.py +11 -0
  123. txtai/embeddings/search/base.py +344 -0
  124. txtai/embeddings/search/errors.py +9 -0
  125. txtai/embeddings/search/explain.py +120 -0
  126. txtai/embeddings/search/ids.py +61 -0
  127. txtai/embeddings/search/query.py +69 -0
  128. txtai/embeddings/search/scan.py +196 -0
  129. txtai/embeddings/search/terms.py +46 -0
  130. txtai/graph/__init__.py +10 -0
  131. txtai/graph/base.py +769 -0
  132. txtai/graph/factory.py +61 -0
  133. txtai/graph/networkx.py +275 -0
  134. txtai/graph/query.py +181 -0
  135. txtai/graph/rdbms.py +113 -0
  136. txtai/graph/topics.py +166 -0
  137. txtai/models/__init__.py +9 -0
  138. txtai/models/models.py +268 -0
  139. txtai/models/onnx.py +133 -0
  140. txtai/models/pooling/__init__.py +9 -0
  141. txtai/models/pooling/base.py +141 -0
  142. txtai/models/pooling/cls.py +28 -0
  143. txtai/models/pooling/factory.py +144 -0
  144. txtai/models/pooling/late.py +173 -0
  145. txtai/models/pooling/mean.py +33 -0
  146. txtai/models/pooling/muvera.py +164 -0
  147. txtai/models/registry.py +37 -0
  148. txtai/models/tokendetection.py +122 -0
  149. txtai/pipeline/__init__.py +17 -0
  150. txtai/pipeline/audio/__init__.py +11 -0
  151. txtai/pipeline/audio/audiomixer.py +58 -0
  152. txtai/pipeline/audio/audiostream.py +94 -0
  153. txtai/pipeline/audio/microphone.py +244 -0
  154. txtai/pipeline/audio/signal.py +186 -0
  155. txtai/pipeline/audio/texttoaudio.py +60 -0
  156. txtai/pipeline/audio/texttospeech.py +553 -0
  157. txtai/pipeline/audio/transcription.py +212 -0
  158. txtai/pipeline/base.py +23 -0
  159. txtai/pipeline/data/__init__.py +10 -0
  160. txtai/pipeline/data/filetohtml.py +206 -0
  161. txtai/pipeline/data/htmltomd.py +414 -0
  162. txtai/pipeline/data/segmentation.py +178 -0
  163. txtai/pipeline/data/tabular.py +155 -0
  164. txtai/pipeline/data/textractor.py +139 -0
  165. txtai/pipeline/data/tokenizer.py +112 -0
  166. txtai/pipeline/factory.py +77 -0
  167. txtai/pipeline/hfmodel.py +111 -0
  168. txtai/pipeline/hfpipeline.py +96 -0
  169. txtai/pipeline/image/__init__.py +7 -0
  170. txtai/pipeline/image/caption.py +55 -0
  171. txtai/pipeline/image/imagehash.py +90 -0
  172. txtai/pipeline/image/objects.py +80 -0
  173. txtai/pipeline/llm/__init__.py +11 -0
  174. txtai/pipeline/llm/factory.py +86 -0
  175. txtai/pipeline/llm/generation.py +173 -0
  176. txtai/pipeline/llm/huggingface.py +218 -0
  177. txtai/pipeline/llm/litellm.py +90 -0
  178. txtai/pipeline/llm/llama.py +152 -0
  179. txtai/pipeline/llm/llm.py +75 -0
  180. txtai/pipeline/llm/rag.py +477 -0
  181. txtai/pipeline/nop.py +14 -0
  182. txtai/pipeline/tensors.py +52 -0
  183. txtai/pipeline/text/__init__.py +13 -0
  184. txtai/pipeline/text/crossencoder.py +70 -0
  185. txtai/pipeline/text/entity.py +140 -0
  186. txtai/pipeline/text/labels.py +137 -0
  187. txtai/pipeline/text/lateencoder.py +103 -0
  188. txtai/pipeline/text/questions.py +48 -0
  189. txtai/pipeline/text/reranker.py +57 -0
  190. txtai/pipeline/text/similarity.py +83 -0
  191. txtai/pipeline/text/summary.py +98 -0
  192. txtai/pipeline/text/translation.py +298 -0
  193. txtai/pipeline/train/__init__.py +7 -0
  194. txtai/pipeline/train/hfonnx.py +196 -0
  195. txtai/pipeline/train/hftrainer.py +398 -0
  196. txtai/pipeline/train/mlonnx.py +63 -0
  197. txtai/scoring/__init__.py +12 -0
  198. txtai/scoring/base.py +188 -0
  199. txtai/scoring/bm25.py +29 -0
  200. txtai/scoring/factory.py +95 -0
  201. txtai/scoring/pgtext.py +181 -0
  202. txtai/scoring/sif.py +32 -0
  203. txtai/scoring/sparse.py +218 -0
  204. txtai/scoring/terms.py +499 -0
  205. txtai/scoring/tfidf.py +358 -0
  206. txtai/serialize/__init__.py +10 -0
  207. txtai/serialize/base.py +85 -0
  208. txtai/serialize/errors.py +9 -0
  209. txtai/serialize/factory.py +29 -0
  210. txtai/serialize/messagepack.py +42 -0
  211. txtai/serialize/pickle.py +98 -0
  212. txtai/serialize/serializer.py +46 -0
  213. txtai/util/__init__.py +7 -0
  214. txtai/util/resolver.py +32 -0
  215. txtai/util/sparsearray.py +62 -0
  216. txtai/util/template.py +16 -0
  217. txtai/vectors/__init__.py +8 -0
  218. txtai/vectors/base.py +476 -0
  219. txtai/vectors/dense/__init__.py +12 -0
  220. txtai/vectors/dense/external.py +55 -0
  221. txtai/vectors/dense/factory.py +121 -0
  222. txtai/vectors/dense/huggingface.py +44 -0
  223. txtai/vectors/dense/litellm.py +86 -0
  224. txtai/vectors/dense/llama.py +84 -0
  225. txtai/vectors/dense/m2v.py +67 -0
  226. txtai/vectors/dense/sbert.py +92 -0
  227. txtai/vectors/dense/words.py +211 -0
  228. txtai/vectors/recovery.py +57 -0
  229. txtai/vectors/sparse/__init__.py +7 -0
  230. txtai/vectors/sparse/base.py +90 -0
  231. txtai/vectors/sparse/factory.py +55 -0
  232. txtai/vectors/sparse/sbert.py +34 -0
  233. txtai/version.py +6 -0
  234. txtai/workflow/__init__.py +8 -0
  235. txtai/workflow/base.py +184 -0
  236. txtai/workflow/execute.py +99 -0
  237. txtai/workflow/factory.py +42 -0
  238. txtai/workflow/task/__init__.py +18 -0
  239. txtai/workflow/task/base.py +490 -0
  240. txtai/workflow/task/console.py +24 -0
  241. txtai/workflow/task/export.py +64 -0
  242. txtai/workflow/task/factory.py +89 -0
  243. txtai/workflow/task/file.py +28 -0
  244. txtai/workflow/task/image.py +36 -0
  245. txtai/workflow/task/retrieve.py +61 -0
  246. txtai/workflow/task/service.py +102 -0
  247. txtai/workflow/task/storage.py +110 -0
  248. txtai/workflow/task/stream.py +33 -0
  249. txtai/workflow/task/template.py +116 -0
  250. txtai/workflow/task/url.py +20 -0
  251. txtai/workflow/task/workflow.py +14 -0
@@ -0,0 +1,190 @@
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
+ Copyright 2020- NeuML LLC
179
+
180
+ Licensed under the Apache License, Version 2.0 (the "License");
181
+ you may not use this file except in compliance with the License.
182
+ You may obtain a copy of the License at
183
+
184
+ http://www.apache.org/licenses/LICENSE-2.0
185
+
186
+ Unless required by applicable law or agreed to in writing, software
187
+ distributed under the License is distributed on an "AS IS" BASIS,
188
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
189
+ See the License for the specific language governing permissions and
190
+ limitations under the License.
@@ -0,0 +1 @@
1
+ txtai
txtai/__init__.py ADDED
@@ -0,0 +1,16 @@
1
+ """
2
+ Base imports
3
+ """
4
+
5
+ import logging
6
+
7
+ # Top-level imports
8
+ from .agent import Agent
9
+ from .app import Application
10
+ from .embeddings import Embeddings
11
+ from .pipeline import LLM, RAG
12
+ from .workflow import Workflow
13
+
14
+ # Configure logging per standard Python library recommendations
15
+ logger = logging.getLogger(__name__)
16
+ logger.addHandler(logging.NullHandler())
@@ -0,0 +1,12 @@
1
+ """
2
+ Agent imports
3
+ """
4
+
5
+ # Conditional import
6
+ try:
7
+ from .base import Agent
8
+ from .factory import ProcessFactory
9
+ from .model import PipelineModel
10
+ from .tool import *
11
+ except ImportError:
12
+ from .placeholder import Agent
txtai/agent/base.py ADDED
@@ -0,0 +1,54 @@
1
+ """
2
+ Agent module
3
+ """
4
+
5
+ from .factory import ProcessFactory
6
+
7
+
8
+ class Agent:
9
+ """
10
+ An agent automatically creates workflows to answer multi-faceted user requests. Agents iteratively prompt and/or interface with tools to
11
+ step through a process and ultimately come to an answer for a request.
12
+
13
+ Agents excel at complex tasks where multiple tools and/or methods are required. They incorporate a level of randomness similar to different
14
+ people working on the same task. When the request is simple and/or there is a rule-based process, other methods such as RAG and Workflows
15
+ should be explored.
16
+ """
17
+
18
+ def __init__(self, **kwargs):
19
+ """
20
+ Creates a new Agent.
21
+
22
+ Args:
23
+ kwargs: arguments to pass to the underlying Agent backend and LLM pipeline instance
24
+ """
25
+
26
+ # Ensure backwards compatibility
27
+ if "max_iterations" in kwargs:
28
+ kwargs["max_steps"] = kwargs.pop("max_iterations")
29
+
30
+ # Create agent process runner
31
+ self.process = ProcessFactory.create(kwargs)
32
+
33
+ # Tools dictionary
34
+ self.tools = self.process.tools
35
+
36
+ def __call__(self, text, maxlength=8192, stream=False, **kwargs):
37
+ """
38
+ Runs an agent loop.
39
+
40
+ Args:
41
+ text: instructions to run
42
+ maxlength: maximum sequence length
43
+ stream: stream response if True, defaults to False
44
+ kwargs: additional keyword arguments
45
+
46
+ Returns:
47
+ result
48
+ """
49
+
50
+ # Process parameters
51
+ self.process.model.parameters(maxlength)
52
+
53
+ # Run agent loop
54
+ return self.process.run(text, stream=stream, **kwargs)
txtai/agent/factory.py ADDED
@@ -0,0 +1,39 @@
1
+ """
2
+ Factory module
3
+ """
4
+
5
+ from smolagents import CodeAgent, ToolCallingAgent
6
+
7
+ from .model import PipelineModel
8
+ from .tool import ToolFactory
9
+
10
+
11
+ class ProcessFactory:
12
+ """
13
+ Methods to create agent processes.
14
+ """
15
+
16
+ @staticmethod
17
+ def create(config):
18
+ """
19
+ Create an agent process runner. The agent process runner takes a list of tools and an LLM
20
+ and executes an agent process flow.
21
+
22
+ Args:
23
+ config: agent configuration
24
+
25
+ Returns:
26
+ agent process runner
27
+ """
28
+
29
+ constructor = ToolCallingAgent
30
+ method = config.pop("method", None)
31
+ if method == "code":
32
+ constructor = CodeAgent
33
+
34
+ # Create model backed by LLM pipeline
35
+ model = config.pop("model", config.pop("llm", None))
36
+ model = PipelineModel(**model) if isinstance(model, dict) else PipelineModel(model)
37
+
38
+ # Create the agent process
39
+ return constructor(tools=ToolFactory.create(config), model=model, **config)
txtai/agent/model.py ADDED
@@ -0,0 +1,107 @@
1
+ """
2
+ Model module
3
+ """
4
+
5
+ import re
6
+
7
+ from enum import Enum
8
+
9
+ from smolagents import ChatMessage, Model, get_clean_message_list, tool_role_conversions
10
+ from smolagents.models import get_tool_call_from_text, remove_stop_sequences
11
+
12
+ from ..pipeline import LLM
13
+
14
+
15
+ class PipelineModel(Model):
16
+ """
17
+ Model backed by a LLM pipeline.
18
+ """
19
+
20
+ def __init__(self, path=None, method=None, **kwargs):
21
+ """
22
+ Creates a new LLM model.
23
+
24
+ Args:
25
+ path: model path or instance
26
+ method: llm model framework, infers from path if not provided
27
+ kwargs: model keyword arguments
28
+ """
29
+
30
+ self.llm = path if isinstance(path, LLM) else LLM(path, method, **kwargs)
31
+ self.maxlength = 8192
32
+
33
+ # Set base class parameters
34
+ self.model_id = self.llm.generator.path
35
+
36
+ # Call parent constructor
37
+ super().__init__(flatten_messages_as_text=not self.llm.isvision(), **kwargs)
38
+
39
+ # pylint: disable=W0613
40
+ def generate(self, messages, stop_sequences=None, response_format=None, tools_to_call_from=None, **kwargs):
41
+ """
42
+ Runs LLM inference. This method signature must match the smolagents specification.
43
+
44
+ Args:
45
+ messages: list of messages to run
46
+ stop_sequences: optional list of stop sequences
47
+ response_format: response format to use in the model's response.
48
+ tools_to_call_from: list of tools that the model can use to generate responses.
49
+ kwargs: additional keyword arguments
50
+
51
+ Returns:
52
+ result
53
+ """
54
+
55
+ # Get clean message list
56
+ messages = self.clean(messages)
57
+
58
+ # Get LLM output
59
+ response = self.llm(messages, maxlength=self.maxlength, stop=stop_sequences, **kwargs)
60
+
61
+ # Remove stop sequences from LLM output
62
+ if stop_sequences is not None:
63
+ response = remove_stop_sequences(response, stop_sequences)
64
+
65
+ # Load response into a chat message
66
+ message = ChatMessage(role="assistant", content=response)
67
+
68
+ # Extract first tool action, if necessary
69
+ if tools_to_call_from:
70
+ message.tool_calls = [
71
+ get_tool_call_from_text(
72
+ re.sub(r".*?Action:(.*?\n\}).*", r"\1", response, flags=re.DOTALL), self.tool_name_key, self.tool_arguments_key
73
+ )
74
+ ]
75
+
76
+ return message
77
+
78
+ def parameters(self, maxlength):
79
+ """
80
+ Set LLM inference parameters.
81
+
82
+ Args:
83
+ maxlength: maximum sequence length
84
+ """
85
+
86
+ self.maxlength = maxlength
87
+
88
+ def clean(self, messages):
89
+ """
90
+ Gets a clean message list.
91
+
92
+ Args:
93
+ messages: input messages
94
+
95
+ Returns:
96
+ clean messages
97
+ """
98
+
99
+ # Get clean message list
100
+ messages = get_clean_message_list(messages, role_conversions=tool_role_conversions, flatten_messages_as_text=self.flatten_messages_as_text)
101
+
102
+ # Ensure all roles are strings and not enums for compability across LLM frameworks
103
+ for message in messages:
104
+ if "role" in message:
105
+ message["role"] = message["role"].value if isinstance(message["role"], Enum) else message["role"]
106
+
107
+ return messages
@@ -0,0 +1,16 @@
1
+ """
2
+ Placeholder module
3
+ """
4
+
5
+
6
+ class Agent:
7
+ """
8
+ Agent placeholder stub for when smolagents isn't installed
9
+ """
10
+
11
+ def __init__(self, *args, **kwargs):
12
+ """
13
+ Raises an exception that smolagents isn't installed.
14
+ """
15
+
16
+ raise ImportError('smolagents is not available - install "agent" extra to enable')
@@ -0,0 +1,7 @@
1
+ """
2
+ Tool imports
3
+ """
4
+
5
+ from .embeddings import EmbeddingsTool
6
+ from .factory import ToolFactory
7
+ from .function import FunctionTool
@@ -0,0 +1,69 @@
1
+ """
2
+ Embeddings module
3
+ """
4
+
5
+ from smolagents import Tool
6
+
7
+ from ...embeddings import Embeddings
8
+
9
+
10
+ class EmbeddingsTool(Tool):
11
+ """
12
+ Tool to execute an Embeddings search.
13
+ """
14
+
15
+ def __init__(self, config):
16
+ """
17
+ Creates a new EmbeddingsTool.
18
+
19
+ Args:
20
+ config: embeddings tool configuration
21
+ """
22
+
23
+ # Tool parameters
24
+ self.name = config["name"]
25
+ self.description = f"""{config['description']}. Results are returned as a list of dict elements.
26
+ Each result has keys 'id', 'text', 'score'."""
27
+
28
+ # Input and output descriptions
29
+ self.inputs = {"query": {"type": "string", "description": "The search query to perform."}}
30
+ self.output_type = "any"
31
+
32
+ # Load embeddings instance
33
+ self.embeddings = self.load(config)
34
+
35
+ # Validate parameters and initialize tool
36
+ super().__init__()
37
+
38
+ # pylint: disable=W0221
39
+ def forward(self, query):
40
+ """
41
+ Runs a search.
42
+
43
+ Args:
44
+ query: input query
45
+
46
+ Returns:
47
+ search results
48
+ """
49
+
50
+ return self.embeddings.search(query, 5)
51
+
52
+ def load(self, config):
53
+ """
54
+ Loads an embeddings instance from config.
55
+
56
+ Args:
57
+ config: embeddings tool configuration
58
+
59
+ Returns:
60
+ Embeddings
61
+ """
62
+
63
+ if "target" in config:
64
+ return config["target"]
65
+
66
+ embeddings = Embeddings()
67
+ embeddings.load(**config)
68
+
69
+ return embeddings
@@ -0,0 +1,130 @@
1
+ """
2
+ Factory module
3
+ """
4
+
5
+ import inspect
6
+
7
+ from types import FunctionType, MethodType
8
+
9
+ import mcpadapt.core
10
+
11
+ from mcpadapt.smolagents_adapter import SmolAgentsAdapter
12
+ from smolagents import PythonInterpreterTool, Tool, tool as CreateTool, VisitWebpageTool, WebSearchTool
13
+ from transformers.utils import chat_template_utils, TypeHintParsingException
14
+
15
+ from ...embeddings import Embeddings
16
+ from .embeddings import EmbeddingsTool
17
+ from .function import FunctionTool
18
+
19
+
20
+ class ToolFactory:
21
+ """
22
+ Methods to create tools.
23
+ """
24
+
25
+ # Default toolkit
26
+ DEFAULTS = {"python": PythonInterpreterTool(), "websearch": WebSearchTool(), "webview": VisitWebpageTool()}
27
+
28
+ @staticmethod
29
+ def create(config):
30
+ """
31
+ Creates a new list of tools. This method iterates of the `tools` configuration option and creates a Tool instance
32
+ for each entry. This supports the following:
33
+
34
+ - Tool instance
35
+ - Dictionary with `name`, `description`, `inputs`, `output` and `target` function configuration
36
+ - String with a tool alias name
37
+
38
+ Returns:
39
+ list of tools
40
+ """
41
+
42
+ tools = []
43
+ for tool in config.pop("tools", []):
44
+ # Create tool from function and it's documentation
45
+ if not isinstance(tool, Tool) and (isinstance(tool, (FunctionType, MethodType)) or hasattr(tool, "__call__")):
46
+ tool = ToolFactory.createtool(tool)
47
+
48
+ # Create tool from input dictionary
49
+ elif isinstance(tool, dict):
50
+ # Get target function
51
+ target = tool.get("target")
52
+
53
+ # Create tool from input dictionary
54
+ tool = (
55
+ EmbeddingsTool(tool)
56
+ if isinstance(target, Embeddings) or any(x in tool for x in ["container", "path"])
57
+ else ToolFactory.createtool(target, tool)
58
+ )
59
+
60
+ # Get default tool, if applicable
61
+ elif isinstance(tool, str) and tool in ToolFactory.DEFAULTS:
62
+ tool = ToolFactory.DEFAULTS[tool]
63
+
64
+ # Support importing MCP tool collections
65
+ elif isinstance(tool, str) and tool.startswith("http"):
66
+ tools.extend(mcpadapt.core.MCPAdapt({"url": tool}, SmolAgentsAdapter()).tools())
67
+ tool = None
68
+
69
+ # Add tool
70
+ if tool:
71
+ tools.append(tool)
72
+
73
+ return tools
74
+
75
+ @staticmethod
76
+ def createtool(target, config=None):
77
+ """
78
+ Creates a new Tool.
79
+
80
+ Args:
81
+ target: target object or function
82
+ config: optional tool configuration
83
+
84
+ Returns:
85
+ Tool
86
+ """
87
+
88
+ try:
89
+ # Try to create using CreateTool function - this fails when no annotations are available
90
+ return CreateTool(target)
91
+ except (TypeHintParsingException, TypeError):
92
+ return ToolFactory.fromdocs(target, config if config else {})
93
+
94
+ @staticmethod
95
+ def fromdocs(target, config):
96
+ """
97
+ Creates a tool from method documentation.
98
+
99
+ Args:
100
+ target: target object or function
101
+ config: tool configuration
102
+
103
+ Returns:
104
+ Tool
105
+ """
106
+
107
+ # Get function name and target - use target if it's a function or method, else use target.__call__
108
+ name = target.__name__ if isinstance(target, (FunctionType, MethodType)) or not hasattr(target, "__call__") else target.__class__.__name__
109
+ target = target if isinstance(target, (FunctionType, MethodType)) or not hasattr(target, "__call__") else target.__call__
110
+
111
+ # Extract target documentation
112
+ doc = inspect.getdoc(target)
113
+ description, parameters, _ = chat_template_utils.parse_google_format_docstring(doc.strip()) if doc else (None, {}, None)
114
+
115
+ # Get list of required parameters
116
+ signature = inspect.signature(target)
117
+ inputs = {}
118
+ for pname, param in signature.parameters.items():
119
+ if param.default == inspect.Parameter.empty and pname in parameters:
120
+ inputs[pname] = {"type": "any", "description": parameters[pname]}
121
+
122
+ # Create function tool
123
+ return FunctionTool(
124
+ {
125
+ "name": config.get("name", name.lower()),
126
+ "description": config.get("description", description),
127
+ "inputs": config.get("inputs", inputs),
128
+ "target": config.get("target", target),
129
+ }
130
+ )