From aca516cf5e4dcb00da69e10740a79da62e036242 Mon Sep 17 00:00:00 2001 From: Vladimir Blagojevic Date: Fri, 15 Mar 2024 14:42:43 +0100 Subject: [PATCH 1/5] feat: Add AnthropicGenerator and AnthropicChatGenerator (#573) * Initial version * Add workflow file * ANTHROPIC_API_KEY env var declaration fix * Pylint ignore on Secret from_env_var * Initial version of AnthropicGenerator * Add generator module to pydoc * PR feedback - Julian * fix typo in example ChatMessage --------- Co-authored-by: Julian Risch --- .github/workflows/anthropic.yml | 64 +++++ integrations/anthropic/LICENSE.txt | 73 +++++ integrations/anthropic/README.md | 44 +++ .../example/documentation_rag_with_claude.py | 42 +++ integrations/anthropic/pydoc/config.yml | 29 ++ integrations/anthropic/pyproject.toml | 186 ++++++++++++ .../generators/anthropic/__init__.py | 7 + .../generators/anthropic/chat/__init__.py | 3 + .../anthropic/chat/chat_generator.py | 268 ++++++++++++++++++ .../generators/anthropic/generator.py | 187 ++++++++++++ integrations/anthropic/tests/__init__.py | 3 + integrations/anthropic/tests/conftest.py | 23 ++ .../anthropic/tests/test_chat_generator.py | 218 ++++++++++++++ .../anthropic/tests/test_generator.py | 227 +++++++++++++++ 14 files changed, 1374 insertions(+) create mode 100644 .github/workflows/anthropic.yml create mode 100644 integrations/anthropic/LICENSE.txt create mode 100644 integrations/anthropic/README.md create mode 100644 integrations/anthropic/example/documentation_rag_with_claude.py 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/src/haystack_integrations/components/generators/anthropic/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 create mode 100644 integrations/anthropic/tests/test_generator.py diff --git a/.github/workflows/anthropic.yml b/.github/workflows/anthropic.yml new file mode 100644 index 000000000..755660bfc --- /dev/null +++ b/.github/workflows/anthropic.yml @@ -0,0 +1,64 @@ +# This workflow comes from https://github.com/ofek/hatch-mypyc +# https://github.com/ofek/hatch-mypyc/blob/5a198c0ba8660494d02716cfc9d79ce4adfb1442/.github/workflows/test.yml +name: Test / anthropic + +on: + schedule: + - cron: "0 0 * * *" + pull_request: + paths: + - "integrations/anthropic/**" + - ".github/workflows/anthropic.yml" + +defaults: + run: + working-directory: integrations/anthropic + +concurrency: + group: cohere-${{ github.head_ref }} + cancel-in-progress: true + +env: + PYTHONUNBUFFERED: "1" + FORCE_COLOR: "1" + ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_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 + + - name: Send event to Datadog for nightly failures + if: github.event_name == 'schedule' && failure() + uses: ./.github/actions/send_failure + with: + title: "core-integrations nightly failure: ${{ github.workflow }}" + api-key: ${{ secrets.CORE_DATADOG_API_KEY }} 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..316d327aa --- /dev/null +++ b/integrations/anthropic/README.md @@ -0,0 +1,44 @@ +# 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) +- [Examples](#examples) +- [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 +``` + +## Examples +You can find an example of how to do a simple RAG with Claude using online documentation in the `example/` folder of this repo. + +## 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/example/documentation_rag_with_claude.py b/integrations/anthropic/example/documentation_rag_with_claude.py new file mode 100644 index 000000000..a3cc452ad --- /dev/null +++ b/integrations/anthropic/example/documentation_rag_with_claude.py @@ -0,0 +1,42 @@ +# To run this example, you will need to set a `ANTHROPIC_API_KEY` environment variable. + +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.dataclasses import ChatMessage +from haystack.utils import Secret + +from haystack_integrations.components.generators.anthropic import AnthropicChatGenerator + +messages = [ + ChatMessage.from_system("You are a prompt expert who answers questions based on the given documents."), + ChatMessage.from_user("Here are the documents: {{documents}} \\n Answer: {{query}}"), +] + +rag_pipeline = Pipeline() +rag_pipeline.add_component("fetcher", LinkContentFetcher()) +rag_pipeline.add_component("converter", HTMLToDocument()) +rag_pipeline.add_component("prompt_builder", DynamicChatPromptBuilder(runtime_variables=["documents"])) +rag_pipeline.add_component( + "llm", + AnthropicChatGenerator( + api_key=Secret.from_env_var("ANTHROPIC_API_KEY"), + model="claude-3-sonnet", + streaming_callback=print_streaming_chunk, + ), +) + + +rag_pipeline.connect("fetcher", "converter") +rag_pipeline.connect("converter", "prompt_builder") +rag_pipeline.connect("prompt_builder", "llm") + +question = "What are the best practices in prompt engineering?" +rag_pipeline.run( + data={ + "fetcher": {"urls": ["https://docs.anthropic.com/claude/docs/prompt-engineering"]}, + "prompt_builder": {"template_variables": {"query": question}, "prompt_source": messages}, + } +) diff --git a/integrations/anthropic/pydoc/config.yml b/integrations/anthropic/pydoc/config.yml new file mode 100644 index 000000000..553dfcaef --- /dev/null +++ b/integrations/anthropic/pydoc/config.yml @@ -0,0 +1,29 @@ +loaders: + - type: haystack_pydoc_tools.loaders.CustomPythonLoader + search_path: [../src] + modules: [ + "haystack_integrations.components.generators.anthropic.generator", + "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..79cc5850d --- /dev/null +++ b/integrations/anthropic/pyproject.toml @@ -0,0 +1,186 @@ +[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", +] +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..c2c1ee40d --- /dev/null +++ b/integrations/anthropic/src/haystack_integrations/components/generators/anthropic/__init__.py @@ -0,0 +1,7 @@ +# SPDX-FileCopyrightText: 2023-present deepset GmbH +# +# SPDX-License-Identifier: Apache-2.0 +from .chat.chat_generator import AnthropicChatGenerator +from .generator import AnthropicGenerator + +__all__ = ["AnthropicGenerator", "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..6f43855b7 --- /dev/null +++ b/integrations/anthropic/src/haystack_integrations/components/generators/anthropic/chat/chat_generator.py @@ -0,0 +1,268 @@ +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 Message API [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}})]} + ``` + + For more details on supported models and their capabilities, refer to the Anthropic + [documentation](https://docs.anthropic.com/claude/docs/intro-to-claude). + + Note: We don't yet support vision [capabilities](https://docs.anthropic.com/claude/docs/vision) in the current + implementation. + """ + + # 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", + "stop_sequences", + "temperature", + "top_p", + "top_k", + ] + + def __init__( + self, + api_key: Secret = Secret.from_env_var("ANTHROPIC_API_KEY"), # noqa: B008 + 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/src/haystack_integrations/components/generators/anthropic/generator.py b/integrations/anthropic/src/haystack_integrations/components/generators/anthropic/generator.py new file mode 100644 index 000000000..aa78dfed1 --- /dev/null +++ b/integrations/anthropic/src/haystack_integrations/components/generators/anthropic/generator.py @@ -0,0 +1,187 @@ +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 StreamingChunk +from haystack.utils import Secret, deserialize_callable, deserialize_secrets_inplace, serialize_callable + +from anthropic import Anthropic, Stream +from anthropic.types import ( + ContentBlockDeltaEvent, + Message, + MessageDeltaEvent, + MessageParam, + MessageStartEvent, + MessageStreamEvent, +) + +logger = logging.getLogger(__name__) + + +@component +class AnthropicGenerator: + """ + Enables text generation using Anthropic large language models (LLMs). It supports the Claude family of models. + + Although Anthropic natively supports a much richer messaging API, we have intentionally simplified it in this + component so that the main input/output interface is string-based. + For more complete support, consider using the AnthropicChatGenerator. + + ```python + from haystack_integrations.components.generators.anthropic import AnthropicGenerator + + client = AnthropicGenerator(model="claude-2.1") + response = client.run("What's Natural Language Processing? Be brief.") + print(response) + >>{'replies': ['Natural language processing (NLP) is a branch of artificial intelligence focused on enabling + >>computers to understand, interpret, and manipulate human language. The goal of NLP is to read, decipher, + >> understand, and make sense of the human languages in a manner that is valuable.'], 'meta': {'model': + >> 'claude-2.1', 'index': 0, 'finish_reason': 'end_turn', 'usage': {'input_tokens': 18, 'output_tokens': 58}}} + ``` + """ + + # 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", + "stop_sequences", + "temperature", + "top_p", + "top_k", + ] + + def __init__( + self, + api_key: Secret = Secret.from_env_var("ANTHROPIC_API_KEY"), # noqa: B008 + model: str = "claude-3-sonnet-20240229", + streaming_callback: Optional[Callable[[StreamingChunk], None]] = None, + system_prompt: Optional[str] = None, + generation_kwargs: Optional[Dict[str, Any]] = None, + ): + """ + Initialize the AnthropicGenerator. + + :param api_key: The Anthropic API key. + :param model: The name of the Anthropic model to use. + :param streaming_callback: An optional callback function to handle streaming chunks. + :param system_prompt: An optional system prompt to use for generation. + :param generation_kwargs: Additional keyword arguments for generation. + """ + self.api_key = api_key + self.model = model + self.generation_kwargs = generation_kwargs or {} + self.streaming_callback = streaming_callback + self.system_prompt = system_prompt + self.client = Anthropic(api_key=self.api_key.resolve_value()) + + def _get_telemetry_data(self) -> Dict[str, Any]: + """ + Get telemetry data for the component. + + :returns: A dictionary containing telemetry data. + """ + 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, + system_prompt=self.system_prompt, + generation_kwargs=self.generation_kwargs, + api_key=self.api_key.to_dict(), + ) + + @classmethod + def from_dict(cls, data: Dict[str, Any]) -> "AnthropicGenerator": + """ + 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[str], meta=List[Dict[str, Any]]) + def run(self, prompt: str, generation_kwargs: Optional[Dict[str, Any]] = None): + """ + Generate replies using the Anthropic API. + + :param prompt: The input prompt for generation. + :param generation_kwargs: Additional keyword arguments for generation. + :returns: A dictionary containing: + - `replies`: A list of generated replies. + - `meta`: A list of metadata dictionaries for each reply. + """ + # 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}." + ) + + response: Union[Message, Stream[MessageStreamEvent]] = self.client.messages.create( + max_tokens=filtered_generation_kwargs.pop("max_tokens", 512), + system=self.system_prompt if self.system_prompt else filtered_generation_kwargs.pop("system", ""), + model=self.model, + messages=[MessageParam(content=prompt, role="user")], + stream=self.streaming_callback is not None, + **filtered_generation_kwargs, + ) + + completions: List[str] = [] + meta: Dict[str, Any] = {} + # 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 = StreamingChunk(content=stream_event.delta.text) + 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 = ["".join([chunk.content for chunk in chunks])] + meta.update( + { + "model": self.model, + "index": 0, + "finish_reason": delta.delta.stop_reason if delta else "end_turn", + "usage": {**dict(start_event.message.usage, **dict(delta.usage))} if delta and start_event else {}, + } + ) + # if streaming is disabled, the response is an Anthropic Message + elif isinstance(response, Message): + completions = [content_block.text for content_block in response.content] + meta.update( + { + "model": response.model, + "index": 0, + "finish_reason": response.stop_reason, + "usage": dict(response.usage or {}), + } + ) + + return {"replies": completions, "meta": [meta]} 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..41cc3eb5d --- /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 Anthropic 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 Anthropic 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 Anthropic 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 Anthropic 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" diff --git a/integrations/anthropic/tests/test_generator.py b/integrations/anthropic/tests/test_generator.py new file mode 100644 index 000000000..029cd3920 --- /dev/null +++ b/integrations/anthropic/tests/test_generator.py @@ -0,0 +1,227 @@ +import os + +import anthropic +import pytest +from haystack.components.generators.utils import print_streaming_chunk +from haystack.dataclasses import StreamingChunk +from haystack.utils.auth import Secret + +from haystack_integrations.components.generators.anthropic import AnthropicGenerator + + +class TestAnthropicGenerator: + def test_init_default(self, monkeypatch): + monkeypatch.setenv("ANTHROPIC_API_KEY", "test-api-key") + component = AnthropicGenerator() + 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"): + AnthropicGenerator() + + def test_init_with_parameters(self): + component = AnthropicGenerator( + 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 = AnthropicGenerator() + data = component.to_dict() + assert data == { + "type": "haystack_integrations.components.generators.anthropic.generator.AnthropicGenerator", + "init_parameters": { + "api_key": {"env_vars": ["ANTHROPIC_API_KEY"], "strict": True, "type": "env_var"}, + "model": "claude-3-sonnet-20240229", + "streaming_callback": None, + "system_prompt": None, + "generation_kwargs": {}, + }, + } + + def test_to_dict_with_parameters(self, monkeypatch): + monkeypatch.setenv("ENV_VAR", "test-api-key") + component = AnthropicGenerator( + api_key=Secret.from_env_var("ENV_VAR"), + streaming_callback=print_streaming_chunk, + system_prompt="test-prompt", + generation_kwargs={"max_tokens": 10, "some_test_param": "test-params"}, + ) + data = component.to_dict() + assert data == { + "type": "haystack_integrations.components.generators.anthropic.generator.AnthropicGenerator", + "init_parameters": { + "api_key": {"env_vars": ["ENV_VAR"], "strict": True, "type": "env_var"}, + "model": "claude-3-sonnet-20240229", + "system_prompt": "test-prompt", + "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 = AnthropicGenerator( + 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.generator.AnthropicGenerator", + "init_parameters": { + "api_key": {"env_vars": ["ANTHROPIC_API_KEY"], "strict": True, "type": "env_var"}, + "model": "claude-3-sonnet-20240229", + "streaming_callback": "tests.test_generator.", + "system_prompt": None, + "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.generator.AnthropicGenerator", + "init_parameters": { + "api_key": {"env_vars": ["ANTHROPIC_API_KEY"], "strict": True, "type": "env_var"}, + "model": "claude-3-sonnet-20240229", + "system_prompt": "test-prompt", + "streaming_callback": "haystack.components.generators.utils.print_streaming_chunk", + "generation_kwargs": {"max_tokens": 10, "some_test_param": "test-params"}, + }, + } + component = AnthropicGenerator.from_dict(data) + assert component.model == "claude-3-sonnet-20240229" + assert component.streaming_callback is print_streaming_chunk + assert component.system_prompt == "test-prompt" + 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.generator.AnthropicGenerator", + "init_parameters": { + "api_key": {"env_vars": ["ANTHROPIC_API_KEY"], "strict": True, "type": "env_var"}, + "model": "claude-3-sonnet-20240229", + "system_prompt": "test-prompt", + "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"): + AnthropicGenerator.from_dict(data) + + def test_run(self, mock_chat_completion): + component = AnthropicGenerator(api_key=Secret.from_token("test-api-key")) + response = component.run("What is the capital of France?") + + # check that the component returns the correct ChatMessage response + assert isinstance(response, dict) + assert "replies" in response + assert "meta" in response + assert isinstance(response["replies"], list) + assert isinstance(response["meta"], list) + assert len(response["replies"]) == 1 + assert len(response["meta"]) == 1 + assert [isinstance(reply, str) for reply in response["replies"]] + assert [isinstance(meta, dict) for meta in response["meta"]] + + def test_run_with_params(self, mock_chat_completion): + component = AnthropicGenerator( + api_key=Secret.from_token("test-api-key"), generation_kwargs={"max_tokens": 10, "temperature": 0.5} + ) + response = component.run("What is the capital of France?") + + # check that the component calls the Anthropic 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, str) for reply in response["replies"]] + assert "meta" in response + assert isinstance(response["meta"], list) + assert len(response["meta"]) == 1 + assert [isinstance(meta, dict) for meta in response["meta"]] + + @pytest.mark.skipif( + not os.environ.get("ANTHROPIC_API_KEY", None), + reason="Export an env var called ANTHROPIC_API_KEY containing the Anthropic API key to run this test.", + ) + @pytest.mark.integration + def test_live_run_wrong_model(self): + component = AnthropicGenerator(model="something-obviously-wrong") + with pytest.raises(anthropic.NotFoundError): + component.run("What is the capital of France?") + + @pytest.mark.skipif( + not os.environ.get("ANTHROPIC_API_KEY", None), + reason="Export an env var called ANTHROPIC_API_KEY containing the Anthropic API key to run this test.", + ) + @pytest.mark.integration + def test_default_inference_params(self): + client = AnthropicGenerator() + response = client.run("What is the capital of France?") + + 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, str), "First reply is not a str instance" + assert first_reply, "First reply has no content" + assert "paris" in first_reply.lower(), "First reply does not contain 'paris'" + + assert "meta" in response, "Response does not contain 'meta' key" + meta = response["meta"] + assert isinstance(meta, list), "Meta is not a list" + assert len(meta) > 0, "No meta received" + assert isinstance(meta[0], dict), "First meta is not a dict instance" + + @pytest.mark.skipif( + not os.environ.get("ANTHROPIC_API_KEY", None), + reason="Export an env var called ANTHROPIC_API_KEY containing the Anthropic API key to run this test.", + ) + @pytest.mark.integration + def test_default_inference_with_streaming(self): + 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 = AnthropicGenerator(streaming_callback=streaming_callback) + response = client.run("What is the capital of France?") + + 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, str), "First reply is not a str instance" + assert first_reply, "First reply has no content" + assert "paris" in first_reply.lower(), "First reply does not contain 'paris'" From 9033dab9a4c2d59c9905b58304543edf8c7ca22b Mon Sep 17 00:00:00 2001 From: Julian Risch Date: Fri, 15 Mar 2024 15:05:59 +0100 Subject: [PATCH 2/5] replace amazon-bedrock with anthropic in readme (#584) --- integrations/anthropic/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/integrations/anthropic/README.md b/integrations/anthropic/README.md index 316d327aa..2ed55d4af 100644 --- a/integrations/anthropic/README.md +++ b/integrations/anthropic/README.md @@ -1,7 +1,7 @@ # 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) +[![PyPI - Version](https://img.shields.io/pypi/v/anthropic-haystack.svg)](https://pypi.org/project/anthropic-haystack) +[![PyPI - Python Version](https://img.shields.io/pypi/pyversions/anthropic-haystack.svg)](https://pypi.org/project/anthropic-haystack) ----- From f4730e5f536d0d443112a85101a8c380fd0c4f78 Mon Sep 17 00:00:00 2001 From: Julian Risch Date: Fri, 15 Mar 2024 16:05:26 +0100 Subject: [PATCH 3/5] docs: Add anthropic integration to inventory and sort alphabetically (#585) --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 2db267f6b..50a4bebc4 100644 --- a/README.md +++ b/README.md @@ -24,9 +24,10 @@ Please check out our [Contribution Guidelines](CONTRIBUTING.md) for all the deta | Package | Type | PyPi Package | Status | | ------------------------------------------------------------------- | ------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| [astra-haystack](integrations/astra/) | Document Store | [![PyPI - Version](https://img.shields.io/pypi/v/astra-haystack.svg)](https://pypi.org/project/astra-haystack) | [![Test / astra](https://github.com/deepset-ai/haystack-core-integrations/actions/workflows/astra.yml/badge.svg)](https://github.com/deepset-ai/haystack-core-integrations/actions/workflows/astra.yml) | | [amazon-bedrock-haystack](integrations/amazon-bedrock/) | Generator | [![PyPI - Version](https://img.shields.io/pypi/v/amazon-bedrock-haystack.svg)](https://pypi.org/project/amazon-bedrock-haystack) | [![Test / amazon_bedrock](https://github.com/deepset-ai/haystack-core-integrations/actions/workflows/amazon_bedrock.yml/badge.svg)](https://github.com/deepset-ai/haystack-core-integrations/actions/workflows/amazon_bedrock.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) | +| [anthropic-haystack](integrations/anthropic/) | Generator | [![PyPI - Version](https://img.shields.io/pypi/v/anthropic-haystack.svg)](https://pypi.org/project/anthropic-haystack) | [![Test / anthropic](https://github.com/deepset-ai/haystack-core-integrations/actions/workflows/anthropic.yml/badge.svg)](https://github.com/deepset-ai/haystack-core-integrations/actions/workflows/anthropic.yml) | +| [astra-haystack](integrations/astra/) | Document Store | [![PyPI - Version](https://img.shields.io/pypi/v/astra-haystack.svg)](https://pypi.org/project/astra-haystack) | [![Test / astra](https://github.com/deepset-ai/haystack-core-integrations/actions/workflows/astra.yml/badge.svg)](https://github.com/deepset-ai/haystack-core-integrations/actions/workflows/astra.yml) | | [chroma-haystack](integrations/chroma/) | Document Store | [![PyPI - Version](https://img.shields.io/pypi/v/chroma-haystack.svg)](https://pypi.org/project/chroma-haystack) | [![Test / chroma](https://github.com/deepset-ai/haystack-core-integrations/actions/workflows/chroma.yml/badge.svg)](https://github.com/deepset-ai/haystack-core-integrations/actions/workflows/chroma.yml) | | [cohere-haystack](integrations/cohere/) | Embedder, Generator | [![PyPI - Version](https://img.shields.io/pypi/v/cohere-haystack.svg)](https://pypi.org/project/cohere-haystack) | [![Test / cohere](https://github.com/deepset-ai/haystack-core-integrations/actions/workflows/cohere.yml/badge.svg)](https://github.com/deepset-ai/haystack-core-integrations/actions/workflows/cohere.yml) | | [deepeval-haystack](integrations/deepeval/) | Evaluator | [![PyPI - Version](https://img.shields.io/pypi/v/deepeval-haystack.svg)](https://pypi.org/project/deepeval-haystack) | [![Test / deepeval](https://github.com/deepset-ai/haystack-core-integrations/actions/workflows/deepeval.yml/badge.svg)](https://github.com/deepset-ai/haystack-core-integrations/actions/workflows/deepeval.yml) | From d2780c9d4b4ee757b41c28b9835f4ea0d3578631 Mon Sep 17 00:00:00 2001 From: Massimiliano Pippi Date: Fri, 15 Mar 2024 16:06:41 +0100 Subject: [PATCH 4/5] docs: fix docstrings (#586) * fix docstrings for retrievers * document store * fix test * actual fix --- .../retrievers/weaviate/bm25_retriever.py | 45 ++++++++++++-- .../weaviate/embedding_retriever.py | 61 ++++++++++++++++--- .../weaviate/document_store.py | 49 ++++++++++----- .../tests/test_embedding_retriever.py | 4 +- 4 files changed, 130 insertions(+), 29 deletions(-) diff --git a/integrations/weaviate/src/haystack_integrations/components/retrievers/weaviate/bm25_retriever.py b/integrations/weaviate/src/haystack_integrations/components/retrievers/weaviate/bm25_retriever.py index c37312604..6deef5eb6 100644 --- a/integrations/weaviate/src/haystack_integrations/components/retrievers/weaviate/bm25_retriever.py +++ b/integrations/weaviate/src/haystack_integrations/components/retrievers/weaviate/bm25_retriever.py @@ -7,7 +7,17 @@ @component class WeaviateBM25Retriever: """ - Retriever that uses BM25 to find the most promising documents for a given query. + A component for retrieving documents from Weaviate using the BM25 algorithm. + + Example usage: + ```python + from haystack_integrations.document_stores.weaviate.document_store import WeaviateDocumentStore + from haystack_integrations.components.retrievers.weaviate.bm25_retriever import WeaviateBM25Retriever + + document_store = WeaviateDocumentStore(url="http://localhost:8080") + retriever = WeaviateBM25Retriever(document_store=document_store) + retriever.run(query="How to make a pizza", top_k=3) + ``` """ def __init__( @@ -20,15 +30,24 @@ def __init__( """ Create a new instance of WeaviateBM25Retriever. - :param document_store: Instance of WeaviateDocumentStore that will be associated with this retriever. - :param filters: Custom filters applied when running the retriever, defaults to None - :param top_k: Maximum number of documents to return, defaults to 10 + :param document_store: + Instance of WeaviateDocumentStore that will be used from this retriever. + :param filters: + Custom filters applied when running the retriever + :param top_k: + Maximum number of documents to return """ self._document_store = document_store self._filters = filters or {} self._top_k = top_k def to_dict(self) -> Dict[str, Any]: + """ + Serializes the component to a dictionary. + + :returns: + Dictionary with serialized data. + """ return default_to_dict( self, filters=self._filters, @@ -38,6 +57,14 @@ def to_dict(self) -> Dict[str, Any]: @classmethod def from_dict(cls, data: Dict[str, Any]) -> "WeaviateBM25Retriever": + """ + Deserializes the component from a dictionary. + + :param data: + Dictionary to deserialize from. + :returns: + Deserialized component. + """ data["init_parameters"]["document_store"] = WeaviateDocumentStore.from_dict( data["init_parameters"]["document_store"] ) @@ -45,6 +72,16 @@ def from_dict(cls, data: Dict[str, Any]) -> "WeaviateBM25Retriever": @component.output_types(documents=List[Document]) def run(self, query: str, filters: Optional[Dict[str, Any]] = None, top_k: Optional[int] = None): + """ + Retrieves documents from Weaviate using the BM25 algorithm. + + :param query: + The query text. + :param filters: + Filters to use when running the retriever. + :param top_k: + The maximum number of documents to return. + """ filters = filters or self._filters top_k = top_k or self._top_k documents = self._document_store._bm25_retrieval(query=query, filters=filters, top_k=top_k) diff --git a/integrations/weaviate/src/haystack_integrations/components/retrievers/weaviate/embedding_retriever.py b/integrations/weaviate/src/haystack_integrations/components/retrievers/weaviate/embedding_retriever.py index 38f7cd85f..cdf578fee 100644 --- a/integrations/weaviate/src/haystack_integrations/components/retrievers/weaviate/embedding_retriever.py +++ b/integrations/weaviate/src/haystack_integrations/components/retrievers/weaviate/embedding_retriever.py @@ -20,16 +20,22 @@ def __init__( certainty: Optional[float] = None, ): """ - Create a new instance of WeaviateEmbeddingRetriever. - Raises ValueError if both `distance` and `certainty` are provided. - See the official Weaviate documentation to learn more about the `distance` and `certainty` parameters: - https://weaviate.io/developers/weaviate/api/graphql/search-operators#variables + Creates a new instance of WeaviateEmbeddingRetriever. - :param document_store: Instance of WeaviateDocumentStore that will be associated with this retriever. - :param filters: Custom filters applied when running the retriever, defaults to None - :param top_k: Maximum number of documents to return, defaults to 10 - :param distance: The maximum allowed distance between Documents' embeddings, defaults to None - :param certainty: Normalized distance between the result item and the search vector, defaults to None + :param document_store: + Instance of WeaviateDocumentStore that will be used from this retriever. + :param filters: + Custom filters applied when running the retriever. + :param top_k: + Maximum number of documents to return. + :param distance: + The maximum allowed distance between Documents' embeddings. + :param certainty: + Normalized distance between the result item and the search vector. + :raises ValueError: + If both `distance` and `certainty` are provided. + See https://weaviate.io/developers/weaviate/api/graphql/search-operators#variables to learn more about + `distance` and `certainty` parameters. """ if distance is not None and certainty is not None: msg = "Can't use 'distance' and 'certainty' parameters together" @@ -42,6 +48,12 @@ def __init__( self._certainty = certainty def to_dict(self) -> Dict[str, Any]: + """ + Serializes the component to a dictionary. + + :returns: + Dictionary with serialized data. + """ return default_to_dict( self, filters=self._filters, @@ -53,6 +65,14 @@ def to_dict(self) -> Dict[str, Any]: @classmethod def from_dict(cls, data: Dict[str, Any]) -> "WeaviateEmbeddingRetriever": + """ + Deserializes the component from a dictionary. + + :param data: + Dictionary to deserialize from. + :returns: + Deserialized component. + """ data["init_parameters"]["document_store"] = WeaviateDocumentStore.from_dict( data["init_parameters"]["document_store"] ) @@ -67,10 +87,33 @@ def run( distance: Optional[float] = None, certainty: Optional[float] = None, ): + """ + Retrieves documents from Weaviate using the vector search. + + :param query_embedding: + Embedding of the query. + :param filters: + Filters to use when running the retriever. + :param top_k: + The maximum number of documents to return. + :param distance: + The maximum allowed distance between Documents' embeddings. + :param certainty: + Normalized distance between the result item and the search vector. + :raises ValueError: + If both `distance` and `certainty` are provided. + See https://weaviate.io/developers/weaviate/api/graphql/search-operators#variables to learn more about + `distance` and `certainty` parameters. + """ filters = filters or self._filters top_k = top_k or self._top_k + distance = distance or self._distance certainty = certainty or self._certainty + if distance is not None and certainty is not None: + msg = "Can't use 'distance' and 'certainty' parameters together" + raise ValueError(msg) + documents = self._document_store._embedding_retrieval( query_embedding=query_embedding, filters=filters, diff --git a/integrations/weaviate/src/haystack_integrations/document_stores/weaviate/document_store.py b/integrations/weaviate/src/haystack_integrations/document_stores/weaviate/document_store.py index 34fefa0a5..e7d97ae32 100644 --- a/integrations/weaviate/src/haystack_integrations/document_stores/weaviate/document_store.py +++ b/integrations/weaviate/src/haystack_integrations/document_stores/weaviate/document_store.py @@ -76,9 +76,11 @@ def __init__( """ Create a new instance of WeaviateDocumentStore and connects to the Weaviate instance. - :param url: The URL to the weaviate instance, defaults to None. - :param collection_settings: The collection settings to use, defaults to None. - If None it will use a collection named `default` with the following properties: + :param url: + The URL to the weaviate instance. + :param collection_settings: + The collection settings to use. If `None`, it will use a collection named `default` with the following + properties: - _original_id: text - content: text - dataframe: text @@ -93,22 +95,27 @@ def __init__( production use. See the official `Weaviate documentation`_ for more information on collections and their properties. - :param auth_client_secret: Authentication credentials, defaults to None. - Can be one of the following types depending on the authentication mode: + :param auth_client_secret: + Authentication credentials. Can be one of the following types depending on the authentication mode: - `AuthBearerToken` to use existing access and (optionally, but recommended) refresh tokens - `AuthClientPassword` to use username and password for oidc Resource Owner Password flow - `AuthClientCredentials` to use a client secret for oidc client credential flow - `AuthApiKey` to use an API key - :param additional_headers: Additional headers to include in the requests, defaults to None. - Can be used to set OpenAI/HuggingFace keys. OpenAI/HuggingFace key looks like this: + :param additional_headers: + Additional headers to include in the requests. Can be used to set OpenAI/HuggingFace keys. + OpenAI/HuggingFace key looks like this: ``` {"X-OpenAI-Api-Key": ""}, {"X-HuggingFace-Api-Key": ""} ``` - :param embedded_options: If set create an embedded Weaviate cluster inside the client, defaults to None. - For a full list of options see `weaviate.embedded.EmbeddedOptions`. - :param additional_config: Additional and advanced configuration options for weaviate, defaults to None. - :param grpc_port: The port to use for the gRPC connection, defaults to 50051. - :param grpc_secure: Whether to use a secure channel for the underlying gRPC API. + :param embedded_options: + If set, create an embedded Weaviate cluster inside the client. For a full list of options see + `weaviate.embedded.EmbeddedOptions`. + :param additional_config: + Additional and advanced configuration options for weaviate. + :param grpc_port: + The port to use for the gRPC connection. + :param grpc_secure: + Whether to use a secure channel for the underlying gRPC API. """ # proxies, timeout_config, trust_env are part of additional_config now # startup_period has been removed @@ -153,6 +160,12 @@ def __init__( self._collection = self._client.collections.get(collection_settings["class"]) def to_dict(self) -> Dict[str, Any]: + """ + Serializes the component to a dictionary. + + :returns: + Dictionary with serialized data. + """ embedded_options = asdict(self._embedded_options) if self._embedded_options else None additional_config = ( json.loads(self._additional_config.model_dump_json(by_alias=True)) if self._additional_config else None @@ -170,6 +183,14 @@ def to_dict(self) -> Dict[str, Any]: @classmethod def from_dict(cls, data: Dict[str, Any]) -> "WeaviateDocumentStore": + """ + Deserializes the component from a dictionary. + + :param data: + Dictionary to deserialize from. + :returns: + Deserialized component. + """ if (auth_client_secret := data["init_parameters"].get("auth_client_secret")) is not None: data["init_parameters"]["auth_client_secret"] = AuthCredentials.from_dict(auth_client_secret) if (embedded_options := data["init_parameters"].get("embedded_options")) is not None: @@ -187,7 +208,7 @@ def count_documents(self) -> int: def _to_data_object(self, document: Document) -> Dict[str, Any]: """ - Convert a Document to a Weaviate data object ready to be saved. + Converts a Document to a Weaviate data object ready to be saved. """ data = document.to_dict() # Weaviate forces a UUID as an id. @@ -207,7 +228,7 @@ def _to_data_object(self, document: Document) -> Dict[str, Any]: def _to_document(self, data: DataObject[Dict[str, Any], None]) -> Document: """ - Convert a data object read from Weaviate into a Document. + Converts a data object read from Weaviate into a Document. """ document_data = data.properties document_data["id"] = document_data.pop("_original_id") diff --git a/integrations/weaviate/tests/test_embedding_retriever.py b/integrations/weaviate/tests/test_embedding_retriever.py index a406c40db..c7c147ba5 100644 --- a/integrations/weaviate/tests/test_embedding_retriever.py +++ b/integrations/weaviate/tests/test_embedding_retriever.py @@ -105,7 +105,7 @@ def test_run(mock_document_store): retriever = WeaviateEmbeddingRetriever(document_store=mock_document_store) query_embedding = [0.1, 0.1, 0.1, 0.1] filters = {"field": "content", "operator": "==", "value": "Some text"} - retriever.run(query_embedding=query_embedding, filters=filters, top_k=5, distance=0.1, certainty=0.1) + retriever.run(query_embedding=query_embedding, filters=filters, top_k=5, distance=0.1) mock_document_store._embedding_retrieval.assert_called_once_with( - query_embedding=query_embedding, filters=filters, top_k=5, distance=0.1, certainty=0.1 + query_embedding=query_embedding, filters=filters, top_k=5, distance=0.1, certainty=None ) From bf2a4af2b9f73c37d3d25f8ec4cb39c975440d5d Mon Sep 17 00:00:00 2001 From: Vladimir Blagojevic Date: Fri, 15 Mar 2024 16:26:55 +0100 Subject: [PATCH 5/5] Use the correct sonnet model name (#587) --- integrations/anthropic/example/documentation_rag_with_claude.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/integrations/anthropic/example/documentation_rag_with_claude.py b/integrations/anthropic/example/documentation_rag_with_claude.py index a3cc452ad..98cc9d40e 100644 --- a/integrations/anthropic/example/documentation_rag_with_claude.py +++ b/integrations/anthropic/example/documentation_rag_with_claude.py @@ -23,7 +23,7 @@ "llm", AnthropicChatGenerator( api_key=Secret.from_env_var("ANTHROPIC_API_KEY"), - model="claude-3-sonnet", + model="claude-3-sonnet-20240229", streaming_callback=print_streaming_chunk, ), )