From 9b79e0760b51299316655797ea34de4e146f14f3 Mon Sep 17 00:00:00 2001 From: Vladimir Blagojevic Date: Tue, 12 Mar 2024 14:44:52 +0100 Subject: [PATCH] Initial version --- integrations/anthropic/LICENSE.txt | 73 +++++ integrations/anthropic/README.md | 40 +++ integrations/anthropic/pydoc/config.yml | 28 ++ integrations/anthropic/pyproject.toml | 187 ++++++++++++ .../generators/anthropic/__init__.py | 6 + .../generators/anthropic/chat/__init__.py | 3 + .../anthropic/chat/chat_generator.py | 281 ++++++++++++++++++ integrations/anthropic/tests/__init__.py | 3 + integrations/anthropic/tests/conftest.py | 23 ++ .../anthropic/tests/test_chat_generator.py | 218 ++++++++++++++ 10 files changed, 862 insertions(+) create mode 100644 integrations/anthropic/LICENSE.txt create mode 100644 integrations/anthropic/README.md create mode 100644 integrations/anthropic/pydoc/config.yml create mode 100644 integrations/anthropic/pyproject.toml create mode 100644 integrations/anthropic/src/haystack_integrations/components/generators/anthropic/__init__.py create mode 100644 integrations/anthropic/src/haystack_integrations/components/generators/anthropic/chat/__init__.py create mode 100644 integrations/anthropic/src/haystack_integrations/components/generators/anthropic/chat/chat_generator.py create mode 100644 integrations/anthropic/tests/__init__.py create mode 100644 integrations/anthropic/tests/conftest.py create mode 100644 integrations/anthropic/tests/test_chat_generator.py diff --git a/integrations/anthropic/LICENSE.txt b/integrations/anthropic/LICENSE.txt new file mode 100644 index 000000000..137069b82 --- /dev/null +++ b/integrations/anthropic/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/anthropic/README.md b/integrations/anthropic/README.md new file mode 100644 index 000000000..0dac0a16d --- /dev/null +++ b/integrations/anthropic/README.md @@ -0,0 +1,40 @@ +# anthropic-haystack + +[![PyPI - Version](https://img.shields.io/pypi/v/amazon-bedrock-haystack.svg)](https://pypi.org/project/amazon-bedrock-haystack) +[![PyPI - Python Version](https://img.shields.io/pypi/pyversions/amazon-bedrock-haystack.svg)](https://pypi.org/project/amazon-bedrock-haystack) + +----- + +**Table of Contents** + +- [Installation](#installation) +- [Contributing](#contributing) +- [License](#license) + +## Installation + +```console +pip install anthropic-haystack +``` + +## Contributing + +`hatch` is the best way to interact with this project, to install it: +```sh +pip install hatch +``` + +With `hatch` installed, to run all the tests: +``` +hatch run test +``` +> Note: there are no integration tests for this project. + +To run the linters `ruff` and `mypy`: +``` +hatch run lint:all +``` + +## License + +`anthropic-haystack` is distributed under the terms of the [Apache-2.0](https://spdx.org/licenses/Apache-2.0.html) license. diff --git a/integrations/anthropic/pydoc/config.yml b/integrations/anthropic/pydoc/config.yml new file mode 100644 index 000000000..d43d73c17 --- /dev/null +++ b/integrations/anthropic/pydoc/config.yml @@ -0,0 +1,28 @@ +loaders: + - type: haystack_pydoc_tools.loaders.CustomPythonLoader + search_path: [../src] + modules: [ + "haystack_integrations.components.generators.anthropic.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: Anthropic integration for Haystack + category_slug: integrations-api + title: Anthropic + slug: integrations-anthropic + order: 22 + markdown: + descriptive_class_title: false + descriptive_module_title: true + add_method_class_prefix: true + add_member_class_prefix: false + filename: _readme_anthropic.md diff --git a/integrations/anthropic/pyproject.toml b/integrations/anthropic/pyproject.toml new file mode 100644 index 000000000..053f3938a --- /dev/null +++ b/integrations/anthropic/pyproject.toml @@ -0,0 +1,187 @@ +[build-system] +requires = ["hatchling", "hatch-vcs"] +build-backend = "hatchling.build" + +[project] +name = "anthropic-haystack" +dynamic = ["version"] +description = 'An integration of Anthropic Claude models into the Haystack framework.' +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 :: 3.12", + "Programming Language :: Python :: Implementation :: CPython", + "Programming Language :: Python :: Implementation :: PyPy", +] +dependencies = [ + "haystack-ai", + "anthropic", +] + +[project.urls] +Documentation = "https://github.com/deepset-ai/haystack-core-integrations/tree/main/integrations/anthropic#readme" +Issues = "https://github.com/deepset-ai/haystack-core-integrations/issues" +Source = "https://github.com/deepset-ai/haystack-core-integrations/tree/main/integrations/anthropic" + +[tool.hatch.build.targets.wheel] +packages = ["src/haystack_integrations"] + +[tool.hatch.version] +source = "vcs" +tag-pattern = 'integrations\/anthropic-v(?P.*)' + +[tool.hatch.version.raw-options] +root = "../.." +git_describe_command = 'git describe --tags --match="integrations/anthropic-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", "3.12"] + +[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", + # Ignore unused params + "ARG001", "ARG002", "ARG005", +] +unfixable = [ + # Don't touch unused imports + "F401", +] + +[tool.ruff.isort] +known-first-party = ["haystack_integrations"] + +[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 = ["haystack_integrations"] +branch = true +parallel = true + +[tool.coverage.report] +omit = ["*/tests/*", "*/__init__.py"] +show_missing=true +exclude_lines = [ + "no cov", + "if __name__ == .__main__.:", + "if TYPE_CHECKING:", +] + +[[tool.mypy.overrides]] +module = [ + "anthropic.*", + "haystack.*", + "haystack_integrations.*", + "pytest.*", + "numpy.*", +] +ignore_missing_imports = true + +[tool.pytest.ini_options] +addopts = "--strict-markers" +markers = [ + "unit: unit tests", + "integration: integration tests", + "generators: generators tests", +] +log_cli = true diff --git a/integrations/anthropic/src/haystack_integrations/components/generators/anthropic/__init__.py b/integrations/anthropic/src/haystack_integrations/components/generators/anthropic/__init__.py new file mode 100644 index 000000000..7c683c3ac --- /dev/null +++ b/integrations/anthropic/src/haystack_integrations/components/generators/anthropic/__init__.py @@ -0,0 +1,6 @@ +# SPDX-FileCopyrightText: 2023-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 +from .chat.chat_generator import AnthropicChatGenerator + +__all__ = ["AnthropicChatGenerator"] diff --git a/integrations/anthropic/src/haystack_integrations/components/generators/anthropic/chat/__init__.py b/integrations/anthropic/src/haystack_integrations/components/generators/anthropic/chat/__init__.py new file mode 100644 index 000000000..e873bc332 --- /dev/null +++ b/integrations/anthropic/src/haystack_integrations/components/generators/anthropic/chat/__init__.py @@ -0,0 +1,3 @@ +# SPDX-FileCopyrightText: 2023-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 diff --git a/integrations/anthropic/src/haystack_integrations/components/generators/anthropic/chat/chat_generator.py b/integrations/anthropic/src/haystack_integrations/components/generators/anthropic/chat/chat_generator.py new file mode 100644 index 000000000..9600747f4 --- /dev/null +++ b/integrations/anthropic/src/haystack_integrations/components/generators/anthropic/chat/chat_generator.py @@ -0,0 +1,281 @@ +import dataclasses +from typing import Any, Callable, ClassVar, Dict, List, Optional, Union + +from haystack import component, default_from_dict, default_to_dict, logging +from haystack.dataclasses import ChatMessage, ChatRole, StreamingChunk +from haystack.utils import Secret, deserialize_callable, deserialize_secrets_inplace, serialize_callable + +from anthropic import Anthropic, Stream +from anthropic.types import ( + ContentBlock, + ContentBlockDeltaEvent, + Message, + MessageDeltaEvent, + MessageStartEvent, + MessageStreamEvent, + TextDelta, +) + +logger = logging.getLogger(__name__) + + +@component +class AnthropicChatGenerator: + """ + Enables text generation using Anthropic state-of-the-art Claude 3 family of large language models (LLMs) through + the Anthropic messaging API. + + It supports models like `claude-3-opus`, `claude-3-sonnet`, and `claude-3-haiku`, accessed through the + `/v1/messages` API endpoint using the Claude v2.1 messaging version. + + Users can pass any text generation parameters valid for the Anthropic messaging API directly to this component + via the `generation_kwargs` parameter in `__init__` or the `generation_kwargs` parameter in the `run` method. + + For more details on the parameters supported by the Anthropic API, refer to the + Anthropic [documentation](https://docs.anthropic.com/claude/reference/messages_post). + + ```python + from haystack_integrations.components.generators.anthropic import AnthropicChatGenerator + from haystack.dataclasses import ChatMessage + + messages = [ChatMessage.from_user("What's Natural Language Processing?")] + client = AnthropicChatGenerator(model="claude-3-sonnet-20240229") + response = client.run(messages) + print(response) + + >> {'replies': [ChatMessage(content='Natural Language Processing (NLP) is a field of artificial intelligence that + >> focuses on enabling computers to understand, interpret, and generate human language. It involves developing + >> techniques and algorithms to analyze and process text or speech data, allowing machines to comprehend and + >> communicate in natural languages like English, Spanish, or Chinese.', role=, + >> name=None, meta={'model': 'claude-3-sonnet-20240229', 'index': 0, 'finish_reason': 'end_turn', + >> 'usage': {'input_tokens': 15, 'output_tokens': 64}})]} + ``` + + Key Features and Compatibility: + + `Primary Compatibility`: designed to work seamlessly with the Anthropic messaging API (Claude v2.1) and the Claude + 3 family of models, including claude-3-opus, claude-3-sonnet, and claude-3-haiku. + + `Multilingual Support`: Claude 3 models offer improved fluency in non-English languages such as Spanish and + Japanese. + + `Vision and Image Processing`: although all Claude 3 models can process and analyze visual input we do not yet have + the support for this feature in the current version of the component. + + `Steerability and Ease of Use`: Claude 3 models are easier to steer and better at following directions, providing + more control over model behavior and more predictable, higher-quality outputs. + + `Streaming Support`: supports streaming responses from the Anthropic messaging API. + + `Customizability`: supports all parameters supported by the Anthropic messaging API. + """ + + # The parameters that can be passed to the Anthropic API https://docs.anthropic.com/claude/reference/messages_post + ALLOWED_PARAMS: ClassVar[List[str]] = [ + "system", + "max_tokens", + "metadata", + # "stream", explicitly passed to the interface + "stop_sequences", + "temperature", + "top_p", + "top_k", + ] + + def __init__( + self, + api_key: Secret = Secret.from_env_var("ANTHROPIC_API_KEY"), + model: str = "claude-3-sonnet-20240229", + streaming_callback: Optional[Callable[[StreamingChunk], None]] = None, + generation_kwargs: Optional[Dict[str, Any]] = None, + ): + """ + Creates an instance of AnthropicChatGenerator. + + :param api_key: The Anthropic API key + :param model: The name of the 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 generation_kwargs: Other parameters to use for the model. These parameters are all sent directly to + the Anthropic endpoint. See Anthropic [documentation](https://docs.anthropic.com/claude/reference/messages_post) + for more details. + + Supported generation_kwargs parameters are: + - `system`: The system message to be passed to the model. + - `max_tokens`: The maximum number of tokens to generate. + - `metadata`: A dictionary of metadata to be passed to the model. + - `stop_sequences`: A list of strings that the model should stop generating at. + - `temperature`: The temperature to use for sampling. + - `top_p`: The top_p value to use for nucleus sampling. + - `top_k`: The top_k value to use for top-k sampling. + + """ + self.api_key = api_key + self.model = model + self.generation_kwargs = generation_kwargs or {} + self.streaming_callback = streaming_callback + self.client = Anthropic(api_key=self.api_key.resolve_value()) + + def _get_telemetry_data(self) -> Dict[str, Any]: + """ + Data that is sent to Posthog for usage analytics. + """ + return {"model": self.model} + + def to_dict(self) -> Dict[str, Any]: + """ + Serialize this component to a dictionary. + + :returns: + The serialized component as a dictionary. + """ + callback_name = serialize_callable(self.streaming_callback) if self.streaming_callback else None + return default_to_dict( + self, + model=self.model, + streaming_callback=callback_name, + generation_kwargs=self.generation_kwargs, + api_key=self.api_key.to_dict(), + ) + + @classmethod + def from_dict(cls, data: Dict[str, Any]) -> "AnthropicChatGenerator": + """ + Deserialize this component from a dictionary. + + :param data: The dictionary representation of this component. + :returns: + The deserialized component instance. + """ + deserialize_secrets_inplace(data["init_parameters"], keys=["api_key"]) + init_params = data.get("init_parameters", {}) + serialized_callback_handler = init_params.get("streaming_callback") + if serialized_callback_handler: + data["init_parameters"]["streaming_callback"] = deserialize_callable(serialized_callback_handler) + return default_from_dict(cls, data) + + @component.output_types(replies=List[ChatMessage]) + def run(self, messages: List[ChatMessage], generation_kwargs: Optional[Dict[str, Any]] = None): + """ + Invoke the text generation inference based on the provided messages and generation parameters. + + :param messages: A list of ChatMessage instances representing the input messages. + :param generation_kwargs: Additional keyword arguments for text generation. These parameters will + potentially override the parameters passed in the `__init__` method. + For more details on the parameters supported by the Anthropic API, refer to the + Anthropic [documentation](https://www.anthropic.com/python-library). + + :returns: + - `replies`: A list of ChatMessage instances representing the generated responses. + """ + + # update generation kwargs by merging with the generation kwargs passed to the run method + generation_kwargs = {**self.generation_kwargs, **(generation_kwargs or {})} + filtered_generation_kwargs = {k: v for k, v in generation_kwargs.items() if k in self.ALLOWED_PARAMS} + disallowed_params = set(generation_kwargs) - set(self.ALLOWED_PARAMS) + if disallowed_params: + logger.warning( + f"Model parameters {disallowed_params} are not allowed and will be ignored. " + f"Allowed parameters are {self.ALLOWED_PARAMS}." + ) + + # adapt ChatMessage(s) to the format expected by the Anthropic API + anthropic_formatted_messages = self._convert_to_anthropic_format(messages) + + # system message provided by the user overrides the system message from the self.generation_kwargs + system = messages[0].content if messages and messages[0].is_from(ChatRole.SYSTEM) else None + if system: + anthropic_formatted_messages = anthropic_formatted_messages[1:] + + response: Union[Message, Stream[MessageStreamEvent]] = self.client.messages.create( + max_tokens=filtered_generation_kwargs.pop("max_tokens", 512), + system=system if system else filtered_generation_kwargs.pop("system", ""), + model=self.model, + messages=anthropic_formatted_messages, + stream=self.streaming_callback is not None, + **filtered_generation_kwargs, + ) + + completions: List[ChatMessage] = [] + # if streaming is enabled, the response is a Stream[MessageStreamEvent] + if isinstance(response, Stream): + chunks: List[StreamingChunk] = [] + stream_event, delta, start_event = None, None, None + for stream_event in response: + if isinstance(stream_event, MessageStartEvent): + # capture start message to count input tokens + start_event = stream_event + if isinstance(stream_event, ContentBlockDeltaEvent): + chunk_delta: StreamingChunk = self._build_chunk(stream_event.delta) + chunks.append(chunk_delta) + if self.streaming_callback: + self.streaming_callback(chunk_delta) # invoke callback with the chunk_delta + if isinstance(stream_event, MessageDeltaEvent): + # capture stop reason and stop sequence + delta = stream_event + completions = [self._connect_chunks(chunks, start_event, delta)] + # if streaming is disabled, the response is an Anthropic Message + elif isinstance(response, Message): + completions = [self._build_message(content_block, response) for content_block in response.content] + + return {"replies": completions} + + def _build_message(self, content_block: ContentBlock, message: Message) -> ChatMessage: + """ + Converts the non-streaming Anthropic Message to a ChatMessage. + :param content_block: The content block of the message. + :param message: The non-streaming Anthropic Message. + :returns: The ChatMessage. + """ + chat_message = ChatMessage.from_assistant(content_block.text) + chat_message.meta.update( + { + "model": message.model, + "index": 0, + "finish_reason": message.stop_reason, + "usage": dict(message.usage or {}), + } + ) + return chat_message + + def _convert_to_anthropic_format(self, messages: List[ChatMessage]) -> List[Dict[str, Any]]: + """ + Converts the list of ChatMessage to the list of messages in the format expected by the Anthropic API. + :param messages: The list of ChatMessage. + :returns: The list of messages in the format expected by the Anthropic API. + """ + anthropic_formatted_messages = [] + for m in messages: + message_dict = dataclasses.asdict(m) + filtered_message = {k: v for k, v in message_dict.items() if k in {"role", "content"} and v} + anthropic_formatted_messages.append(filtered_message) + return anthropic_formatted_messages + + def _connect_chunks( + self, chunks: List[StreamingChunk], message_start: MessageStartEvent, delta: MessageDeltaEvent + ) -> ChatMessage: + """ + Connects the streaming chunks into a single ChatMessage. + :param chunks: The list of all chunks returned by the Anthropic API. + :param message_start: The MessageStartEvent. + :param delta: The MessageDeltaEvent. + :returns: The complete ChatMessage. + """ + complete_response = ChatMessage.from_assistant("".join([chunk.content for chunk in chunks])) + complete_response.meta.update( + { + "model": self.model, + "index": 0, + "finish_reason": delta.delta.stop_reason if delta else "end_turn", + "usage": {**dict(message_start.message.usage, **dict(delta.usage))} if delta and message_start else {}, + } + ) + return complete_response + + def _build_chunk(self, delta: TextDelta) -> StreamingChunk: + """ + Converts the ContentBlockDeltaEvent to a StreamingChunk. + :param delta: The ContentBlockDeltaEvent. + :returns: The StreamingChunk. + """ + return StreamingChunk(content=delta.text) diff --git a/integrations/anthropic/tests/__init__.py b/integrations/anthropic/tests/__init__.py new file mode 100644 index 000000000..e873bc332 --- /dev/null +++ b/integrations/anthropic/tests/__init__.py @@ -0,0 +1,3 @@ +# SPDX-FileCopyrightText: 2023-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 diff --git a/integrations/anthropic/tests/conftest.py b/integrations/anthropic/tests/conftest.py new file mode 100644 index 000000000..e70223143 --- /dev/null +++ b/integrations/anthropic/tests/conftest.py @@ -0,0 +1,23 @@ +from unittest.mock import patch + +import pytest +from anthropic.types import Message + + +@pytest.fixture +def mock_chat_completion(): + """ + Mock the OpenAI API completion response and reuse it for tests + """ + with patch("anthropic.resources.messages.Messages.create") as mock_chat_completion_create: + completion = Message( + id="foo", + content=[{"type": "text", "text": "Hello, world!"}], + model="claude-3-sonnet-20240229", + role="assistant", + type="message", + usage={"input_tokens": 57, "output_tokens": 40}, + ) + + mock_chat_completion_create.return_value = completion + yield mock_chat_completion_create diff --git a/integrations/anthropic/tests/test_chat_generator.py b/integrations/anthropic/tests/test_chat_generator.py new file mode 100644 index 000000000..923937500 --- /dev/null +++ b/integrations/anthropic/tests/test_chat_generator.py @@ -0,0 +1,218 @@ +import os + +import anthropic +import pytest +from haystack.components.generators.utils import print_streaming_chunk +from haystack.dataclasses import ChatMessage, ChatRole, StreamingChunk +from haystack.utils.auth import Secret + +from haystack_integrations.components.generators.anthropic import AnthropicChatGenerator + + +@pytest.fixture +def chat_messages(): + return [ + ChatMessage.from_system("\\nYou are a helpful assistant, be super brief in your responses."), + ChatMessage.from_user("What's the capital of France?"), + ] + + +class TestAnthropicChatGenerator: + def test_init_default(self, monkeypatch): + monkeypatch.setenv("ANTHROPIC_API_KEY", "test-api-key") + component = AnthropicChatGenerator() + assert component.client.api_key == "test-api-key" + assert component.model == "claude-3-sonnet-20240229" + assert component.streaming_callback is None + assert not component.generation_kwargs + + def test_init_fail_wo_api_key(self, monkeypatch): + monkeypatch.delenv("ANTHROPIC_API_KEY", raising=False) + with pytest.raises(ValueError, match="None of the .* environment variables are set"): + AnthropicChatGenerator() + + def test_init_with_parameters(self): + component = AnthropicChatGenerator( + api_key=Secret.from_token("test-api-key"), + model="claude-3-sonnet-20240229", + streaming_callback=print_streaming_chunk, + generation_kwargs={"max_tokens": 10, "some_test_param": "test-params"}, + ) + assert component.client.api_key == "test-api-key" + assert component.model == "claude-3-sonnet-20240229" + 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("ANTHROPIC_API_KEY", "test-api-key") + component = AnthropicChatGenerator() + data = component.to_dict() + assert data == { + "type": "haystack_integrations.components.generators.anthropic.chat.chat_generator.AnthropicChatGenerator", + "init_parameters": { + "api_key": {"env_vars": ["ANTHROPIC_API_KEY"], "strict": True, "type": "env_var"}, + "model": "claude-3-sonnet-20240229", + "streaming_callback": None, + "generation_kwargs": {}, + }, + } + + def test_to_dict_with_parameters(self, monkeypatch): + monkeypatch.setenv("ENV_VAR", "test-api-key") + component = AnthropicChatGenerator( + api_key=Secret.from_env_var("ENV_VAR"), + streaming_callback=print_streaming_chunk, + generation_kwargs={"max_tokens": 10, "some_test_param": "test-params"}, + ) + data = component.to_dict() + assert data == { + "type": "haystack_integrations.components.generators.anthropic.chat.chat_generator.AnthropicChatGenerator", + "init_parameters": { + "api_key": {"env_vars": ["ENV_VAR"], "strict": True, "type": "env_var"}, + "model": "claude-3-sonnet-20240229", + "streaming_callback": "haystack.components.generators.utils.print_streaming_chunk", + "generation_kwargs": {"max_tokens": 10, "some_test_param": "test-params"}, + }, + } + + def test_to_dict_with_lambda_streaming_callback(self, monkeypatch): + monkeypatch.setenv("ANTHROPIC_API_KEY", "test-api-key") + component = AnthropicChatGenerator( + model="claude-3-sonnet-20240229", + streaming_callback=lambda x: x, + generation_kwargs={"max_tokens": 10, "some_test_param": "test-params"}, + ) + data = component.to_dict() + assert data == { + "type": "haystack_integrations.components.generators.anthropic.chat.chat_generator.AnthropicChatGenerator", + "init_parameters": { + "api_key": {"env_vars": ["ANTHROPIC_API_KEY"], "strict": True, "type": "env_var"}, + "model": "claude-3-sonnet-20240229", + "streaming_callback": "tests.test_chat_generator.", + "generation_kwargs": {"max_tokens": 10, "some_test_param": "test-params"}, + }, + } + + def test_from_dict(self, monkeypatch): + monkeypatch.setenv("ANTHROPIC_API_KEY", "fake-api-key") + data = { + "type": "haystack_integrations.components.generators.anthropic.chat.chat_generator.AnthropicChatGenerator", + "init_parameters": { + "api_key": {"env_vars": ["ANTHROPIC_API_KEY"], "strict": True, "type": "env_var"}, + "model": "claude-3-sonnet-20240229", + "streaming_callback": "haystack.components.generators.utils.print_streaming_chunk", + "generation_kwargs": {"max_tokens": 10, "some_test_param": "test-params"}, + }, + } + component = AnthropicChatGenerator.from_dict(data) + assert component.model == "claude-3-sonnet-20240229" + assert component.streaming_callback is print_streaming_chunk + assert component.generation_kwargs == {"max_tokens": 10, "some_test_param": "test-params"} + assert component.api_key == Secret.from_env_var("ANTHROPIC_API_KEY") + + def test_from_dict_fail_wo_env_var(self, monkeypatch): + monkeypatch.delenv("ANTHROPIC_API_KEY", raising=False) + data = { + "type": "haystack_integrations.components.generators.anthropic.chat.chat_generator.AnthropicChatGenerator", + "init_parameters": { + "api_key": {"env_vars": ["ANTHROPIC_API_KEY"], "strict": True, "type": "env_var"}, + "model": "claude-3-sonnet-20240229", + "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"): + AnthropicChatGenerator.from_dict(data) + + def test_run(self, chat_messages, mock_chat_completion): + component = AnthropicChatGenerator(api_key=Secret.from_token("test-api-key")) + 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 = AnthropicChatGenerator( + api_key=Secret.from_token("test-api-key"), 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"]] + + @pytest.mark.skipif( + not os.environ.get("ANTHROPIC_API_KEY", None), + reason="Export an env var called ANTHROPIC_API_KEY containing the OpenAI API key to run this test.", + ) + @pytest.mark.integration + def test_live_run_wrong_model(self, chat_messages): + component = AnthropicChatGenerator(model="something-obviously-wrong") + with pytest.raises(anthropic.NotFoundError): + component.run(chat_messages) + + @pytest.mark.skipif( + not os.environ.get("ANTHROPIC_API_KEY", None), + reason="Export an env var called ANTHROPIC_API_KEY containing the OpenAI API key to run this test.", + ) + @pytest.mark.integration + def test_default_inference_params(self, chat_messages): + client = AnthropicChatGenerator() + response = client.run(chat_messages) + + assert "replies" in response, "Response does not contain 'replies' key" + replies = response["replies"] + assert isinstance(replies, list), "Replies is not a list" + assert len(replies) > 0, "No replies received" + + first_reply = replies[0] + assert isinstance(first_reply, ChatMessage), "First reply is not a ChatMessage instance" + assert first_reply.content, "First reply has no content" + assert ChatMessage.is_from(first_reply, ChatRole.ASSISTANT), "First reply is not from the assistant" + assert "paris" in first_reply.content.lower(), "First reply does not contain 'paris'" + assert first_reply.meta, "First reply has no metadata" + + @pytest.mark.skipif( + not os.environ.get("ANTHROPIC_API_KEY", None), + reason="Export an env var called ANTHROPIC_API_KEY containing the OpenAI API key to run this test.", + ) + @pytest.mark.integration + def test_default_inference_with_streaming(self, chat_messages): + streaming_callback_called = False + paris_found_in_response = False + + def streaming_callback(chunk: StreamingChunk): + nonlocal streaming_callback_called, paris_found_in_response + streaming_callback_called = True + assert isinstance(chunk, StreamingChunk) + assert chunk.content is not None + if not paris_found_in_response: + paris_found_in_response = "paris" in chunk.content.lower() + + client = AnthropicChatGenerator(streaming_callback=streaming_callback) + response = client.run(chat_messages) + + assert streaming_callback_called, "Streaming callback was not called" + assert paris_found_in_response, "The streaming callback response did not contain 'paris'" + replies = response["replies"] + assert isinstance(replies, list), "Replies is not a list" + assert len(replies) > 0, "No replies received" + + first_reply = replies[0] + assert isinstance(first_reply, ChatMessage), "First reply is not a ChatMessage instance" + assert first_reply.content, "First reply has no content" + assert ChatMessage.is_from(first_reply, ChatRole.ASSISTANT), "First reply is not from the assistant" + assert "paris" in first_reply.content.lower(), "First reply does not contain 'paris'" + assert first_reply.meta, "First reply has no metadata"