diff --git a/.github/labeler.yml b/.github/labeler.yml index dac3bf015..486dd41bd 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:ollama: - changed-files: - any-glob-to-any-file: "integrations/ollama/**/*" diff --git a/.github/workflows/mistral.yml b/.github/workflows/mistral.yml new file mode 100644 index 000000000..90b2c3436 --- /dev/null +++ b/.github/workflows/mistral.yml @@ -0,0 +1,57 @@ +# 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: Run tests + run: hatch run cov diff --git a/README.md b/README.md index 21c1e7d9d..40370a5f1 100644 --- a/README.md +++ b/README.md @@ -83,3 +83,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/chat_generation.py b/integrations/mistral/examples/chat_generation.py new file mode 100644 index 000000000..4869ee509 --- /dev/null +++ b/integrations/mistral/examples/chat_generation.py @@ -0,0 +1,9 @@ +from haystack_integrations.components.generators.mistral import MistralChatGenerator +from haystack.dataclasses import ChatMessage +from haystack.components.generators.utils import print_streaming_chunk + +messages = [ChatMessage.from_user("What's Natural Language Processing?")] + +client = MistralChatGenerator(model= "mistral-small", streaming_callback=print_streaming_chunk) +response = client.run(messages) +print(response) \ No newline at end of file diff --git a/integrations/mistral/examples/indexing_pipeline.py b/integrations/mistral/examples/indexing_pipeline.py new file mode 100644 index 000000000..31caed4f0 --- /dev/null +++ b/integrations/mistral/examples/indexing_pipeline.py @@ -0,0 +1,9 @@ +from haystack import Document +from haystack_integrations.components.embedders.mistral.document_embedder import MistralDocumentEmbedder + +doc = Document(content="I love pizza!") + +document_embedder = MistralDocumentEmbedder() + +result = document_embedder.run([doc]) +print(result['documents'][0].embedding) \ No newline at end of file diff --git a/integrations/mistral/pyproject.toml b/integrations/mistral/pyproject.toml new file mode 100644 index 000000000..6562afa7a --- /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.7" +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.7", + "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"] + +[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.7", "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.*", + "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..e69de29bb 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..5ea979c8e --- /dev/null +++ b/integrations/mistral/src/haystack_integrations/components/embedders/mistral/document_embedder.py @@ -0,0 +1,72 @@ +# SPDX-FileCopyrightText: 2023-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 +from typing import List, Optional + +from haystack import component +from haystack.utils.auth import Secret +from haystack.components.embedders import OpenAIDocumentEmbedder + + +@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", + dimensions: Optional[int] = None, + api_base_url: Optional[str] = "https://api.mistral.ai/v1", + organization: Optional[str] = None, + 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 dimensions: The number of dimensions the resulting output embeddings should have. Only supported in text-embedding-3 and later models. + :param api_base_url: The Mistral API Base url, defaults to None. For more details, see Mistral [docs](https://docs.mistral.ai/api/). + :param organization: The Organization ID, defaults to `None`. + :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__(api_key, + model, + dimensions, + api_base_url, + organization, + prefix, + suffix, + batch_size, + progress_bar, + meta_fields_to_embed, + embedding_separator) \ No newline at end of file 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..2eb61c1d7 --- /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.utils.auth import Secret +from haystack.components.embedders import OpenAITextEmbedder + + +@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", + dimensions: Optional[int] = None, + api_base_url: Optional[str] = "https://api.mistral.ai/v1", + organization: Optional[str] = None, + 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 dimensions: Not yet supported with Mistral embedding models + :param organization: The Organization ID, defaults to `None`. + :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: Not yet supported with Mistral embedding models + :param suffix: Not yet supported with Mistral embedding models + """ + super(MistralTextEmbedder, self).__init__(api_key, + model, + dimensions, + api_base_url, + organization, + prefix, + suffix) \ No newline at end of file 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..831b5991e --- /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"] \ No newline at end of file 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..8a2ec1188 --- /dev/null +++ b/integrations/mistral/src/haystack_integrations/components/generators/mistral/chat/chat_generator.py @@ -0,0 +1,95 @@ +# SPDX-FileCopyrightText: 2023-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 +import asyncio +from typing import Any, Callable, Dict, Optional + +from haystack import component +from haystack.dataclasses import StreamingChunk, ChatMessage +from haystack.utils.auth import Secret +from haystack.components.generators.chat import OpenAIChatGenerator + +@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': 'gpt-3.5-turbo-0613', '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. + """ + + 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", + organization: Optional[str] = None, + 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 organization: Not yet supported with Mistral chat completion models + :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. If set, different calls will generate deterministic results. + """ + super(MistralChatGenerator, self).__init__(api_key, + model, + streaming_callback, + api_base_url, + organization, + generation_kwargs) \ No newline at end of file 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_document_embedder.py b/integrations/mistral/tests/test_mistral_document_embedder.py new file mode 100644 index 000000000..1cdfc6272 --- /dev/null +++ b/integrations/mistral/tests/test_mistral_document_embedder.py @@ -0,0 +1,140 @@ +# 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="embed-multilingual-v2.0", + # input_type="search_query", + # api_base_url="https://custom-api-base-url.com", + # truncate="START", + # use_async_client=True, + # max_retries=5, + # timeout=60, + # 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 == "embed-multilingual-v2.0" + # assert embedder.input_type == "search_query" + # assert embedder.api_base_url == "https://custom-api-base-url.com" + # assert embedder.truncate == "START" + # assert embedder.use_async_client is True + # assert embedder.max_retries == 5 + # assert embedder.timeout == 60 + # 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.cohere.document_embedder.CohereDocumentEmbedder", + # "init_parameters": { + # "api_key": {"env_vars": ["COHERE_API_KEY", "CO_API_KEY"], "strict": True, "type": "env_var"}, + # "model": "embed-english-v2.0", + # "input_type": "search_document", + # "api_base_url": COHERE_API_URL, + # "truncate": "END", + # "use_async_client": False, + # "max_retries": 3, + # "timeout": 120, + # "batch_size": 32, + # "progress_bar": True, + # "meta_fields_to_embed": [], + # "embedding_separator": "\n", + # }, + # } + + # def test_to_dict_with_custom_init_parameters(self): + # embedder_component = CohereDocumentEmbedder( + # api_key=Secret.from_env_var("ENV_VAR", strict=False), + # model="embed-multilingual-v2.0", + # input_type="search_query", + # api_base_url="https://custom-api-base-url.com", + # truncate="START", + # use_async_client=True, + # max_retries=5, + # timeout=60, + # batch_size=64, + # progress_bar=False, + # meta_fields_to_embed=["text_field"], + # embedding_separator="-", + # ) + # component_dict = embedder_component.to_dict() + # assert component_dict == { + # "type": "haystack_integrations.components.embedders.cohere.document_embedder.CohereDocumentEmbedder", + # "init_parameters": { + # "api_key": {"env_vars": ["ENV_VAR"], "strict": False, "type": "env_var"}, + # "model": "embed-multilingual-v2.0", + # "input_type": "search_query", + # "api_base_url": "https://custom-api-base-url.com", + # "truncate": "START", + # "use_async_client": True, + # "max_retries": 5, + # "timeout": 60, + # "batch_size": 64, + # "progress_bar": False, + # "meta_fields_to_embed": ["text_field"], + # "embedding_separator": "-", + # }, + # } + + # @pytest.mark.skipif( + # not os.environ.get("COHERE_API_KEY", None) and not os.environ.get("CO_API_KEY", None), + # reason="Export an env var called COHERE_API_KEY/CO_API_KEY containing the Cohere API key to run this test.", + # ) + # @pytest.mark.integration + # def test_run(self): + # embedder = CohereDocumentEmbedder() + + # 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 = CohereDocumentEmbedder(api_key=Secret.from_token("test-api-key")) + + # with pytest.raises(TypeError, match="CohereDocumentEmbedder expects a list of Documents as input"): + # embedder.run(documents="text") + # with pytest.raises(TypeError, match="CohereDocumentEmbedder expects a list of Documents as input"): + # embedder.run(documents=[1, 2, 3]) + + # assert embedder.run(documents=[]) == {"documents": [], "meta": {}}