mistral-haystack 0.0.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,136 @@
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ pip-wheel-metadata/
24
+ share/python-wheels/
25
+ *.egg-info/
26
+ .installed.cfg
27
+ *.egg
28
+ MANIFEST
29
+
30
+ # PyInstaller
31
+ # Usually these files are written by a python script from a template
32
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
33
+ *.manifest
34
+ *.spec
35
+
36
+ # Installer logs
37
+ pip-log.txt
38
+ pip-delete-this-directory.txt
39
+
40
+ # Unit test / coverage reports
41
+ htmlcov/
42
+ .tox/
43
+ .nox/
44
+ .coverage
45
+ .coverage.*
46
+ .cache
47
+ nosetests.xml
48
+ coverage.xml
49
+ *.cover
50
+ *.py,cover
51
+ .hypothesis/
52
+ .pytest_cache/
53
+ volumes/
54
+
55
+ # Translations
56
+ *.mo
57
+ *.pot
58
+
59
+ # Django stuff:
60
+ *.log
61
+ local_settings.py
62
+ db.sqlite3
63
+ db.sqlite3-journal
64
+
65
+ # Flask stuff:
66
+ instance/
67
+ .webassets-cache
68
+
69
+ # Scrapy stuff:
70
+ .scrapy
71
+
72
+ # Sphinx documentation
73
+ docs/_build/
74
+
75
+ # PyBuilder
76
+ target/
77
+
78
+ # Jupyter Notebook
79
+ .ipynb_checkpoints
80
+
81
+ # IPython
82
+ profile_default/
83
+ ipython_config.py
84
+
85
+ # pyenv
86
+ .python-version
87
+
88
+ # pipenv
89
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
90
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
91
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
92
+ # install all needed dependencies.
93
+ #Pipfile.lock
94
+
95
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow
96
+ __pypackages__/
97
+
98
+ # Celery stuff
99
+ celerybeat-schedule
100
+ celerybeat.pid
101
+
102
+ # SageMath parsed files
103
+ *.sage.py
104
+
105
+ # Environments
106
+ .env
107
+ .venv
108
+ env/
109
+ venv/
110
+ ENV/
111
+ env.bak/
112
+ venv.bak/
113
+
114
+ # Spyder project settings
115
+ .spyderproject
116
+ .spyproject
117
+
118
+ # Rope project settings
119
+ .ropeproject
120
+
121
+ # mkdocs documentation
122
+ /site
123
+
124
+ # mypy
125
+ .mypy_cache/
126
+ .dmypy.json
127
+ dmypy.json
128
+
129
+ # Pyre type checker
130
+ .pyre/
131
+
132
+ # IDEs
133
+ .vscode
134
+
135
+ # Docs generation artifacts
136
+ _readme_*.md
@@ -0,0 +1,73 @@
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, and distribution as defined by Sections 1 through 9 of this document.
10
+
11
+ "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
12
+
13
+ "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
14
+
15
+ "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
16
+
17
+ "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
18
+
19
+ "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
20
+
21
+ "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
22
+
23
+ "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
24
+
25
+ "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
26
+
27
+ "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
28
+
29
+ 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
30
+
31
+ 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
32
+
33
+ 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
34
+
35
+ (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
36
+
37
+ (b) You must cause any modified files to carry prominent notices stating that You changed the files; and
38
+
39
+ (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
40
+
41
+ (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
42
+
43
+ You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
44
+
45
+ 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
46
+
47
+ 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
48
+
49
+ 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
50
+
51
+ 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
52
+
53
+ 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
54
+
55
+ END OF TERMS AND CONDITIONS
56
+
57
+ APPENDIX: How to apply the Apache License to your work.
58
+
59
+ To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
60
+
61
+ Copyright [yyyy] [name of copyright owner]
62
+
63
+ Licensed under the Apache License, Version 2.0 (the "License");
64
+ you may not use this file except in compliance with the License.
65
+ You may obtain a copy of the License at
66
+
67
+ http://www.apache.org/licenses/LICENSE-2.0
68
+
69
+ Unless required by applicable law or agreed to in writing, software
70
+ distributed under the License is distributed on an "AS IS" BASIS,
71
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
72
+ See the License for the specific language governing permissions and
73
+ limitations under the License.
@@ -0,0 +1,42 @@
1
+ Metadata-Version: 2.1
2
+ Name: mistral-haystack
3
+ Version: 0.0.1
4
+ Project-URL: Documentation, https://github.com/deepset-ai/haystack-core-integrations/tree/main/integrations/mistral#readme
5
+ Project-URL: Issues, https://github.com/deepset-ai/haystack-core-integrations/issues
6
+ Project-URL: Source, https://github.com/deepset-ai/haystack-core-integrations/tree/main/integrations/mistral
7
+ Author-email: deepset GmbH <info@deepset.ai>
8
+ License-Expression: Apache-2.0
9
+ License-File: LICENSE.txt
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Programming Language :: Python
12
+ Classifier: Programming Language :: Python :: 3.8
13
+ Classifier: Programming Language :: Python :: 3.9
14
+ Classifier: Programming Language :: Python :: 3.10
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: Implementation :: CPython
17
+ Classifier: Programming Language :: Python :: Implementation :: PyPy
18
+ Requires-Python: >=3.8
19
+ Requires-Dist: haystack-ai>=2.0.0b6
20
+ Description-Content-Type: text/markdown
21
+
22
+ # mistral-haystack
23
+
24
+ [![PyPI - Version](https://img.shields.io/pypi/v/mistral-haystack.svg)](https://pypi.org/project/mistral-haystack)
25
+ [![PyPI - Python Version](https://img.shields.io/pypi/pyversions/mistral-haystack.svg)](https://pypi.org/project/mistral-haystack)
26
+
27
+ -----
28
+
29
+ **Table of Contents**
30
+
31
+ - [Installation](#installation)
32
+ - [License](#license)
33
+
34
+ ## Installation
35
+
36
+ ```console
37
+ pip install mistral-haystack
38
+ ```
39
+
40
+ ## License
41
+
42
+ `mistral-haystack` is distributed under the terms of the [Apache-2.0](https://spdx.org/licenses/Apache-2.0.html) license.
@@ -0,0 +1,21 @@
1
+ # mistral-haystack
2
+
3
+ [![PyPI - Version](https://img.shields.io/pypi/v/mistral-haystack.svg)](https://pypi.org/project/mistral-haystack)
4
+ [![PyPI - Python Version](https://img.shields.io/pypi/pyversions/mistral-haystack.svg)](https://pypi.org/project/mistral-haystack)
5
+
6
+ -----
7
+
8
+ **Table of Contents**
9
+
10
+ - [Installation](#installation)
11
+ - [License](#license)
12
+
13
+ ## Installation
14
+
15
+ ```console
16
+ pip install mistral-haystack
17
+ ```
18
+
19
+ ## License
20
+
21
+ `mistral-haystack` is distributed under the terms of the [Apache-2.0](https://spdx.org/licenses/Apache-2.0.html) license.
@@ -0,0 +1,32 @@
1
+ # To run this example, you will need an to set a `MISTRAL_API_KEY` environment variable.
2
+ # This example streams chat replies to the console.
3
+
4
+ from haystack import Pipeline
5
+ from haystack.components.converters import HTMLToDocument
6
+ from haystack.components.fetchers import LinkContentFetcher
7
+ from haystack.components.preprocessors import DocumentSplitter
8
+ from haystack.components.writers import DocumentWriter
9
+ from haystack.document_stores.in_memory import InMemoryDocumentStore
10
+ from haystack_integrations.components.embedders.mistral.document_embedder import MistralDocumentEmbedder
11
+
12
+ document_store = InMemoryDocumentStore()
13
+ fetcher = LinkContentFetcher()
14
+ converter = HTMLToDocument()
15
+ chunker = DocumentSplitter()
16
+ embedder = MistralDocumentEmbedder()
17
+ writer = DocumentWriter(document_store=document_store)
18
+
19
+ indexing = Pipeline()
20
+
21
+ indexing.add_component(name="fetcher", instance=fetcher)
22
+ indexing.add_component(name="converter", instance=converter)
23
+ indexing.add_component(name="chunker", instance=chunker)
24
+ indexing.add_component(name="embedder", instance=embedder)
25
+ indexing.add_component(name="writer", instance=writer)
26
+
27
+ indexing.connect("fetcher", "converter")
28
+ indexing.connect("converter", "chunker")
29
+ indexing.connect("chunker", "embedder")
30
+ indexing.connect("embedder", "writer")
31
+
32
+ indexing.run(data={"fetcher": {"urls": ["https://mistral.ai/news/la-plateforme/"]}})
@@ -0,0 +1,66 @@
1
+ # To run this example, you will need an to set a `MISTRAL_API_KEY` environment variable.
2
+ # This example streams chat replies to the console.
3
+
4
+ from haystack import Pipeline
5
+ from haystack.components.builders import DynamicChatPromptBuilder
6
+ from haystack.components.converters import HTMLToDocument
7
+ from haystack.components.fetchers import LinkContentFetcher
8
+ from haystack.components.generators.utils import print_streaming_chunk
9
+ from haystack.components.preprocessors import DocumentSplitter
10
+ from haystack.components.retrievers.in_memory import InMemoryEmbeddingRetriever
11
+ from haystack.components.writers import DocumentWriter
12
+ from haystack.dataclasses import ChatMessage
13
+ from haystack.document_stores.in_memory import InMemoryDocumentStore
14
+ from haystack_integrations.components.embedders.mistral.document_embedder import MistralDocumentEmbedder
15
+ from haystack_integrations.components.embedders.mistral.text_embedder import MistralTextEmbedder
16
+ from haystack_integrations.components.generators.mistral import MistralChatGenerator
17
+
18
+ document_store = InMemoryDocumentStore()
19
+ fetcher = LinkContentFetcher()
20
+ converter = HTMLToDocument()
21
+ chunker = DocumentSplitter()
22
+ embedder = MistralDocumentEmbedder()
23
+ writer = DocumentWriter(document_store=document_store)
24
+
25
+ indexing = Pipeline()
26
+
27
+ indexing.add_component(name="fetcher", instance=fetcher)
28
+ indexing.add_component(name="converter", instance=converter)
29
+ indexing.add_component(name="chunker", instance=chunker)
30
+ indexing.add_component(name="embedder", instance=embedder)
31
+ indexing.add_component(name="writer", instance=writer)
32
+
33
+ indexing.connect("fetcher", "converter")
34
+ indexing.connect("converter", "chunker")
35
+ indexing.connect("chunker", "embedder")
36
+ indexing.connect("embedder", "writer")
37
+
38
+ indexing.run(data={"fetcher": {"urls": ["https://mistral.ai/news/la-plateforme/"]}})
39
+
40
+ text_embedder = MistralTextEmbedder()
41
+ retriever = InMemoryEmbeddingRetriever(document_store=document_store)
42
+ prompt_builder = DynamicChatPromptBuilder(runtime_variables=["documents"])
43
+ llm = MistralChatGenerator(streaming_callback=print_streaming_chunk)
44
+
45
+ messages = [ChatMessage.from_user("Here are some the documents: {{documents}} \\n Answer: {{query}}")]
46
+
47
+ rag_pipeline = Pipeline()
48
+ rag_pipeline.add_component("text_embedder", text_embedder)
49
+ rag_pipeline.add_component("retriever", retriever)
50
+ rag_pipeline.add_component("prompt_builder", prompt_builder)
51
+ rag_pipeline.add_component("llm", llm)
52
+
53
+
54
+ rag_pipeline.connect("text_embedder.embedding", "retriever.query_embedding")
55
+ rag_pipeline.connect("retriever.documents", "prompt_builder.documents")
56
+ rag_pipeline.connect("prompt_builder.prompt", "llm.messages")
57
+
58
+ question = "What are the available models?"
59
+
60
+ result = rag_pipeline.run(
61
+ {
62
+ "text_embedder": {"text": question},
63
+ "prompt_builder": {"template_variables": {"query": question}, "prompt_source": messages},
64
+ "llm": {"generation_kwargs": {"max_tokens": 165}},
65
+ }
66
+ )
@@ -0,0 +1,30 @@
1
+ loaders:
2
+ - type: haystack_pydoc_tools.loaders.CustomPythonLoader
3
+ search_path: [../src]
4
+ modules: [
5
+ "haystack_integrations.components.embedders.mistral.document_embedder",
6
+ "haystack_integrations.components.embedders.mistral.text_embedder",
7
+ "haystack_integrations.components.generators.mistral.chat.chat_generator",
8
+ ]
9
+ ignore_when_discovered: ["__init__"]
10
+ processors:
11
+ - type: filter
12
+ expression:
13
+ documented_only: true
14
+ do_not_filter_modules: false
15
+ skip_empty_modules: true
16
+ - type: smart
17
+ - type: crossref
18
+ renderer:
19
+ type: haystack_pydoc_tools.renderers.ReadmePreviewRenderer
20
+ excerpt: Mistral integration for Haystack
21
+ category_slug: haystack-integrations
22
+ title: Mistral
23
+ slug: integrations-mistral
24
+ order: 40
25
+ markdown:
26
+ descriptive_class_title: false
27
+ descriptive_module_title: true
28
+ add_method_class_prefix: true
29
+ add_member_class_prefix: false
30
+ filename: _readme_mistral.md
@@ -0,0 +1,163 @@
1
+ [build-system]
2
+ requires = ["hatchling", "hatch-vcs"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "mistral-haystack"
7
+ dynamic = ["version"]
8
+ description = ''
9
+ readme = "README.md"
10
+ requires-python = ">=3.8"
11
+ license = "Apache-2.0"
12
+ keywords = []
13
+ authors = [{ name = "deepset GmbH", email = "info@deepset.ai" }]
14
+ classifiers = [
15
+ "Development Status :: 4 - Beta",
16
+ "Programming Language :: Python",
17
+ "Programming Language :: Python :: 3.8",
18
+ "Programming Language :: Python :: 3.9",
19
+ "Programming Language :: Python :: 3.10",
20
+ "Programming Language :: Python :: 3.11",
21
+ "Programming Language :: Python :: Implementation :: CPython",
22
+ "Programming Language :: Python :: Implementation :: PyPy",
23
+ ]
24
+ dependencies = ["haystack-ai>=2.0.0b6"]
25
+
26
+ [project.urls]
27
+ Documentation = "https://github.com/deepset-ai/haystack-core-integrations/tree/main/integrations/mistral#readme"
28
+ Issues = "https://github.com/deepset-ai/haystack-core-integrations/issues"
29
+ Source = "https://github.com/deepset-ai/haystack-core-integrations/tree/main/integrations/mistral"
30
+
31
+ [tool.hatch.build.targets.wheel]
32
+ packages = ["src/haystack_integrations"]
33
+
34
+ [tool.hatch.version]
35
+ source = "vcs"
36
+ tag-pattern = 'integrations\/mistral-v(?P<version>.*)'
37
+
38
+ [tool.hatch.version.raw-options]
39
+ root = "../.."
40
+ git_describe_command = 'git describe --tags --match="integrations/mistral-v[0-9]*"'
41
+
42
+ [tool.hatch.envs.default]
43
+ dependencies = ["coverage[toml]>=6.5", "pytest", "haystack-pydoc-tools"]
44
+ [tool.hatch.envs.default.scripts]
45
+ test = "pytest {args:tests}"
46
+ test-cov = "coverage run -m pytest {args:tests}"
47
+ cov-report = ["- coverage combine", "coverage report"]
48
+ cov = ["test-cov", "cov-report"]
49
+ docs = ["pydoc-markdown pydoc/config.yml"]
50
+
51
+ [[tool.hatch.envs.all.matrix]]
52
+ python = ["3.8", "3.9", "3.10", "3.11"]
53
+
54
+ [tool.hatch.envs.lint]
55
+ detached = true
56
+ dependencies = ["black>=23.1.0", "mypy>=1.0.0", "ruff>=0.0.243"]
57
+ [tool.hatch.envs.lint.scripts]
58
+ typing = "mypy --install-types --non-interactive --explicit-package-bases {args:src/ tests}"
59
+ style = ["ruff {args:.}", "black --check --diff {args:.}"]
60
+ fmt = ["black {args:.}", "ruff --fix {args:.}", "style"]
61
+ all = ["style", "typing"]
62
+
63
+ [tool.black]
64
+ target-version = ["py37"]
65
+ line-length = 120
66
+ skip-string-normalization = true
67
+
68
+ [tool.ruff]
69
+ target-version = "py37"
70
+ line-length = 120
71
+ select = [
72
+ "A",
73
+ "ARG",
74
+ "B",
75
+ "C",
76
+ "DTZ",
77
+ "E",
78
+ "EM",
79
+ "F",
80
+ "I",
81
+ "ICN",
82
+ "ISC",
83
+ "N",
84
+ "PLC",
85
+ "PLE",
86
+ "PLR",
87
+ "PLW",
88
+ "Q",
89
+ "RUF",
90
+ "S",
91
+ "T",
92
+ "TID",
93
+ "UP",
94
+ "W",
95
+ "YTT",
96
+ ]
97
+ ignore = [
98
+ # Allow non-abstract empty methods in abstract base classes
99
+ "B027",
100
+ # Ignore checks for possible passwords
101
+ "S105",
102
+ "S106",
103
+ "S107",
104
+ # Ignore complexity
105
+ "C901",
106
+ "PLR0911",
107
+ "PLR0912",
108
+ "PLR0913",
109
+ "PLR0915",
110
+ # Misc
111
+ "B008",
112
+ "S101",
113
+ ]
114
+ unfixable = [
115
+ # Don't touch unused imports
116
+ "F401",
117
+ ]
118
+
119
+ [tool.ruff.isort]
120
+ known-first-party = ["src"]
121
+
122
+ [tool.ruff.flake8-tidy-imports]
123
+ ban-relative-imports = "parents"
124
+
125
+ [tool.ruff.per-file-ignores]
126
+ # Tests can use magic values, assertions, and relative imports
127
+ "tests/**/*" = ["PLR2004", "S101", "TID252"]
128
+
129
+ [tool.coverage.run]
130
+ source_pkgs = ["src", "tests"]
131
+ branch = true
132
+ parallel = true
133
+
134
+ [tool.coverage.paths]
135
+ mistral_haystack = [
136
+ "src/haystack_integrations",
137
+ "*/mistral/src/haystack_integrations",
138
+ ]
139
+ tests = ["tests", "*/mistral/tests"]
140
+
141
+ [tool.coverage.report]
142
+ exclude_lines = ["no cov", "if __name__ == .__main__.:", "if TYPE_CHECKING:"]
143
+
144
+ [[tool.mypy.overrides]]
145
+ module = [
146
+ "mistral.*",
147
+ "haystack.*",
148
+ "haystack_integrations.*",
149
+ "openai.*",
150
+ "pytest.*",
151
+ "numpy.*",
152
+ ]
153
+ ignore_missing_imports = true
154
+
155
+ [tool.pytest.ini_options]
156
+ addopts = "--strict-markers"
157
+ markers = [
158
+ "integration: integration tests",
159
+ "unit: unit tests",
160
+ "embedders: embedders tests",
161
+ "chat_generators: chat_generators tests",
162
+ ]
163
+ log_cli = true
@@ -0,0 +1,7 @@
1
+ # SPDX-FileCopyrightText: 2023-present deepset GmbH <info@deepset.ai>
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+ from .document_embedder import MistralDocumentEmbedder
5
+ from .text_embedder import MistralTextEmbedder
6
+
7
+ __all__ = ["MistralDocumentEmbedder", "MistralTextEmbedder"]
@@ -0,0 +1,70 @@
1
+ # SPDX-FileCopyrightText: 2023-present deepset GmbH <info@deepset.ai>
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+ from typing import List, Optional
5
+
6
+ from haystack import component
7
+ from haystack.components.embedders import OpenAIDocumentEmbedder
8
+ from haystack.utils.auth import Secret
9
+
10
+
11
+ @component
12
+ class MistralDocumentEmbedder(OpenAIDocumentEmbedder):
13
+ """
14
+ A component for computing Document embeddings using Mistral models.
15
+ The embedding of each Document is stored in the `embedding` field of the Document.
16
+
17
+ Usage example:
18
+ ```python
19
+ from haystack import Document
20
+ from haystack_integrations.components.embedders.mistral import MistralDocumentEmbedder
21
+
22
+ doc = Document(content="I love pizza!")
23
+
24
+ document_embedder = MistralDocumentEmbedder()
25
+
26
+ result = document_embedder.run([doc])
27
+ print(result['documents'][0].embedding)
28
+
29
+ # [0.017020374536514282, -0.023255806416273117, ...]
30
+ ```
31
+ """
32
+
33
+ def __init__(
34
+ self,
35
+ api_key: Secret = Secret.from_env_var("MISTRAL_API_KEY"),
36
+ model: str = "mistral-embed",
37
+ api_base_url: Optional[str] = "https://api.mistral.ai/v1",
38
+ prefix: str = "",
39
+ suffix: str = "",
40
+ batch_size: int = 32,
41
+ progress_bar: bool = True,
42
+ meta_fields_to_embed: Optional[List[str]] = None,
43
+ embedding_separator: str = "\n",
44
+ ):
45
+ """
46
+ Create a MistralDocumentEmbedder component.
47
+ :param api_key: The Mistral API key.
48
+ :param model: The name of the model to use.
49
+ :param api_base_url: The Mistral API Base url, defaults to None. For more details, see Mistral [docs](https://docs.mistral.ai/api/).
50
+ :param prefix: A string to add to the beginning of each text.
51
+ :param suffix: A string to add to the end of each text.
52
+ :param batch_size: Number of Documents to encode at once.
53
+ :param progress_bar: Whether to show a progress bar or not. Can be helpful to disable in production deployments
54
+ to keep the logs clean.
55
+ :param meta_fields_to_embed: List of meta fields that should be embedded along with the Document text.
56
+ :param embedding_separator: Separator used to concatenate the meta fields to the Document text.
57
+ """
58
+ super(MistralDocumentEmbedder, self).__init__( # noqa: UP008
59
+ api_key=api_key,
60
+ model=model,
61
+ dimensions=None,
62
+ api_base_url=api_base_url,
63
+ organization=None,
64
+ prefix=prefix,
65
+ suffix=suffix,
66
+ batch_size=batch_size,
67
+ progress_bar=progress_bar,
68
+ meta_fields_to_embed=meta_fields_to_embed,
69
+ embedding_separator=embedding_separator,
70
+ )
@@ -0,0 +1,58 @@
1
+ # SPDX-FileCopyrightText: 2023-present deepset GmbH <info@deepset.ai>
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+ from typing import Optional
5
+
6
+ from haystack import component
7
+ from haystack.components.embedders import OpenAITextEmbedder
8
+ from haystack.utils.auth import Secret
9
+
10
+
11
+ @component
12
+ class MistralTextEmbedder(OpenAITextEmbedder):
13
+ """
14
+ A component for embedding strings using Mistral models.
15
+
16
+ Usage example:
17
+ ```python
18
+ from haystack_integrations.components.embedders.mistral.text_embedder import MistralTextEmbedder
19
+
20
+ text_to_embed = "I love pizza!"
21
+
22
+ text_embedder = MistralTextEmbedder()
23
+
24
+ print(text_embedder.run(text_to_embed))
25
+
26
+ # {'embedding': [0.017020374536514282, -0.023255806416273117, ...],
27
+ # 'meta': {'model': 'text-embedding-ada-002-v2',
28
+ # 'usage': {'prompt_tokens': 4, 'total_tokens': 4}}}
29
+ ```
30
+ """
31
+
32
+ def __init__(
33
+ self,
34
+ api_key: Secret = Secret.from_env_var("MISTRAL_API_KEY"),
35
+ model: str = "mistral-embed",
36
+ api_base_url: Optional[str] = "https://api.mistral.ai/v1",
37
+ prefix: str = "",
38
+ suffix: str = "",
39
+ ):
40
+ """
41
+ Create an MistralTextEmbedder component.
42
+
43
+ :param api_key: The Misttal API key.
44
+ :param model: The name of the Mistral embedding models to be used.
45
+ :param api_base_url: The Mistral API Base url, defaults to `https://api.mistral.ai/v1`.
46
+ For more details, see Mistral [docs](https://docs.mistral.ai/api/).
47
+ :param prefix: A string to add to the beginning of each text.
48
+ :param suffix: A string to add to the end of each text.
49
+ """
50
+ super(MistralTextEmbedder, self).__init__( # noqa: UP008
51
+ api_key=api_key,
52
+ model=model,
53
+ dimensions=None,
54
+ api_base_url=api_base_url,
55
+ organization=None,
56
+ prefix=prefix,
57
+ suffix=suffix,
58
+ )
@@ -0,0 +1,3 @@
1
+ from .chat.chat_generator import MistralChatGenerator
2
+
3
+ __all__ = ["MistralChatGenerator"]
@@ -0,0 +1,97 @@
1
+ # SPDX-FileCopyrightText: 2023-present deepset GmbH <info@deepset.ai>
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+ from typing import Any, Callable, Dict, Optional
5
+
6
+ from haystack import component
7
+ from haystack.components.generators.chat import OpenAIChatGenerator
8
+ from haystack.dataclasses import StreamingChunk
9
+ from haystack.utils.auth import Secret
10
+
11
+
12
+ @component
13
+ class MistralChatGenerator(OpenAIChatGenerator):
14
+ """
15
+ Enables text generation using Mistral's large language models (LLMs).
16
+ Currently supports `mistral-tiny`, `mistral-small` and `mistral-medium`
17
+ models accessed through the chat completions API endpoint.
18
+
19
+ Users can pass any text generation parameters valid for the `openai.ChatCompletion.create` method
20
+ directly to this component via the `**generation_kwargs` parameter in __init__ or the `**generation_kwargs`
21
+ parameter in `run` method.
22
+
23
+ For more details on the parameters supported by the Mistral API, refer to the
24
+ [Mistral API Docs](https://docs.mistral.ai/api/).
25
+
26
+ ```python
27
+ from haystack_integrations.components.generators.mistral import MistralChatGenerator
28
+ from haystack.dataclasses import ChatMessage
29
+
30
+ messages = [ChatMessage.from_user("What's Natural Language Processing?")]
31
+
32
+ client = MistralChatGenerator()
33
+ response = client.run(messages)
34
+ print(response)
35
+
36
+ >>{'replies': [ChatMessage(content='Natural Language Processing (NLP) is a branch of artificial intelligence
37
+ >>that focuses on enabling computers to understand, interpret, and generate human language in a way that is
38
+ >>meaningful and useful.', role=<ChatRole.ASSISTANT: 'assistant'>, name=None,
39
+ >>meta={'model': 'mistral-tiny', 'index': 0, 'finish_reason': 'stop',
40
+ >>'usage': {'prompt_tokens': 15, 'completion_tokens': 36, 'total_tokens': 51}})]}
41
+
42
+ ```
43
+
44
+ Key Features and Compatibility:
45
+ - **Primary Compatibility**: Designed to work seamlessly with the Mistral API Chat Completion endpoint.
46
+ - **Streaming Support**: Supports streaming responses from the Mistral API Chat Completion endpoint.
47
+ - **Customizability**: Supports all parameters supported by the Mistral API Chat Completion endpoint.
48
+
49
+ Input and Output Format:
50
+ - **ChatMessage Format**: This component uses the ChatMessage format for structuring both input and output,
51
+ ensuring coherent and contextually relevant responses in chat-based text generation scenarios.
52
+ Details on the ChatMessage format can be found at: https://github.com/openai/openai-python/blob/main/chatml.md.
53
+ Note that the Mistral API does not accept `system` messages yet. You can use `user` and `assistant` messages.
54
+ """
55
+
56
+ def __init__(
57
+ self,
58
+ api_key: Secret = Secret.from_env_var("MISTRAL_API_KEY"),
59
+ model: str = "mistral-tiny",
60
+ streaming_callback: Optional[Callable[[StreamingChunk], None]] = None,
61
+ api_base_url: Optional[str] = "https://api.mistral.ai/v1",
62
+ generation_kwargs: Optional[Dict[str, Any]] = None,
63
+ ):
64
+ """
65
+ Creates an instance of MistralChatGenerator. Unless specified otherwise in the `model`, this is for Mistral's
66
+ `mistral-tiny` model.
67
+
68
+ :param api_key: The Mistral API key.
69
+ :param model: The name of the Mistral chat completion model to use.
70
+ :param streaming_callback: A callback function that is called when a new token is received from the stream.
71
+ The callback function accepts StreamingChunk as an argument.
72
+ :param api_base_url: The Mistral API Base url, defaults to `https://api.mistral.ai/v1`.
73
+ For more details, see Mistral [docs](https://docs.mistral.ai/api/).
74
+ :param generation_kwargs: Other parameters to use for the model. These parameters are all sent directly to
75
+ the Mistrak endpoint. See [Mistral API docs](https://docs.mistral.ai/api/t) for
76
+ more details.
77
+ Some of the supported parameters:
78
+ - `max_tokens`: The maximum number of tokens the output text can have.
79
+ - `temperature`: What sampling temperature to use. Higher values mean the model will take more risks.
80
+ Try 0.9 for more creative applications and 0 (argmax sampling) for ones with a well-defined answer.
81
+ - `top_p`: An alternative to sampling with temperature, called nucleus sampling, where the model
82
+ considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens
83
+ comprising the top 10% probability mass are considered.
84
+ - `stream`: Whether to stream back partial progress. If set, tokens will be sent as data-only server-sent
85
+ events as they become available, with the stream terminated by a data: [DONE] message.
86
+ - `stop`: One or more sequences after which the LLM should stop generating tokens.
87
+ - `safe_prompt`: Whether to inject a safety prompt before all conversations.
88
+ - `random_seed`: The seed to use for random sampling.
89
+ """
90
+ super(MistralChatGenerator, self).__init__( # noqa: UP008
91
+ api_key=api_key,
92
+ model=model,
93
+ streaming_callback=streaming_callback,
94
+ api_base_url=api_base_url,
95
+ organization=None,
96
+ generation_kwargs=generation_kwargs,
97
+ )
@@ -0,0 +1,3 @@
1
+ # SPDX-FileCopyrightText: 2024-present deepset GmbH <info@deepset.ai>
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
@@ -0,0 +1,276 @@
1
+ import os
2
+ from datetime import datetime
3
+ from unittest.mock import patch
4
+
5
+ import pytest
6
+ import pytz
7
+ from haystack.components.generators.utils import print_streaming_chunk
8
+ from haystack.dataclasses import ChatMessage, StreamingChunk
9
+ from haystack.utils.auth import Secret
10
+ from haystack_integrations.components.generators.mistral.chat.chat_generator import MistralChatGenerator
11
+ from openai import OpenAIError
12
+ from openai.types.chat import ChatCompletion, ChatCompletionMessage
13
+ from openai.types.chat.chat_completion import Choice
14
+
15
+
16
+ @pytest.fixture
17
+ def chat_messages():
18
+ return [
19
+ ChatMessage.from_system("You are a helpful assistant"),
20
+ ChatMessage.from_user("What's the capital of France"),
21
+ ]
22
+
23
+
24
+ @pytest.fixture
25
+ def mock_chat_completion():
26
+ """
27
+ Mock the OpenAI API completion response and reuse it for tests
28
+ """
29
+ with patch("openai.resources.chat.completions.Completions.create") as mock_chat_completion_create:
30
+ completion = ChatCompletion(
31
+ id="foo",
32
+ model="mistral-tiny",
33
+ object="chat.completion",
34
+ choices=[
35
+ Choice(
36
+ finish_reason="stop",
37
+ logprobs=None,
38
+ index=0,
39
+ message=ChatCompletionMessage(content="Hello world!", role="assistant"),
40
+ )
41
+ ],
42
+ created=int(datetime.now(tz=pytz.timezone("UTC")).timestamp()),
43
+ usage={"prompt_tokens": 57, "completion_tokens": 40, "total_tokens": 97},
44
+ )
45
+
46
+ mock_chat_completion_create.return_value = completion
47
+ yield mock_chat_completion_create
48
+
49
+
50
+ class TestMistralChatGenerator:
51
+ def test_init_default(self, monkeypatch):
52
+ monkeypatch.setenv("MISTRAL_API_KEY", "test-api-key")
53
+ component = MistralChatGenerator()
54
+ assert component.client.api_key == "test-api-key"
55
+ assert component.model == "mistral-tiny"
56
+ assert component.api_base_url == "https://api.mistral.ai/v1"
57
+ assert component.streaming_callback is None
58
+ assert not component.generation_kwargs
59
+
60
+ def test_init_fail_wo_api_key(self, monkeypatch):
61
+ monkeypatch.delenv("MISTRAL_API_KEY", raising=False)
62
+ with pytest.raises(ValueError, match="None of the .* environment variables are set"):
63
+ MistralChatGenerator()
64
+
65
+ def test_init_with_parameters(self):
66
+ component = MistralChatGenerator(
67
+ api_key=Secret.from_token("test-api-key"),
68
+ model="mistral-small",
69
+ streaming_callback=print_streaming_chunk,
70
+ api_base_url="test-base-url",
71
+ generation_kwargs={"max_tokens": 10, "some_test_param": "test-params"},
72
+ )
73
+ assert component.client.api_key == "test-api-key"
74
+ assert component.model == "mistral-small"
75
+ assert component.streaming_callback is print_streaming_chunk
76
+ assert component.generation_kwargs == {"max_tokens": 10, "some_test_param": "test-params"}
77
+
78
+ def test_to_dict_default(self, monkeypatch):
79
+ monkeypatch.setenv("MISTRAL_API_KEY", "test-api-key")
80
+ component = MistralChatGenerator()
81
+ data = component.to_dict()
82
+ assert data == {
83
+ "type": "haystack_integrations.components.generators.mistral.chat.chat_generator.MistralChatGenerator",
84
+ "init_parameters": {
85
+ "api_key": {"env_vars": ["MISTRAL_API_KEY"], "strict": True, "type": "env_var"},
86
+ "model": "mistral-tiny",
87
+ "organization": None,
88
+ "streaming_callback": None,
89
+ "api_base_url": "https://api.mistral.ai/v1",
90
+ "generation_kwargs": {},
91
+ },
92
+ }
93
+
94
+ def test_to_dict_with_parameters(self, monkeypatch):
95
+ monkeypatch.setenv("ENV_VAR", "test-api-key")
96
+ component = MistralChatGenerator(
97
+ api_key=Secret.from_env_var("ENV_VAR"),
98
+ model="mistral-small",
99
+ streaming_callback=print_streaming_chunk,
100
+ api_base_url="test-base-url",
101
+ generation_kwargs={"max_tokens": 10, "some_test_param": "test-params"},
102
+ )
103
+ data = component.to_dict()
104
+ assert data == {
105
+ "type": "haystack_integrations.components.generators.mistral.chat.chat_generator.MistralChatGenerator",
106
+ "init_parameters": {
107
+ "api_key": {"env_vars": ["ENV_VAR"], "strict": True, "type": "env_var"},
108
+ "model": "mistral-small",
109
+ "api_base_url": "test-base-url",
110
+ "organization": None,
111
+ "streaming_callback": "haystack.components.generators.utils.print_streaming_chunk",
112
+ "generation_kwargs": {"max_tokens": 10, "some_test_param": "test-params"},
113
+ },
114
+ }
115
+
116
+ def test_from_dict(self, monkeypatch):
117
+ monkeypatch.setenv("MISTRAL_API_KEY", "fake-api-key")
118
+ data = {
119
+ "type": "haystack_integrations.components.generators.mistral.chat.chat_generator.MistralChatGenerator",
120
+ "init_parameters": {
121
+ "api_key": {"env_vars": ["MISTRAL_API_KEY"], "strict": True, "type": "env_var"},
122
+ "model": "mistral-small",
123
+ "api_base_url": "test-base-url",
124
+ "streaming_callback": "haystack.components.generators.utils.print_streaming_chunk",
125
+ "generation_kwargs": {"max_tokens": 10, "some_test_param": "test-params"},
126
+ },
127
+ }
128
+ component = MistralChatGenerator.from_dict(data)
129
+ assert component.model == "mistral-small"
130
+ assert component.streaming_callback is print_streaming_chunk
131
+ assert component.api_base_url == "test-base-url"
132
+ assert component.generation_kwargs == {"max_tokens": 10, "some_test_param": "test-params"}
133
+ assert component.api_key == Secret.from_env_var("MISTRAL_API_KEY")
134
+
135
+ def test_from_dict_fail_wo_env_var(self, monkeypatch):
136
+ monkeypatch.delenv("MISTRAL_API_KEY", raising=False)
137
+ data = {
138
+ "type": "haystack_integrations.components.generators.mistral.chat.chat_generator.MistralChatGenerator",
139
+ "init_parameters": {
140
+ "api_key": {"env_vars": ["MISTRAL_API_KEY"], "strict": True, "type": "env_var"},
141
+ "model": "mistral-small",
142
+ "api_base_url": "test-base-url",
143
+ "streaming_callback": "haystack.components.generators.utils.print_streaming_chunk",
144
+ "generation_kwargs": {"max_tokens": 10, "some_test_param": "test-params"},
145
+ },
146
+ }
147
+ with pytest.raises(ValueError, match="None of the .* environment variables are set"):
148
+ MistralChatGenerator.from_dict(data)
149
+
150
+ def test_run(self, chat_messages):
151
+ component = MistralChatGenerator()
152
+ response = component.run(chat_messages)
153
+
154
+ # check that the component returns the correct ChatMessage response
155
+ assert isinstance(response, dict)
156
+ assert "replies" in response
157
+ assert isinstance(response["replies"], list)
158
+ assert len(response["replies"]) == 1
159
+ assert [isinstance(reply, ChatMessage) for reply in response["replies"]]
160
+
161
+ def test_run_with_params(self, chat_messages, mock_chat_completion):
162
+ component = MistralChatGenerator(generation_kwargs={"max_tokens": 10, "temperature": 0.5})
163
+ response = component.run(chat_messages)
164
+
165
+ # check that the component calls the OpenAI API with the correct parameters
166
+ _, kwargs = mock_chat_completion.call_args
167
+ assert kwargs["max_tokens"] == 10
168
+ assert kwargs["temperature"] == 0.5
169
+
170
+ # check that the component returns the correct response
171
+ assert isinstance(response, dict)
172
+ assert "replies" in response
173
+ assert isinstance(response["replies"], list)
174
+ assert len(response["replies"]) == 1
175
+ assert [isinstance(reply, ChatMessage) for reply in response["replies"]]
176
+
177
+ def test_run_with_params_streaming(self, chat_messages):
178
+ streaming_callback_called = False
179
+
180
+ def streaming_callback(chunk: StreamingChunk) -> None: # noqa: ARG001
181
+ nonlocal streaming_callback_called
182
+ streaming_callback_called = True
183
+
184
+ component = MistralChatGenerator(streaming_callback=streaming_callback)
185
+ response = component.run(chat_messages)
186
+
187
+ # check we called the streaming callback
188
+ assert streaming_callback_called
189
+
190
+ # check that the component still returns the correct response
191
+ assert isinstance(response, dict)
192
+ assert "replies" in response
193
+ assert isinstance(response["replies"], list)
194
+ assert len(response["replies"]) == 1
195
+ assert [isinstance(reply, ChatMessage) for reply in response["replies"]]
196
+ assert "Paris" in response["replies"][0].content # see mock_chat_completion_chunk
197
+
198
+ def test_check_abnormal_completions(self, caplog):
199
+ component = MistralChatGenerator(api_key=Secret.from_token("test-api-key"))
200
+ messages = [
201
+ ChatMessage.from_assistant(
202
+ "", meta={"finish_reason": "content_filter" if i % 2 == 0 else "length", "index": i}
203
+ )
204
+ for i, _ in enumerate(range(4))
205
+ ]
206
+
207
+ for m in messages:
208
+ component._check_finish_reason(m)
209
+
210
+ # check truncation warning
211
+ message_template = (
212
+ "The completion for index {index} has been truncated before reaching a natural stopping point. "
213
+ "Increase the max_tokens parameter to allow for longer completions."
214
+ )
215
+
216
+ for index in [1, 3]:
217
+ assert caplog.records[index].message == message_template.format(index=index)
218
+
219
+ # check content filter warning
220
+ message_template = "The completion for index {index} has been truncated due to the content filter."
221
+ for index in [0, 2]:
222
+ assert caplog.records[index].message == message_template.format(index=index)
223
+
224
+ @pytest.mark.skipif(
225
+ not os.environ.get("MISTRAL_API_KEY", None),
226
+ reason="Export an env var called MISTRAL_API_KEY containing the OpenAI API key to run this test.",
227
+ )
228
+ @pytest.mark.integration
229
+ def test_live_run(self):
230
+ chat_messages = [ChatMessage.from_user("What's the capital of France")]
231
+ component = MistralChatGenerator()
232
+ results = component.run(chat_messages)
233
+ assert len(results["replies"]) == 1
234
+ message: ChatMessage = results["replies"][0]
235
+ assert "Paris" in message.content
236
+ assert "mistral-tiny" in message.meta["model"]
237
+ assert message.meta["finish_reason"] == "stop"
238
+
239
+ @pytest.mark.skipif(
240
+ not os.environ.get("MISTRAL_API_KEY", None),
241
+ reason="Export an env var called MISTRAL_API_KEY containing the OpenAI API key to run this test.",
242
+ )
243
+ @pytest.mark.integration
244
+ def test_live_run_wrong_model(self, chat_messages):
245
+ component = MistralChatGenerator(model="something-obviously-wrong")
246
+ with pytest.raises(OpenAIError):
247
+ component.run(chat_messages)
248
+
249
+ @pytest.mark.skipif(
250
+ not os.environ.get("MISTRAL_API_KEY", None),
251
+ reason="Export an env var called MISTRAL_API_KEY containing the OpenAI API key to run this test.",
252
+ )
253
+ @pytest.mark.integration
254
+ def test_live_run_streaming(self):
255
+ class Callback:
256
+ def __init__(self):
257
+ self.responses = ""
258
+ self.counter = 0
259
+
260
+ def __call__(self, chunk: StreamingChunk) -> None:
261
+ self.counter += 1
262
+ self.responses += chunk.content if chunk.content else ""
263
+
264
+ callback = Callback()
265
+ component = MistralChatGenerator(streaming_callback=callback)
266
+ results = component.run([ChatMessage.from_user("What's the capital of France?")])
267
+
268
+ assert len(results["replies"]) == 1
269
+ message: ChatMessage = results["replies"][0]
270
+ assert "Paris" in message.content
271
+
272
+ assert "mistral-tiny" in message.meta["model"]
273
+ assert message.meta["finish_reason"] == "stop"
274
+
275
+ assert callback.counter > 1
276
+ assert "Paris" in callback.responses
@@ -0,0 +1,135 @@
1
+ # SPDX-FileCopyrightText: 2023-present deepset GmbH <info@deepset.ai>
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+ import os
5
+
6
+ import pytest
7
+ from haystack import Document
8
+ from haystack.utils import Secret
9
+ from haystack_integrations.components.embedders.mistral.document_embedder import MistralDocumentEmbedder
10
+
11
+ pytestmark = pytest.mark.embedders
12
+
13
+
14
+ class TestMistralDocumentEmbedder:
15
+ def test_init_default(self):
16
+ embedder = MistralDocumentEmbedder()
17
+ assert embedder.api_key == Secret.from_env_var(["MISTRAL_API_KEY"])
18
+ assert embedder.model == "mistral-embed"
19
+ assert embedder.api_base_url == "https://api.mistral.ai/v1"
20
+ assert embedder.prefix == ""
21
+ assert embedder.suffix == ""
22
+ assert embedder.batch_size == 32
23
+ assert embedder.progress_bar is True
24
+ assert embedder.meta_fields_to_embed == []
25
+ assert embedder.embedding_separator == "\n"
26
+
27
+ def test_init_with_parameters(self):
28
+ embedder = MistralDocumentEmbedder(
29
+ api_key=Secret.from_token("test-api-key"),
30
+ model="mistral-embed-v2",
31
+ api_base_url="https://custom-api-base-url.com",
32
+ prefix="START",
33
+ suffix="END",
34
+ batch_size=64,
35
+ progress_bar=False,
36
+ meta_fields_to_embed=["test_field"],
37
+ embedding_separator="-",
38
+ )
39
+ assert embedder.api_key == Secret.from_token("test-api-key")
40
+ assert embedder.model == "mistral-embed-v2"
41
+ assert embedder.api_base_url == "https://custom-api-base-url.com"
42
+ assert embedder.prefix == "START"
43
+ assert embedder.suffix == "END"
44
+ assert embedder.batch_size == 64
45
+ assert embedder.progress_bar is False
46
+ assert embedder.meta_fields_to_embed == ["test_field"]
47
+ assert embedder.embedding_separator == "-"
48
+
49
+ def test_to_dict(self):
50
+ embedder_component = MistralDocumentEmbedder()
51
+ component_dict = embedder_component.to_dict()
52
+ assert component_dict == {
53
+ "type": "haystack_integrations.components.embedders.mistral.document_embedder.MistralDocumentEmbedder",
54
+ "init_parameters": {
55
+ "api_key": {"env_vars": ["MISTRAL_API_KEY"], "strict": True, "type": "env_var"},
56
+ "model": "mistral-embed",
57
+ "api_base_url": "https://api.mistral.ai/v1",
58
+ "dimensions": None,
59
+ "organization": None,
60
+ "prefix": "",
61
+ "suffix": "",
62
+ "batch_size": 32,
63
+ "progress_bar": True,
64
+ "meta_fields_to_embed": [],
65
+ "embedding_separator": "\n",
66
+ },
67
+ }
68
+
69
+ def test_to_dict_with_custom_init_parameters(self, monkeypatch):
70
+ monkeypatch.setenv("ENV_VAR", "test-secret-key")
71
+ embedder = MistralDocumentEmbedder(
72
+ api_key=Secret.from_env_var("ENV_VAR", strict=False),
73
+ model="mistral-embed-v2",
74
+ api_base_url="https://custom-api-base-url.com",
75
+ prefix="START",
76
+ suffix="END",
77
+ batch_size=64,
78
+ progress_bar=False,
79
+ meta_fields_to_embed=["test_field"],
80
+ embedding_separator="-",
81
+ )
82
+ component_dict = embedder.to_dict()
83
+ assert component_dict == {
84
+ "type": "haystack_integrations.components.embedders.mistral.document_embedder.MistralDocumentEmbedder",
85
+ "init_parameters": {
86
+ "api_key": {"env_vars": ["ENV_VAR"], "strict": False, "type": "env_var"},
87
+ "model": "mistral-embed-v2",
88
+ "dimensions": None,
89
+ "api_base_url": "https://custom-api-base-url.com",
90
+ "organization": None,
91
+ "prefix": "START",
92
+ "suffix": "END",
93
+ "batch_size": 64,
94
+ "progress_bar": False,
95
+ "meta_fields_to_embed": ["test_field"],
96
+ "embedding_separator": "-",
97
+ },
98
+ }
99
+
100
+ @pytest.mark.skipif(
101
+ not os.environ.get("MISTRAL_API_KEY", None),
102
+ reason="Export an env var called MISTRAL_API_KEY containing the Cohere API key to run this test.",
103
+ )
104
+ @pytest.mark.integration
105
+ def test_run(self):
106
+ embedder = MistralDocumentEmbedder()
107
+
108
+ docs = [
109
+ Document(content="I love cheese", meta={"topic": "Cuisine"}),
110
+ Document(content="A transformer is a deep learning architecture", meta={"topic": "ML"}),
111
+ ]
112
+
113
+ result = embedder.run(docs)
114
+ docs_with_embeddings = result["documents"]
115
+
116
+ assert isinstance(docs_with_embeddings, list)
117
+ assert len(docs_with_embeddings) == len(docs)
118
+ for doc in docs_with_embeddings:
119
+ assert isinstance(doc.embedding, list)
120
+ assert isinstance(doc.embedding[0], float)
121
+
122
+ def test_run_wrong_input_format(self):
123
+ embedder = MistralDocumentEmbedder(api_key=Secret.from_token("test-api-key"))
124
+
125
+ match_error_msg = (
126
+ "OpenAIDocumentEmbedder expects a list of Documents as input.In case you want to embed a string, "
127
+ "please use the OpenAITextEmbedder."
128
+ )
129
+
130
+ with pytest.raises(TypeError, match=match_error_msg):
131
+ embedder.run(documents="text")
132
+ with pytest.raises(TypeError, match=match_error_msg):
133
+ embedder.run(documents=[1, 2, 3])
134
+
135
+ assert embedder.run(documents=[]) == {"documents": [], "meta": {}}
@@ -0,0 +1,90 @@
1
+ # SPDX-FileCopyrightText: 2023-present deepset GmbH <info@deepset.ai>
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+ import os
5
+
6
+ import pytest
7
+ from haystack.utils import Secret
8
+ from haystack_integrations.components.embedders.mistral.text_embedder import MistralTextEmbedder
9
+
10
+ pytestmark = pytest.mark.embedders
11
+
12
+
13
+ class TestMistralTextEmbedder:
14
+ def test_init_default(self):
15
+ embedder = MistralTextEmbedder()
16
+ assert embedder.api_key == Secret.from_env_var(["MISTRAL_API_KEY"])
17
+ assert embedder.model == "mistral-embed"
18
+ assert embedder.prefix == ""
19
+ assert embedder.suffix == ""
20
+
21
+ def test_init_with_parameters(self):
22
+ embedder = MistralTextEmbedder(
23
+ api_key=Secret.from_token("test-api-key"),
24
+ model="mistral-embed-v2",
25
+ prefix="START",
26
+ suffix="END",
27
+ )
28
+ assert embedder.api_key == Secret.from_token("test-api-key")
29
+ assert embedder.model == "mistral-embed-v2"
30
+ assert embedder.prefix == "START"
31
+ assert embedder.suffix == "END"
32
+
33
+ def test_to_dict(self):
34
+ embedder_component = MistralTextEmbedder()
35
+ component_dict = embedder_component.to_dict()
36
+ assert component_dict == {
37
+ "type": "haystack_integrations.components.embedders.mistral.text_embedder.MistralTextEmbedder",
38
+ "init_parameters": {
39
+ "api_key": {"env_vars": ["MISTRAL_API_KEY"], "strict": True, "type": "env_var"},
40
+ "model": "mistral-embed",
41
+ "dimensions": None,
42
+ "organization": None,
43
+ "prefix": "",
44
+ "suffix": "",
45
+ },
46
+ }
47
+
48
+ def test_to_dict_with_custom_init_parameters(self, monkeypatch):
49
+ monkeypatch.setenv("ENV_VAR", "test-secret-key")
50
+ embedder = MistralTextEmbedder(
51
+ api_key=Secret.from_env_var("ENV_VAR", strict=False),
52
+ model="mistral-embed-v2",
53
+ api_base_url="https://custom-api-base-url.com",
54
+ prefix="START",
55
+ suffix="END",
56
+ )
57
+ component_dict = embedder.to_dict()
58
+ assert component_dict == {
59
+ "type": "haystack_integrations.components.embedders.mistral.text_embedder.MistralTextEmbedder",
60
+ "init_parameters": {
61
+ "api_key": {"env_vars": ["ENV_VAR"], "strict": False, "type": "env_var"},
62
+ "model": "mistral-embed-v2",
63
+ "dimensions": None,
64
+ "organization": None,
65
+ "prefix": "START",
66
+ "suffix": "END",
67
+ },
68
+ }
69
+
70
+ @pytest.mark.skipif(
71
+ not os.environ.get("MISTRAL_API_KEY", None),
72
+ reason="Export an env var called MISTRAL_API_KEY containing the Cohere API key to run this test.",
73
+ )
74
+ @pytest.mark.integration
75
+ def test_run(self):
76
+ embedder = MistralTextEmbedder()
77
+ text = "The food was delicious"
78
+ result = embedder.run(text)
79
+ assert all(isinstance(x, float) for x in result["embedding"])
80
+
81
+ def test_run_wrong_input_format(self):
82
+ embedder = MistralTextEmbedder(api_key=Secret.from_token("test-api-key"))
83
+ list_integers_input = ["text_snippet_1", "text_snippet_2"]
84
+ match_error_msg = (
85
+ "OpenAITextEmbedder expects a string as an input.In case you want to embed a list of Documents,"
86
+ " please use the OpenAIDocumentEmbedder."
87
+ )
88
+
89
+ with pytest.raises(TypeError, match=match_error_msg):
90
+ embedder.run(text=list_integers_input)