diff --git a/.github/labeler.yml b/.github/labeler.yml index b60cbbfee..5f1b76912 100644 --- a/.github/labeler.yml +++ b/.github/labeler.yml @@ -64,6 +64,11 @@ integration:llama_cpp: - any-glob-to-any-file: "integrations/llama_cpp/**/*" - any-glob-to-any-file: ".github/workflows/llama_cpp.yml" +integration:mistral: + - changed-files: + - any-glob-to-any-file: "integrations/mistral/**/*" + - any-glob-to-any-file: ".github/workflows/mistral.yml" + integration:mongodb-atlas: - changed-files: - any-glob-to-any-file: "integrations/mongodb_atlas/**/*" diff --git a/.github/workflows/mistral.yml b/.github/workflows/mistral.yml new file mode 100644 index 000000000..a02b5ad43 --- /dev/null +++ b/.github/workflows/mistral.yml @@ -0,0 +1,61 @@ +# This workflow comes from https://github.com/ofek/hatch-mypyc +# https://github.com/ofek/hatch-mypyc/blob/5a198c0ba8660494d02716cfc9d79ce4adfb1442/.github/workflows/test.yml +name: Test / mistral + +on: + schedule: + - cron: "0 0 * * *" + pull_request: + paths: + - "integrations/mistral/**" + - ".github/workflows/mistral.yml" + +defaults: + run: + working-directory: integrations/mistral + +concurrency: + group: mistral-${{ github.head_ref }} + cancel-in-progress: true + +env: + PYTHONUNBUFFERED: "1" + FORCE_COLOR: "1" + MISTRAL_API_KEY: ${{ secrets.MISTRAL_API_KEY }} + +jobs: + run: + name: Python ${{ matrix.python-version }} on ${{ startsWith(matrix.os, 'macos-') && 'macOS' || startsWith(matrix.os, 'windows-') && 'Windows' || 'Linux' }} + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, windows-latest, macos-latest] + python-version: ["3.9", "3.10"] + + steps: + - name: Support longpaths + if: matrix.os == 'windows-latest' + working-directory: . + run: git config --system core.longpaths true + + - uses: actions/checkout@v4 + + - name: Set up Python ${{ matrix.python-version }} + uses: actions/setup-python@v5 + with: + python-version: ${{ matrix.python-version }} + + - name: Install Hatch + run: pip install --upgrade hatch + + - name: Lint + if: matrix.python-version == '3.9' && runner.os == 'Linux' + run: hatch run lint:all + + - name: Generate docs + if: matrix.python-version == '3.9' && runner.os == 'Linux' + run: hatch run docs + + - name: Run tests + run: hatch run cov diff --git a/README.md b/README.md index 8bda94773..81909c3de 100644 --- a/README.md +++ b/README.md @@ -85,3 +85,4 @@ deepset-haystack | [unstructured-fileconverter-haystack](integrations/unstructured/) | File converter | [![PyPI - Version](https://img.shields.io/pypi/v/unstructured-fileconverter-haystack.svg)](https://pypi.org/project/unstructured-fileconverter-haystack) | [![Test / unstructured](https://github.com/deepset-ai/haystack-core-integrations/actions/workflows/unstructured.yml/badge.svg)](https://github.com/deepset-ai/haystack-core-integrations/actions/workflows/unstructured.yml) | | [uptrain-haystack](integrations/uptrain/) | Evaluator | [![PyPI - Version](https://img.shields.io/pypi/v/uptrain-haystack.svg)](https://pypi.org/project/uptrain-haystack) | [![Test / uptrain](https://github.com/deepset-ai/haystack-core-integrations/actions/workflows/uptrain.yml/badge.svg)](https://github.com/deepset-ai/haystack-core-integrations/actions/workflows/uptrain.yml) | | [amazon-sagemaker-haystack](integrations/amazon_sagemaker/) | Generator | [![PyPI - Version](https://img.shields.io/pypi/v/amazon-sagemaker-haystack.svg)](https://pypi.org/project/amazon-sagemaker-haystack) | [![Test / amazon_sagemaker](https://github.com/deepset-ai/haystack-core-integrations/actions/workflows/amazon_sagemaker.yml/badge.svg)](https://github.com/deepset-ai/haystack-core-integrations/actions/workflows/amazon_sagemaker.yml) | +| [mistral-haystack](integrations/mistral/) | Embedder, Generator | [![PyPI - Version](https://img.shields.io/pypi/v/mistral-haystack.svg)](https://pypi.org/project/mistral-haystack) | [![Test / astra](https://github.com/deepset-ai/haystack-core-integrations/actions/workflows/mistral.yml/badge.svg)](https://github.com/deepset-ai/haystack-core-integrations/actions/workflows/mistral.yml) | diff --git a/integrations/mistral/LICENSE.txt b/integrations/mistral/LICENSE.txt new file mode 100644 index 000000000..137069b82 --- /dev/null +++ b/integrations/mistral/LICENSE.txt @@ -0,0 +1,73 @@ +Apache License +Version 2.0, January 2004 +http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + +"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. + +"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. + +"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. + +"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. + +"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. + +"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. + +"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). + +"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. + +"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." + +"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. + +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. + +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. + +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: + + (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices stating that You changed the files; and + + (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 + + (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. + + 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. + +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. + +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. + +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. + +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. + +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. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + +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. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/integrations/mistral/README.md b/integrations/mistral/README.md new file mode 100644 index 000000000..8abced890 --- /dev/null +++ b/integrations/mistral/README.md @@ -0,0 +1,21 @@ +# mistral-haystack + +[![PyPI - Version](https://img.shields.io/pypi/v/mistral-haystack.svg)](https://pypi.org/project/mistral-haystack) +[![PyPI - Python Version](https://img.shields.io/pypi/pyversions/mistral-haystack.svg)](https://pypi.org/project/mistral-haystack) + +----- + +**Table of Contents** + +- [Installation](#installation) +- [License](#license) + +## Installation + +```console +pip install mistral-haystack +``` + +## License + +`mistral-haystack` is distributed under the terms of the [Apache-2.0](https://spdx.org/licenses/Apache-2.0.html) license. diff --git a/integrations/mistral/examples/indexing_pipeline.py b/integrations/mistral/examples/indexing_pipeline.py new file mode 100644 index 000000000..0329fab8c --- /dev/null +++ b/integrations/mistral/examples/indexing_pipeline.py @@ -0,0 +1,32 @@ +# To run this example, you will need an to set a `MISTRAL_API_KEY` environment variable. +# This example streams chat replies to the console. + +from haystack import Pipeline +from haystack.components.converters import HTMLToDocument +from haystack.components.fetchers import LinkContentFetcher +from haystack.components.preprocessors import DocumentSplitter +from haystack.components.writers import DocumentWriter +from haystack.document_stores.in_memory import InMemoryDocumentStore +from haystack_integrations.components.embedders.mistral.document_embedder import MistralDocumentEmbedder + +document_store = InMemoryDocumentStore() +fetcher = LinkContentFetcher() +converter = HTMLToDocument() +chunker = DocumentSplitter() +embedder = MistralDocumentEmbedder() +writer = DocumentWriter(document_store=document_store) + +indexing = Pipeline() + +indexing.add_component(name="fetcher", instance=fetcher) +indexing.add_component(name="converter", instance=converter) +indexing.add_component(name="chunker", instance=chunker) +indexing.add_component(name="embedder", instance=embedder) +indexing.add_component(name="writer", instance=writer) + +indexing.connect("fetcher", "converter") +indexing.connect("converter", "chunker") +indexing.connect("chunker", "embedder") +indexing.connect("embedder", "writer") + +indexing.run(data={"fetcher": {"urls": ["https://mistral.ai/news/la-plateforme/"]}}) diff --git a/integrations/mistral/examples/streaming_chat_with_rag.py b/integrations/mistral/examples/streaming_chat_with_rag.py new file mode 100644 index 000000000..2e3eeee5a --- /dev/null +++ b/integrations/mistral/examples/streaming_chat_with_rag.py @@ -0,0 +1,66 @@ +# To run this example, you will need an to set a `MISTRAL_API_KEY` environment variable. +# This example streams chat replies to the console. + +from haystack import Pipeline +from haystack.components.builders import DynamicChatPromptBuilder +from haystack.components.converters import HTMLToDocument +from haystack.components.fetchers import LinkContentFetcher +from haystack.components.generators.utils import print_streaming_chunk +from haystack.components.preprocessors import DocumentSplitter +from haystack.components.retrievers.in_memory import InMemoryEmbeddingRetriever +from haystack.components.writers import DocumentWriter +from haystack.dataclasses import ChatMessage +from haystack.document_stores.in_memory import InMemoryDocumentStore +from haystack_integrations.components.embedders.mistral.document_embedder import MistralDocumentEmbedder +from haystack_integrations.components.embedders.mistral.text_embedder import MistralTextEmbedder +from haystack_integrations.components.generators.mistral import MistralChatGenerator + +document_store = InMemoryDocumentStore() +fetcher = LinkContentFetcher() +converter = HTMLToDocument() +chunker = DocumentSplitter() +embedder = MistralDocumentEmbedder() +writer = DocumentWriter(document_store=document_store) + +indexing = Pipeline() + +indexing.add_component(name="fetcher", instance=fetcher) +indexing.add_component(name="converter", instance=converter) +indexing.add_component(name="chunker", instance=chunker) +indexing.add_component(name="embedder", instance=embedder) +indexing.add_component(name="writer", instance=writer) + +indexing.connect("fetcher", "converter") +indexing.connect("converter", "chunker") +indexing.connect("chunker", "embedder") +indexing.connect("embedder", "writer") + +indexing.run(data={"fetcher": {"urls": ["https://mistral.ai/news/la-plateforme/"]}}) + +text_embedder = MistralTextEmbedder() +retriever = InMemoryEmbeddingRetriever(document_store=document_store) +prompt_builder = DynamicChatPromptBuilder(runtime_variables=["documents"]) +llm = MistralChatGenerator(streaming_callback=print_streaming_chunk) + +messages = [ChatMessage.from_user("Here are some the documents: {{documents}} \\n Answer: {{query}}")] + +rag_pipeline = Pipeline() +rag_pipeline.add_component("text_embedder", text_embedder) +rag_pipeline.add_component("retriever", retriever) +rag_pipeline.add_component("prompt_builder", prompt_builder) +rag_pipeline.add_component("llm", llm) + + +rag_pipeline.connect("text_embedder.embedding", "retriever.query_embedding") +rag_pipeline.connect("retriever.documents", "prompt_builder.documents") +rag_pipeline.connect("prompt_builder.prompt", "llm.messages") + +question = "What are the available models?" + +result = rag_pipeline.run( + { + "text_embedder": {"text": question}, + "prompt_builder": {"template_variables": {"query": question}, "prompt_source": messages}, + "llm": {"generation_kwargs": {"max_tokens": 165}}, + } +) diff --git a/integrations/mistral/pydoc/config.yml b/integrations/mistral/pydoc/config.yml new file mode 100644 index 000000000..40c534f43 --- /dev/null +++ b/integrations/mistral/pydoc/config.yml @@ -0,0 +1,30 @@ +loaders: + - type: haystack_pydoc_tools.loaders.CustomPythonLoader + search_path: [../src] + modules: [ + "haystack_integrations.components.embedders.mistral.document_embedder", + "haystack_integrations.components.embedders.mistral.text_embedder", + "haystack_integrations.components.generators.mistral.chat.chat_generator", + ] + ignore_when_discovered: ["__init__"] +processors: + - type: filter + expression: + documented_only: true + do_not_filter_modules: false + skip_empty_modules: true + - type: smart + - type: crossref +renderer: + type: haystack_pydoc_tools.renderers.ReadmePreviewRenderer + excerpt: Mistral integration for Haystack + category_slug: haystack-integrations + title: Mistral + slug: integrations-mistral + order: 40 + markdown: + descriptive_class_title: false + descriptive_module_title: true + add_method_class_prefix: true + add_member_class_prefix: false + filename: _readme_mistral.md \ No newline at end of file diff --git a/integrations/mistral/pyproject.toml b/integrations/mistral/pyproject.toml new file mode 100644 index 000000000..6abf98704 --- /dev/null +++ b/integrations/mistral/pyproject.toml @@ -0,0 +1,163 @@ +[build-system] +requires = ["hatchling", "hatch-vcs"] +build-backend = "hatchling.build" + +[project] +name = "mistral-haystack" +dynamic = ["version"] +description = '' +readme = "README.md" +requires-python = ">=3.8" +license = "Apache-2.0" +keywords = [] +authors = [{ name = "deepset GmbH", email = "info@deepset.ai" }] +classifiers = [ + "Development Status :: 4 - Beta", + "Programming Language :: Python", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: Implementation :: CPython", + "Programming Language :: Python :: Implementation :: PyPy", +] +dependencies = ["haystack-ai>=2.0.0b6"] + +[project.urls] +Documentation = "https://github.com/deepset-ai/haystack-core-integrations/tree/main/integrations/mistral#readme" +Issues = "https://github.com/deepset-ai/haystack-core-integrations/issues" +Source = "https://github.com/deepset-ai/haystack-core-integrations/tree/main/integrations/mistral" + +[tool.hatch.build.targets.wheel] +packages = ["src/haystack_integrations"] + +[tool.hatch.version] +source = "vcs" +tag-pattern = 'integrations\/mistral-v(?P.*)' + +[tool.hatch.version.raw-options] +root = "../.." +git_describe_command = 'git describe --tags --match="integrations/mistral-v[0-9]*"' + +[tool.hatch.envs.default] +dependencies = ["coverage[toml]>=6.5", "pytest", "haystack-pydoc-tools"] +[tool.hatch.envs.default.scripts] +test = "pytest {args:tests}" +test-cov = "coverage run -m pytest {args:tests}" +cov-report = ["- coverage combine", "coverage report"] +cov = ["test-cov", "cov-report"] +docs = ["pydoc-markdown pydoc/config.yml"] + +[[tool.hatch.envs.all.matrix]] +python = ["3.8", "3.9", "3.10", "3.11"] + +[tool.hatch.envs.lint] +detached = true +dependencies = ["black>=23.1.0", "mypy>=1.0.0", "ruff>=0.0.243"] +[tool.hatch.envs.lint.scripts] +typing = "mypy --install-types --non-interactive --explicit-package-bases {args:src/ tests}" +style = ["ruff {args:.}", "black --check --diff {args:.}"] +fmt = ["black {args:.}", "ruff --fix {args:.}", "style"] +all = ["style", "typing"] + +[tool.black] +target-version = ["py37"] +line-length = 120 +skip-string-normalization = true + +[tool.ruff] +target-version = "py37" +line-length = 120 +select = [ + "A", + "ARG", + "B", + "C", + "DTZ", + "E", + "EM", + "F", + "I", + "ICN", + "ISC", + "N", + "PLC", + "PLE", + "PLR", + "PLW", + "Q", + "RUF", + "S", + "T", + "TID", + "UP", + "W", + "YTT", +] +ignore = [ + # Allow non-abstract empty methods in abstract base classes + "B027", + # Ignore checks for possible passwords + "S105", + "S106", + "S107", + # Ignore complexity + "C901", + "PLR0911", + "PLR0912", + "PLR0913", + "PLR0915", + # Misc + "B008", + "S101", +] +unfixable = [ + # Don't touch unused imports + "F401", +] + +[tool.ruff.isort] +known-first-party = ["src"] + +[tool.ruff.flake8-tidy-imports] +ban-relative-imports = "parents" + +[tool.ruff.per-file-ignores] +# Tests can use magic values, assertions, and relative imports +"tests/**/*" = ["PLR2004", "S101", "TID252"] + +[tool.coverage.run] +source_pkgs = ["src", "tests"] +branch = true +parallel = true + +[tool.coverage.paths] +mistral_haystack = [ + "src/haystack_integrations", + "*/mistral/src/haystack_integrations", +] +tests = ["tests", "*/mistral/tests"] + +[tool.coverage.report] +exclude_lines = ["no cov", "if __name__ == .__main__.:", "if TYPE_CHECKING:"] + +[[tool.mypy.overrides]] +module = [ + "mistral.*", + "haystack.*", + "haystack_integrations.*", + "openai.*", + "pytest.*", + "numpy.*", +] +ignore_missing_imports = true + +[tool.pytest.ini_options] +addopts = "--strict-markers" +markers = [ + "integration: integration tests", + "unit: unit tests", + "embedders: embedders tests", + "chat_generators: chat_generators tests", +] +log_cli = true diff --git a/integrations/mistral/src/haystack_integrations/components/embedders/mistral/__init__.py b/integrations/mistral/src/haystack_integrations/components/embedders/mistral/__init__.py new file mode 100644 index 000000000..b3b3b57ac --- /dev/null +++ b/integrations/mistral/src/haystack_integrations/components/embedders/mistral/__init__.py @@ -0,0 +1,7 @@ +# SPDX-FileCopyrightText: 2023-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 +from .document_embedder import MistralDocumentEmbedder +from .text_embedder import MistralTextEmbedder + +__all__ = ["MistralDocumentEmbedder", "MistralTextEmbedder"] diff --git a/integrations/mistral/src/haystack_integrations/components/embedders/mistral/document_embedder.py b/integrations/mistral/src/haystack_integrations/components/embedders/mistral/document_embedder.py new file mode 100644 index 000000000..29161fd95 --- /dev/null +++ b/integrations/mistral/src/haystack_integrations/components/embedders/mistral/document_embedder.py @@ -0,0 +1,70 @@ +# SPDX-FileCopyrightText: 2023-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 +from typing import List, Optional + +from haystack import component +from haystack.components.embedders import OpenAIDocumentEmbedder +from haystack.utils.auth import Secret + + +@component +class MistralDocumentEmbedder(OpenAIDocumentEmbedder): + """ + A component for computing Document embeddings using Mistral models. + The embedding of each Document is stored in the `embedding` field of the Document. + + Usage example: + ```python + from haystack import Document + from haystack_integrations.components.embedders.mistral import MistralDocumentEmbedder + + doc = Document(content="I love pizza!") + + document_embedder = MistralDocumentEmbedder() + + result = document_embedder.run([doc]) + print(result['documents'][0].embedding) + + # [0.017020374536514282, -0.023255806416273117, ...] + ``` + """ + + def __init__( + self, + api_key: Secret = Secret.from_env_var("MISTRAL_API_KEY"), + model: str = "mistral-embed", + api_base_url: Optional[str] = "https://api.mistral.ai/v1", + prefix: str = "", + suffix: str = "", + batch_size: int = 32, + progress_bar: bool = True, + meta_fields_to_embed: Optional[List[str]] = None, + embedding_separator: str = "\n", + ): + """ + Create a MistralDocumentEmbedder component. + :param api_key: The Mistral API key. + :param model: The name of the model to use. + :param api_base_url: The Mistral API Base url, defaults to None. For more details, see Mistral [docs](https://docs.mistral.ai/api/). + :param prefix: A string to add to the beginning of each text. + :param suffix: A string to add to the end of each text. + :param batch_size: Number of Documents to encode at once. + :param progress_bar: Whether to show a progress bar or not. Can be helpful to disable in production deployments + to keep the logs clean. + :param meta_fields_to_embed: List of meta fields that should be embedded along with the Document text. + :param embedding_separator: Separator used to concatenate the meta fields to the Document text. + """ + super(MistralDocumentEmbedder, self).__init__( # noqa: UP008 + api_key=api_key, + model=model, + dimensions=None, + api_base_url=api_base_url, + organization=None, + prefix=prefix, + suffix=suffix, + batch_size=batch_size, + progress_bar=progress_bar, + meta_fields_to_embed=meta_fields_to_embed, + embedding_separator=embedding_separator, + ) diff --git a/integrations/mistral/src/haystack_integrations/components/embedders/mistral/text_embedder.py b/integrations/mistral/src/haystack_integrations/components/embedders/mistral/text_embedder.py new file mode 100644 index 000000000..d65828ef6 --- /dev/null +++ b/integrations/mistral/src/haystack_integrations/components/embedders/mistral/text_embedder.py @@ -0,0 +1,58 @@ +# SPDX-FileCopyrightText: 2023-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 +from typing import Optional + +from haystack import component +from haystack.components.embedders import OpenAITextEmbedder +from haystack.utils.auth import Secret + + +@component +class MistralTextEmbedder(OpenAITextEmbedder): + """ + A component for embedding strings using Mistral models. + + Usage example: + ```python + from haystack_integrations.components.embedders.mistral.text_embedder import MistralTextEmbedder + + text_to_embed = "I love pizza!" + + text_embedder = MistralTextEmbedder() + + print(text_embedder.run(text_to_embed)) + + # {'embedding': [0.017020374536514282, -0.023255806416273117, ...], + # 'meta': {'model': 'text-embedding-ada-002-v2', + # 'usage': {'prompt_tokens': 4, 'total_tokens': 4}}} + ``` + """ + + def __init__( + self, + api_key: Secret = Secret.from_env_var("MISTRAL_API_KEY"), + model: str = "mistral-embed", + api_base_url: Optional[str] = "https://api.mistral.ai/v1", + prefix: str = "", + suffix: str = "", + ): + """ + Create an MistralTextEmbedder component. + + :param api_key: The Misttal API key. + :param model: The name of the Mistral embedding models to be used. + :param api_base_url: The Mistral API Base url, defaults to `https://api.mistral.ai/v1`. + For more details, see Mistral [docs](https://docs.mistral.ai/api/). + :param prefix: A string to add to the beginning of each text. + :param suffix: A string to add to the end of each text. + """ + super(MistralTextEmbedder, self).__init__( # noqa: UP008 + api_key=api_key, + model=model, + dimensions=None, + api_base_url=api_base_url, + organization=None, + prefix=prefix, + suffix=suffix, + ) diff --git a/integrations/mistral/src/haystack_integrations/components/generators/mistral/__init__.py b/integrations/mistral/src/haystack_integrations/components/generators/mistral/__init__.py new file mode 100644 index 000000000..a6320494a --- /dev/null +++ b/integrations/mistral/src/haystack_integrations/components/generators/mistral/__init__.py @@ -0,0 +1,3 @@ +from .chat.chat_generator import MistralChatGenerator + +__all__ = ["MistralChatGenerator"] diff --git a/integrations/mistral/src/haystack_integrations/components/generators/mistral/chat/__init__.py b/integrations/mistral/src/haystack_integrations/components/generators/mistral/chat/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/integrations/mistral/src/haystack_integrations/components/generators/mistral/chat/chat_generator.py b/integrations/mistral/src/haystack_integrations/components/generators/mistral/chat/chat_generator.py new file mode 100644 index 000000000..e1399c203 --- /dev/null +++ b/integrations/mistral/src/haystack_integrations/components/generators/mistral/chat/chat_generator.py @@ -0,0 +1,97 @@ +# SPDX-FileCopyrightText: 2023-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 +from typing import Any, Callable, Dict, Optional + +from haystack import component +from haystack.components.generators.chat import OpenAIChatGenerator +from haystack.dataclasses import StreamingChunk +from haystack.utils.auth import Secret + + +@component +class MistralChatGenerator(OpenAIChatGenerator): + """ + Enables text generation using Mistral's large language models (LLMs). + Currently supports `mistral-tiny`, `mistral-small` and `mistral-medium` + models accessed through the chat completions API endpoint. + + Users can pass any text generation parameters valid for the `openai.ChatCompletion.create` method + directly to this component via the `**generation_kwargs` parameter in __init__ or the `**generation_kwargs` + parameter in `run` method. + + For more details on the parameters supported by the Mistral API, refer to the + [Mistral API Docs](https://docs.mistral.ai/api/). + + ```python + from haystack_integrations.components.generators.mistral import MistralChatGenerator + from haystack.dataclasses import ChatMessage + + messages = [ChatMessage.from_user("What's Natural Language Processing?")] + + client = MistralChatGenerator() + response = client.run(messages) + print(response) + + >>{'replies': [ChatMessage(content='Natural Language Processing (NLP) is a branch of artificial intelligence + >>that focuses on enabling computers to understand, interpret, and generate human language in a way that is + >>meaningful and useful.', role=, name=None, + >>meta={'model': 'mistral-tiny', 'index': 0, 'finish_reason': 'stop', + >>'usage': {'prompt_tokens': 15, 'completion_tokens': 36, 'total_tokens': 51}})]} + + ``` + + Key Features and Compatibility: + - **Primary Compatibility**: Designed to work seamlessly with the Mistral API Chat Completion endpoint. + - **Streaming Support**: Supports streaming responses from the Mistral API Chat Completion endpoint. + - **Customizability**: Supports all parameters supported by the Mistral API Chat Completion endpoint. + + Input and Output Format: + - **ChatMessage Format**: This component uses the ChatMessage format for structuring both input and output, + ensuring coherent and contextually relevant responses in chat-based text generation scenarios. + Details on the ChatMessage format can be found at: https://github.com/openai/openai-python/blob/main/chatml.md. + Note that the Mistral API does not accept `system` messages yet. You can use `user` and `assistant` messages. + """ + + def __init__( + self, + api_key: Secret = Secret.from_env_var("MISTRAL_API_KEY"), + model: str = "mistral-tiny", + streaming_callback: Optional[Callable[[StreamingChunk], None]] = None, + api_base_url: Optional[str] = "https://api.mistral.ai/v1", + generation_kwargs: Optional[Dict[str, Any]] = None, + ): + """ + Creates an instance of MistralChatGenerator. Unless specified otherwise in the `model`, this is for Mistral's + `mistral-tiny` model. + + :param api_key: The Mistral API key. + :param model: The name of the Mistral chat completion model to use. + :param streaming_callback: A callback function that is called when a new token is received from the stream. + The callback function accepts StreamingChunk as an argument. + :param api_base_url: The Mistral API Base url, defaults to `https://api.mistral.ai/v1`. + For more details, see Mistral [docs](https://docs.mistral.ai/api/). + :param generation_kwargs: Other parameters to use for the model. These parameters are all sent directly to + the Mistrak endpoint. See [Mistral API docs](https://docs.mistral.ai/api/t) for + more details. + Some of the supported parameters: + - `max_tokens`: The maximum number of tokens the output text can have. + - `temperature`: What sampling temperature to use. Higher values mean the model will take more risks. + Try 0.9 for more creative applications and 0 (argmax sampling) for ones with a well-defined answer. + - `top_p`: An alternative to sampling with temperature, called nucleus sampling, where the model + considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens + comprising the top 10% probability mass are considered. + - `stream`: Whether to stream back partial progress. If set, tokens will be sent as data-only server-sent + events as they become available, with the stream terminated by a data: [DONE] message. + - `stop`: One or more sequences after which the LLM should stop generating tokens. + - `safe_prompt`: Whether to inject a safety prompt before all conversations. + - `random_seed`: The seed to use for random sampling. + """ + super(MistralChatGenerator, self).__init__( # noqa: UP008 + api_key=api_key, + model=model, + streaming_callback=streaming_callback, + api_base_url=api_base_url, + organization=None, + generation_kwargs=generation_kwargs, + ) diff --git a/integrations/mistral/tests/__init__.py b/integrations/mistral/tests/__init__.py new file mode 100644 index 000000000..6b5e14dc1 --- /dev/null +++ b/integrations/mistral/tests/__init__.py @@ -0,0 +1,3 @@ +# SPDX-FileCopyrightText: 2024-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 diff --git a/integrations/mistral/tests/test_mistral_chat_generator.py b/integrations/mistral/tests/test_mistral_chat_generator.py new file mode 100644 index 000000000..d2a4129e2 --- /dev/null +++ b/integrations/mistral/tests/test_mistral_chat_generator.py @@ -0,0 +1,276 @@ +import os +from datetime import datetime +from unittest.mock import patch + +import pytest +import pytz +from haystack.components.generators.utils import print_streaming_chunk +from haystack.dataclasses import ChatMessage, StreamingChunk +from haystack.utils.auth import Secret +from haystack_integrations.components.generators.mistral.chat.chat_generator import MistralChatGenerator +from openai import OpenAIError +from openai.types.chat import ChatCompletion, ChatCompletionMessage +from openai.types.chat.chat_completion import Choice + + +@pytest.fixture +def chat_messages(): + return [ + ChatMessage.from_system("You are a helpful assistant"), + ChatMessage.from_user("What's the capital of France"), + ] + + +@pytest.fixture +def mock_chat_completion(): + """ + Mock the OpenAI API completion response and reuse it for tests + """ + with patch("openai.resources.chat.completions.Completions.create") as mock_chat_completion_create: + completion = ChatCompletion( + id="foo", + model="mistral-tiny", + object="chat.completion", + choices=[ + Choice( + finish_reason="stop", + logprobs=None, + index=0, + message=ChatCompletionMessage(content="Hello world!", role="assistant"), + ) + ], + created=int(datetime.now(tz=pytz.timezone("UTC")).timestamp()), + usage={"prompt_tokens": 57, "completion_tokens": 40, "total_tokens": 97}, + ) + + mock_chat_completion_create.return_value = completion + yield mock_chat_completion_create + + +class TestMistralChatGenerator: + def test_init_default(self, monkeypatch): + monkeypatch.setenv("MISTRAL_API_KEY", "test-api-key") + component = MistralChatGenerator() + assert component.client.api_key == "test-api-key" + assert component.model == "mistral-tiny" + assert component.api_base_url == "https://api.mistral.ai/v1" + assert component.streaming_callback is None + assert not component.generation_kwargs + + def test_init_fail_wo_api_key(self, monkeypatch): + monkeypatch.delenv("MISTRAL_API_KEY", raising=False) + with pytest.raises(ValueError, match="None of the .* environment variables are set"): + MistralChatGenerator() + + def test_init_with_parameters(self): + component = MistralChatGenerator( + api_key=Secret.from_token("test-api-key"), + model="mistral-small", + streaming_callback=print_streaming_chunk, + api_base_url="test-base-url", + generation_kwargs={"max_tokens": 10, "some_test_param": "test-params"}, + ) + assert component.client.api_key == "test-api-key" + assert component.model == "mistral-small" + assert component.streaming_callback is print_streaming_chunk + assert component.generation_kwargs == {"max_tokens": 10, "some_test_param": "test-params"} + + def test_to_dict_default(self, monkeypatch): + monkeypatch.setenv("MISTRAL_API_KEY", "test-api-key") + component = MistralChatGenerator() + data = component.to_dict() + assert data == { + "type": "haystack_integrations.components.generators.mistral.chat.chat_generator.MistralChatGenerator", + "init_parameters": { + "api_key": {"env_vars": ["MISTRAL_API_KEY"], "strict": True, "type": "env_var"}, + "model": "mistral-tiny", + "organization": None, + "streaming_callback": None, + "api_base_url": "https://api.mistral.ai/v1", + "generation_kwargs": {}, + }, + } + + def test_to_dict_with_parameters(self, monkeypatch): + monkeypatch.setenv("ENV_VAR", "test-api-key") + component = MistralChatGenerator( + api_key=Secret.from_env_var("ENV_VAR"), + model="mistral-small", + streaming_callback=print_streaming_chunk, + api_base_url="test-base-url", + generation_kwargs={"max_tokens": 10, "some_test_param": "test-params"}, + ) + data = component.to_dict() + assert data == { + "type": "haystack_integrations.components.generators.mistral.chat.chat_generator.MistralChatGenerator", + "init_parameters": { + "api_key": {"env_vars": ["ENV_VAR"], "strict": True, "type": "env_var"}, + "model": "mistral-small", + "api_base_url": "test-base-url", + "organization": None, + "streaming_callback": "haystack.components.generators.utils.print_streaming_chunk", + "generation_kwargs": {"max_tokens": 10, "some_test_param": "test-params"}, + }, + } + + def test_from_dict(self, monkeypatch): + monkeypatch.setenv("MISTRAL_API_KEY", "fake-api-key") + data = { + "type": "haystack_integrations.components.generators.mistral.chat.chat_generator.MistralChatGenerator", + "init_parameters": { + "api_key": {"env_vars": ["MISTRAL_API_KEY"], "strict": True, "type": "env_var"}, + "model": "mistral-small", + "api_base_url": "test-base-url", + "streaming_callback": "haystack.components.generators.utils.print_streaming_chunk", + "generation_kwargs": {"max_tokens": 10, "some_test_param": "test-params"}, + }, + } + component = MistralChatGenerator.from_dict(data) + assert component.model == "mistral-small" + assert component.streaming_callback is print_streaming_chunk + assert component.api_base_url == "test-base-url" + assert component.generation_kwargs == {"max_tokens": 10, "some_test_param": "test-params"} + assert component.api_key == Secret.from_env_var("MISTRAL_API_KEY") + + def test_from_dict_fail_wo_env_var(self, monkeypatch): + monkeypatch.delenv("MISTRAL_API_KEY", raising=False) + data = { + "type": "haystack_integrations.components.generators.mistral.chat.chat_generator.MistralChatGenerator", + "init_parameters": { + "api_key": {"env_vars": ["MISTRAL_API_KEY"], "strict": True, "type": "env_var"}, + "model": "mistral-small", + "api_base_url": "test-base-url", + "streaming_callback": "haystack.components.generators.utils.print_streaming_chunk", + "generation_kwargs": {"max_tokens": 10, "some_test_param": "test-params"}, + }, + } + with pytest.raises(ValueError, match="None of the .* environment variables are set"): + MistralChatGenerator.from_dict(data) + + def test_run(self, chat_messages): + component = MistralChatGenerator() + response = component.run(chat_messages) + + # check that the component returns the correct ChatMessage response + assert isinstance(response, dict) + assert "replies" in response + assert isinstance(response["replies"], list) + assert len(response["replies"]) == 1 + assert [isinstance(reply, ChatMessage) for reply in response["replies"]] + + def test_run_with_params(self, chat_messages, mock_chat_completion): + component = MistralChatGenerator(generation_kwargs={"max_tokens": 10, "temperature": 0.5}) + response = component.run(chat_messages) + + # check that the component calls the OpenAI API with the correct parameters + _, kwargs = mock_chat_completion.call_args + assert kwargs["max_tokens"] == 10 + assert kwargs["temperature"] == 0.5 + + # check that the component returns the correct response + assert isinstance(response, dict) + assert "replies" in response + assert isinstance(response["replies"], list) + assert len(response["replies"]) == 1 + assert [isinstance(reply, ChatMessage) for reply in response["replies"]] + + def test_run_with_params_streaming(self, chat_messages): + streaming_callback_called = False + + def streaming_callback(chunk: StreamingChunk) -> None: # noqa: ARG001 + nonlocal streaming_callback_called + streaming_callback_called = True + + component = MistralChatGenerator(streaming_callback=streaming_callback) + response = component.run(chat_messages) + + # check we called the streaming callback + assert streaming_callback_called + + # check that the component still returns the correct response + assert isinstance(response, dict) + assert "replies" in response + assert isinstance(response["replies"], list) + assert len(response["replies"]) == 1 + assert [isinstance(reply, ChatMessage) for reply in response["replies"]] + assert "Paris" in response["replies"][0].content # see mock_chat_completion_chunk + + def test_check_abnormal_completions(self, caplog): + component = MistralChatGenerator(api_key=Secret.from_token("test-api-key")) + messages = [ + ChatMessage.from_assistant( + "", meta={"finish_reason": "content_filter" if i % 2 == 0 else "length", "index": i} + ) + for i, _ in enumerate(range(4)) + ] + + for m in messages: + component._check_finish_reason(m) + + # check truncation warning + message_template = ( + "The completion for index {index} has been truncated before reaching a natural stopping point. " + "Increase the max_tokens parameter to allow for longer completions." + ) + + for index in [1, 3]: + assert caplog.records[index].message == message_template.format(index=index) + + # check content filter warning + message_template = "The completion for index {index} has been truncated due to the content filter." + for index in [0, 2]: + assert caplog.records[index].message == message_template.format(index=index) + + @pytest.mark.skipif( + not os.environ.get("MISTRAL_API_KEY", None), + reason="Export an env var called MISTRAL_API_KEY containing the OpenAI API key to run this test.", + ) + @pytest.mark.integration + def test_live_run(self): + chat_messages = [ChatMessage.from_user("What's the capital of France")] + component = MistralChatGenerator() + results = component.run(chat_messages) + assert len(results["replies"]) == 1 + message: ChatMessage = results["replies"][0] + assert "Paris" in message.content + assert "mistral-tiny" in message.meta["model"] + assert message.meta["finish_reason"] == "stop" + + @pytest.mark.skipif( + not os.environ.get("MISTRAL_API_KEY", None), + reason="Export an env var called MISTRAL_API_KEY containing the OpenAI API key to run this test.", + ) + @pytest.mark.integration + def test_live_run_wrong_model(self, chat_messages): + component = MistralChatGenerator(model="something-obviously-wrong") + with pytest.raises(OpenAIError): + component.run(chat_messages) + + @pytest.mark.skipif( + not os.environ.get("MISTRAL_API_KEY", None), + reason="Export an env var called MISTRAL_API_KEY containing the OpenAI API key to run this test.", + ) + @pytest.mark.integration + def test_live_run_streaming(self): + class Callback: + def __init__(self): + self.responses = "" + self.counter = 0 + + def __call__(self, chunk: StreamingChunk) -> None: + self.counter += 1 + self.responses += chunk.content if chunk.content else "" + + callback = Callback() + component = MistralChatGenerator(streaming_callback=callback) + results = component.run([ChatMessage.from_user("What's the capital of France?")]) + + assert len(results["replies"]) == 1 + message: ChatMessage = results["replies"][0] + assert "Paris" in message.content + + assert "mistral-tiny" in message.meta["model"] + assert message.meta["finish_reason"] == "stop" + + assert callback.counter > 1 + assert "Paris" in callback.responses diff --git a/integrations/mistral/tests/test_mistral_document_embedder.py b/integrations/mistral/tests/test_mistral_document_embedder.py new file mode 100644 index 000000000..85d56bbaf --- /dev/null +++ b/integrations/mistral/tests/test_mistral_document_embedder.py @@ -0,0 +1,135 @@ +# SPDX-FileCopyrightText: 2023-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 +import os + +import pytest +from haystack import Document +from haystack.utils import Secret +from haystack_integrations.components.embedders.mistral.document_embedder import MistralDocumentEmbedder + +pytestmark = pytest.mark.embedders + + +class TestMistralDocumentEmbedder: + def test_init_default(self): + embedder = MistralDocumentEmbedder() + assert embedder.api_key == Secret.from_env_var(["MISTRAL_API_KEY"]) + assert embedder.model == "mistral-embed" + assert embedder.api_base_url == "https://api.mistral.ai/v1" + assert embedder.prefix == "" + assert embedder.suffix == "" + assert embedder.batch_size == 32 + assert embedder.progress_bar is True + assert embedder.meta_fields_to_embed == [] + assert embedder.embedding_separator == "\n" + + def test_init_with_parameters(self): + embedder = MistralDocumentEmbedder( + api_key=Secret.from_token("test-api-key"), + model="mistral-embed-v2", + api_base_url="https://custom-api-base-url.com", + prefix="START", + suffix="END", + batch_size=64, + progress_bar=False, + meta_fields_to_embed=["test_field"], + embedding_separator="-", + ) + assert embedder.api_key == Secret.from_token("test-api-key") + assert embedder.model == "mistral-embed-v2" + assert embedder.api_base_url == "https://custom-api-base-url.com" + assert embedder.prefix == "START" + assert embedder.suffix == "END" + assert embedder.batch_size == 64 + assert embedder.progress_bar is False + assert embedder.meta_fields_to_embed == ["test_field"] + assert embedder.embedding_separator == "-" + + def test_to_dict(self): + embedder_component = MistralDocumentEmbedder() + component_dict = embedder_component.to_dict() + assert component_dict == { + "type": "haystack_integrations.components.embedders.mistral.document_embedder.MistralDocumentEmbedder", + "init_parameters": { + "api_key": {"env_vars": ["MISTRAL_API_KEY"], "strict": True, "type": "env_var"}, + "model": "mistral-embed", + "api_base_url": "https://api.mistral.ai/v1", + "dimensions": None, + "organization": None, + "prefix": "", + "suffix": "", + "batch_size": 32, + "progress_bar": True, + "meta_fields_to_embed": [], + "embedding_separator": "\n", + }, + } + + def test_to_dict_with_custom_init_parameters(self, monkeypatch): + monkeypatch.setenv("ENV_VAR", "test-secret-key") + embedder = MistralDocumentEmbedder( + api_key=Secret.from_env_var("ENV_VAR", strict=False), + model="mistral-embed-v2", + api_base_url="https://custom-api-base-url.com", + prefix="START", + suffix="END", + batch_size=64, + progress_bar=False, + meta_fields_to_embed=["test_field"], + embedding_separator="-", + ) + component_dict = embedder.to_dict() + assert component_dict == { + "type": "haystack_integrations.components.embedders.mistral.document_embedder.MistralDocumentEmbedder", + "init_parameters": { + "api_key": {"env_vars": ["ENV_VAR"], "strict": False, "type": "env_var"}, + "model": "mistral-embed-v2", + "dimensions": None, + "api_base_url": "https://custom-api-base-url.com", + "organization": None, + "prefix": "START", + "suffix": "END", + "batch_size": 64, + "progress_bar": False, + "meta_fields_to_embed": ["test_field"], + "embedding_separator": "-", + }, + } + + @pytest.mark.skipif( + not os.environ.get("MISTRAL_API_KEY", None), + reason="Export an env var called MISTRAL_API_KEY containing the Cohere API key to run this test.", + ) + @pytest.mark.integration + def test_run(self): + embedder = MistralDocumentEmbedder() + + docs = [ + Document(content="I love cheese", meta={"topic": "Cuisine"}), + Document(content="A transformer is a deep learning architecture", meta={"topic": "ML"}), + ] + + result = embedder.run(docs) + docs_with_embeddings = result["documents"] + + assert isinstance(docs_with_embeddings, list) + assert len(docs_with_embeddings) == len(docs) + for doc in docs_with_embeddings: + assert isinstance(doc.embedding, list) + assert isinstance(doc.embedding[0], float) + + def test_run_wrong_input_format(self): + embedder = MistralDocumentEmbedder(api_key=Secret.from_token("test-api-key")) + + match_error_msg = ( + "OpenAIDocumentEmbedder expects a list of Documents as input.In case you want to embed a string, " + "please use the OpenAITextEmbedder." + ) + + with pytest.raises(TypeError, match=match_error_msg): + embedder.run(documents="text") + with pytest.raises(TypeError, match=match_error_msg): + embedder.run(documents=[1, 2, 3]) + + assert embedder.run(documents=[]) == {"documents": [], "meta": {}} diff --git a/integrations/mistral/tests/test_mistral_text_embedder.py b/integrations/mistral/tests/test_mistral_text_embedder.py new file mode 100644 index 000000000..82e9d23ee --- /dev/null +++ b/integrations/mistral/tests/test_mistral_text_embedder.py @@ -0,0 +1,90 @@ +# SPDX-FileCopyrightText: 2023-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 +import os + +import pytest +from haystack.utils import Secret +from haystack_integrations.components.embedders.mistral.text_embedder import MistralTextEmbedder + +pytestmark = pytest.mark.embedders + + +class TestMistralTextEmbedder: + def test_init_default(self): + embedder = MistralTextEmbedder() + assert embedder.api_key == Secret.from_env_var(["MISTRAL_API_KEY"]) + assert embedder.model == "mistral-embed" + assert embedder.prefix == "" + assert embedder.suffix == "" + + def test_init_with_parameters(self): + embedder = MistralTextEmbedder( + api_key=Secret.from_token("test-api-key"), + model="mistral-embed-v2", + prefix="START", + suffix="END", + ) + assert embedder.api_key == Secret.from_token("test-api-key") + assert embedder.model == "mistral-embed-v2" + assert embedder.prefix == "START" + assert embedder.suffix == "END" + + def test_to_dict(self): + embedder_component = MistralTextEmbedder() + component_dict = embedder_component.to_dict() + assert component_dict == { + "type": "haystack_integrations.components.embedders.mistral.text_embedder.MistralTextEmbedder", + "init_parameters": { + "api_key": {"env_vars": ["MISTRAL_API_KEY"], "strict": True, "type": "env_var"}, + "model": "mistral-embed", + "dimensions": None, + "organization": None, + "prefix": "", + "suffix": "", + }, + } + + def test_to_dict_with_custom_init_parameters(self, monkeypatch): + monkeypatch.setenv("ENV_VAR", "test-secret-key") + embedder = MistralTextEmbedder( + api_key=Secret.from_env_var("ENV_VAR", strict=False), + model="mistral-embed-v2", + api_base_url="https://custom-api-base-url.com", + prefix="START", + suffix="END", + ) + component_dict = embedder.to_dict() + assert component_dict == { + "type": "haystack_integrations.components.embedders.mistral.text_embedder.MistralTextEmbedder", + "init_parameters": { + "api_key": {"env_vars": ["ENV_VAR"], "strict": False, "type": "env_var"}, + "model": "mistral-embed-v2", + "dimensions": None, + "organization": None, + "prefix": "START", + "suffix": "END", + }, + } + + @pytest.mark.skipif( + not os.environ.get("MISTRAL_API_KEY", None), + reason="Export an env var called MISTRAL_API_KEY containing the Cohere API key to run this test.", + ) + @pytest.mark.integration + def test_run(self): + embedder = MistralTextEmbedder() + text = "The food was delicious" + result = embedder.run(text) + assert all(isinstance(x, float) for x in result["embedding"]) + + def test_run_wrong_input_format(self): + embedder = MistralTextEmbedder(api_key=Secret.from_token("test-api-key")) + list_integers_input = ["text_snippet_1", "text_snippet_2"] + match_error_msg = ( + "OpenAITextEmbedder expects a string as an input.In case you want to embed a list of Documents," + " please use the OpenAIDocumentEmbedder." + ) + + with pytest.raises(TypeError, match=match_error_msg): + embedder.run(text=list_integers_input)